问:
Android Search view not invoking search activity

Please dont mark as duplicate as I have viewed several other same question and those solution didnt worked for me.

category_menu.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/category.search"
        android:title="Search"
        app:showAsAction="ifRoom|collapseActionView"
        app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>
</code>```

Mainfest.xml

```<code><activity android:name=".CategoryActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <meta-data android:name="android.app.default_searchable" android:value=".SearchResultsActivity" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SearchResultsActivity"
            android:label="@string/title_activity_search_results"
            android:theme="@style/AppTheme.NoActionBar"
            android:launchMode="singleTop">
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <meta-data                android:name="android.app.searchable"                android:resource="@xml/searchable" />
            <meta-data                android:name="android.support.PARENT_ACTIVITY"                android:value=".CategoryActivity" />
        </activity>
</code>```

CategoryActivity.java

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.category_menu, menu);
        SearchView searchView = (SearchView) menu.findItem(R.id.category_search).getActionView();
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        searchView.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(this, SearchResultsActivity.class)));
        return true;
}
</code>```

SearchResultsActivity.java

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG,"Search Began");
    setContentView(R.layout.search_results_activity);
    handleIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
    handleIntent(intent);
}

private void handleIntent(Intent intent) {
    Log.d(TAG, "Herer");
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        //use the query to search your data somehow
        Log.d(TAG, query);
    }
}
</code>```

Searchable.xml under res/xml/

```<code><?xml version="1.0" encoding="utf-8"?>

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="Recipe Search" />
</code>```

答:
if in searchable.xml not contain android:label, it doesn't start SearchResultActivity, make sure you add this code in searchable.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_name" ===================> can not contain empty strings
android:hint="Recipe Search" />
</code>```

Body:
Please dont mark as duplicate as I have viewed several other same question and those solution didnt worked for me.

category_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/category.search"
        android:title="Search"
        app:showAsAction="ifRoom|collapseActionView"
        app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>

Mainfest.xml

<activity android:name=".CategoryActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <meta-data android:name="android.app.default_searchable" android:value=".SearchResultsActivity" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SearchResultsActivity"
            android:label="@string/title_activity_search_results"
            android:theme="@style/AppTheme.NoActionBar"
            android:launchMode="singleTop">
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <meta-data                android:name="android.app.searchable"                android:resource="@xml/searchable" />
            <meta-data                android:name="android.support.PARENT_ACTIVITY"                android:value=".CategoryActivity" />
        </activity>

CategoryActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.category_menu, menu);
        SearchView searchView = (SearchView) menu.findItem(R.id.category_search).getActionView();
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        searchView.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(this, SearchResultsActivity.class)));
        return true;
}

SearchResultsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG,"Search Began");
    setContentView(R.layout.search_results_activity);
    handleIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
    handleIntent(intent);
}

private void handleIntent(Intent intent) {
    Log.d(TAG, "Herer");
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        //use the query to search your data somehow
        Log.d(TAG, query);
    }
}

Searchable.xml under res/xml/

<?xml version="1.0" encoding="utf-8"?>

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="Recipe Search" />

Body:
if in searchable.xml not contain android:label, it doesn't start SearchResultActivity, make sure you add this code in searchable.xml:

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_name" ===================> can not contain empty strings
android:hint="Recipe Search" />


来源: stackexchange

问:
MTurk HITs created Through Java API are not showing on Manage Tab on UI
I am creating HITs on MTurk Sandbox using JAVA API. I am able to create HITs and also work on it by searching through worker UI. But those hits are not showing up in the "Manage" tab of the requester UI.</p>

答:
The "Manage" tab in the MTurk Requester Website is for managing Batches created with the MTurk Requester Website (using the Create) tab. If you need/want to view HITs that you create with the API, you can use the ListHITs API method either with the API directly (using your Java code) or using the AWS Command Line Interface (CLI).

Here's a blog explaining how to do this with the AWS CLI:
https://blog.mturk.com/tutorial-managing-mturk-hits-with-the-aws-command-line-interface-56eaabb7fd4c

The blog shows how to use aws-shell, which is a more interactive shell that sits atop the AWS CLI. It has autocomplete and shows you inline "man" pages on each command. I personally prefer this.

The CLI and aws-shell will also let you write filters and formatters for results. So you can do things like this:

```<code>aws mturk list-hits --output table --query 'HITs[].{"1. HITId": HITId, "2. Title": Title, "3. Status":HITStatus}' --endpoint-url https://mturk-requester-sandbox.us-east-1.amazonaws.com --max-results 5
</code>```

This calls ListHITs, on the Sandbox (--endpoint), getting only 5 results (--max-results), formats the output as a table instead of the default JSON (--output) and filters that JSON for the HITs object (HITs[]) pulling down only the fields HITId, Title, and Status while also setting titles for those fields as "1. HITId", "2. Title", and "3. Status".

There used to be a link in the MTurk Requester Website for a GUI to manage HITs individually which would show HITs from the API, but it was deprecated this month. There's a brief thread on it here: https://forums.aws.amazon.com/thread.jspa?threadID=267769&tstart=0

ContentLicense: CC BY-SA 3.0

Body:
The "Manage" tab in the MTurk Requester Website is for managing Batches created with the MTurk Requester Website (using the Create) tab. If you need/want to view HITs that you create with the API, you can use the ListHITs API method either with the API directly (using your Java code) or using the AWS Command Line Interface (CLI).

Here's a blog explaining how to do this with the AWS CLI:
https://blog.mturk.com/tutorial-managing-mturk-hits-with-the-aws-command-line-interface-56eaabb7fd4c

The blog shows how to use aws-shell, which is a more interactive shell that sits atop the AWS CLI. It has autocomplete and shows you inline "man" pages on each command. I personally prefer this.

The CLI and aws-shell will also let you write filters and formatters for results. So you can do things like this:

aws mturk list-hits --output table --query 'HITs[].{"1. HITId": HITId, "2. Title": Title, "3. Status":HITStatus}' --endpoint-url https://mturk-requester-sandbox.us-east-1.amazonaws.com --max-results 5

This calls ListHITs, on the Sandbox (--endpoint), getting only 5 results (--max-results), formats the output as a table instead of the default JSON (--output) and filters that JSON for the HITs object (HITs[]) pulling down only the fields HITId, Title, and Status while also setting titles for those fields as "1. HITId", "2. Title", and "3. Status".

There used to be a link in the MTurk Requester Website for a GUI to manage HITs individually which would show HITs from the API, but it was deprecated this month. There's a brief thread on it here: https://forums.aws.amazon.com/thread.jspa?threadID=267769&tstart=0


问:
hidden field vs viewstate
What is the difference when using

Hidden field vs View state?

When to use each one ?

Which one more secure?

Which is better in performance?

what are the alternatives?

答: ViewState is stored in a hidden field and it contains information about the entire page. It can also be encrypted. Because the view state is always sent to the codebehind when performing Postbacks it is very practical as you always get the values. The drawback is that it can get really large if you start putting much information inside it and performance could start to suffer. For example in some AJAX requests you want to only send some small information to the server and if you used UpdatePanels the entire ViewState will be sent and it will contain information that is not necessary.</p>

Title: hidden field vs viewstate

ContentLicense: CC BY-SA 2.5


问:
Apply complex arithmetic formulas to all fields in a table SQL
I got a problem on this request:

```<code>SELECT
    CASE WHEN ApNumber=0 THEN 0
        WHEN ApNumber=1 THEN 100
        WHEN ApNumber=2 THEN 250
        WHEN ApNumber=3 THEN 500
        WHEN ApNumber=4 THEN 750
        WHEN ApNumber<=5 THEN 1000 END AS ApPoint,

    FactionInfo.FactionUUID

FROM
    (
        SELECT COUNT(isAP) AS ApNumber
        FROM ClaimInfo
        WHERE FactionOwnerUUID =FactionInfo.FactionUUID
    )f0,

    FactionInfo
</code>```

The problem is that

```<code>FactionInfo.FactionUUID
</code>```

in  WHERE FactionOwnerUUID =FactionInfo.FactionUUID

produce the unknow column error.

The problem is that I want to perform all the calculations located in the select for all the lines located in the FactionInfo.
Advices ?

The final request should give me:

```<code>FactionUUID - ApPoint
----------------------
FactionUUIDName 250
FactionUUIDOtherName 750
</code>```

答:
You seem to want:</p>

```<code>SELECT (CASE WHEN COUNT(isAP) = 0 THEN 0 -- this will never happen
             WHEN COUNT(isAP) = 1 THEN 100
             WHEN COUNT(isAP) = 2 THEN 250
             WHEN COUNT(isAP) = 3 THEN 500
             WHEN COUNT(isAP) = 4 THEN 750
             ELSE 1000
        END) AS ApPoint,
       ci.FactionOwnerUUID
FROM ClaimInfo ci
GROUP BY ci.FactionOwnerUUID;
</code>```

Body:
I got a problem on this request:

SELECT
    CASE WHEN ApNumber=0 THEN 0
        WHEN ApNumber=1 THEN 100
        WHEN ApNumber=2 THEN 250
        WHEN ApNumber=3 THEN 500
        WHEN ApNumber=4 THEN 750
        WHEN ApNumber<=5 THEN 1000 END AS ApPoint,

    FactionInfo.FactionUUID

FROM
    (
        SELECT COUNT(isAP) AS ApNumber
        FROM ClaimInfo
        WHERE FactionOwnerUUID =FactionInfo.FactionUUID
    )f0,

    FactionInfo

The problem is that

FactionInfo.FactionUUID

in  WHERE FactionOwnerUUID =FactionInfo.FactionUUID

produce the unknow column error.

The problem is that I want to perform all the calculations located in the select for all the lines located in the FactionInfo.
Advices ?

The final request should give me:

FactionUUID - ApPoint
----------------------
FactionUUIDName 250
FactionUUIDOtherName 750

Body:
You seem to want:

SELECT (CASE WHEN COUNT(isAP) = 0 THEN 0 -- this will never happen
             WHEN COUNT(isAP) = 1 THEN 100
             WHEN COUNT(isAP) = 2 THEN 250
             WHEN COUNT(isAP) = 3 THEN 500
             WHEN COUNT(isAP) = 4 THEN 750
             ELSE 1000
        END) AS ApPoint,
       ci.FactionOwnerUUID
FROM ClaimInfo ci
GROUP BY ci.FactionOwnerUUID;


问:
Property [date] does not exist on this collection instance. When i call the API
When I call this API, I got this error "Property [date] does not exist on this collection instance."

This is my API code.

```<code> public function apiGetAttend($id, Request $request)
    {
        $tokenuser = User::with('attendance')
            ->where('token', $request->input('token'))->first();
        $user = User::with('attendance')->find($id);

        if($user && $tokenuser == $user){
            return response()->json([
                'MacAddress' => $user->mac_address,
                'SerialNo'=>$user->serial_no,
                'Date' => $user->attendance->date,
                'Time' => $user->attendance->time,
                'Present' => $user->attendance->present
            ]);
        }
        return response()->json([
            'status' => 'Fail',
            'message' => 'You dont have access to see this user.'
        ]);
    }
</code>```

答:
Since user has many attendancies, $user->attendance is a collection and not an object. So, you may want to iterate over it and all attendancies dates etc. Or you can use the first() collection method to get data from the first attendance in the collection:

```<code>'Date' => $user->attendance->first()->date,
'Time' => $user->attendance->first()->time,
'Present' => $user->attendance->first()->present
</code>```

Body:
When I call this API, I got this error "Property [date] does not exist on this collection instance."

This is my API code.

 public function apiGetAttend($id, Request $request)
    {
        $tokenuser = User::with('attendance')
            ->where('token', $request->input('token'))->first();
        $user = User::with('attendance')->find($id);

        if($user && $tokenuser == $user){
            return response()->json([
                'MacAddress' => $user->mac_address,
                'SerialNo'=>$user->serial_no,
                'Date' => $user->attendance->date,
                'Time' => $user->attendance->time,
                'Present' => $user->attendance->present
            ]);
        }
        return response()->json([
            'status' => 'Fail',
            'message' => 'You dont have access to see this user.'
        ]);
    }

Body:
Since user has many attendancies, $user->attendance is a collection and not an object. So, you may want to iterate over it and all attendancies dates etc. Or you can use the first() collection method to get data from the first attendance in the collection:

'Date' => $user->attendance->first()->date,
'Time' => $user->attendance->first()->time,
'Present' => $user->attendance->first()->present


问:
Converting data back to its original items
I have some code and I don't understand how to get the individual items back:

```<code>u32_t foo = ((u32_t)((d) & 0xff) << 24) | ((u32_t)((c) & 0xff) << 16) |
((u32_t)((b) & 0xff) << 8)  | (u32_t)((a) & 0xff)
</code>```

I would like to input the result of this conversion
I want this to convert a IP address back to its parts to display.
But when I enter 192 168 1 200 I get 0xC801A8C0 and I don't get it converted back.

Does anyone know how I can items in a union struct?
I try to use LwIP but have problems with union structs. I try to access local_ip and remote_ip.

答:
```<code>u32_t d = (foo >> 24) & 0xFF; // Get the bits 32nd...25th
u32_t c = (foo >> 16) & 0xFF; // 24th...17th
u32_t b = (foo >> 8) & 0xFF;  // 16th...9th
u32_t a = (foo) & 0xFF;       // 8th...1st
</code>```

This is actually doing the opposite of the code above.

Body:
I have some code and I don't understand how to get the individual items back:

u32_t foo = ((u32_t)((d) & 0xff) << 24) | ((u32_t)((c) & 0xff) << 16) |
((u32_t)((b) & 0xff) << 8)  | (u32_t)((a) & 0xff)

I would like to input the result of this conversion
I want this to convert a IP address back to its parts to display.
But when I enter 192 168 1 200 I get 0xC801A8C0 and I don't get it converted back.

Does anyone know how I can items in a union struct?
I try to use LwIP but have problems with union structs. I try to access local_ip and remote_ip.

Body:
u32_t d = (foo >> 24) & 0xFF; // Get the bits 32nd...25th
u32_t c = (foo >> 16) & 0xFF; // 24th...17th
u32_t b = (foo >> 8) & 0xFF;  // 16th...9th
u32_t a = (foo) & 0xFF;       // 8th...1st

This is actually doing the opposite of the code above.


问:
I would like some guidance on sizing toolbars on hi res screens
I want to change the size of my toolbars at run time and to accommodate different screen resolutions.

My toolbars are on a TControlBar, with Toolbars and ControlBar set to autosize. I have 4 differently sized TImagelists 16*16 through to 48*48 which I can I assign to the toolbars.  What I am finding is that the controlbar and toolbars increase in height when I assign a larger Imagelist but do not shrink back down when I choose a smaller imagelist.  I have also found that the toolbars do not expand in length to accommodate the wider images. Is this expected behaviour?

I have also found that at design time my largest imagelist 48*48 has actually loaded the 32*32 images.  All images are coming from a set of Icons which hold images from 64*64, 48*48 ... down to 16*16. Is there a limit to size of images an image list can store.  Each image list  holds 36 images.

```<code>procedure TfmIDEMain.SetIconSize(Large: Boolean);
begin
  if Large then
    case screen.PixelsPerInch of
    96..111:  ilTBIcons := ilMedIcons;          // Large Icons - Low res
    112..120: ilTBIcons := ilLargeIcons;        // Large Icons - Hi Med
    121..144: ilTBIcons := ilExLargeIcons;      // Large Icons - hi res
    end
  else
    case screen.PixelsPerInch of
    96..111:  ilTBIcons := ilSmallIcons;        // Small Icons - Low res
    112..120: ilTBIcons := ilMedIcons;          // Small Icons - Med res
    121..144: ilTBIcons := ilLargeIcons;        // Small Icons - hi res
    end;

  tbFiles.Images := ilTBIcons;
  tbEdit.Images := ilTBIcons;
  tbBookmarks.Images := ilTBIcons;
  tbCodeFolding.Images := ilTBIcons;
end;
</code>```

The above routine assigns the images according to the screen resolution and the "Large" boolean. Is there anything else I should be doing to get the toolbars and control bar to resize down to the small image size?

答:
As you already found yourself, the ToolBar and ControlBar adjust themselves to the Imagelist size if they don't fit already. That is why they don't shrink when assigning smaller a Imagelist. Even the Toolbar should adjust its width when you trigger an AutoSize by setting it to False and True.

This reaction on the Imagelist size has an impact on the ScaleBy functionality which is used when the control reacts on DPI changes. Assigning a larger Imagelist will enlarge the Toolbar and the following ScaleBy will use the wrong base sizes. The other way round when the DPI decreases the Toolbar cannot reduce its size accordingly as long as the large Imagelist is still assigned.

This requires to assign the Imagelist in the right order:

a larger Imagelist must be assigned after scaling the control to a bigger size

a smaller Imagelist must be assigned before scaling the control to a smaller size

Body:
I want to change the size of my toolbars at run time and to accommodate different screen resolutions.

My toolbars are on a TControlBar, with Toolbars and ControlBar set to autosize. I have 4 differently sized TImagelists 16*16 through to 48*48 which I can I assign to the toolbars.  What I am finding is that the controlbar and toolbars increase in height when I assign a larger Imagelist but do not shrink back down when I choose a smaller imagelist.  I have also found that the toolbars do not expand in length to accommodate the wider images. Is this expected behaviour?

I have also found that at design time my largest imagelist 48*48 has actually loaded the 32*32 images.  All images are coming from a set of Icons which hold images from 64*64, 48*48 ... down to 16*16. Is there a limit to size of images an image list can store.  Each image list  holds 36 images.

procedure TfmIDEMain.SetIconSize(Large: Boolean);
begin
  if Large then
    case screen.PixelsPerInch of
    96..111:  ilTBIcons := ilMedIcons;          // Large Icons - Low res
    112..120: ilTBIcons := ilLargeIcons;        // Large Icons - Hi Med
    121..144: ilTBIcons := ilExLargeIcons;      // Large Icons - hi res
    end
  else
    case screen.PixelsPerInch of
    96..111:  ilTBIcons := ilSmallIcons;        // Small Icons - Low res
    112..120: ilTBIcons := ilMedIcons;          // Small Icons - Med res
    121..144: ilTBIcons := ilLargeIcons;        // Small Icons - hi res
    end;

  tbFiles.Images := ilTBIcons;
  tbEdit.Images := ilTBIcons;
  tbBookmarks.Images := ilTBIcons;
  tbCodeFolding.Images := ilTBIcons;
end;

The above routine assigns the images according to the screen resolution and the "Large" boolean. Is there anything else I should be doing to get the toolbars and control bar to resize down to the small image size?


问:
how tf.space_to_depth() works in tensorflow?
I am a pytorch user. I have got a pretrained model in tensorflow and I would like to transfer it into pytorch. In one part of model architecture, I mean in tensorflow-defined model, there is a function tf.space_to_depth which transfers an input size of (None, 38,38,64) to (None, 19,19, 256). (https://www.tensorflow.org/api_docs/python/tf/space_to_depth) is the doc of this function. But I could not understand what this function actually do. Could you please provide some numpy codes to illustrate it for me?

Actually I would like to make an exact similar layer in pytorch.

Some codes in tensorflow reveals another secret:
Here is some codes:

```<code>import numpy as np
import tensorflow as tf

norm = tf.random_normal([1, 2, 2, 1], mean=0, stddev=1)
trans = tf.space_to_depth(norm,2)

with tf.Session() as s:
    norm = s.run(norm)
    trans = s.run(trans)

print("Norm")
print(norm.shape)
for index,value in np.ndenumerate(norm):
    print(value)

print("Trans")
print(trans.shape)
for index,value in np.ndenumerate(trans):
    print(value)
</code>```

And here is the output:

```<code>Norm
(1, 2, 2, 1)
0.695261
0.455764
1.04699
-0.237587
Trans
(1, 1, 1, 4)
1.01139
0.898777
0.210135
2.36742
</code>```

As you can see above, In Addition to data reshaping, the tensor values has changed!

答:
Using split and stack functions along with permute in Pytorch gives us the same result as space_to_depth in tensorflow does. Here is the code in Pytorch.
Assume that input is in BHWC format.

Based on block_size and input shape, we can caculate the output shape.
First, it splits the input on the "width" dimension or dimension #2 by block_size. The result of this operation is an array of length d_width. It's just like you cut a cake (by block_size) into d_width pieces.
Then for each piece, you reshape it so it has correct output height and output depth (channel). Finally, we stack those pieces together and perform a permutation.

Hope it helps.

```<code>def space_to_depth(input, block_size)
    block_size_sq = block_size*block_size
    (batch_size, s_height, s_width, s_depth) = input.size()
    d_depth = s_depth * self.block_size_sq
    d_width = int(s_width / self.block_size)
    d_height = int(s_height / self.block_size)
    t_1 = input.split(self.block_size, 2)
    stack = [t_t.contiguous().view(batch_size, d_height, d_depth) for t_t in t_1]
    output = torch.stack(stack, 1)
    output = output.permute(0, 2, 1, 3)
    return output
</code>```

Body:
I am a pytorch user. I have got a pretrained model in tensorflow and I would like to transfer it into pytorch. In one part of model architecture, I mean in tensorflow-defined model, there is a function tf.space_to_depth which transfers an input size of (None, 38,38,64) to (None, 19,19, 256). (https://www.tensorflow.org/api_docs/python/tf/space_to_depth) is the doc of this function. But I could not understand what this function actually do. Could you please provide some numpy codes to illustrate it for me?

Actually I would like to make an exact similar layer in pytorch.

Some codes in tensorflow reveals another secret:
Here is some codes:

import numpy as np
import tensorflow as tf

norm = tf.random_normal([1, 2, 2, 1], mean=0, stddev=1)
trans = tf.space_to_depth(norm,2)

with tf.Session() as s:
    norm = s.run(norm)
    trans = s.run(trans)

print("Norm")
print(norm.shape)
for index,value in np.ndenumerate(norm):
    print(value)

print("Trans")
print(trans.shape)
for index,value in np.ndenumerate(trans):
    print(value)

And here is the output:

Norm
(1, 2, 2, 1)
0.695261
0.455764
1.04699
-0.237587
Trans
(1, 1, 1, 4)
1.01139
0.898777
0.210135
2.36742

As you can see above, In Addition to data reshaping, the tensor values has changed!

Body:
Using split and stack functions along with permute in Pytorch gives us the same result as space_to_depth in tensorflow does. Here is the code in Pytorch.
Assume that input is in BHWC format.

Based on block_size and input shape, we can caculate the output shape.
First, it splits the input on the "width" dimension or dimension #2 by block_size. The result of this operation is an array of length d_width. It's just like you cut a cake (by block_size) into d_width pieces.
Then for each piece, you reshape it so it has correct output height and output depth (channel). Finally, we stack those pieces together and perform a permutation.

Hope it helps.

def space_to_depth(input, block_size)
    block_size_sq = block_size*block_size
    (batch_size, s_height, s_width, s_depth) = input.size()
    d_depth = s_depth * self.block_size_sq
    d_width = int(s_width / self.block_size)
    d_height = int(s_height / self.block_size)
    t_1 = input.split(self.block_size, 2)
    stack = [t_t.contiguous().view(batch_size, d_height, d_depth) for t_t in t_1]
    output = torch.stack(stack, 1)
    output = output.permute(0, 2, 1, 3)
    return output


问:
Elastic Beanstalk with Django: is there a way to run manage.py shell and have access to environment variables?
Similar question was asked here, however the solution does not give the shell access to the same environment as the deployment. If I inspect os.environ from within the shell, none of the environment variables appear.

Is there a way to run the manage.py shell with the environment?

PS: As a little side question, I know the mantra for EBS is to stop using eb ssh, but then how would you run one-off management scripts (that you don't want to run on every deploy)?

答:
One of the cases you have to run something once is db schema migrations. Usually you store information about that in the db... So you can use db to sync / ensure that something was triggered only once.

Personally I have nothing against using eb ssh, I see problems with it however. If you want to have CI/CD, that manual operation is against the rules.

Looks like you are referring to WWW/API part of Beanstalk. If you need something that is quite frequent... maybe worker is more suitable? Problem here is that if API goes deployed first you would have wrong schema.

In general you are using EC2, so it's user data stores information that spins up you service. So there you can put your "stuff". Still you need to sync / ensure. Here are docs for beanstalk - for more information how to do that.

Edit

Beanstalk is kind of instrumentation on top of EC2. So there must be a way to work with it, since you have access to user data of that EC2s. No worries you don't need to dig that deep. There is good way of instrumenting your server. It is called ebextensions. It can be used to put files on the server, trigger commands, instrument cron. What ever you want.

You can create ebextension, with container_commands this time Python Configuration Namespaces section. That commands are executed on each deployment. Still, problem is that you need to sync since more then one deployment can go at the same time. Good part is that you can set env in the way you want.

I have no problem to access to the environment variables. How did you get the problem? Try do prepare page with the map.


问:
Node.js buffer garbage collection
buf.slice([start[, end]])

Returns a new Buffer that references the same memory as the original, but offset and cropped by the start and end indices.

Note that modifying the new Buffer slice will modify the memory in the original Buffer because the allocated memory of the two objects overlap.

How does garbage collector handle allocated memory if one of the references is gone?

答:
From the Node.js buffer documentation: "The implementation of Buffer#slice() creates a view over the existing Buffer without copying, making Buffer#slice() far more efficient.". This means that the buffers reference the same memory location resulting in the overlap. Only once all references to the buffer have been removed, can the memory be reallocated by the garbage collector (gc). When the gc runs, it will delete the buffers that have no references and return the memory to the respective pools.

Node buffers vary in behavior depending on how you initialized them. If you used the new Buffer() methods, they are now deprecated and should revisit the docs. You should use the buffer alloc(), bufferUnsafe() and bufferUnsafeSlow() methods.

Title: Node.js buffer garbage collection


问:
Replace image source and attribute adding stops after AJAX call
```<code><div id="fbAdsIconDiv" class="social_icon">
                        <img src="~/Content/images/fbAdsAddOn_1.png" onclick="toggleImage(this)" id="fbAdsAddOn" data-toggle="tooltip"
                        title="click to enable" class="confirmBox fb_ads-icon" /></div>
</code>```

what i doing is that i have two images i.e. fbAdsAddOn_1.png  and fbAdsAddOn_2.png.For this i am simply using below Jquery code to replace image with some extra attributes:

```<code>$(".social_icon img").each(function () {
            var imgsrc = $(this).attr('src');
            $(this).attr('src', imgsrc.replace('2', '1'));
            $(this).attr('data-original-title', 'click to enable');
            $(this).attr('data-target', '');
            $(this).attr('data-toggle', '');
        });

function loadNewLocation(leadId) {
        var form = $('#brand-add-form');
        var summary = form.find('[data-valmsg-summary="true"]'); // get summary
        summary.hide(); // hide to avoid flicker

        $.ajax({
            url: '/locations/_createwizarditem',
            data: { index: location_count , leadId: leadId},
            success: function (data) {
                alert((data));
                $('.location-setup').last().after($.parseHTML($.trim(data)));
                //$('.location-setup').last().after($(data));
                location_count += 1;
                addAsterisk();
                initStateDropdown();
                reinitializeValidator($('#brand-add-form'));
                prevStep();
                prevStep();

                summary.show();
            },
            error: function (response) {
                toastr.error("Something went wrong loading a new location", 'Oh No!');
                console.error(response);
                summary.show();
            }
        })
    }
</code>```

It works first time but it stops working after AJAX call...how can i resolve this?????

答:
If I understood your question correctly, you want to replace the image after success Ajax call. Just put the replace function in success event;</p>

```<code>            success: function (data) {
                alert((data));
                $('.location-setup').last().after($.parseHTML($.trim(data)));
                //$('.location-setup').last().after($(data));
                location_count += 1;
                addAsterisk();
                initStateDropdown();
                reinitializeValidator($('#brand-add-form'));
                prevStep();
                prevStep();
                $(".social_icon img").each(function () {
                    var imgsrc = $(this).attr('src');
                    $(this).attr('src', imgsrc.replace('1', '2'));
                    $(this).attr('data-original-title', 'click to enable');
                    $(this).attr('data-target', '');
                    $(this).attr('data-toggle', '');
                });
                summary.show();
            }
</code>```

Body:
what i doing is that i have two images i.e. fbAdsAddOn_1.png  and fbAdsAddOn_2.png.For this i am simply using below Jquery code to replace image with some extra attributes:

$(".social_icon img").each(function () {
            var imgsrc = $(this).attr('src');
            $(this).attr('src', imgsrc.replace('2', '1'));
            $(this).attr('data-original-title', 'click to enable');
            $(this).attr('data-target', '');
            $(this).attr('data-toggle', '');
        });

function loadNewLocation(leadId) {
        var form = $('#brand-add-form');
        var summary = form.find('[data-valmsg-summary="true"]'); // get summary
        summary.hide(); // hide to avoid flicker

        $.ajax({
            url: '/locations/_createwizarditem',
            data: { index: location_count , leadId: leadId},
            success: function (data) {
                alert((data));
                $('.location-setup').last().after($.parseHTML($.trim(data)));
                //$('.location-setup').last().after($(data));
                location_count += 1;
                addAsterisk();
                initStateDropdown();
                reinitializeValidator($('#brand-add-form'));
                prevStep();
                prevStep();

                summary.show();
            },
            error: function (response) {
                toastr.error("Something went wrong loading a new location", 'Oh No!');
                console.error(response);
                summary.show();
            }
        })
    }

It works first time but it stops working after AJAX call...how can i resolve this?????

Body:
If I understood your question correctly, you want to replace the image after success Ajax call. Just put the replace function in success event;

            success: function (data) {
                alert((data));
                $('.location-setup').last().after($.parseHTML($.trim(data)));
                //$('.location-setup').last().after($(data));
                location_count += 1;
                addAsterisk();
                initStateDropdown();
                reinitializeValidator($('#brand-add-form'));
                prevStep();
                prevStep();
                $(".social_icon img").each(function () {
                    var imgsrc = $(this).attr('src');
                    $(this).attr('src', imgsrc.replace('1', '2'));
                    $(this).attr('data-original-title', 'click to enable');
                    $(this).attr('data-target', '');
                    $(this).attr('data-toggle', '');
                });
                summary.show();
            }


答:
You can mask out the values inside foo

```<code>u32_t thisWasD = (foo & 0xff000000) >> 24; // ==> will null out the lowest 24 bits
u32_t thisWasC = (foo & 0x00ff0000) >> 16; // ==> will null out the upper 8 and lowest 16 bit
u32_t thisWasB = (foo & 0x0000ff00) >> 8; // ==> etc
u32_t thisWasA = (foo & 0xff) // etc - no shift needed
</code>```

and shift them back so they are alignt in fist 8 bit ( by 24,16,8 - last one is already ok

Title: Converting data back to its original items

Body:
You can mask out the values inside foo

u32_t thisWasD = (foo & 0xff000000) >> 24; // ==> will null out the lowest 24 bits
u32_t thisWasC = (foo & 0x00ff0000) >> 16; // ==> will null out the upper 8 and lowest 16 bit
u32_t thisWasB = (foo & 0x0000ff00) >> 8; // ==> etc
u32_t thisWasA = (foo & 0xff) // etc - no shift needed

and shift them back so they are alignt in fist 8 bit ( by 24,16,8 - last one is already ok


问:
How to write a 'where' query in hibernate using criteria
Let me consider one simple sql query

```<code>select username from tbl_customer where username="user" and password="12345";
</code>```

How can i write this query in hibernate using criteria

Thanks. Hoping for positive response..

答:
first you have to create the Criteria object, then you need to pass the where clause condition to the criteria object as well you have to set the projection property for selecting particular column data.

By seeing your SQL query,

```<code>select username from tbl_customer where username="user" and password="12345";
</code>```

I believe you want to fetch the particular column username from the table tbl_customer. This can be done using Projections. You have to set the projection property for which column data you want.

```<code>Criteria criteria = session.createCriteria(MyClass.class)
  criteria.setProjection(Projections.property("username"));
  criteria.add(Restrictions.and(Restrictions.eq("username", user),Restrictions.eq("password", 12345))
);
List<String> userNames = criteria.list();
</code>```

This will return only the username column data from that table.

Body:
Let me consider one simple sql query

select username from tbl_customer where username="user" and password="12345";

How can i write this query in hibernate using criteria

Thanks. Hoping for positive response..

Body:
first you have to create the Criteria object, then you need to pass the where clause condition to the criteria object as well you have to set the projection property for selecting particular column data.

By seeing your SQL query,

select username from tbl_customer where username="user" and password="12345";

I believe you want to fetch the particular column username from the table tbl_customer. This can be done using Projections. You have to set the projection property for which column data you want.

Criteria criteria = session.createCriteria(MyClass.class)
  criteria.setProjection(Projections.property("username"));
  criteria.add(Restrictions.and(Restrictions.eq("username", user),Restrictions.eq("password", 12345))
);
List<String> userNames = criteria.list();

This will return only the username column data from that table.


问:
GWT get users local decimal separator char
How can I get users local decimal separator character from GWT. I have found the NumberFormat utility, which only returns the whole format and provides parsing.

```<code>NumberFormat.getDecimalFormat()...
</code>```

Is there a (simple) way to get the decimal separator, thousand separator from the decimal format.

答:
You can seed it with a known number and then parse it for the characters you want. </p>

```<code>import com.google.gwt.i18n.client.NumberFormat;

NumberFormat fmt = NumberFormat.getDecimalFormat();
double value = 1234.5;
String formatted = fmt.format(value);
String thousandSeparator = formatted.substring(1,2);
String decimalSeparator = formatted.substring(5,6);
</code>```

OwnerDisplayName: Drejc

Body:
How can I get users local decimal separator character from GWT. I have found the NumberFormat utility, which only returns the whole format and provides parsing.

NumberFormat.getDecimalFormat()...

Is there a (simple) way to get the decimal separator, thousand separator from the decimal format.

Body:
You can seed it with a known number and then parse it for the characters you want.

import com.google.gwt.i18n.client.NumberFormat;

NumberFormat fmt = NumberFormat.getDecimalFormat();
double value = 1234.5;
String formatted = fmt.format(value);
String thousandSeparator = formatted.substring(1,2);
String decimalSeparator = formatted.substring(5,6);

OwnerDisplayName: Bill

LastEditorDisplayName: Bill


答:
```<code>Criteria criteria = session.createCriteria(Customer.class)
.add(Restrictions.eq("username",
"user").add(Restrictions.eq("password","12345"));
</code>```

Please note that, I do consider entity name as Customer for tbl_customer and you created session correctly.

Title: How to write a 'where' query in hibernate using criteria

Body:
Criteria criteria = session.createCriteria(Customer.class)
.add(Restrictions.eq("username",
"user").add(Restrictions.eq("password","12345"));

Please note that, I do consider entity name as Customer for tbl_customer and you created session correctly.


问:
Set Production on ng build in angular 4
I want my API Endpoint URL to point to production on running

```<code>ng build
</code>```

how can this be achieved in angular 4 ?

答:
You can use '--prod' with ng build. Adding this actually does a lot of things such as reducing code size using tree shaking,switching environment configurations etc.You can refer to official documentation for details.

If you are referring to changing like property file,well you can use environment.ts file. Ng build without prod flag takes values from environment.ts file and with prod flag takes values from environment.prod.ts file.

Title: Set Production on ng build in angular 4

Body:
I want my API Endpoint URL to point to production on running

ng build

how can this be achieved in angular 4 ?


问:
Alarm Manager does not show notification api 26
Works perfectly in the verses until api 25.
I am new to android and working on Notification Alarm Manager to show notification.

Can Any one help me what is the error in it?

Main Activity:

```<code>package br.exemploalarmmanagerbn;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        boolean alarmeAtivo = (PendingIntent.getBroadcast(this, 0, new Intent("ALARME_DISPARADO"), PendingIntent.FLAG_NO_CREATE) == null);

        if(alarmeAtivo){
            Log.i("Script", "Novo alarme");

            Intent intent = new Intent("ALARME_DISPARADO");
            PendingIntent p = PendingIntent.getBroadcast(this, 0, intent, 0);

            Calendar c = Calendar.getInstance();
            c.setTimeInMillis(System.currentTimeMillis());
            c.add(Calendar.SECOND, 3);

            AlarmManager alarme = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarme.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 5000, p);
        }
        else{
            Log.i("Script", "Alarme já ativo");
        }
    }

    @Override
    public void onDestroy(){
        super.onDestroy();

        /*Intent intent = new Intent("ALARME_DISPARADO");
        PendingIntent p = PendingIntent.getBroadcast(this, 0, intent, 0);

        AlarmManager alarme = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarme.cancel(p);*/
    }
}
</code>```

BroadcastReceiverAux

```<code>package br.exemploalarmmanagerbn;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

public class BroadcastReceiverAux extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Log.i("Script", "-> Alarme");

        gerarNotificacao(context, new Intent(context, MainActivity.class), "Nova mensagem", "Título", "Descrição nova mensagem");
    }

    public void gerarNotificacao(Context context, Intent intent, CharSequence ticker, CharSequence titulo, CharSequence descricao){

if (Build.VERSION.SDK_INT >= 26) {
            if (nm.getNotificationChannel(CHANNEL_ID) == null) {
                nm.createNotificationChannel(new NotificationChannel(CHANNEL_ID, CHANNEL_NAME,
                        NotificationManager.IMPORTANCE_DEFAULT));
            }
        }

        NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        PendingIntent p = PendingIntent.getActivity(context, 0, intent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setTicker(ticker);
        builder.setContentTitle(titulo);
        builder.setContentText(descricao);
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher));
        builder.setContentIntent(p);

        Notification n = builder.build();
        n.vibrate = new long[]{150, 300, 150, 600};
        n.flags = Notification.FLAG_AUTO_CANCEL;
        nm.notify(R.drawable.ic_launcher, n);

        try{
            Uri som = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone toque = RingtoneManager.getRingtone(context, som);
            toque.play();
        }
        catch(Exception e){}
    }
}
</code>```

Manifest

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="br.exemploalarmmanagerbn"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.VIBRATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="br.exemploalarmmanagerbn.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="BroadcastReceiverAux" android:label="BroadcastReceiverAux">
            <intent-filter>
                <action android:name="ALARME_DISPARADO"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>
</code>```

答:
You have to create notification channel first and then use that channel to post notificatins</p>

```<code>NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// The id of the channel.
String id = "my_channel_01";
// The user-visible name of the channel.
CharSequence name = getString(R.string.channel_name);
// The user-visible description of the channel.
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);

// The id of the channel.
String CHANNEL_ID = "my_channel_01";
NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.notification_icon)
            .setContentTitle("My notification")
            .setContentText("Hello World!");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Works perfectly in the verses until api 25.
I am new to android and working on Notification Alarm Manager to show notification.

Can Any one help me what is the error in it?

Main Activity:

package br.exemploalarmmanagerbn;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        boolean alarmeAtivo = (PendingIntent.getBroadcast(this, 0, new Intent("ALARME_DISPARADO"), PendingIntent.FLAG_NO_CREATE) == null);

        if(alarmeAtivo){
            Log.i("Script", "Novo alarme");

            Intent intent = new Intent("ALARME_DISPARADO");
            PendingIntent p = PendingIntent.getBroadcast(this, 0, intent, 0);

            Calendar c = Calendar.getInstance();
            c.setTimeInMillis(System.currentTimeMillis());
            c.add(Calendar.SECOND, 3);

            AlarmManager alarme = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarme.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 5000, p);
        }
        else{
            Log.i("Script", "Alarme já ativo");
        }
    }

    @Override
    public void onDestroy(){
        super.onDestroy();

        /*Intent intent = new Intent("ALARME_DISPARADO");
        PendingIntent p = PendingIntent.getBroadcast(this, 0, intent, 0);

        AlarmManager alarme = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarme.cancel(p);*/
    }
}

BroadcastReceiverAux

package br.exemploalarmmanagerbn;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

public class BroadcastReceiverAux extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Log.i("Script", "-> Alarme");

        gerarNotificacao(context, new Intent(context, MainActivity.class), "Nova mensagem", "Título", "Descrição nova mensagem");
    }

    public void gerarNotificacao(Context context, Intent intent, CharSequence ticker, CharSequence titulo, CharSequence descricao){

if (Build.VERSION.SDK_INT >= 26) {
            if (nm.getNotificationChannel(CHANNEL_ID) == null) {
                nm.createNotificationChannel(new NotificationChannel(CHANNEL_ID, CHANNEL_NAME,
                        NotificationManager.IMPORTANCE_DEFAULT));
            }
        }

        NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        PendingIntent p = PendingIntent.getActivity(context, 0, intent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setTicker(ticker);
        builder.setContentTitle(titulo);
        builder.setContentText(descricao);
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher));
        builder.setContentIntent(p);

        Notification n = builder.build();
        n.vibrate = new long[]{150, 300, 150, 600};
        n.flags = Notification.FLAG_AUTO_CANCEL;
        nm.notify(R.drawable.ic_launcher, n);

        try{
            Uri som = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone toque = RingtoneManager.getRingtone(context, som);
            toque.play();
        }
        catch(Exception e){}
    }
}

Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="br.exemploalarmmanagerbn"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.VIBRATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="br.exemploalarmmanagerbn.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="BroadcastReceiverAux" android:label="BroadcastReceiverAux">
            <intent-filter>
                <action android:name="ALARME_DISPARADO"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

Body:
You have to create notification channel first and then use that channel to post notificatins

NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// The id of the channel.
String id = "my_channel_01";
// The user-visible name of the channel.
CharSequence name = getString(R.string.channel_name);
// The user-visible description of the channel.
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);

// The id of the channel.
String CHANNEL_ID = "my_channel_01";
NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.notification_icon)
            .setContentTitle("My notification")
            .setContentText("Hello World!");


答:
it's like you have one int input and you want to divide into bytes by bytes & store each bytes in seperate integers

```<code>int main() {

         a = ((uint32_t)((foo) & 0x000000ff) << 24);
         b = ((uint32_t)((foo) & 0x0000ff00) << 16);
         c = ((uint32_t)((foo) & 0x00ff0000) << 8);
         d = ((uint32_t)((foo) & 0xff000000);

}
</code>```

Body:
it's like you have one int input and you want to divide into bytes by bytes & store each bytes in seperate integers

int main() {

         a = ((uint32_t)((foo) & 0x000000ff) << 24);
         b = ((uint32_t)((foo) & 0x0000ff00) << 16);
         c = ((uint32_t)((foo) & 0x00ff0000) << 8);
         d = ((uint32_t)((foo) & 0xff000000);

}


问:
Can I break an SQL statement with JOINs into smaller queries or optimize query?
I have query that's breaking an area of my website. The site spins forever when attempting to load the following SQL statement! I'm fairly new to sql statements and this particular statement was created by another developer. Is there a way to optimize the following statement? Or break it up into smaller statements so that it will run more quickly? I'm at a loss! I appreciate any help.</p>

```<code>SELECT
    `wp_quiz_users`.`Id`,
    `wp_quiz_users`.`SessionId`,
    `wp_quiz_users`.`Score`,
    `wp_quiz_users`.`Date`,
    `wp_quiz_users`.`Referrer`,
    `wp_quiz_users`.`ContactData`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 1) AS `SectionOne`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 2) AS `SectionTwo`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 3) AS `SectionThree`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 4) AS `SectionFour`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 5) AS `SectionFive`
FROM
    `wp_quiz_users`
</code>```

答:
I would start with

```<code>    FROM (
        SELECT  ua.`UserId`,
                q.Category,
                SUM(ua.`AnswerValue`)
            FROM  `wp_quiz_users_answers` AS ua
            JOIN  `wp_quiz_questions` AS q
              ON ua.`QuestionId` = q.`id`
            GROUP BY ua.`UserId`, q.Category
         ) AS x
    JOIN wp_quiz_users AS u
      ON u.Id = x.UserId
</code>```

and build up around it.

(But since I see other answers, I'll be lazy and not finish this thought.)

Hmmm... I wonder if my approach -- or the other approaches -- will inflate the SUMs due to waiting too late to do GROUP BY??

Body:
I have query that's breaking an area of my website. The site spins forever when attempting to load the following SQL statement! I'm fairly new to sql statements and this particular statement was created by another developer. Is there a way to optimize the following statement? Or break it up into smaller statements so that it will run more quickly? I'm at a loss! I appreciate any help.

SELECT
    `wp_quiz_users`.`Id`,
    `wp_quiz_users`.`SessionId`,
    `wp_quiz_users`.`Score`,
    `wp_quiz_users`.`Date`,
    `wp_quiz_users`.`Referrer`,
    `wp_quiz_users`.`ContactData`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 1) AS `SectionOne`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 2) AS `SectionTwo`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 3) AS `SectionThree`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 4) AS `SectionFour`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 5) AS `SectionFive`
FROM
    `wp_quiz_users`

Body:
I would start with

    FROM (
        SELECT  ua.`UserId`,
                q.Category,
                SUM(ua.`AnswerValue`)
            FROM  `wp_quiz_users_answers` AS ua
            JOIN  `wp_quiz_questions` AS q
              ON ua.`QuestionId` = q.`id`
            GROUP BY ua.`UserId`, q.Category
         ) AS x
    JOIN wp_quiz_users AS u
      ON u.Id = x.UserId

and build up around it.

(But since I see other answers, I'll be lazy and not finish this thought.)

Hmmm... I wonder if my approach -- or the other approaches -- will inflate the SUMs due to waiting too late to do GROUP BY??


问:
Confusion matrix for Clustering in scikit-learn
I have a set of data with known labels. I want to try clustering and see if I can get the same clusters given by known labels. To measure the accuracy, I need to get something like a confusion matrix.

I know I can get a confusion matrix easily for a test set of a classification problem. I already tried that like this.

However, it can't be used for clustering as it expected both columns and rows to have the same set of labels, which makes sense for a classification problem. But for a clustering problem what I expect is something like this.

Rows - Actual labels

Columns - New cluster names (i.e. cluster-1, cluster-2 etc.)

Is there a way to do this?

Edit: Here are more details.

In sklearn.metrics.confusion_matrix, it expects y_test and y_pred to have the same values, and labels to be the labels of those values.

That's why it gives a matrix which has the same labels for both rows and columns like this.

But in my case (KMeans Clustering), the real values are Strings and estimated values are numbers (i.e. cluster number)

Therefore, if I call confusion_matrix(y_true, y_pred) it gives below error.

```<code>ValueError: Mix of label input types (string and number)
</code>```

This is the real problem. For a classification problem, this makes sense. But for a clustering problem, this restriction shouldn't be there, because real label names and new cluster names don't need to be the same.

With this, I understand I'm trying to use a tool, which is supposed to be used for classification problems, for a clustering problem. So, my question is, is there a way I can get such a matrix for may clustered data.

Hope the question is now clearer. Please let me know if it isn't.

答:
You can easily compute a pairwise intersection matrix.

But it may be necessary to do this yourself, if the sklearn library has been optimized for the classification use case.

Body:
I have a set of data with known labels. I want to try clustering and see if I can get the same clusters given by known labels. To measure the accuracy, I need to get something like a confusion matrix.

I know I can get a confusion matrix easily for a test set of a classification problem. I already tried that like this.

However, it can't be used for clustering as it expected both columns and rows to have the same set of labels, which makes sense for a classification problem. But for a clustering problem what I expect is something like this.

Rows - Actual labels

Columns - New cluster names (i.e. cluster-1, cluster-2 etc.)

Is there a way to do this?

Edit: Here are more details.

In sklearn.metrics.confusion_matrix, it expects y_test and y_pred to have the same values, and labels to be the labels of those values.

That's why it gives a matrix which has the same labels for both rows and columns like this.

But in my case (KMeans Clustering), the real values are Strings and estimated values are numbers (i.e. cluster number)

Therefore, if I call confusion_matrix(y_true, y_pred) it gives below error.

ValueError: Mix of label input types (string and number)

This is the real problem. For a classification problem, this makes sense. But for a clustering problem, this restriction shouldn't be there, because real label names and new cluster names don't need to be the same.

With this, I understand I'm trying to use a tool, which is supposed to be used for classification problems, for a clustering problem. So, my question is, is there a way I can get such a matrix for may clustered data.

Hope the question is now clearer. Please let me know if it isn't.


问:
React native null is not an object (evaluating '_scrollView.scrollTo') on Android
React native null is not an object (evaluating '_scrollView.scrollTo')  on Android

```<code>  componentDidMount() {

      let scrollValue = 0;
      setInterval(function(){
          scrollValue = scrollValue + width;   // width = screen width
          _scrollView.scrollTo({x: scrollValue})
      }, 3000);
}

<ScrollView
ref={(scrollView) => { _scrollView = scrollView; }}
horizontal={true} pagingEnabled={true} >
 {items}
</ScrollView>
</code>```

it's work auto slide content but when I'm going back from another page it's return error null is not an object (evaluating '_scrollView.scrollTo')  I don't know about that

答:
You should save the reference on this. Even so it might work if the reference is in some other scope you will run into problems when multiple ScrollViews are mounted.

```<code>componentDidMount() {
  let scrollValue = 0;
  setInterval(() => {
      scrollValue = scrollValue + width;
      this._scrollView.scrollTo({x: scrollValue})
  }, 3000);
}

render() {
  // ...
  return (
    <ScrollView
      ref={scrollView => this._scrollView = scrollView}
      horizontal={true}
      pagingEnabled={true}
    >
      {items}
    </ScrollView>
  )
}
</code>```

Be aware that this has to be binded by your-self when you create custom methods in your component

```<code>scrollListToLeft = () => {
  this._scrollView.scrollTo({x: 0})
}
</code>```

Body:
React native null is not an object (evaluating '_scrollView.scrollTo')  on Android

  componentDidMount() {

      let scrollValue = 0;
      setInterval(function(){
          scrollValue = scrollValue + width;   // width = screen width
          _scrollView.scrollTo({x: scrollValue})
      }, 3000);
}

<ScrollView
ref={(scrollView) => { _scrollView = scrollView; }}
horizontal={true} pagingEnabled={true} >
 {items}
</ScrollView>

it's work auto slide content but when I'm going back from another page it's return error null is not an object (evaluating '_scrollView.scrollTo')  I don't know about that

Body:
You should save the reference on this. Even so it might work if the reference is in some other scope you will run into problems when multiple ScrollViews are mounted.

componentDidMount() {
  let scrollValue = 0;
  setInterval(() => {
      scrollValue = scrollValue + width;
      this._scrollView.scrollTo({x: scrollValue})
  }, 3000);
}

render() {
  // ...
  return (
    <ScrollView
      ref={scrollView => this._scrollView = scrollView}
      horizontal={true}
      pagingEnabled={true}
    >
      {items}
    </ScrollView>
  )
}

Be aware that this has to be binded by your-self when you create custom methods in your component

scrollListToLeft = () => {
  this._scrollView.scrollTo({x: 0})
}


问:
Go build project with cmd and pkg layout - build error
I'm trying to build a Go project using the layout as described in Go Project Layout

I'm using go 1.9.2 on Ubuntu. My project layout is as follows

```<code>$GOPATH/src/github.com/ayubmalik/cleanprops
    /cmd
        /cleanprops
            /main.go
    /internal
        /pkg
            /readprops.go
</code>```

The file cmd/cleanprops/main.go is referring to the cleanprops package i.e.

```<code>package main

import (
    "fmt"
    "github.com/ayubmalik/cleanprops"
)

func main() {
    body := cleanprops.ReadProps("/tmp/hello.props")
    fmt.Println("%s", body)
}
</code>```

The contents of internal/pkg/readprops.go are:

```<code>package cleanprops

import (
    "fmt"
    "io/ioutil"
)

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func ReadProps(file string) string {
    body, err := ioutil.ReadFile(file)
    check(err)
    fmt.Println(string(body))
    return body
}
</code>```

However when I build cmd/cleanprops/main.go, from inside directory $GOPATH/src/github.com/ayubmalik/cleanprops, using command:

```<code>go build cmd/cleanprops/main.go
</code>```

I get the following error:

```<code>cmd/cleanprops/main.go:5:2: no Go files in /home/xyz/go/src/github.com/ayubmalik/cleanprops
</code>```

What am I missing?

答:
The document suggests this structure:

```<code>$GOPATH/src/github.com/ayubmalik/cleanprops
    /cmd
        /cleanprops
            /main.go
    /internal
        /pkg
            /cleanprops
                /readprops.go
</code>```

Import the package like this. The import path matches the directory structure below $GOPATH/src.

```<code>package main

import (
    "fmt"
    "github.com/ayubmalik/cleanprops/internal/pkg/cleanprops"
)

func main() {
    body := cleanprops.ReadProps("/tmp/hello.props")
    fmt.Println("%s", body)
}
</code>```

Body:
I'm trying to build a Go project using the layout as described in Go Project Layout

I'm using go 1.9.2 on Ubuntu. My project layout is as follows

$GOPATH/src/github.com/ayubmalik/cleanprops
    /cmd
        /cleanprops
            /main.go
    /internal
        /pkg
            /readprops.go

The file cmd/cleanprops/main.go is referring to the cleanprops package i.e.

package main

import (
    "fmt"
    "github.com/ayubmalik/cleanprops"
)

func main() {
    body := cleanprops.ReadProps("/tmp/hello.props")
    fmt.Println("%s", body)
}

The contents of internal/pkg/readprops.go are:

package cleanprops

import (
    "fmt"
    "io/ioutil"
)

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func ReadProps(file string) string {
    body, err := ioutil.ReadFile(file)
    check(err)
    fmt.Println(string(body))
    return body
}

However when I build cmd/cleanprops/main.go, from inside directory $GOPATH/src/github.com/ayubmalik/cleanprops, using command:

go build cmd/cleanprops/main.go

I get the following error:

cmd/cleanprops/main.go:5:2: no Go files in /home/xyz/go/src/github.com/ayubmalik/cleanprops

What am I missing?

Body:
The document suggests this structure:

$GOPATH/src/github.com/ayubmalik/cleanprops
    /cmd
        /cleanprops
            /main.go
    /internal
        /pkg
            /cleanprops
                /readprops.go

Import the package like this. The import path matches the directory structure below $GOPATH/src.

package main

import (
    "fmt"
    "github.com/ayubmalik/cleanprops/internal/pkg/cleanprops"
)

func main() {
    body := cleanprops.ReadProps("/tmp/hello.props")
    fmt.Println("%s", body)
}


问:
Convert utf-8 to Unicode to find emoji in string in java
I'm trying to write a java code in which I have utf8 string which contains an emoji, I want to replace that emoji with a text.
for example:

I have this text:    طلبت منهم مبالغ كبيرة لإتمام دراستهم

and I want it to be like this:
   grinningFace طلبت منهم مبالغ كبيرة لإتمام دراستهم

I tried this:

```<code>String string = "";
    try {

        byte[] utf8Bytes = string.getBytes("UTF-8");

        string = new String(utf8Bytes, "UTF-8");
    } catch (
        UnsupportedEncodingException e
    ) {
        e.printStackTrace();
    }
    string=string.replaceAll("[\u1F600]", "grinningF");
    //also tried "\u1F600" and "u1F600"
    System.out.println(string);
</code>```

but it didn't work, how to do it?

答:
Your problem is that the Emoji in not in the Basic Multilingual Plane because its code is greater than U+FFFF. Java characters are only 16 bits long, so only characters in the BMP use one single java character. Characters outside the BMP are encoded in UTF16.

The unicode Emoji  is the GRINNING FACE character U+1F600. Its utf8 encoding is 0xf0,0x9f,0x98,0x80, and its UTF-16 encoding is (as said by Jon Skeet in its comment) 0xd83d, 0xde00. That means that the internal Java representation of "" is "\ud83d\ude00", as a debugger could show.

So your code should be:

```<code>string.replaceAll("\ud83d\ude00", "grinningF");
</code>```

or

```<code>string.replaceAll("", "grinningF");
</code>```

which is exactly the same.

Body:
I'm trying to write a java code in which I have utf8 string which contains an emoji, I want to replace that emoji with a text.
for example:

I have this text:    طلبت منهم مبالغ كبيرة لإتمام دراستهم

and I want it to be like this:
   grinningFace طلبت منهم مبالغ كبيرة لإتمام دراستهم

I tried this:

String string = "";
    try {

        byte[] utf8Bytes = string.getBytes("UTF-8");

        string = new String(utf8Bytes, "UTF-8");
    } catch (
        UnsupportedEncodingException e
    ) {
        e.printStackTrace();
    }
    string=string.replaceAll("[\u1F600]", "grinningF");
    //also tried "\u1F600" and "u1F600"
    System.out.println(string);

but it didn't work, how to do it?

Body:
Your problem is that the Emoji in not in the Basic Multilingual Plane because its code is greater than U+FFFF. Java characters are only 16 bits long, so only characters in the BMP use one single java character. Characters outside the BMP are encoded in UTF16.

The unicode Emoji  is the GRINNING FACE character U+1F600. Its utf8 encoding is 0xf0,0x9f,0x98,0x80, and its UTF-16 encoding is (as said by Jon Skeet in its comment) 0xd83d, 0xde00. That means that the internal Java representation of "" is "\ud83d\ude00", as a debugger could show.

So your code should be:

string.replaceAll("\ud83d\ude00", "grinningF");

or

string.replaceAll("", "grinningF");

which is exactly the same.


问:
-Adding a column to a pandas dataframe that is sum of 3 different rows in another column AND slides those rows down like in excel
I have a data frame like:

```<code>   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9
3 10 11 12
4 13 14 15
5 16 17 18
6 19 20 21
7 22 23 24
8 25 26 27
</code>```

I'd like to add a column d that is the sum of column A row 0, column A row 2, and column A row 5.

I figured out how to do:

```<code>df['d']=df.loc[0,'a'] + df.loc[2,'a'] + df.loc[5,'a']
</code>```

But the result is a static d tied to only those rows. I'd like a dynamic d, such that column d, row 2 is the sum of column a, row 1, column a, row3, and column a, row 6.

The end result should be:

```<code>   a  b  c  d
0  1  2  3 24
1  4  5  6 33
2  7  8  9 42
3 10 11 12 ---And so on
4 13 14 15 ---
5 16 17 18 ---
6 19 20 21 ---
7 22 23 24 ---
8 25 26 27 ---
</code>```

Thanks for any help!

Body:
I have a data frame like:

   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9
3 10 11 12
4 13 14 15
5 16 17 18
6 19 20 21
7 22 23 24
8 25 26 27

I'd like to add a column d that is the sum of column A row 0, column A row 2, and column A row 5.

I figured out how to do:

df['d']=df.loc[0,'a'] + df.loc[2,'a'] + df.loc[5,'a']

But the result is a static d tied to only those rows. I'd like a dynamic d, such that column d, row 2 is the sum of column a, row 1, column a, row3, and column a, row 6.

The end result should be:

   a  b  c  d
0  1  2  3 24
1  4  5  6 33
2  7  8  9 42
3 10 11 12 ---And so on
4 13 14 15 ---
5 16 17 18 ---
6 19 20 21 ---
7 22 23 24 ---
8 25 26 27 ---

Thanks for any help!

Body:
this is shift

df.a+df.a.shift(-2)+df.a.shift(-5)
Out[412]:
0    24.0
1    33.0
2    42.0
3    51.0
4     NaN
5     NaN
6     NaN
7     NaN
8     NaN
Name: a, dtype: float64

df['d']=df.a+df.a.shift(-2)+df.a.shift(-5)
df
Out[414]:
    a   b   c     d
0   1   2   3  24.0
1   4   5   6  33.0
2   7   8   9  42.0
3  10  11  12  51.0
4  13  14  15   NaN
5  16  17  18   NaN
6  19  20  21   NaN
7  22  23  24   NaN
8  25  26  27   NaN


问:
Silverlight ViewModelLocator defined in app.xaml needs a reference to the DI container
I have a ViewModelLocator class that I am defining in app.xaml which is used by my views to databind to the correct ViewModel.

```<code>DataContext="{Binding HomeViewModel, Source={StaticResource Locator}}"
</code>```

I am using Prism and Unity and my ViewModelLocator class needs a reference to an application level unity container.

I wanted inject the IUnityContainer into the ctor of the ViewModelLocator but the ViewModelLocator gets instanciated from app.xaml using a parameterless ctor.

Is there a preferred way to get access to an application level container - for all other classes in the app I just use ctor injection to get the global container.

What I am currenlty doing for the ViewModelLocator is defining a static variable in my BootStrapper class to store the container. I create the container by overriding the CreateContainer method on UnityBootStrapper.

```<code>protected override IUnityContainer CreateContainer()
{
    BootStrapper.DIContainer = base.CreateContainer();
    return BootStrapper.DIContainer;
}
</code>```

Then in the ViewModelLocator class I just reference the BootStrapper.DIContainer property to register my viewmodels

```<code>BootStrapper.DIContainer.RegisterType<IShellViewModel, DesignShellViewModel>();
</code>```

This works fine but it is the only place in the application that needs to reference this static property on the bootstrapper  - and would like to get rid of it if possible.

thanks
Michael

答:
I had the same issue while converting a Silverlight RIA Business app of mine to use Prism, Unity, and MVVM light toolkit. I came up with this workaround which is to just let the App.xaml create an instance of my ViewModelLocator class and during the application startup event I remove that instance it created from the application resources and re-add an instance using Unity container's Resolve method.

Register the VML with Unity.

Boostrapper.cs: (UnityBootstrapper class)

```<code>protected override void ConfigureContainer()
{
    Container.RegisterType<ViewModelLocator>(new ContainerControlledLifetimeManager());
    base.ConfigureContainer();
}
</code>```

Use either constructor or property injection in the VML for IUnityContainer. Here I'm using property injection. Also note that the default parameterless constructor is required because App.xaml is going to instantiate its own instance that we'll just wind up throwing away.

ViewModelLocator.cs: (used for blendability)

```<code>public class ViewModelLocator
{
    [Dependency]
    public IUnityContainer Container { get; set; }

    public ViewModelLocator() { }

....
</code>```

}

Remove and re-add the VML to the application resources. Replace the string literal "Locator" with whatever you called your VML in the App.xaml ResourceDictionary section.

App.xaml.cs:

```<code>private void Application_Startup(object sender, StartupEventArgs e)
{
    Bootstrapper bootstrapper = new Bootstrapper();
    bootstrapper.Run();

    Resources.Remove("Locator");
    Resources.Add("Locator", bootstrapper.Container.Resolve<ViewModelLocator>());
}
</code>```

Your now cocked, locked, and ready to rock..

Body:
I have a ViewModelLocator class that I am defining in app.xaml which is used by my views to databind to the correct ViewModel.

DataContext="{Binding HomeViewModel, Source={StaticResource Locator}}"

I am using Prism and Unity and my ViewModelLocator class needs a reference to an application level unity container.

I wanted inject the IUnityContainer into the ctor of the ViewModelLocator but the ViewModelLocator gets instanciated from app.xaml using a parameterless ctor.

Is there a preferred way to get access to an application level container - for all other classes in the app I just use ctor injection to get the global container.

What I am currenlty doing for the ViewModelLocator is defining a static variable in my BootStrapper class to store the container. I create the container by overriding the CreateContainer method on UnityBootStrapper.

protected override IUnityContainer CreateContainer()
{
    BootStrapper.DIContainer = base.CreateContainer();
    return BootStrapper.DIContainer;
}

Then in the ViewModelLocator class I just reference the BootStrapper.DIContainer property to register my viewmodels

BootStrapper.DIContainer.RegisterType<IShellViewModel, DesignShellViewModel>();

This works fine but it is the only place in the application that needs to reference this static property on the bootstrapper  - and would like to get rid of it if possible.

thanks
Michael

Body:
I had the same issue while converting a Silverlight RIA Business app of mine to use Prism, Unity, and MVVM light toolkit. I came up with this workaround which is to just let the App.xaml create an instance of my ViewModelLocator class and during the application startup event I remove that instance it created from the application resources and re-add an instance using Unity container's Resolve method.

Register the VML with Unity.

Boostrapper.cs: (UnityBootstrapper class)

protected override void ConfigureContainer()
{
    Container.RegisterType<ViewModelLocator>(new ContainerControlledLifetimeManager());
    base.ConfigureContainer();
}

Use either constructor or property injection in the VML for IUnityContainer. Here I'm using property injection. Also note that the default parameterless constructor is required because App.xaml is going to instantiate its own instance that we'll just wind up throwing away.

ViewModelLocator.cs: (used for blendability)

public class ViewModelLocator
{
    [Dependency]
    public IUnityContainer Container { get; set; }

    public ViewModelLocator() { }

....

}

Remove and re-add the VML to the application resources. Replace the string literal "Locator" with whatever you called your VML in the App.xaml ResourceDictionary section.

App.xaml.cs:

private void Application_Startup(object sender, StartupEventArgs e)
{
    Bootstrapper bootstrapper = new Bootstrapper();
    bootstrapper.Run();

    Resources.Remove("Locator");
    Resources.Add("Locator", bootstrapper.Container.Resolve<ViewModelLocator>());
}

Your now cocked, locked, and ready to rock..


问:
Batch Script: Export last git commit message to a variable
I'm trying to assign the last commit message inside a git repository to a variable in a windows batch script and then export the variable. From a lot of questions from StackOverflow, it seems that the command should be:

```<code>for /f "Tokens=2" %a in ('git log -1 --pretty=%B') do @set commit_message=%a

export %commit_message%
</code>```

But it's giving the following error.

```<code>fatal: ambiguous argument '%B': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
</code>```

In Linux it is quite straight forward. Only export commit_message=$(git log -1 --pretty=%B).

答:
It looks like you can't parse the git command directly. This worked on my site:

```<code>@echo off
git log -1 --pretty=%%B > %temp%\git.txt
for /f "Tokens=*" %%a in (%temp%\git.txt) do @set commit_message=%%a

echo %commit_message%
::export %commit_message%
</code>```

Note the doubled '%'. I'm not sure about that export command. I've never seen this. Maybe setx is what you need?

Body:
I'm trying to assign the last commit message inside a git repository to a variable in a windows batch script and then export the variable. From a lot of questions from StackOverflow, it seems that the command should be:

for /f "Tokens=2" %a in ('git log -1 --pretty=%B') do @set commit_message=%a

export %commit_message%

But it's giving the following error.

fatal: ambiguous argument '%B': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

In Linux it is quite straight forward. Only export commit_message=$(git log -1 --pretty=%B).

Body:
It looks like you can't parse the git command directly. This worked on my site:

@echo off
git log -1 --pretty=%%B > %temp%\git.txt
for /f "Tokens=*" %%a in (%temp%\git.txt) do @set commit_message=%%a

echo %commit_message%
::export %commit_message%

Note the doubled '%'. I'm not sure about that export command. I've never seen this. Maybe setx is what you need?


问:
Get coordinates from photo with JavaScript
I was following this thread Get coordinates from photo with JavaScript to obtain the latitud and longitud from a picture (I checked the picture and has the properties), I'm trying to get with javascript using:

$(function(){

  $("#file-input").on("change", function(e) {
            EXIF.getData(e.target.files[0], function() {

                var result = EXIF.pretty(this);
                $("#span").text(result);
            });
        });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://raw.githubusercontent.com/exif-js/exif-js/master/exif.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<input type="file" id="file-input" />
<span id="span">Here</span></code>```

But it's always returnig as GPSLatitude and LGPSLongitud: [3 values] but I can't access to those properties.

答: Also, make sure the image is fully loaded before trying to read the EXIF header. The EXIF-JS docs warn about it in greater detail, with specific warnings about jQuery.</p>

Body:
I was following this thread Get coordinates from photo with JavaScript to obtain the latitud and longitud from a picture (I checked the picture and has the properties), I'm trying to get with javascript using:

$(function(){

  $("#file-input").on("change", function(e) {
            EXIF.getData(e.target.files[0], function() {

                var result = EXIF.pretty(this);
                $("#span").text(result);
            });
        });

});

<input type="file" id="file-input" />
Here

But it's always returnig as GPSLatitude and LGPSLongitud: [3 values] but I can't access to those properties.


问:
Where to save repeated value (MVC)
In my Spring MVC project i have the following jsp forms

```<code>1)Login
2)View with all groups
3) Clicking to group you will be redirected to student list of this group
4)In student view I can add new student to group
</code>```

My quetion is: after clicking on group i pass group id to controller and save group id in the Model

```<code>@RequestMapping(method = RequestMethod.GET)
    public String getStudents(@SessionAttribute("admin") final Admins admin,
            @RequestParam(name = "id") final int groupId,
            final Model model) {
        final List<Students> students = studentService.getStudentsByGroupid(groupId);
        model.addAttribute("students", students);
        model.addAttribute("groupId", groupId);
        return "students";
    }
</code>```

When you want to save new user i pass group id as hidden parameter to controller

```<code>@RequestMapping(value = "doCreate", method = RequestMethod.POST)
    public String createStudent(@Valid @ModelAttribute("studentData") final Students student,
            final BindingResult bindingResult,
            @RequestParam("groupId") final int groupId,
            Model model) {
        model.addAttribute("groupId", groupId);
        if (bindingResult.hasErrors()) {
            model.addAttribute("message", bindingResult.getFieldError().getDefaultMessage());
            return "create_student";
        }
        final Groups group = groupService.getById(groupId);
        student.setGroupId(group);
        final boolean isSavedSeccessfully = studentService.save(student);
        if (!isSavedSeccessfully) {
            model.addAttribute("message", "No unique login");
            return "create_student";
        }
        return getStudents(admin, groupId, model);
    }
</code>```

But in this case i should to pass group id to each controller that related to student CRUD and in controller save group id in model. How to avoid code dulication in this case? I think about saving group id in session , but as i know, session attributes should be related to user info only

答:
Set a session variable and store your object inside it. Use the annotation

```<code>@SessionAttributes("name")
</code>```

It is fine if you store it in session.

Title: Where to save repeated value (MVC)

Body:
In my Spring MVC project i have the following jsp forms

1)Login
2)View with all groups
3) Clicking to group you will be redirected to student list of this group
4)In student view I can add new student to group

My quetion is: after clicking on group i pass group id to controller and save group id in the Model

@RequestMapping(method = RequestMethod.GET)
    public String getStudents(@SessionAttribute("admin") final Admins admin,
            @RequestParam(name = "id") final int groupId,
            final Model model) {
        final List<Students> students = studentService.getStudentsByGroupid(groupId);
        model.addAttribute("students", students);
        model.addAttribute("groupId", groupId);
        return "students";
    }

When you want to save new user i pass group id as hidden parameter to controller

@RequestMapping(value = "doCreate", method = RequestMethod.POST)
    public String createStudent(@Valid @ModelAttribute("studentData") final Students student,
            final BindingResult bindingResult,
            @RequestParam("groupId") final int groupId,
            Model model) {
        model.addAttribute("groupId", groupId);
        if (bindingResult.hasErrors()) {
            model.addAttribute("message", bindingResult.getFieldError().getDefaultMessage());
            return "create_student";
        }
        final Groups group = groupService.getById(groupId);
        student.setGroupId(group);
        final boolean isSavedSeccessfully = studentService.save(student);
        if (!isSavedSeccessfully) {
            model.addAttribute("message", "No unique login");
            return "create_student";
        }
        return getStudents(admin, groupId, model);
    }

But in this case i should to pass group id to each controller that related to student CRUD and in controller save group id in model. How to avoid code dulication in this case? I think about saving group id in session , but as i know, session attributes should be related to user info only

Body:
Set a session variable and store your object inside it. Use the annotation

@SessionAttributes("name")

It is fine if you store it in session.


问:
(Background-color) switch isn't working
I'm using the following code to turn the color of a guitar string first to red on the first click, then lightblue on the second click, and so on back and fourth between the two colors. The string turns red on the first click, but remains red with following clicks and I don't understand why.

```<code>var string = document.getElementById("a-string");
if (string.backgroundColor !== "red") {
  string.style.backgroundColor = "red";
} else {
  string.style.backgroundColor = "lightblue";
}
</code>```

Cam anyone see why this shouldn't work as I expect?

答:
your code has few error. An error is string.backgroundColor !== "red". It should be string.style.backgroundColor !== "red"

```<code>var string = document.getElementById("a-string");
if (string.style.backgroundColor !== "red")  {
  string.style.backgroundColor = "red";
}
else {
  string.style.backgroundColor = "lightblue";
}
</code>```

Title: (Background-color) switch isn't working

Body:
I'm using the following code to turn the color of a guitar string first to red on the first click, then lightblue on the second click, and so on back and fourth between the two colors. The string turns red on the first click, but remains red with following clicks and I don't understand why.

var string = document.getElementById("a-string");
if (string.backgroundColor !== "red") {
  string.style.backgroundColor = "red";
} else {
  string.style.backgroundColor = "lightblue";
}

Cam anyone see why this shouldn't work as I expect?

Body:
your code has few error. An error is string.backgroundColor !== "red". It should be string.style.backgroundColor !== "red"

var string = document.getElementById("a-string");
if (string.style.backgroundColor !== "red")  {
  string.style.backgroundColor = "red";
}
else {
  string.style.backgroundColor = "lightblue";
}