问:
Gettitng ReferenceError: "CryptoJS" is not defined
I have written javascript to for RSASHA256 but gettitng error crypto.js is not defined.</p>

```<code> function aaa(message,secret) {
     <script src="http://crypto-
      js.googlecode.com/svn/tags/3.0.2/build/rollups/hmac-sha256.js"></script>;
     <script src="http://crypto-
      js.googlecode.com/svn/tags/3.0.2/build/components/enc-base64-min.js"></script>;
     var hash = CryptoJS.HmacSHA256("Message", "secret");
     var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
     document.write(hashInBase64);
}
</code>```

答:
Use script tag in html

or you can use jquery to load the script

```<code>$.getScript("YourScriptOrLibraryFile.js", function(){
  //your code
});
</code>```

Body:
I have written javascript to for RSASHA256 but gettitng error crypto.js is not defined.

 function aaa(message,secret) {
     ;
     ;
     var hash = CryptoJS.HmacSHA256("Message", "secret");
     var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
     document.write(hashInBase64);
}

Body:
Use script tag in html

or you can use jquery to load the script

$.getScript("YourScriptOrLibraryFile.js", function(){
  //your code
});


来源: stackexchange

问:
Is it possible to store authentication token in a separate file?
I am building a command line tool using python that interfaces with an RESTful api. The API uses oauth2 for authentication. Rather than asking for access_token every time user runs the python tool. Can I store the access_token in some way so that I can use it till its lifespan? If it is then how safe it is. </p>

答:
Do you want to store it on the service side or locally?

Since your tool interfaces RESTful API, which is stateless, meaning that no information is stored between different requests to API, you actually need to provide access token every time your client accesses any of the REST endpoints. I am maybe missing some of the details in your design, but access tokens should be used only for authorization, since your user is already authenticated if he has a token. This is why tokens are valid only for a certain amount of time, usually 1 hour.

So you need to provide a state either by using cookie (web interface) or storing the token locally (Which is what you meant). However, you should trigger the entire oauth flow every time a user logs in to your client (authenticating user and providing a new auth token) otherwise you are not utilizing the benefits of oauth.

ContentLicense: CC BY-SA 3.0


问:
How to Upgrade HTTP Request to Websocket (Autobahn & Twisted Web )
To give you an idea of what I am trying to accomplish with Twisted Web and Autobahn websockets: my UI currently sends an initial HTTP GET request with an upgrade to a websocket in the header. Upon reading that in Twisted Web, the connection needs to switch from HTTP to a websocket protocol to pass data back and forth. Note that this websocket upgrade happens on the same port, port 8000.

Does anyone know how I can implement what I am trying to do? Thank you so much.

EDIT: updated code for working example. You can find it here: Payload from POST Request is Cutoff (Twisted Web)

Here is my code using Twisted Web:

```<code>class HttpResource(resource.Resource):
    isLeaf = 1

    def __init__(self):
        self.children = {}
        self.ws_port = None

    print 'resource invoked'
    def render_GET(self, request):

        print 'render invoked'
        if request.getHeader('Sec-WebSocket-Key'):
            # Processing the Key as per RFC 6455
            key = request.getHeader('Sec-WebSocket-Key')
            h = hashlib.sha1(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
            request.setHeader('Sec-WebSocket-Accept', base64.b64encode(h.digest()))

            # setting response headers
            request.setHeader('Upgrade', 'websocket')
            request.setHeader('Connection', 'Upgrade')
            request.setResponseCode(101)
            return ''
        else:
            log("Regular HTTP GET request.")
            return "<html><body style='margin: 0; overflow: hidden;'><iframe style='width: 100%; height: 100%; border: none;' src='http://tsa-graphiql.herokuapp.com/'></iframe></body></html>"

    def render_POST(self,request):
        log("POST request")
        request.setResponseCode(200)

    def handle_single_query(self, queryData):
        log("Handle single query data.")
        return

class HttpWsChannel(http.HTTPChannel):

    def dataReceived(self, data):
        log('Data received:\n{}'.format(data))
        if data.startswith('GET'):
            # This will invoke the render method of resource provided
            http.HTTPChannel.dataReceived(self, data)
        if data.startswith('POST'):
            http.HTTPChannel.dataReceived(self, data)
        else:
            """
            Pass binary data to websocket class.
            """
            ws_protocol = self.site.ws_factory.protocol(self.site.ws_factory.connection_subscriptions)
            log(ws_protocol)
            #just echo for now
            # self.transport.write(data)

class HttpFactory(Site):
    """
    Factory which takes care of tracking which protocol
    instances or request instances are responsible for which
    named response channels, so incoming messages can be
    routed appropriately.
    """

    def __init__(self, resource):
        http.HTTPFactory.__init__(self)
        self.resource = resource
        self.ws_factory = WsProtocolFactory("ws://127.0.0.1:8000")
        self.ws_factory.protocol = WsProtocol

    def buildProtocol(self, addr):
        try:
            channel = HttpWsChannel()
            channel.requestFactory = self.requestFactory
            channel.site = self
            return channel
        except Exception as e:
            log("Could not build protocol: {}".format(e))

site = HttpFactory(HttpResource())

if __name__ == '__main__':
    reactor.listenTCP(8000, site)
    reactor.run()
</code>```

EDIT 7/8/2017: Here is the new code I am trying below. The websocket messages are received successfully via the onMessage method. However the HTTP requests are not working. The current error I am getting on a GET request is:

```<code><html>
  <head><title>404 - No Such Resource</title></head>
  <body>
    <h1>No Such Resource</h1>
    <p>No such child resource.</p>
  </body>
</html>
</code>```

Python code

```<code>from twisted.web.server import (
    Site,
)
from twisted.internet import reactor
from twisted.web.resource import (
    Resource,
)
from autobahn.twisted.websocket import (
    WebSocketServerProtocol,
    WebSocketServerFactory,
)
from autobahn.twisted.resource import (
    WebSocketResource,
)

class WebSocketProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("WebSocket connection request: {}".format(request))

    def onMessage(self, payload, isBinary):
        print("onMessage: {}".format(payload))

if __name__ == '__main__':

    factory = WebSocketServerFactory()
    factory.protocol = WebSocketProtocol
    resource = WebSocketResource(factory)

    root = Resource()
    root.putChild(b"ws", resource)

    site = Site(root)
    reactor.listenTCP(8000, site)

    reactor.run()
</code>```

答:
Use WebSocketResource to expose a WebSocketServerFactory as part of a Site.

```<code>from twisted.web.server import (
    Site,
)
from twisted.web.resource import (
    Resource,
)
from autobahn.twisted.websocket import (
    WebSocketServerProtocol,
    WebSocketServerFactory,
)
from autobahn.twisted.resource import (
    WebSocketResource,
)

class YourAppProtocol(WebSocketServerProtocol):
    def onConnect(self, request):
        ...

    ...

def main():
    factory = WebSocketRendezvousFactory()
    factory.protocol = YourAppProtocol
    resource = WebSocketResource(factory)
    root = Resource()
    root.putChild(b"some-path-segment", resource)
    root.putChild(...)
    site = Site(root)
    reactor.listenTCP(8080, site)
    reactor.run()
</code>```

The problems with truncated request bodies is probably because your upgrade protocol implementation is buggy.  There is no framing applied at the level of dataReceived so you can't expect checks like startswith("GET") to be reliable.

Using WebSocketResource and Site gives you the correct HTTP parsing code from Twisted Web and Autobahn while also allowing you to speak WebSocket to a particular URL and regular HTTP to others.

Body:
To give you an idea of what I am trying to accomplish with Twisted Web and Autobahn websockets: my UI currently sends an initial HTTP GET request with an upgrade to a websocket in the header. Upon reading that in Twisted Web, the connection needs to switch from HTTP to a websocket protocol to pass data back and forth. Note that this websocket upgrade happens on the same port, port 8000.

Does anyone know how I can implement what I am trying to do? Thank you so much.

EDIT: updated code for working example. You can find it here: Payload from POST Request is Cutoff (Twisted Web)

Here is my code using Twisted Web:

class HttpResource(resource.Resource):
    isLeaf = 1

    def __init__(self):
        self.children = {}
        self.ws_port = None

    print 'resource invoked'
    def render_GET(self, request):

        print 'render invoked'
        if request.getHeader('Sec-WebSocket-Key'):
            # Processing the Key as per RFC 6455
            key = request.getHeader('Sec-WebSocket-Key')
            h = hashlib.sha1(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
            request.setHeader('Sec-WebSocket-Accept', base64.b64encode(h.digest()))

            # setting response headers
            request.setHeader('Upgrade', 'websocket')
            request.setHeader('Connection', 'Upgrade')
            request.setResponseCode(101)
            return ''
        else:
            log("Regular HTTP GET request.")
            return ""

    def render_POST(self,request):
        log("POST request")
        request.setResponseCode(200)

    def handle_single_query(self, queryData):
        log("Handle single query data.")
        return

class HttpWsChannel(http.HTTPChannel):

    def dataReceived(self, data):
        log('Data received:\n{}'.format(data))
        if data.startswith('GET'):
            # This will invoke the render method of resource provided
            http.HTTPChannel.dataReceived(self, data)
        if data.startswith('POST'):
            http.HTTPChannel.dataReceived(self, data)
        else:
            """
            Pass binary data to websocket class.
            """
            ws_protocol = self.site.ws_factory.protocol(self.site.ws_factory.connection_subscriptions)
            log(ws_protocol)
            #just echo for now
            # self.transport.write(data)

class HttpFactory(Site):
    """
    Factory which takes care of tracking which protocol
    instances or request instances are responsible for which
    named response channels, so incoming messages can be
    routed appropriately.
    """

    def __init__(self, resource):
        http.HTTPFactory.__init__(self)
        self.resource = resource
        self.ws_factory = WsProtocolFactory("ws://127.0.0.1:8000")
        self.ws_factory.protocol = WsProtocol

    def buildProtocol(self, addr):
        try:
            channel = HttpWsChannel()
            channel.requestFactory = self.requestFactory
            channel.site = self
            return channel
        except Exception as e:
            log("Could not build protocol: {}".format(e))

site = HttpFactory(HttpResource())

if __name__ == '__main__':
    reactor.listenTCP(8000, site)
    reactor.run()

EDIT 7/8/2017: Here is the new code I am trying below. The websocket messages are received successfully via the onMessage method. However the HTTP requests are not working. The current error I am getting on a GET request is:

  <title>404 - No Such Resource</title>

No Such Resource

No such child resource.

Python code

from twisted.web.server import (
    Site,
)
from twisted.internet import reactor
from twisted.web.resource import (
    Resource,
)
from autobahn.twisted.websocket import (
    WebSocketServerProtocol,
    WebSocketServerFactory,
)
from autobahn.twisted.resource import (
    WebSocketResource,
)

class WebSocketProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("WebSocket connection request: {}".format(request))

    def onMessage(self, payload, isBinary):
        print("onMessage: {}".format(payload))

if __name__ == '__main__':

    factory = WebSocketServerFactory()
    factory.protocol = WebSocketProtocol
    resource = WebSocketResource(factory)

    root = Resource()
    root.putChild(b"ws", resource)

    site = Site(root)
    reactor.listenTCP(8000, site)

    reactor.run()

Body:
Use WebSocketResource to expose a WebSocketServerFactory as part of a Site.

from twisted.web.server import (
    Site,
)
from twisted.web.resource import (
    Resource,
)
from autobahn.twisted.websocket import (
    WebSocketServerProtocol,
    WebSocketServerFactory,
)
from autobahn.twisted.resource import (
    WebSocketResource,
)

class YourAppProtocol(WebSocketServerProtocol):
    def onConnect(self, request):
        ...

    ...

def main():
    factory = WebSocketRendezvousFactory()
    factory.protocol = YourAppProtocol
    resource = WebSocketResource(factory)
    root = Resource()
    root.putChild(b"some-path-segment", resource)
    root.putChild(...)
    site = Site(root)
    reactor.listenTCP(8080, site)
    reactor.run()

The problems with truncated request bodies is probably because your upgrade protocol implementation is buggy.  There is no framing applied at the level of dataReceived so you can't expect checks like startswith("GET") to be reliable.

Using WebSocketResource and Site gives you the correct HTTP parsing code from Twisted Web and Autobahn while also allowing you to speak WebSocket to a particular URL and regular HTTP to others.


问:
Django with PyPy
Are there some reasons of using Django with PyPy?
I read PyPy increases perfomance.</p>

答:
Depends.

PyPy does improve performance for all benchmarks that are in the PyPy's benchmark suite. This is only template rendering for now, but noone submitted anything else. It's however safe to assume that performance critical code will be faster (especially after some tuning).

Compatibility-wise databases are a bit of an issue, because only sqlite is working and it's slow (there is a branch to fix it though). People also reported pg8000 working with sqlalchemy for example, but I don't have a first-hand experience.

Cheers,
fijal

ContentLicense: CC BY-SA 2.5

Title: Django with PyPy


问:
Cannot excecute make devserver command
I am new to pelican and when I try execute the following command it, fails.

```<code>make devserver
</code>```

It gives me this error

```<code>make: *** No rule to make target `devserver'.  Stop.
</code>```

I am new to pelican and building blogs. Please help me here.

答: You need to call make devserver from the directory where the `Makefile´ is. So, change to this directory and try again.

Title: Cannot excecute make devserver command

Body:
I am new to pelican and when I try execute the following command it, fails.

make devserver

It gives me this error

make: *** No rule to make target `devserver'.  Stop.

I am new to pelican and building blogs. Please help me here.


问:
populate dropdown menu on SQL columns
i have been trying to populate a dropdown menu with the columns of a SQL table, but i am stuck. Or all the fields in the dropdown menu are : Array, or the dropdown menu is populated with empty values.

am i missing something?

i tried this code.

SHOW COLUMNS, DESCRIBE 'TABLE' AND SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE = ikbb;

```<code>    <?php
    $conn = new mysqli('localhost', 'heijsdb_user', 'maus', 'heijsdb')
    or die ('Cannot connect to db');
    $result = $conn->query("SHOW COLUMNS FROM ikbb FROM heijsdb");
    echo "selecteer een input om aan te passen";
    echo "<html>";
    echo "<body>";
    echo "<select name='id'>";
    while ($row = $result->fetch_assoc()) {

                $rows[0] = $row;
                  echo '<option value="'.$row.'">'.$row.'</option>';

}

    echo "</select>";
    echo "</body>";
    echo "</html>";
?>
</code>```

result
result 2

答:
You're trying to populate a dropdown with an array, and this is why you see Array in your select input. Furthermore, you shouldn't add the html tag later than echo something.

I would recommend this query for getting the columns of a table :

```<code>SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='your_database' AND `TABLE_NAME`='your_table'
</code>```

To populate a dropdown with these names, simply use this script :

```<code><?php
$conn = new mysqli("server", "user", "password", "database");
$result = $conn->query("SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='your_database' AND `TABLE_NAME`='your_table'");
echo '<html>';
echo '<body>';
echo '<select name="id">';
while($row = $result->fetch_assoc()) {
    echo '<option value="'.$row['COLUMN_NAME'].'">'.$row['COLUMN_NAME'].'</option>';
}
echo '</select>';
echo '</body>';
echo '</html>';
?>
</code>```

Title: populate dropdown menu on SQL columns

Body:
i have been trying to populate a dropdown menu with the columns of a SQL table, but i am stuck. Or all the fields in the dropdown menu are : Array, or the dropdown menu is populated with empty values.

am i missing something?

i tried this code.

SHOW COLUMNS, DESCRIBE 'TABLE' AND SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE = ikbb;

    <?php
    $conn = new mysqli('localhost', 'heijsdb_user', 'maus', 'heijsdb')
    or die ('Cannot connect to db');
    $result = $conn->query("SHOW COLUMNS FROM ikbb FROM heijsdb");
    echo "selecteer een input om aan te passen";
    echo "";
    echo "";
    echo "<select name='id'>";
    while ($row = $result->fetch_assoc()) {

                $rows[0] = $row;
                  echo '<option value="'.$row.'">'.$row.'</option>';

}

    echo "</select>";
    echo "";
    echo "";
?>

result
result 2

Body:
You're trying to populate a dropdown with an array, and this is why you see Array in your select input. Furthermore, you shouldn't add the html tag later than echo something.

I would recommend this query for getting the columns of a table :

SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='your_database' AND `TABLE_NAME`='your_table'

To populate a dropdown with these names, simply use this script :

<?php
$conn = new mysqli("server", "user", "password", "database");
$result = $conn->query("SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='your_database' AND `TABLE_NAME`='your_table'");
echo '<html>';
echo '<body>';
echo '<select name="id">';
while($row = $result->fetch_assoc()) {
    echo '<option value="'.$row['COLUMN_NAME'].'">'.$row['COLUMN_NAME'].'</option>';
}
echo '</select>';
echo '</body>';
echo '</html>';
?>


问:
Workaround for Youtube API?
I know this might have been asked before, but this is a special case I am involved into..

IMPORTANT
I need to do this inside a separate class, not an activity. Actually my class extends a BaseViewPagerAdapter wrote by someone else..

The idea is that, I can't use YoutubePlayerView because I can not extend YoutubeBaseActivity.

I also tried using YoutubePlayerSupportFragment, same not working because I can't get the refernce for the  from my XML file...

I did try something like this

```<code>public class YTVideoFragment extends YouTubePlayerSupportFragment {
private final static String TAG = "YoutubeVideoFragment";
private static final String DEV_KEY = "key";
private static String id;
private YouTubePlayer mPlayer;
public static YTVideoFragment newInstance(String url){
    YTVideoFragment videoFragment = new YTVideoFragment();
    Bundle bundle = new Bundle();
    bundle.putString("uri", url);
    videoFragment.setArguments(bundle);
    videoFragment.init(0);

    Log.i(TAG, "new Instance FINAL ");
    return videoFragment;

}

public void init(final int time) {
    initialize(DEV_KEY, new YouTubePlayer.OnInitializedListener() {
        @Override
        public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
            mPlayer = youTubePlayer;
            Log.i(TAG, "-=onInitializationSuccess=-");
            mPlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
            id = getArguments().getString("url");
            if (!b){
                mPlayer.loadVideo(id, time);
            }
        }

        @Override
        public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
            Log.i(TAG, "-=onInitializationFailure=-");
            Log.e(TAG, youTubeInitializationResult.toString());
        }
    });
}
</code>```

}

And I made an instance of this into the class that extends BaseViewPageAdapter and tried to do

```<code>YouTubePlayerSupportFragment youtube = YouTubePlayerSupportFragment.newInstance();
                youtube.getFragmentManager().beginTransaction().replace(R.id.youtubeplayerfragment,youtube);
</code>```

But there I get an error that replace function is applied on a null object reference ..

If you have any suggestion, or idea how I could make it work on this particular case I would be grateful

答:
Ok, I managed to make it work on my context like this

First of all, I changed my YTVideoFragment class to extends Fragment

```<code>public class YoutubeFragment extends Fragment {

private static final String API_KEY = DateUtils.getDeveloperKey();

private static String VIDEO_ID;

public void setVideoID(String id){
    VIDEO_ID = id;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.youtube_layout, container, false);

    YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();

    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    transaction.add(R.id.youtube_layout, youTubePlayerFragment).commit();

    youTubePlayerFragment.initialize(API_KEY, new OnInitializedListener() {

        @Override
        public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
            if (!wasRestored) {
                player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
                player.loadVideo(VIDEO_ID);
                player.play();
            }
        }

        @Override
        public void onInitializationFailure(Provider provider, YouTubeInitializationResult error) {
            // YouTube error
            String errorMessage = error.toString();
            Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
            Log.d("errorMessage:", errorMessage);
        }
    });

    return rootView;
}
}
</code>```

And made an instance of that class where I needed it like this

```<code>YoutubeFragment youtubeFragment = new YoutubeFragment();
                youtubeFragment.setVideoID(eventData.getYoutube_id());
                FragmentManager fragmentManager = ((FragmentActivity) context).getSupportFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.relativeLayout, youtubeFragment)
                        .commit();
</code>```

I have to mention here, that being inside a BaseViewPagerAdapter I had to cast my context to (FragmentActivity) in order to be able to call getSupportFragmentManager();

Frame layout XML which will replace a VideoView inside my main XML file is this:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
    android:id="@+id/youtube_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:visibility="visible" />
</RelativeLayout>
</code>```

Title: Workaround for Youtube API?

Body:
I know this might have been asked before, but this is a special case I am involved into..

IMPORTANT
I need to do this inside a separate class, not an activity. Actually my class extends a BaseViewPagerAdapter wrote by someone else..

The idea is that, I can't use YoutubePlayerView because I can not extend YoutubeBaseActivity.

I also tried using YoutubePlayerSupportFragment, same not working because I can't get the refernce for the  from my XML file...

I did try something like this

public class YTVideoFragment extends YouTubePlayerSupportFragment {
private final static String TAG = "YoutubeVideoFragment";
private static final String DEV_KEY = "key";
private static String id;
private YouTubePlayer mPlayer;
public static YTVideoFragment newInstance(String url){
    YTVideoFragment videoFragment = new YTVideoFragment();
    Bundle bundle = new Bundle();
    bundle.putString("uri", url);
    videoFragment.setArguments(bundle);
    videoFragment.init(0);

    Log.i(TAG, "new Instance FINAL ");
    return videoFragment;

}

public void init(final int time) {
    initialize(DEV_KEY, new YouTubePlayer.OnInitializedListener() {
        @Override
        public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
            mPlayer = youTubePlayer;
            Log.i(TAG, "-=onInitializationSuccess=-");
            mPlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
            id = getArguments().getString("url");
            if (!b){
                mPlayer.loadVideo(id, time);
            }
        }

        @Override
        public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
            Log.i(TAG, "-=onInitializationFailure=-");
            Log.e(TAG, youTubeInitializationResult.toString());
        }
    });
}

}

And I made an instance of this into the class that extends BaseViewPageAdapter and tried to do

YouTubePlayerSupportFragment youtube = YouTubePlayerSupportFragment.newInstance();
                youtube.getFragmentManager().beginTransaction().replace(R.id.youtubeplayerfragment,youtube);

But there I get an error that replace function is applied on a null object reference ..

If you have any suggestion, or idea how I could make it work on this particular case I would be grateful

Body:
Ok, I managed to make it work on my context like this

First of all, I changed my YTVideoFragment class to extends Fragment

public class YoutubeFragment extends Fragment {

private static final String API_KEY = DateUtils.getDeveloperKey();

private static String VIDEO_ID;

public void setVideoID(String id){
    VIDEO_ID = id;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.youtube_layout, container, false);

    YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();

    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    transaction.add(R.id.youtube_layout, youTubePlayerFragment).commit();

    youTubePlayerFragment.initialize(API_KEY, new OnInitializedListener() {

        @Override
        public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
            if (!wasRestored) {
                player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
                player.loadVideo(VIDEO_ID);
                player.play();
            }
        }

        @Override
        public void onInitializationFailure(Provider provider, YouTubeInitializationResult error) {
            // YouTube error
            String errorMessage = error.toString();
            Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
            Log.d("errorMessage:", errorMessage);
        }
    });

    return rootView;
}
}

And made an instance of that class where I needed it like this

YoutubeFragment youtubeFragment = new YoutubeFragment();
                youtubeFragment.setVideoID(eventData.getYoutube_id());
                FragmentManager fragmentManager = ((FragmentActivity) context).getSupportFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.relativeLayout, youtubeFragment)
                        .commit();

I have to mention here, that being inside a BaseViewPagerAdapter I had to cast my context to (FragmentActivity) in order to be able to call getSupportFragmentManager();

Frame layout XML which will replace a VideoView inside my main XML file is this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
    android:id="@+id/youtube_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:visibility="visible" />
</RelativeLayout>


问:
ERROR. 'keytool' is not recognized as an internal or external command, operable program or batch file
I try to add facebook login to my android app. I exactly followed the documentation but when I try to run a command line in Android Studio terminal to generate a development hash key, it says "'keytool' is not recognized as an internal or external command,
operable program or batch file.

This is my command code:

keytool -exportcert -alias androiddebugkey -keystore
  %HOMEPATH%.android\debug.keystore | openssl sha1 -binary | openssl
  base64

What should I do?

答: Click on the gradle tab on the right hand side of android studio and navigate to :app and click on tasks -> android and run the signing report to get the hash key for your app, like this:


问:
I want to set actionbar color and title in a fragment class which is in tablayout
This is my tabhost Activity and i want to set each fragment title at actionbar.My tabs are at bottom in xml and i want each tab title at top in actionbar.Can we write code in this tabhostActivity?Or can write any code in each fragment.Can anyone suggest any option for this?</p>

```<code>public class TabHostActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
        R.drawable.hm_icon,
        R.drawable.a_icon,
        R.drawable.user_icon_white,
        R.drawable.gear,
        R.drawable.mail_icon_white
};
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tabs);

    toolbar = (Toolbar) findViewById(R.id.toolbar);

   /* setSupportActionBar(toolbar);*/
    /*getSupportActionBar().setDisplayHomeAsUpEnabled(true);*/

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();

    permissionCheck = ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_CONTACTS);

    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CONTACTS}, REQUEST_READ_PHONE_STATE);

    }
}
private void setupTabIcons() {
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    tabLayout.getTabAt(1).setIcon(tabIcons[1]);
    tabLayout.getTabAt(2).setIcon(tabIcons[2]);
    tabLayout.getTabAt(3).setIcon(tabIcons[3]);
    tabLayout.getTabAt(4).setIcon(tabIcons[4]);

}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new HomeMain(), "");
    adapter.addFrag(new ChooseDefault(), "");
    adapter.addFrag(new MyAccountActivity(), "");
    adapter.addFrag(new UtitlityFragment(), "");
    adapter.addFrag(new SMSFragment(), "");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}
</code>```

答:
You can use the TabLayout.OnTabSelectedListener</p>

```<code>mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            final int position = tab.getPosition();
            final String title = mFragmentTitleList.get(position);
            mActionBar.setTitle(titleRes);
        }
    }
</code>```

Body:
This is my tabhost Activity and i want to set each fragment title at actionbar.My tabs are at bottom in xml and i want each tab title at top in actionbar.Can we write code in this tabhostActivity?Or can write any code in each fragment.Can anyone suggest any option for this?

public class TabHostActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
        R.drawable.hm_icon,
        R.drawable.a_icon,
        R.drawable.user_icon_white,
        R.drawable.gear,
        R.drawable.mail_icon_white
};
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tabs);

    toolbar = (Toolbar) findViewById(R.id.toolbar);

   /* setSupportActionBar(toolbar);*/
    /*getSupportActionBar().setDisplayHomeAsUpEnabled(true);*/

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();

    permissionCheck = ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_CONTACTS);

    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CONTACTS}, REQUEST_READ_PHONE_STATE);

    }
}
private void setupTabIcons() {
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    tabLayout.getTabAt(1).setIcon(tabIcons[1]);
    tabLayout.getTabAt(2).setIcon(tabIcons[2]);
    tabLayout.getTabAt(3).setIcon(tabIcons[3]);
    tabLayout.getTabAt(4).setIcon(tabIcons[4]);

}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new HomeMain(), "");
    adapter.addFrag(new ChooseDefault(), "");
    adapter.addFrag(new MyAccountActivity(), "");
    adapter.addFrag(new UtitlityFragment(), "");
    adapter.addFrag(new SMSFragment(), "");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

Body:
You can use the TabLayout.OnTabSelectedListener

mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            final int position = tab.getPosition();
            final String title = mFragmentTitleList.get(position);
            mActionBar.setTitle(titleRes);
        }
    }


问:
c# entity framework with virtual property query
I have this class:

```<code>    public class Message
    {
        public Message()
        {
            Contacts = new List<Contact>();
        }

        public Message(string Sub_Message, string Body_Message, string Date_Send_Message)
        {
            Contacts = new List<Contact>();

            Subject = Sub_Message;
            Body = Body_Message;
            Date = Date_Send_Message;
        }

        public int MessageId { get; set; }
        public string Subject { get; set; }

        public string Date { get; set; }

        public string Body { get; set; }

        public virtual IList<Contact> Contacts { get; set; }
    }
</code>```

I want to get the table of the Contact, because of that Messages is virtual and all the lazy loading stuff,

This call didn't work to me and got this error:

The ObjectContext instance has been disposed and can no longer be used
  for operations that require a connection. in Reference Table

syntax:

```<code>    public ObservableCollection<Model.Message> LoadMessages()
    {
      using (db) {
       var x = from qr in db.Messages
                            order by qr.Subject
                            select qr;
          }
     }
</code>```

While this works:

```<code>public ObservableCollection<Model.Message> LoadMessages()
{
    using (db)
    {
        var Messages = db.Messages.Include(z => z.Contacts).ToList();

        return new ObservableCollection<Model.Message>(Messages);
    }
}
</code>```

So I am using the queries inside a service called MessageService, Everytime I want to use the dbContext I create a function for it and put it inside using(db)

Like this:

```<code>     public class MessageService
        {
            ReadingFromData db = new ReadingFromData();
            public ObservableCollection<Model.Message> LoadMessages()
            {
                using (db)
                {
                    //Do something with db
                }
            }
}
</code>```

Also, can someone explain to me how this works, and how to work with entity framework queries correct

Thanks

答:
Lazy loading will work only if the property is accessed while the connection to the context is open (or not disposed).

```<code>            using (db)
            {
                //If you try to load the data here, lazy loading will work.
            }
</code>```

Now, when you use include, EF does eager loading and gets the related data for you. That is why your data is available when you are using include.

```<code>var Messages = db.Messages.Include(z => z.Contacts).ToList();
</code>```

Body:
I have this class:

    public class Message
    {
        public Message()
        {
            Contacts = new List<Contact>();
        }

        public Message(string Sub_Message, string Body_Message, string Date_Send_Message)
        {
            Contacts = new List<Contact>();

            Subject = Sub_Message;
            Body = Body_Message;
            Date = Date_Send_Message;
        }

        public int MessageId { get; set; }
        public string Subject { get; set; }

        public string Date { get; set; }

        public string Body { get; set; }

        public virtual IList<Contact> Contacts { get; set; }
    }

I want to get the table of the Contact, because of that Messages is virtual and all the lazy loading stuff,

This call didn't work to me and got this error:

The ObjectContext instance has been disposed and can no longer be used
  for operations that require a connection. in Reference Table

syntax:

    public ObservableCollection<Model.Message> LoadMessages()
    {
      using (db) {
       var x = from qr in db.Messages
                            order by qr.Subject
                            select qr;
          }
     }

While this works:

public ObservableCollection<Model.Message> LoadMessages()
{
    using (db)
    {
        var Messages = db.Messages.Include(z => z.Contacts).ToList();

        return new ObservableCollection<Model.Message>(Messages);
    }
}

So I am using the queries inside a service called MessageService, Everytime I want to use the dbContext I create a function for it and put it inside using(db)

Like this:

     public class MessageService
        {
            ReadingFromData db = new ReadingFromData();
            public ObservableCollection<Model.Message> LoadMessages()
            {
                using (db)
                {
                    //Do something with db
                }
            }
}

Also, can someone explain to me how this works, and how to work with entity framework queries correct

Thanks

Body:
Lazy loading will work only if the property is accessed while the connection to the context is open (or not disposed).

            using (db)
            {
                //If you try to load the data here, lazy loading will work.
            }

Now, when you use include, EF does eager loading and gets the related data for you. That is why your data is available when you are using include.

var Messages = db.Messages.Include(z => z.Contacts).ToList();


问:
Custom type parsing issue
I have a type product defined like this :

```<code>export class Product {
  id: number;
  //other fields
}
</code>```

a variable formattedProducts inside my component :

```<code>  formattedProducts: Product[] = [];
</code>```

I want to update this variable here:

```<code>refreshSummary(product: Product): void{
    var found = false;
    for (var p in this.formattedProducts){
        console.log('parsing product summary', p);
        if (p.id == product.id){
          // we update
          console.log('updating product')
          found = true;
          break;
        }
    }
</code>```

My issue is that I have debugger error :

```<code>Property 'id' does not exist on type 'string'
</code>```

which occurs on my "p.id". My variable this.formattedProducts is an array of Product, so I don't know how is it interpreted as a string.
Is it possible to force define a type of my variable p or to make my formattedProduct an array of Product in another way that the one I used?

答:
Here for (var p in this.formattedProducts){ should be for (var p of this.formattedProducts){

Currently, you iterating over properties of formattedProducts array object and each p is a name of property

Title: Custom type parsing issue

Body:
I have a type product defined like this :

export class Product {
  id: number;
  //other fields
}

a variable formattedProducts inside my component :

  formattedProducts: Product[] = [];

I want to update this variable here:

refreshSummary(product: Product): void{
    var found = false;
    for (var p in this.formattedProducts){
        console.log('parsing product summary', p);
        if (p.id == product.id){
          // we update
          console.log('updating product')
          found = true;
          break;
        }
    }

My issue is that I have debugger error :

Property 'id' does not exist on type 'string'

which occurs on my "p.id". My variable this.formattedProducts is an array of Product, so I don't know how is it interpreted as a string.
Is it possible to force define a type of my variable p or to make my formattedProduct an array of Product in another way that the one I used?


问:
better way to handle multiple tables relationship
Suppose i have some tables like...

countries

```<code>id name
1  Cyprus
2  India
</code>```

states

```<code>id name country_id
1   a     1
2   b     2
3   c     2
</code>```

cities

```<code>id name state_id
1   x     1
2   y     2
3   z     3
4   p     2
</code>```

pages

```<code>id name  slug    status
1   ab   a-b       1
2   pq   p-q       0
3   abc  a-b-c     1
</code>```

mode_of_training

```<code>id  name
1   Virtual
2   Classroom
</code>```

items

```<code>id name description
1   a   something
2   b   something
</code>```

prices

```<code>id price currency_code
1   200   USD
2   300   AUD
3   4000  INR
</code>```

offers

```<code>id name   discount
1  xyz-1   20%
2  abc-2   30%
3  pqr-3   10%
</code>```

Creating table structure in that way is correct?? so that i can reuse them
using there ids.

For example

items_relation_table

```<code>id country_id state_id  city_id  page_id item_id price_id offer_id  status
1   0           0         0       1        1       1         0        1
2   0           0         0       1        1       1         1        0
3   1           0         1       2        2       1         2        1
4   1           0         1       3        3       2         1        1
</code>```

Now i don't need to use field values of tables

If i want to change price. i'll change price in one place only

I'm saving number of bytes.

database table size is less

But my problem is
To fetch data i need to use Joins

Or Creating View is better idea

Or There is any Better way to create table structure

答:
Your entity-tables look fine at the first glance. But I don't understand your relation table. Looks like you try to relate everything with everything, which in some cases probably doesn't make sense (do offers really belong to countries?) in in some cases it seems redundant: When a page is linked to (many) cities, there is no need to link it to the countries too, because the countries are determined by the cities.

You should add relation-tables only between those entities that really need to be in a direct many-to-many relation. And for each of those relations you need a separate table.

e.g. for a relation between pages and cities:

```<code>cities(id, name, state_id) <--> cities_pages(city_id, page_id) <--> pages(id, name, slug, status)
</code>```

And yes, you have to join tables to fetch data. Thats one of the basic ideas behind relational databases. Don't be afraid of joins, if your tables are properly indexed thats not an expensive operation at all (assuming that performance is your concern). And of course you could add some views if that makes sense for your application, but that will include the same JOINS you would just abstract them behind CREATE VIEW statements.

Body:
Suppose i have some tables like...

countries

id name
1  Cyprus
2  India

states

id name country_id
1   a     1
2   b     2
3   c     2

cities

id name state_id
1   x     1
2   y     2
3   z     3
4   p     2

pages

id name  slug    status
1   ab   a-b       1
2   pq   p-q       0
3   abc  a-b-c     1

mode_of_training

id  name
1   Virtual
2   Classroom

items

id name description
1   a   something
2   b   something

prices

id price currency_code
1   200   USD
2   300   AUD
3   4000  INR

offers

id name   discount
1  xyz-1   20%
2  abc-2   30%
3  pqr-3   10%

Creating table structure in that way is correct?? so that i can reuse them
using there ids.

For example

items_relation_table

id country_id state_id  city_id  page_id item_id price_id offer_id  status
1   0           0         0       1        1       1         0        1
2   0           0         0       1        1       1         1        0
3   1           0         1       2        2       1         2        1
4   1           0         1       3        3       2         1        1

Now i don't need to use field values of tables

If i want to change price. i'll change price in one place only

I'm saving number of bytes.

database table size is less

But my problem is
To fetch data i need to use Joins

Or Creating View is better idea

Or There is any Better way to create table structure

Body:
Your entity-tables look fine at the first glance. But I don't understand your relation table. Looks like you try to relate everything with everything, which in some cases probably doesn't make sense (do offers really belong to countries?) in in some cases it seems redundant: When a page is linked to (many) cities, there is no need to link it to the countries too, because the countries are determined by the cities.

You should add relation-tables only between those entities that really need to be in a direct many-to-many relation. And for each of those relations you need a separate table.

e.g. for a relation between pages and cities:

cities(id, name, state_id) <--> cities_pages(city_id, page_id) <--> pages(id, name, slug, status)

And yes, you have to join tables to fetch data. Thats one of the basic ideas behind relational databases. Don't be afraid of joins, if your tables are properly indexed thats not an expensive operation at all (assuming that performance is your concern). And of course you could add some views if that makes sense for your application, but that will include the same JOINS you would just abstract them behind CREATE VIEW statements.


问:
Out of range page requests
I am a begginer in cakephp, my version is 2.4.3

In document I find  sample code below

```<code>public function index() {
    try {
        $this->Paginator->paginate();
    } catch (NotFoundException $e) {
        //Do something here like redirecting to first or last page.
        //$this->request->params['paging'] will give you required info.
    }
}
</code>```

My question :

1.How to redirect to the last page, is there any way to get the total number of pages?

2.I tried to output $this->request->params['paging'] with debug(),but nothing was displayed, just a null value,Did i do anything wrong?

please help me, thinks

答:
On CakePHP 3.4 I have this solution:</p>

```<code>$page  = (!empty($this->request->query['pagina']) ? $this->request->query['pagina'] : 1);
    $this->paginate = ['page' => $page, 'limit' => '10'];

    try {

        $products = $this->paginate($products);

    } catch (NotFoundException $e) {

        $this->paginate = ['page' => $page-1, 'limit' => '10'];
        $products = $this->paginate($products);

    }
</code>```

Title: Out of range page requests

Body:
I am a begginer in cakephp, my version is 2.4.3

In document I find  sample code below

public function index() {
    try {
        $this->Paginator->paginate();
    } catch (NotFoundException $e) {
        //Do something here like redirecting to first or last page.
        //$this->request->params['paging'] will give you required info.
    }
}

My question :

1.How to redirect to the last page, is there any way to get the total number of pages?

2.I tried to output $this->request->params['paging'] with debug(),but nothing was displayed, just a null value,Did i do anything wrong?

please help me, thinks

Body:
On CakePHP 3.4 I have this solution:

$page  = (!empty($this->request->query['pagina']) ? $this->request->query['pagina'] : 1);
    $this->paginate = ['page' => $page, 'limit' => '10'];

    try {

        $products = $this->paginate($products);

    } catch (NotFoundException $e) {

        $this->paginate = ['page' => $page-1, 'limit' => '10'];
        $products = $this->paginate($products);

    }

ContentLicense: CC BY-SA 4.0


问:
Flip barplot axes
How can I to turn vertically the names "fast" and "slow" through 'barplot()' ?

```<code>barplot(table(mode))
</code>```

Title: Flip barplot axes

Body:
How can I to turn vertically the names "fast" and "slow" through 'barplot()' ?

barplot(table(mode))

Body:
x <- c("1.3.43.33", "2.2.43.33", "1.3.43.33", "66.3.43.33")
df = as.data.frame(table(x))
df

library(ggplot2)
ggplot(df, aes(x = x, y = Freq))+
  geom_bar(stat = "identity")


问:
Get Specific class with Jquery/ JavaScript
I have got a div containing some html elements. They all have a class named

class="fileItem read write".

But there could be an Element with

class="fileItem read write selected".

Now I want to get this element with the additional 'selected' tag and edit this. Currently I have an in JQuery

```<code>$(".fileItem").click(function(){
    // Code
});
</code>```

which detect an click on one of these fileItems.

Here I want to edit style tag of the element with 'selected' tag. So is there something where I can say get all by class and select the on with "selected"?

答:
Use core java script to do this.</p>

```<code>function func() {
alert("Hello, world!");
}

document.getElementsByClassName("fileItem read write selected")
[0].addEventListener("click", func, false);
</code>```

Body:
I have got a div containing some html elements. They all have a class named

class="fileItem read write".

But there could be an Element with

class="fileItem read write selected".

Now I want to get this element with the additional 'selected' tag and edit this. Currently I have an in JQuery

$(".fileItem").click(function(){
    // Code
});

which detect an click on one of these fileItems.

Here I want to edit style tag of the element with 'selected' tag. So is there something where I can say get all by class and select the on with "selected"?

Body:
Use core java script to do this.

function func() {
alert("Hello, world!");
}

document.getElementsByClassName("fileItem read write selected")
[0].addEventListener("click", func, false);


问:
Get the rows from previous month
I am trying this query

```<code>SELECT *
FROM flexible_products
WHERE YEAR(updated_at) = YEAR(DATE_SUB(CURDATE(), INTERVAL -1 MONTH))
AND MONTH(updated_at) = MONTH(DATE_SUB(CURDATE(), INTERVAL -1 MONTH))
</code>```

for my current work. What I want to do is to get all rows from the previous month,

Like for example, we have today July 04, 2017, I would like to get rows from January to June, which is not the outcome of the above query.

What is the best way to this in MySQL?

答:
You should also try this or you can get data between any two dates.

SELECT * FROM flexible_products WHERE updated_at BETWEEN DATE_ADD(DATE_FORMAT(NOW(),'%Y-%m-01'), INTERVAL -3 MONTH) AND NOW( )

date output is:-

DATE_ADD(DATE_FORMAT(NOW(),'%Y-%m-01'), INTERVAL -3 MONTH) //2017-04-01

NOW( ) //2017-07-04 11:17:38

Title: Get the rows from previous month

Body:
I am trying this query

SELECT *
FROM flexible_products
WHERE YEAR(updated_at) = YEAR(DATE_SUB(CURDATE(), INTERVAL -1 MONTH))
AND MONTH(updated_at) = MONTH(DATE_SUB(CURDATE(), INTERVAL -1 MONTH))

for my current work. What I want to do is to get all rows from the previous month,

Like for example, we have today July 04, 2017, I would like to get rows from January to June, which is not the outcome of the above query.

What is the best way to this in MySQL?


问:
Comparison of variable to all other variables in data frame
I want to check how close is one variable to all of the other variables in a data frame. I want to do this by counting the times they have the same value for the same row (i.e. same observation). For instance, in the mtcars dataset, the variables gear and carb have 7 observations in which they have the same value in the same row (i.e. same car).

I have tried the following, which yields a closeness_matrix. However, the results seem to be non-sensical. Any idea what is not working?

PS: I also tried to use mapply, which I guess it would be faster, but it didn’t work so I ended up with the nested loop.

MWE:

```<code>cols_ls <- colnames(mtcars)

closeness_matrix <- matrix(nrow = ncol(mtcars),
                            ncol = ncol(mtcars))

row.names(closeness_matrix) <- cols_ls; colnames(closeness_matrix) <- cols_ls

for (i in 1:length(cols_ls)){

  for (j in i:length(cols_ls)){

    closeness_matrix[i,j] <- sum(duplicated(mtcars[,c(i,j), with = FALSE])==TRUE)

  }
}
</code>```

答:
Change

```<code>sum(duplicated(mtcars[,c(i,j), with = FALSE])==TRUE)
</code>```

to

```<code>sum(mtcars[,i]==mtcars[,j])
</code>```

duplicated function does not work the way you are using it.

Body:
I want to check how close is one variable to all of the other variables in a data frame. I want to do this by counting the times they have the same value for the same row (i.e. same observation). For instance, in the mtcars dataset, the variables gear and carb have 7 observations in which they have the same value in the same row (i.e. same car).

I have tried the following, which yields a closeness_matrix. However, the results seem to be non-sensical. Any idea what is not working?

PS: I also tried to use mapply, which I guess it would be faster, but it didn’t work so I ended up with the nested loop.

MWE:

cols_ls <- colnames(mtcars)

closeness_matrix <- matrix(nrow = ncol(mtcars),
                            ncol = ncol(mtcars))

row.names(closeness_matrix) <- cols_ls; colnames(closeness_matrix) <- cols_ls

for (i in 1:length(cols_ls)){

  for (j in i:length(cols_ls)){

    closeness_matrix[i,j] <- sum(duplicated(mtcars[,c(i,j), with = FALSE])==TRUE)

  }
}

Body:
Change

sum(duplicated(mtcars[,c(i,j), with = FALSE])==TRUE)

to

sum(mtcars[,i]==mtcars[,j])

duplicated function does not work the way you are using it.


问:
Android: Sugar ORM No Such Table Exception
I am getting the No Such table exception when i am Using Sugar ORM with GPU image Android Library. I am using Gradle and Android Studio. Once i remove GPU image this issue is solved. So i don't know whats causing this exception. Details about this exception are also being discussed in this git issue
and it seems a lot of people are still facing it.

My crash log is posted below

```<code>> 10-09 11:30:21.511 4326-4831/com.example.app E/SQLiteLog: (10) Failed
> to do file read, got: 0, amt: 100, last Errno: 2 10-09 11:30:26.506
> 4326-4831/com.example.app E/SQLiteLog: (1) no such table: IMAGE 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime: FATAL
> EXCEPTION: AsyncTask #1 10-09 11:30:26.516 4326-4831/com.example.app
> E/AndroidRuntime: java.lang.RuntimeException: An error occured while
> executing doInBackground() 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:     at
> android.os.AsyncTask$3.done(AsyncTask.java:299) 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.FutureTask.setException(FutureTask.java:219)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.FutureTask.run(FutureTask.java:239) 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.lang.Thread.run(Thread.java:838) 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:  Caused by:
> android.database.sqlite.SQLiteException: no such table: IMAGE (code
> 1): , while compiling: SELECT * FROM IMAGE 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
> Method) 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:
> at
> android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:886)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:497)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37) 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1238)
</code>```

答:
Resolved

I don't know but the SugarDb.onCreate is not called. So put this code in MainActivity.onCreate and the Sugar ORM will work

```<code>    SugarDb db = new SugarDb(this);
    db.onCreate(db.getDB());
</code>```

Body:
I am getting the No Such table exception when i am Using Sugar ORM with GPU image Android Library. I am using Gradle and Android Studio. Once i remove GPU image this issue is solved. So i don't know whats causing this exception. Details about this exception are also being discussed in this git issue
and it seems a lot of people are still facing it.

My crash log is posted below

> 10-09 11:30:21.511 4326-4831/com.example.app E/SQLiteLog: (10) Failed
> to do file read, got: 0, amt: 100, last Errno: 2 10-09 11:30:26.506
> 4326-4831/com.example.app E/SQLiteLog: (1) no such table: IMAGE 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime: FATAL
> EXCEPTION: AsyncTask #1 10-09 11:30:26.516 4326-4831/com.example.app
> E/AndroidRuntime: java.lang.RuntimeException: An error occured while
> executing doInBackground() 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:     at
> android.os.AsyncTask$3.done(AsyncTask.java:299) 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.FutureTask.setException(FutureTask.java:219)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.FutureTask.run(FutureTask.java:239) 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> java.lang.Thread.run(Thread.java:838) 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:  Caused by:
> android.database.sqlite.SQLiteException: no such table: IMAGE (code
> 1): , while compiling: SELECT * FROM IMAGE 10-09 11:30:26.516
> 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
> Method) 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:
> at
> android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:886)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:497)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37) 10-09
> 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
> 10-09 11:30:26.516 4326-4831/com.example.app E/AndroidRuntime:     at
> android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1238)

Body:
Resolved

I don't know but the SugarDb.onCreate is not called. So put this code in MainActivity.onCreate and the Sugar ORM will work

    SugarDb db = new SugarDb(this);
    db.onCreate(db.getDB());


问:
String replace not working with value returned from a XMLHttpRequest request
I have a (Laravel) PHP code that returns a long string in this way:

```<code>echo json_encode([
    'created' => $count,
    'total' => $num_stores,
    'progressValue' => round((100 / $num_stores) * $count, 2),
    'token' => str_repeat('|',1024*64)
]);
</code>```

I need to get this string in javascript and clean it, removing all "|" character. But it seems not working.

This is my javascript code:

```<code>var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    try {
        if (xhr.readyState == 4) {
            alert('[XHR] Done');
        } else if (xhr.readyState > 2) {
            var new_response = xhr.responseText.substring(xhr.previous_text.length);
            var cleanedResponse = new_response.replace(/[|]/g, '');

            console.log('CLEANED RESPONSE: ' + cleanedResponse);
            var result = JSON.parse( cleanedResponse );
            console.log('AFTER THE PARSE');

            xhr.previous_text = xhr.responseText;
        }
    } catch (e) {
        console.log(xhr.responseText);
        alert("[XHR STATECHANGE] Exception: " + e);
    }
};
xhr.open("POST", "...", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("X-CSRF-TOKEN", jQuery('meta[name="csrf-token"]').attr('content'));
xhr.send(params);
</code>```

I always get the exception when I try to parse JSON, and in the console I still see the "|" characters in the "cleanedResponse" variable.

How is it possible if I replace them?

答:
When xhr.readyState == 3, then xhr.responseText holds only partial data - 3 means that the response has not yet been fully downloaded. You probably try to parse only partial JSON string that is not complete and therefore not valid and parsable. Wait for downloading complete response (xhr.readyState == 4) and then try to clean and parse JSON.

See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState for further explanation of XHR states.

Body:
I have a (Laravel) PHP code that returns a long string in this way:

echo json_encode([
    'created' => $count,
    'total' => $num_stores,
    'progressValue' => round((100 / $num_stores) * $count, 2),
    'token' => str_repeat('|',1024*64)
]);

I need to get this string in javascript and clean it, removing all "|" character. But it seems not working.

This is my javascript code:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    try {
        if (xhr.readyState == 4) {
            alert('[XHR] Done');
        } else if (xhr.readyState > 2) {
            var new_response = xhr.responseText.substring(xhr.previous_text.length);
            var cleanedResponse = new_response.replace(/[|]/g, '');

            console.log('CLEANED RESPONSE: ' + cleanedResponse);
            var result = JSON.parse( cleanedResponse );
            console.log('AFTER THE PARSE');

            xhr.previous_text = xhr.responseText;
        }
    } catch (e) {
        console.log(xhr.responseText);
        alert("[XHR STATECHANGE] Exception: " + e);
    }
};
xhr.open("POST", "...", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("X-CSRF-TOKEN", jQuery('meta[name="csrf-token"]').attr('content'));
xhr.send(params);

I always get the exception when I try to parse JSON, and in the console I still see the "|" characters in the "cleanedResponse" variable.

How is it possible if I replace them?


问:
Yii2 - Bad Request (#400) - Missing required parameters: id
CommentController:

```<code>public function actionCreate()
{

    $model = new Comment();

    var_dump(Yii::$app->request->post());

     if ($model->load(Yii::$app->request->post()))
     {
        $model->user_id = Yii::$app->user->getId();
        $model->created_at = time();
        $model->updated_at = time();
        $model->save();

        return $this->redirect(Url::to(['post/view', 'id'=>$model->post_id]));
     }

    return $this->redirect(Url::to(['/post/index']));
}
</code>```

If I pass as false to $model->save() the data gets stored in the database with no value in the foreign key field 'post_id' but still doesn't redirect me to the correct page.

New to yii and relatively new to software development, any help would be massively appreciated.

答:
you need to do like below in your controller.If id exist this will keep the id value otherwise it defines and keep it as empty.</p>

```<code>public function actionView($id='') {
  //
}
</code>```

Body:
CommentController:

public function actionCreate()
{

    $model = new Comment();

    var_dump(Yii::$app->request->post());

     if ($model->load(Yii::$app->request->post()))
     {
        $model->user_id = Yii::$app->user->getId();
        $model->created_at = time();
        $model->updated_at = time();
        $model->save();

        return $this->redirect(Url::to(['post/view', 'id'=>$model->post_id]));
     }

    return $this->redirect(Url::to(['/post/index']));
}

If I pass as false to $model->save() the data gets stored in the database with no value in the foreign key field 'post_id' but still doesn't redirect me to the correct page.

New to yii and relatively new to software development, any help would be massively appreciated.

Body:
you need to do like below in your controller.If id exist this will keep the id value otherwise it defines and keep it as empty.

public function actionView($id='') {
  //
}


问:
undefined is not and object (evaluating '_props[registrationName]')
react-native:0.43.3

The problem only occurs in Android system, iOS is fine.
When I touch a TouchableOpacity component, the onTouch function won't be executed.

Anyone found this problem?

I built a Calendar with RN. The problem is that when I click the Day unit on Android devices or emulators I'll get the error undefined is not and object (evaluating '_props[registrationName]'). But it's okay to click it on iOS devices and emulators. The Day component' code is like this:

```<code>        <TouchableOpacity style={styles.calendarRowUnit} onPress={() => this.props.onSelect(this.props.date)}>
            <View style={dateWrapperStyle}>
                <Text style={dateTextStyle}>{dateString}</Text>
            </View>
        </TouchableOpacity>
</code>```

And the error image:
error info iamge

I've found that only when I touch the Text area the error will occur.
I don't know it's a react-native bug or my fault. The error never occured before I updated the react-native version to 0.43.3.

答:
There is a bug in #12905 <Text /> This bug is specific to RN 0.43.x and has been fixed in later versions. The bug was , Whenever there is a number inside <Text /> then it will cause this error.
The fix for this is :

Upgrade React Native with latest versions.

TypeCast the value to string.

For Example,

<Text> {100} </Text> to <Text> {''100} </Text>

<Text> {100} </Text> to <Text> {String(100)} </Text>

<Text> {100} </Text> to <Text> {(100).toString} </Text>

Body:
react-native:0.43.3

The problem only occurs in Android system, iOS is fine.
When I touch a TouchableOpacity component, the onTouch function won't be executed.

Anyone found this problem?

I built a Calendar with RN. The problem is that when I click the Day unit on Android devices or emulators I'll get the error undefined is not and object (evaluating '_props[registrationName]'). But it's okay to click it on iOS devices and emulators. The Day component' code is like this:

        <TouchableOpacity style={styles.calendarRowUnit} onPress={() => this.props.onSelect(this.props.date)}>
            <View style={dateWrapperStyle}>
                <Text style={dateTextStyle}>{dateString}</Text>
            </View>
        </TouchableOpacity>

And the error image:
error info iamge

I've found that only when I touch the Text area the error will occur.
I don't know it's a react-native bug or my fault. The error never occured before I updated the react-native version to 0.43.3.


问:
Blueimp jQuery File Upload - Can't change the input name
I try to use the BlueImp jQuery File Uploader (https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin). It works well, but only with the orinial name attribute of the input field, "files[]".
When I use an other name, the JSON response is empty :

{"files":[]}

This is my code :

```<code><tr>
    <td>
        <label>Photos</label>
    </td><td id="photos_container">
        <div class="progress">
            <div class="bar" style="width: 0%;"></div>
        </div>
        <span class="btn btn-success fileinput-button">
            <i class="glyphicon glyphicon-plus"></i>
            <span>Select files...</span>
            <input id="photos" type="file" name="photos[]" multiple>
        </span>
    </td>
</tr>

<script>
    jQuery(document).ready(function($){
        $(function () {
            $('#photos_container').fileupload({
                url: 'tmp/',
                dataType: 'json',
                fileInput: $('#photos'),
                paramName: 'photos[]',
                progressall: function (e, data) {
                    var progress = parseInt(data.loaded / data.total * 100, 10);
                    $('#photos_container .progress .bar').css(
                        'width',
                        progress + '%'
                    );
                },
                done: function (e, data) {
                    $.each(data.result.files, function (index, file) {
                        $('<p/>').text(file.name).appendTo('#photos_container');
                    });
                }
            });
        });
    });
</script>
</code>```

I repeat, but the code works great with the default name of input button "files[]", so the problem isn't a path problem.

EDIT: And I try with and without the fileInput and the paramName options, but I didn't work

答:
The name attribute is used to reference elements in a JavaScript, or to reference form data after a form is submitted.

Your file data will be there in photos property.

Body:
I try to use the BlueImp jQuery File Uploader (https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin). It works well, but only with the orinial name attribute of the input field, "files[]".
When I use an other name, the JSON response is empty :

{"files":[]}

This is my code :

        Photos

            Select files...
            <input id="photos" type="file" name="photos[]" multiple>

I repeat, but the code works great with the default name of input button "files[]", so the problem isn't a path problem.

EDIT: And I try with and without the fileInput and the paramName options, but I didn't work


问:
WPF image alternative source from web
I have images stored into websevers. I would like to have an alternative path where the images are loaded from if the first server is not available.

Something like:

```<code>   <Image Source="http://server1/images/image1"
          AlternativeSource="http://server2/images/image1"/>
</code>```

How to do it?

答:
Lucky for us Image control raises an event when it failed to load an image , so its easy to check if the image loading failed.

One approach you can take is extending the Image control .

```<code>public class AlternativeImage : Image
{

    private bool _tryAlternativeSource ;

    public string AlternativeSource
    {
        get { return (string)GetValue(AlternativeSourceProperty); }
        set { SetValue(AlternativeSourceProperty, value); }
    }

    // Using a DependencyProperty as the backing store for ItemTemplate.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty AlternativeSourceProperty =
        DependencyProperty.Register("AlternativeSource", typeof(string), typeof(AlternativeImage), new PropertyMetadata(null));

    public AlternativeImage()
    {
        Initialized += OnInitialized;
    }

    private void OnInitialized(object sender, EventArgs eventArgs)
    {
        _tryAlternativeSource = !string.IsNullOrEmpty(AlternativeSource);

        //Note , ths need to be unregistered
        ImageFailed += OnImageFailed;
    }

    private void OnImageFailed(object sender, ExceptionRoutedEventArgs exceptionRoutedEventArgs)
    {
        if (!_tryAlternativeSource)
            return;

        _tryAlternativeSource = false;

        Source = new ImageSourceConverter().ConvertFromString(AlternativeSource) as ImageSource;
    }
}
</code>```

And then use it like this

```<code><controls:AlternativeImage Source="http://server1/images/image1"
      AlternativeSource="https://media.licdn.com/mpr/mpr/p/1/005/07f/0e1/07ab226.jpg"/>
</code>```

Uploaded the full code Here

Title: WPF image alternative source from web

Body:
I have images stored into websevers. I would like to have an alternative path where the images are loaded from if the first server is not available.

Something like:

   <Image Source="http://server1/images/image1"
          AlternativeSource="http://server2/images/image1"/>

How to do it?

Body:
Lucky for us Image control raises an event when it failed to load an image , so its easy to check if the image loading failed.

One approach you can take is extending the Image control .

public class AlternativeImage : Image
{

    private bool _tryAlternativeSource ;

    public string AlternativeSource
    {
        get { return (string)GetValue(AlternativeSourceProperty); }
        set { SetValue(AlternativeSourceProperty, value); }
    }

    // Using a DependencyProperty as the backing store for ItemTemplate.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty AlternativeSourceProperty =
        DependencyProperty.Register("AlternativeSource", typeof(string), typeof(AlternativeImage), new PropertyMetadata(null));

    public AlternativeImage()
    {
        Initialized += OnInitialized;
    }

    private void OnInitialized(object sender, EventArgs eventArgs)
    {
        _tryAlternativeSource = !string.IsNullOrEmpty(AlternativeSource);

        //Note , ths need to be unregistered
        ImageFailed += OnImageFailed;
    }

    private void OnImageFailed(object sender, ExceptionRoutedEventArgs exceptionRoutedEventArgs)
    {
        if (!_tryAlternativeSource)
            return;

        _tryAlternativeSource = false;

        Source = new ImageSourceConverter().ConvertFromString(AlternativeSource) as ImageSource;
    }
}

And then use it like this

<controls:AlternativeImage Source="http://server1/images/image1"
      AlternativeSource="https://media.licdn.com/mpr/mpr/p/1/005/07f/0e1/07ab226.jpg"/>

Uploaded the full code Here


问:
How to merge lines with pattern including "[,],{,}" chars with sed/awk
I have a text file following a certain formatting which has lines like :

```<code>{
    "297723": [
        [
          1,
          2
        ],
        [
          5,
          10
        ],
        [
          1,
          157
        ]
      ],
    "369258": [
        [
          3,
          4
        ],
        [
          6,
          11
        ],
        [
          30,
          200
        ]
      ]
}
</code>```

How can I make it look like this ?

```<code>{"297723": [[1, 2], [5, 10], [1,157]],
{"369258": [[3, 4], [6, 11], [30,200]]}
</code>```

Of course, there are several blocks, I just append the first (which starts with "{" and the last which closes with "}" - in all the rest, there is a number (like "2927723" in my example) which notifies the new block.

答:
Your input is a valid JSON, so you may apply jq tool for this case:

```<code>jq -c '.' yourfile | sed 's/,"/,\n"/'
</code>```

The output:

```<code>{"297723":[[1,2],[5,10],[1,157]],
"369258":[[3,4],[6,11],[30,200]]}
</code>```

-c - print the input in compact-output form

Body:
I have a text file following a certain formatting which has lines like :

{
    "297723": [
        [
          1,
          2
        ],
        [
          5,
          10
        ],
        [
          1,
          157
        ]
      ],
    "369258": [
        [
          3,
          4
        ],
        [
          6,
          11
        ],
        [
          30,
          200
        ]
      ]
}

How can I make it look like this ?

{"297723": [[1, 2], [5, 10], [1,157]],
{"369258": [[3, 4], [6, 11], [30,200]]}

Of course, there are several blocks, I just append the first (which starts with "{" and the last which closes with "}" - in all the rest, there is a number (like "2927723" in my example) which notifies the new block.

Body:
Your input is a valid JSON, so you may apply jq tool for this case:

jq -c '.' yourfile | sed 's/,"/,\n"/'

The output:

{"297723":[[1,2],[5,10],[1,157]],
"369258":[[3,4],[6,11],[30,200]]}

-c - print the input in compact-output form


问:
How to get a vCard (.vcf file) into Android contacts from website
I'm trying to add a vCard from a web link to the user's contact list on Android 2.2.  When I direct the user to .vcf file, all I get is text output in the mobile browser.  I have confirmed that the files is being transferred with MIME type text/v-card.  This seems like it should be pretty simple to do.  Any ideas?</p>

答:
What i have also noticed is that you have to save the file as Unicode, UTF-8, no BOM in an Windows format with CRLF (Carriage Return, Line Feed). Because if you don't, the import will break. (Saying something about weird chars in the file)

Good luck :)
Sid


问:
Hibernate sequence not generated
Im working on a Spring (not Boot!) project, with Hibernate and PostgreSQL database. I also use Flyway for migration.
I use Flyway to generate the schema of the database, and insert initial data to it with given SQL scripts in my resources folder. For this reason, I excluded the hibernate.hbm2ddl.auto property from my hibernate.properties file.
On the startup, the schema is created and the data is inserted to the database, but my problem is, that this way Hibernate doesn't generate its sequence, and I cant save data from the application:

```<code>org.postgresql.util.PSQLException: ERROR: relation "hibernate_sequence" does not exist
</code>```

What can I do with this?

答:
You need to create a sequence like this:</p>

```<code>CREATE SEQUENCE hibernate_sequence START 1;
</code>```

Title: Hibernate sequence not generated

Body:
Im working on a Spring (not Boot!) project, with Hibernate and PostgreSQL database. I also use Flyway for migration.
I use Flyway to generate the schema of the database, and insert initial data to it with given SQL scripts in my resources folder. For this reason, I excluded the hibernate.hbm2ddl.auto property from my hibernate.properties file.
On the startup, the schema is created and the data is inserted to the database, but my problem is, that this way Hibernate doesn't generate its sequence, and I cant save data from the application:

org.postgresql.util.PSQLException: ERROR: relation "hibernate_sequence" does not exist

What can I do with this?

Body:
You need to create a sequence like this:

CREATE SEQUENCE hibernate_sequence START 1;


问:
How to sort an array of objects with respect to a particular field in controller in angularjs
I have an array of objects in a scope variable and now I want to sort this array with respect to a particular object ( a date field)   and display. I have mentioned the logic below

```<code><ion-option-button role="button"  data-ng-click="save(data)"></ion-option-button>
</code>```

Controller:

$scope.save = function(data) {
   var action='save';
   //service call happens and response is returned

   if (response.isSuccessful === true && response.responseCode == "1") {

      vm.data = moveElementInArray(vm.data, data, 0);
      //perform sorting with respect to a date field after moving to index 0 , vm.data contains the array objects
   }
};
```

答:
Try using $filter

```<code>arr = $filter('orderBy')(arr, 'Date', true);
</code>```

see the documentation

Body:
I have an array of objects in a scope variable and now I want to sort this array with respect to a particular object ( a date field)   and display. I have mentioned the logic below

<ion-option-button role="button"  data-ng-click="save(data)"></ion-option-button>

Controller:

$scope.save = function(data) {
   var action='save';
   //service call happens and response is returned

   if (response.isSuccessful === true && response.responseCode == "1") {

      vm.data = moveElementInArray(vm.data, data, 0);
      //perform sorting with respect to a date field after moving to index 0 , vm.data contains the array objects
   }
};

Body:
Try using $filter

arr = $filter('orderBy')(arr, 'Date', true);

see the documentation


问:
List all Applications, orchestrations if any, send ports and receive ports for BizTalk 2010?
I need to list all Applications, orchestrations if any, send ports and receive ports for BizTalk 2010. I am trying to write a sql query and getting many duplicates. Can anyone help me?</p>

```<code>SELECT
     APP.nvcName
    ,APP.nvcName as [Application]
    ,A.nvcName AssemblyName
    ,O.nvcFullName OrchestrationFullName
    ,O.nvcName Orchestration
    ,'Send Port' as [PortType]
    ,S.nvcName as [PortName]
    ,S.bTwoWay as [SendType]
    ,'' --S.nvcName [ReceiveLocation]
    ,Adp.Name [AdapterType]
    ,RP.FullyQualifiedName [ReceivePipeline]
    ,SP.FullyQualifiedName [SendPipeline]
    ,S.nvcEncryptionCert [EncryptionCert]
FROM dbo.bts_application as APP
LEFT OUTER JOIN dbo.bts_sendport as S ON APP.nID = S.nApplicationID
LEFT OUTER JOIN  dbo.bts_sendport_transport as ST ON S.nID = ST.nSendPortID
LEFT OUTER JOIN  dbo.bts_assembly as A on A.nApplicationId = APP.nId
LEFT OUTER JOIN  dbo.bts_orchestration as O ON O.nAssemblyID = A.nId
LEFT OUTER JOIN  dbo.bts_orchestration_port AS OP ON OP.nOrchestrationID = O.nID
LEFT OUTER JOIN  dbo.bts_orchestration_port_binding as OPB ON PB.nOrcPortID = OP.nID --and OPB.nSendPortID = S.nID
LEFT OUTER JOIN  dbo.adm_Adapter as Adp ON ST.nTransportTypeId = Adp.Id
LEFT OUTER JOIN  dbo.bts_pipeline as RP on RP.Id = S.nReceivePipelineId
LEFT OUTER JOIN  dbo.bts_pipeline as SP on SP.Id = S.nSendPipelineId
WHERE S.nApplicationID is not null AND Adp.Name IS NOT NULL
</code>```

答:
You could use the powershell for list all applications ,orchestrations, receive and send ports status </p>

```<code># Get BizTalk Application Information

$applications = $BizTalkOM.Applications

# Display BizTalk Application Information

Write-Host "`nBizTalk Applications ("$applications.Count")" -fore DarkGray

Foreach ($application in $applications) {

    if ($application.Status -eq "Started") {

        Write-Host $application.Name "- " -NoNewline

        Write-Host $application.Status -fore Green

    }

    elseif ($application.Status -eq "Stopped") {

        Write-Host $application.Name "- " -NoNewline

        Write-Host $application.Status -fore Red

    }

    else {

        Write-Host $application.Name "- " -NoNewline

        Write-Host $application.Status -fore DarkYellow

    }

}
$trackingRecPorts = get-wmiobject MSBTS_ReceivePort -namespace 'root\MicrosoftBizTalkServer' | Where-Object {$_.Tracking -gt 0 }

$orchs = Get-WmiObject MSBTS_Orchestration -namespace 'root\MicrosoftBizTalkServer' | Where-Object {$_.OrchestrationStatus -ne 4 }
</code>```

Body:
I need to list all Applications, orchestrations if any, send ports and receive ports for BizTalk 2010. I am trying to write a sql query and getting many duplicates. Can anyone help me?

SELECT
     APP.nvcName
    ,APP.nvcName as [Application]
    ,A.nvcName AssemblyName
    ,O.nvcFullName OrchestrationFullName
    ,O.nvcName Orchestration
    ,'Send Port' as [PortType]
    ,S.nvcName as [PortName]
    ,S.bTwoWay as [SendType]
    ,'' --S.nvcName [ReceiveLocation]
    ,Adp.Name [AdapterType]
    ,RP.FullyQualifiedName [ReceivePipeline]
    ,SP.FullyQualifiedName [SendPipeline]
    ,S.nvcEncryptionCert [EncryptionCert]
FROM dbo.bts_application as APP
LEFT OUTER JOIN dbo.bts_sendport as S ON APP.nID = S.nApplicationID
LEFT OUTER JOIN  dbo.bts_sendport_transport as ST ON S.nID = ST.nSendPortID
LEFT OUTER JOIN  dbo.bts_assembly as A on A.nApplicationId = APP.nId
LEFT OUTER JOIN  dbo.bts_orchestration as O ON O.nAssemblyID = A.nId
LEFT OUTER JOIN  dbo.bts_orchestration_port AS OP ON OP.nOrchestrationID = O.nID
LEFT OUTER JOIN  dbo.bts_orchestration_port_binding as OPB ON PB.nOrcPortID = OP.nID --and OPB.nSendPortID = S.nID
LEFT OUTER JOIN  dbo.adm_Adapter as Adp ON ST.nTransportTypeId = Adp.Id
LEFT OUTER JOIN  dbo.bts_pipeline as RP on RP.Id = S.nReceivePipelineId
LEFT OUTER JOIN  dbo.bts_pipeline as SP on SP.Id = S.nSendPipelineId
WHERE S.nApplicationID is not null AND Adp.Name IS NOT NULL

Body:
You could use the powershell for list all applications ,orchestrations, receive and send ports status

# Get BizTalk Application Information

$applications = $BizTalkOM.Applications

# Display BizTalk Application Information

Write-Host "`nBizTalk Applications ("$applications.Count")" -fore DarkGray

Foreach ($application in $applications) {

    if ($application.Status -eq "Started") {

        Write-Host $application.Name "- " -NoNewline

        Write-Host $application.Status -fore Green

    }

    elseif ($application.Status -eq "Stopped") {

        Write-Host $application.Name "- " -NoNewline

        Write-Host $application.Status -fore Red

    }

    else {

        Write-Host $application.Name "- " -NoNewline

        Write-Host $application.Status -fore DarkYellow

    }

}
$trackingRecPorts = get-wmiobject MSBTS_ReceivePort -namespace 'root\MicrosoftBizTalkServer' | Where-Object {$_.Tracking -gt 0 }

$orchs = Get-WmiObject MSBTS_Orchestration -namespace 'root\MicrosoftBizTalkServer' | Where-Object {$_.OrchestrationStatus -ne 4 }


问:
feature selection in multiclass logistic regression in python
I am performing feature selection ( on a dataset with 1,00,000 rows and 32 features) using multinomial Logistic Regression using python.Now, what would be the most efficient way to select features in order to build model for multiclass target variable(1,2,3,4,5,6,7)?</p>

答:
Of course there are several methods to choose your features. But sometimes the next simple approach can help you. You can assess the contribution of your features (by potential prediction of the result variable) with help of linear models. Note that it mainly works for the situations where you suspect linear dependence between your features and the answer.

```<code>import statsmodels.formula.api as smf

# Lottery here is Y, the fields from X are right of ~
mod = smf.ols(formula='Lottery ~ Literacy + Wealth + Region', data=df)
res = mod.fit()
print(res.summary())

OLS Regression Results
==============================================================================
Dep. Variable:                Lottery   R-squared:                       0.338
Model:                            OLS   Adj. R-squared:                  0.287
Method:                 Least Squares   F-statistic:                     6.636
Date:                Tue, 28 Feb 2017   Prob (F-statistic):           1.07e-05
Time:                        21:36:08   Log-Likelihood:                -375.30
No. Observations:                  85   AIC:                             764.6
Df Residuals:                      78   BIC:                             781.7
Df Model:                           6
Covariance Type:            nonrobust
===============================================================================
                  coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------
Intercept      38.6517      9.456      4.087      0.000      19.826      57.478
Region[T.E]   -15.4278      9.727     -1.586      0.117     -34.793       3.938
Region[T.N]   -10.0170      9.260     -1.082      0.283     -28.453       8.419
Region[T.S]    -4.5483      7.279     -0.625      0.534     -19.039       9.943
Region[T.W]   -10.0913      7.196     -1.402      0.165     -24.418       4.235
Literacy       -0.1858      0.210     -0.886      0.378      -0.603       0.232
Wealth          0.4515      0.103      4.390      0.000       0.247       0.656
==============================================================================
Omnibus:                        3.049   Durbin-Watson:                   1.785
Prob(Omnibus):                  0.218   Jarque-Bera (JB):                2.694
Skew:                          -0.340   Prob(JB):                        0.260
Kurtosis:                       2.454   Cond. No.                         371.
==============================================================================
</code>```

The more R-squared value, the better your chosen combination of features can predict the response in linear model. If they can predict in linear models then, I think, they have even bigger potential with more complex models such as decision trees.

Please view the next page for more details (please note that some additional data handling may be required if errors of your data are heteroskedasticity to get a right result):
http://www.statsmodels.org/dev/example_formulas.html

And of course I recommend you build pair plot for your features too.

The methods is not very deep, they referrers to correlations and what you see, but sometimes (in not difficult situations) are pragmatic.

Body:
Of course there are several methods to choose your features. But sometimes the next simple approach can help you. You can assess the contribution of your features (by potential prediction of the result variable) with help of linear models. Note that it mainly works for the situations where you suspect linear dependence between your features and the answer.

import statsmodels.formula.api as smf

# Lottery here is Y, the fields from X are right of ~
mod = smf.ols(formula='Lottery ~ Literacy + Wealth + Region', data=df)
res = mod.fit()
print(res.summary())

OLS Regression Results
==============================================================================
Dep. Variable:                Lottery   R-squared:                       0.338
Model:                            OLS   Adj. R-squared:                  0.287
Method:                 Least Squares   F-statistic:                     6.636
Date:                Tue, 28 Feb 2017   Prob (F-statistic):           1.07e-05
Time:                        21:36:08   Log-Likelihood:                -375.30
No. Observations:                  85   AIC:                             764.6
Df Residuals:                      78   BIC:                             781.7
Df Model:                           6
Covariance Type:            nonrobust
===============================================================================
                  coef    std err          t      P>|t|      [0.025      0.975]
-------------------------------------------------------------------------------
Intercept      38.6517      9.456      4.087      0.000      19.826      57.478
Region[T.E]   -15.4278      9.727     -1.586      0.117     -34.793       3.938
Region[T.N]   -10.0170      9.260     -1.082      0.283     -28.453       8.419
Region[T.S]    -4.5483      7.279     -0.625      0.534     -19.039       9.943
Region[T.W]   -10.0913      7.196     -1.402      0.165     -24.418       4.235
Literacy       -0.1858      0.210     -0.886      0.378      -0.603       0.232
Wealth          0.4515      0.103      4.390      0.000       0.247       0.656
==============================================================================
Omnibus:                        3.049   Durbin-Watson:                   1.785
Prob(Omnibus):                  0.218   Jarque-Bera (JB):                2.694
Skew:                          -0.340   Prob(JB):                        0.260
Kurtosis:                       2.454   Cond. No.                         371.
==============================================================================

The more R-squared value, the better your chosen combination of features can predict the response in linear model. If they can predict in linear models then, I think, they have even bigger potential with more complex models such as decision trees.

Please view the next page for more details (please note that some additional data handling may be required if errors of your data are heteroskedasticity to get a right result):
http://www.statsmodels.org/dev/example_formulas.html

And of course I recommend you build pair plot for your features too.

The methods is not very deep, they referrers to correlations and what you see, but sometimes (in not difficult situations) are pragmatic.


问:
Winform Checklistbox Headers/Columns
Is there a way to implement a new column with a header in a checklistbox in vb.net?  I've done a bit of searching, but didn't find much on the topic.  Should I just abandon the quest and use a listview or some other control?

Thanks for any/all help!
JFV

答: I would suggest using a ListView with a checkbox column.  You'll have better luck.</p>

OwnerDisplayName: JFV

Title: Winform Checklistbox Headers/Columns

OwnerDisplayName: Nick