问:
Porting permutation function from Python to C++
I've been using an algorithm from a Stack Overflow answer: https://stackoverflow.com/a/9650593/4771889
Namely the permute2() function.

I've changed things a little for my purposes, and it generates the correct data that I need.

Here is my Python version:

```<code>def permute(list, nextFixable, num, begin, end):
    if end == begin + 1:
        yield list
    else:
        for i in range(begin, end):
            if nextFixable[list[i]] == num[i]:
                nextFixable[list[i]] += 1
                num[begin], num[i] = num[i], num[begin]
                list[begin], list[i] = list[i], list[begin]
                for p in permute(list, nextFixable, num, begin + 1, end):
                    yield p
                list[begin], list[i] = list[i], list[begin]
                num[begin], num[i] = num[i], num[begin]
                nextFixable[list[i]] -= 1

if __name__ == "__main__":
    list = [0, 1, 2]
    nextFixable = {0:0, 1:0, 2:0}
    num = [0, 0, 0]

    for p in permute(list, nextFixable, num, 0, len(list)):
        print(p)
</code>```

I've simplified the usage a little there to give a basic example.

The output of this example is:

```<code>[0, 1, 2]
[0, 2, 1]
[1, 0, 2]
[1, 2, 0]
[2, 1, 0]
[2, 0, 1]
</code>```

Since my practical usage for this is for longer lists (not the trivial "0, 1, 2") I REALLY like the generator functionality used here (the yield statements).

The problem is that Python is slow, and I sometimes have to wait a couple days to get a result.

I'm not a C++ expert, but previously I've found that C++ is much faster when compared with Python.  So you can guess what I did next - I tried to rewrite this in C++ (Visual Studio 2015).

Here's what I came up with:

```<code>#include "stdafx.h"

#include <iostream> // for std::cout
#include <vector> // for std::vector
#include <map> // for std::map

// https://blogs.msdn.microsoft.com/vcblog/2014/11/12/resumable-functions-in-c/
#include <experimental/generator>
using namespace std::experimental;
using namespace std;

using std::cout;
using std::vector;
using std::map;

void print(vector<unsigned short> data) {
    cout << "[";
    for (unsigned short i = 0; i < data.size(); ++i) {
        cout << (int)data[i];
        if (i < data.size() - 1) {
            cout << ", ";
        }
    }
    cout << "]\n";
}

generator<vector<unsigned short>> permute(
    vector<unsigned short> list,
    map<unsigned short, unsigned short> nextFixable,
    vector<unsigned short> num,
    unsigned short begin,
    unsigned short end
) {
    if (end == begin + 1) {
        __yield_value list;
    }
    else {
        for (unsigned short i = begin; i < end; ++i) {
            if (nextFixable[list[i]] == num[i]) {
                nextFixable[list[i]]++;
                swap(num[begin], num[i]);
                swap(list[begin], list[i]);
                for (auto p : permute(list, nextFixable, num, begin + 1, end)) {
                    __yield_value p;
                    swap(list[begin], list[i]);
                    swap(num[begin], num[i]);
                    nextFixable[list[i]]--;
                }
            }
        }
    }
}

int main()
{
    vector<unsigned short> list = { 0, 1, 2 };
    map<unsigned short, unsigned short> nextFixable = { {0, 0}, {1, 0}, {2, 0} };
    vector<unsigned short> num = { 0, 0, 0 };

    for (auto p : permute(list, nextFixable, num, 0, (unsigned short)list.size())) {
        print(p);
    }

    // Keep output window open.
    std::getchar();
    return 0;
}
</code>```

You can see I've referenced https://blogs.msdn.microsoft.com/vcblog/2014/11/12/resumable-functions-in-c/
which is what gives me the __yield_value feature.   (I presume this isn't portable, which is indeed going to be a problem for me eventually as I would prefer to run this in linux down the track, but for some early experiments it does the trick.)

The code runs fine, but the output is:

```<code>[0, 1, 2]
[0, 2, 1]
[1, 2, 0]
[2, 1, 0]
</code>```

So let's compare to the Python output - it seems we have two lines missing:

```<code>[0, 1, 2] - Yes
[0, 2, 1] - Yes
[1, 0, 2] - Missing
[1, 2, 0] - Yes
[2, 1, 0] - Yes
[2, 0, 1] - Missing
</code>```

Usually at this point of writing a SO question, the answer jumps out at me from having to explain the problem.  In this case it hasn't.

It's possible I've made an incorrect language assumption, and I don't have the knowledge to correct myself.

So to boil the question down - why is my port of the permute() function from Python to C++ not giving me the same output?

答:
I would structure it something like this (c++14):

```<code>#include <iostream>
#include <algorithm>
#include <vector>

// version which mutates the vector
template<class Vec, class F>
auto permute_over_inplace(Vec& vec, F&& f)
{
    auto first = std::begin(vec);
    auto last = std::end(vec);

    // permutation reequires sorted ranges
    if (not std::is_sorted(first, last)) {
        std::sort(first, last);
    }

    // remove duplicates
    last = vec.erase(std::unique(first, last), last);

    // call the functor for each permutation
    do {
        f(vec);
    } while (std::next_permutation(first, last));
};

// version which does not mutate the vector
template<class Vec, class F>
auto permute_over_copy(Vec vec, F&& f)
{
    return permute_over_inplace(vec, std::forward<F>(f));
};

int main()
{
    std::vector<int> list = {0, 1, 2};

    // an operation to perform on each permutation
    auto print_list = [](auto&& c)
    {
        const char* sep = " ";
        auto& os = std::cout;

        os << "[";
        for(auto&& item : c) {
            os << sep << item;
            sep = ", ";
        }
        os << " ]";
        os << "\n";
    };

    permute_over_copy(list, print_list);

    list = { 9, 8, 7, 9, 6 };
    permute_over_inplace(list, print_list);
}
</code>```

expected output:

```<code>[ 0, 1, 2 ]
[ 0, 2, 1 ]
[ 1, 0, 2 ]
[ 1, 2, 0 ]
[ 2, 0, 1 ]
[ 2, 1, 0 ]

[ 6, 7, 8, 9 ]
[ 6, 7, 9, 8 ]
[ 6, 8, 7, 9 ]
[ 6, 8, 9, 7 ]
[ 6, 9, 7, 8 ]
[ 6, 9, 8, 7 ]
[ 7, 6, 8, 9 ]
[ 7, 6, 9, 8 ]
[ 7, 8, 6, 9 ]
[ 7, 8, 9, 6 ]
[ 7, 9, 6, 8 ]
[ 7, 9, 8, 6 ]
[ 8, 6, 7, 9 ]
[ 8, 6, 9, 7 ]
[ 8, 7, 6, 9 ]
[ 8, 7, 9, 6 ]
[ 8, 9, 6, 7 ]
[ 8, 9, 7, 6 ]
[ 9, 6, 7, 8 ]
[ 9, 6, 8, 7 ]
[ 9, 7, 6, 8 ]
[ 9, 7, 8, 6 ]
[ 9, 8, 6, 7 ]
[ 9, 8, 7, 6 ]
</code>```

Body:
I've been using an algorithm from a Stack Overflow answer: https://stackoverflow.com/a/9650593/4771889
Namely the permute2() function.

I've changed things a little for my purposes, and it generates the correct data that I need.

Here is my Python version:

def permute(list, nextFixable, num, begin, end):
    if end == begin + 1:
        yield list
    else:
        for i in range(begin, end):
            if nextFixable[list[i]] == num[i]:
                nextFixable[list[i]] += 1
                num[begin], num[i] = num[i], num[begin]
                list[begin], list[i] = list[i], list[begin]
                for p in permute(list, nextFixable, num, begin + 1, end):
                    yield p
                list[begin], list[i] = list[i], list[begin]
                num[begin], num[i] = num[i], num[begin]
                nextFixable[list[i]] -= 1

if __name__ == "__main__":
    list = [0, 1, 2]
    nextFixable = {0:0, 1:0, 2:0}
    num = [0, 0, 0]

    for p in permute(list, nextFixable, num, 0, len(list)):
        print(p)

I've simplified the usage a little there to give a basic example.

The output of this example is:

[0, 1, 2]
[0, 2, 1]
[1, 0, 2]
[1, 2, 0]
[2, 1, 0]
[2, 0, 1]

Since my practical usage for this is for longer lists (not the trivial "0, 1, 2") I REALLY like the generator functionality used here (the yield statements).

The problem is that Python is slow, and I sometimes have to wait a couple days to get a result.

I'm not a C++ expert, but previously I've found that C++ is much faster when compared with Python.  So you can guess what I did next - I tried to rewrite this in C++ (Visual Studio 2015).

Here's what I came up with:

#include "stdafx.h"

#include <iostream> // for std::cout
#include <vector> // for std::vector
#include <map> // for std::map

// https://blogs.msdn.microsoft.com/vcblog/2014/11/12/resumable-functions-in-c/
#include <experimental/generator>
using namespace std::experimental;
using namespace std;

using std::cout;
using std::vector;
using std::map;

void print(vector<unsigned short> data) {
    cout << "[";
    for (unsigned short i = 0; i < data.size(); ++i) {
        cout << (int)data[i];
        if (i < data.size() - 1) {
            cout << ", ";
        }
    }
    cout << "]\n";
}

generator<vector<unsigned short>> permute(
    vector<unsigned short> list,
    map<unsigned short, unsigned short> nextFixable,
    vector<unsigned short> num,
    unsigned short begin,
    unsigned short end
) {
    if (end == begin + 1) {
        __yield_value list;
    }
    else {
        for (unsigned short i = begin; i < end; ++i) {
            if (nextFixable[list[i]] == num[i]) {
                nextFixable[list[i]]++;
                swap(num[begin], num[i]);
                swap(list[begin], list[i]);
                for (auto p : permute(list, nextFixable, num, begin + 1, end)) {
                    __yield_value p;
                    swap(list[begin], list[i]);
                    swap(num[begin], num[i]);
                    nextFixable[list[i]]--;
                }
            }
        }
    }
}

int main()
{
    vector<unsigned short> list = { 0, 1, 2 };
    map<unsigned short, unsigned short> nextFixable = { {0, 0}, {1, 0}, {2, 0} };
    vector<unsigned short> num = { 0, 0, 0 };

    for (auto p : permute(list, nextFixable, num, 0, (unsigned short)list.size())) {
        print(p);
    }

    // Keep output window open.
    std::getchar();
    return 0;
}

You can see I've referenced https://blogs.msdn.microsoft.com/vcblog/2014/11/12/resumable-functions-in-c/
which is what gives me the __yield_value feature.   (I presume this isn't portable, which is indeed going to be a problem for me eventually as I would prefer to run this in linux down the track, but for some early experiments it does the trick.)

The code runs fine, but the output is:

[0, 1, 2]
[0, 2, 1]
[1, 2, 0]
[2, 1, 0]

So let's compare to the Python output - it seems we have two lines missing:

[0, 1, 2] - Yes
[0, 2, 1] - Yes
[1, 0, 2] - Missing
[1, 2, 0] - Yes
[2, 1, 0] - Yes
[2, 0, 1] - Missing

Usually at this point of writing a SO question, the answer jumps out at me from having to explain the problem.  In this case it hasn't.

It's possible I've made an incorrect language assumption, and I don't have the knowledge to correct myself.

So to boil the question down - why is my port of the permute() function from Python to C++ not giving me the same output?

Body:
I would structure it something like this (c++14):

#include <iostream>
#include <algorithm>
#include <vector>

// version which mutates the vector
template<class Vec, class F>
auto permute_over_inplace(Vec& vec, F&& f)
{
    auto first = std::begin(vec);
    auto last = std::end(vec);

    // permutation reequires sorted ranges
    if (not std::is_sorted(first, last)) {
        std::sort(first, last);
    }

    // remove duplicates
    last = vec.erase(std::unique(first, last), last);

    // call the functor for each permutation
    do {
        f(vec);
    } while (std::next_permutation(first, last));
};

// version which does not mutate the vector
template<class Vec, class F>
auto permute_over_copy(Vec vec, F&& f)
{
    return permute_over_inplace(vec, std::forward<F>(f));
};

int main()
{
    std::vector<int> list = {0, 1, 2};

    // an operation to perform on each permutation
    auto print_list = [](auto&& c)
    {
        const char* sep = " ";
        auto& os = std::cout;

        os << "[";
        for(auto&& item : c) {
            os << sep << item;
            sep = ", ";
        }
        os << " ]";
        os << "\n";
    };

    permute_over_copy(list, print_list);

    list = { 9, 8, 7, 9, 6 };
    permute_over_inplace(list, print_list);
}

expected output:

[ 0, 1, 2 ]
[ 0, 2, 1 ]
[ 1, 0, 2 ]
[ 1, 2, 0 ]
[ 2, 0, 1 ]
[ 2, 1, 0 ]

[ 6, 7, 8, 9 ]
[ 6, 7, 9, 8 ]
[ 6, 8, 7, 9 ]
[ 6, 8, 9, 7 ]
[ 6, 9, 7, 8 ]
[ 6, 9, 8, 7 ]
[ 7, 6, 8, 9 ]
[ 7, 6, 9, 8 ]
[ 7, 8, 6, 9 ]
[ 7, 8, 9, 6 ]
[ 7, 9, 6, 8 ]
[ 7, 9, 8, 6 ]
[ 8, 6, 7, 9 ]
[ 8, 6, 9, 7 ]
[ 8, 7, 6, 9 ]
[ 8, 7, 9, 6 ]
[ 8, 9, 6, 7 ]
[ 8, 9, 7, 6 ]
[ 9, 6, 7, 8 ]
[ 9, 6, 8, 7 ]
[ 9, 7, 6, 8 ]
[ 9, 7, 8, 6 ]
[ 9, 8, 6, 7 ]
[ 9, 8, 7, 6 ]


来源: stackexchange

问:
how to raise an event from another one
I have two panels, and when the first panel is scrolled, I want the other one to be scrolled, How do I do that?

thanks in advance :).

答:
You can listen for ScrollableControl.Scroll to find out when it's scrolling.

Unfortunately I don't know of any easy way to make the other one scroll to the correct location, but I think you should be able to do it by sending WM_VSCROLL or WM_HSCROLL to it using the SendMessage API function.

Depending on the contents of the panels you might also be able to "cheat" by setting AutoScroll to true and then whenever the first panel is scrolled, you set focus to a suitable control in the second panel that is outside the currently visible area and so make it scroll to there. But I'm not sure how well this would work or if it would be easier than doing it properly (if you always want to scroll to the extreme sides of the panel, it might be useful).

ContentLicense: CC BY-SA 2.5

Title: how to raise an event from another one


问:
Custom broadcast receiver block notification to display on Android - IBM mobilefirst
I wanted to detect when notification  arrived in the application. From the documentation, we can't use native android API for notification on Hyrbide application.
I followed this guide
 to detect when notification arrived then send data to javascript part : https://www.ibm.com/support/knowledgecenter/SSZH4A_6.2.0/com.ibm.worklight.dev.doc/devref/c_push_notifications_hybrid.html

The problem is the notification is well received by the broadcast receiver but it is not displayed. Here is the code of the broadcastreceiver :

```<code> @Override
protected void onStart() {
    super.onStart();
    String action = getPackageName() + "." + getString(R.string.app_name) + ".C2DM_MESSAGE";
    //Register Custom Push Broadcast Receiver
    registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
                Log.d("test", "action :" + intent.getAction());
                Log.d("test", "notification received)
                abortBroadcast();
        }
    }, new IntentFilter(action));
}
</code>```

答:
I solved the issue by not using registerReceiver but using a custom class :

```<code>public class MyNotificationReceiver  extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if(action.equals("com.google.android.c2dm.intent.RECEIVE")){
        JSONObject data = new JSONObject();
        try {
            data.put("notifReceived",  true);
            Log.d("test", "is the notif background ? ");
            WL.getInstance().sendActionToJS("androidNotif", data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
</code>```

And in your manifest add :

```<code><receiver android:name=".MyNotificationReceiver" android:enabled="true">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
            <category android:name="com.your.appname"/>
        </intent-filter>
</receiver>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I wanted to detect when notification  arrived in the application. From the documentation, we can't use native android API for notification on Hyrbide application.
I followed this guide
 to detect when notification arrived then send data to javascript part : https://www.ibm.com/support/knowledgecenter/SSZH4A_6.2.0/com.ibm.worklight.dev.doc/devref/c_push_notifications_hybrid.html

The problem is the notification is well received by the broadcast receiver but it is not displayed. Here is the code of the broadcastreceiver :

 @Override
protected void onStart() {
    super.onStart();
    String action = getPackageName() + "." + getString(R.string.app_name) + ".C2DM_MESSAGE";
    //Register Custom Push Broadcast Receiver
    registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
                Log.d("test", "action :" + intent.getAction());
                Log.d("test", "notification received)
                abortBroadcast();
        }
    }, new IntentFilter(action));
}

Body:
I solved the issue by not using registerReceiver but using a custom class :

public class MyNotificationReceiver  extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if(action.equals("com.google.android.c2dm.intent.RECEIVE")){
        JSONObject data = new JSONObject();
        try {
            data.put("notifReceived",  true);
            Log.d("test", "is the notif background ? ");
            WL.getInstance().sendActionToJS("androidNotif", data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

And in your manifest add :

<receiver android:name=".MyNotificationReceiver" android:enabled="true">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE"/>
            <category android:name="com.your.appname"/>
        </intent-filter>
</receiver>


问:
How do I show a different Required message to instances of the same object in MVC3?
I have a Razor MVC3 project which has two user records in a form, one for the key contact and one for a backup contact. For example;

```<code>public class User
{
    [Required(ErrorMessage = "First name is required")]
    public string FirstName { get; set; }
}
</code>```

Validation all works well except for the small issue where the user fails to fill out a field, it says 'First name is required' but I'd like to point the user to which one of the first name fields is missing. Such as 'Backup contact first name is required' or 'Key contact first name is required'.

Ideally I'd like to leave the [Required] annotation on the class as it is used elsewhere.

This seems like one of those small cases that might have been missed and is not easily achieved, but please prove me wrong.

Ryan

答:
```<code>[Required(ErrorMessage = "{0} is required")]
</code>```

{0}=The DisplayName is automatically placed on it

sample

```<code>[DisplayName("Amount per square meter")]
[Required(ErrorMessage = "{0} is required")]
public int PriceMeter { get; set; }
</code>```

output

Amount per square meter  is required

Body:
I have a Razor MVC3 project which has two user records in a form, one for the key contact and one for a backup contact. For example;

public class User
{
    [Required(ErrorMessage = "First name is required")]
    public string FirstName { get; set; }
}

Validation all works well except for the small issue where the user fails to fill out a field, it says 'First name is required' but I'd like to point the user to which one of the first name fields is missing. Such as 'Backup contact first name is required' or 'Key contact first name is required'.

Ideally I'd like to leave the [Required] annotation on the class as it is used elsewhere.

This seems like one of those small cases that might have been missed and is not easily achieved, but please prove me wrong.

Ryan

Body:
[Required(ErrorMessage = "{0} is required")]

{0}=The DisplayName is automatically placed on it

sample

[DisplayName("Amount per square meter")]
[Required(ErrorMessage = "{0} is required")]
public int PriceMeter { get; set; }

output

Amount per square meter  is required


问:
is it possible to close android/ios application webview using java script?
Basically i am opening a web page in Chat bot which is configured over Line messaging application for signup on auth server and after completing signup i tried to close web view using java script but not able to do this below is my code snippet for closing.</p>

```<code><!DOCTYPE html>
<html>
    <head>
      <script>
        function close(){
         window.close();
        }
      </script>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>Test Webview Closing</title>
    </head>
    <body>
         <input type="button" value="test" onclick="close()">
    </body>
</html>
</code>```

答:
Try this.

```<code>WebChromeClient webClient = new WebChromeClient(){

public void onCloseWindow(Window w){
    super.onCloseWindow(w);
    Log.d(TAG, "Window close");
 }
};
</code>```

add webView.setWebChromeClient(webClient); in your application web view code.

Body:
Basically i am opening a web page in Chat bot which is configured over Line messaging application for signup on auth server and after completing signup i tried to close web view using java script but not able to do this below is my code snippet for closing.

<!DOCTYPE html>

      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>Test Webview Closing</title>

         <input type="button" value="test" onclick="close()">

Body:
Try this.

WebChromeClient webClient = new WebChromeClient(){

public void onCloseWindow(Window w){
    super.onCloseWindow(w);
    Log.d(TAG, "Window close");
 }
};

add webView.setWebChromeClient(webClient); in your application web view code.


问:
INT to decimal JavaScript
I'm looking for method to achieve the following:

```<code>var exampleIntOne = 170;
var exampleIntTwo = 1700;
var exampleIntThree = 17000;
var exampleIntFour = 170000;
</code>```

I would like to be able to convert the above to the following expected result:

```<code>1.70
17.00
170.00
1700.00
</code>```

I have tried: exampleIntOne.toFixed(2); but this turns that example into: 170.00

答:
You can do this

function parseDecimal(numberVal){
   return (numberVal / 100).toFixed(2);
}

var exampleIntOne = 170
console.log(parseDecimal(exampleIntOne));
var exampleIntTwo = 1700
console.log(parseDecimal(exampleIntTwo));
var exampleIntThree = 17000
console.log(parseDecimal(exampleIntThree));
var exampleIntFour = 170000
console.log(parseDecimal(exampleIntFour));```

Where parseDecimal() is your common method to get the desired output format.

Title: INT to decimal JavaScript

Body:
I'm looking for method to achieve the following:

var exampleIntOne = 170;
var exampleIntTwo = 1700;
var exampleIntThree = 17000;
var exampleIntFour = 170000;

I would like to be able to convert the above to the following expected result:

1.70
17.00
170.00
1700.00

I have tried: exampleIntOne.toFixed(2); but this turns that example into: 170.00

Body:
You can do this

function parseDecimal(numberVal){
   return (numberVal / 100).toFixed(2);
}

var exampleIntOne = 170
console.log(parseDecimal(exampleIntOne));
var exampleIntTwo = 1700
console.log(parseDecimal(exampleIntTwo));
var exampleIntThree = 17000
console.log(parseDecimal(exampleIntThree));
var exampleIntFour = 170000
console.log(parseDecimal(exampleIntFour));

Where parseDecimal() is your common method to get the desired output format.


问:
Best way to represent a readline loop in Scala?
Coming from a C/C++ background, I'm not very familiar with the functional style of programming so all my code tends to be very imperative, as in most cases I just can't see a better way of doing it.

I'm just wondering if there is a way of making this block of Scala code more "functional"?

```<code>var line:String = "";
var lines:String = "";

do {
    line = reader.readLine();
    lines += line;
} while (line != null)
</code>```

答:
To add how the same can be achieved using the formerly new nio files which I vote to use because it has several advantages:

```<code>val path: Path = Paths.get("foo.txt")
val lines = Source.fromInputStream(Files.newInputStream(path)).getLines()

// Now we can iterate the file or do anything we want,
// e.g. using functional operations such as map. Or simply concatenate.
val result = lines.mkString
</code>```

Don't forget to close the stream afterwards.

Body:
Coming from a C/C++ background, I'm not very familiar with the functional style of programming so all my code tends to be very imperative, as in most cases I just can't see a better way of doing it.

I'm just wondering if there is a way of making this block of Scala code more "functional"?

var line:String = "";
var lines:String = "";

do {
    line = reader.readLine();
    lines += line;
} while (line != null)

Body:
To add how the same can be achieved using the formerly new nio files which I vote to use because it has several advantages:

val path: Path = Paths.get("foo.txt")
val lines = Source.fromInputStream(Files.newInputStream(path)).getLines()

// Now we can iterate the file or do anything we want,
// e.g. using functional operations such as map. Or simply concatenate.
val result = lines.mkString

Don't forget to close the stream afterwards.

ContentLicense: CC BY-SA 4.0


问:
Gem::Ext::BuildError: ERROR: Failed to build gem native extension for rails version 4.2.6
I have created new rails app and try to run bundle install it shows this error,

```<code>Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
current directory: /var/lib/gems/2.3.0/gems/json-1.8.6/ext/json/ext/generator/usr/bin/ruby2.3 -r ./siteconf20170704-11395-12tpg5u.rb extconf.rb
mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h
extconf failed, exit code 1

Gem files will remain installed in /var/lib/gems/2.3.0/gems/json-1.8.6 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/json-1.8.6/gem_make.out

An error occurred while installing json (1.8.6), and Bundler cannot continue.
Make sure that `gem install json -v '1.8.6'` succeeds before bundling
</code>```

Kindly send me some suggestions,Thanks in Advance.

答:
If you have a Mac or Linux machine try the following command:

```<code>sudo apt-get install ruby-dev
</code>```

If that fails, what is your output for:

```<code>gem install json -v '1.8.6'
</code>```

(please copy and paste all the output).

Similar issue

I'm not sure what will fix it for Mac, but people had positive experiences with brew install ruby.

Body:
I have created new rails app and try to run bundle install it shows this error,

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
current directory: /var/lib/gems/2.3.0/gems/json-1.8.6/ext/json/ext/generator/usr/bin/ruby2.3 -r ./siteconf20170704-11395-12tpg5u.rb extconf.rb
mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h
extconf failed, exit code 1

Gem files will remain installed in /var/lib/gems/2.3.0/gems/json-1.8.6 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/json-1.8.6/gem_make.out

An error occurred while installing json (1.8.6), and Bundler cannot continue.
Make sure that `gem install json -v '1.8.6'` succeeds before bundling

Kindly send me some suggestions,Thanks in Advance.

Body:
If you have a Mac or Linux machine try the following command:

sudo apt-get install ruby-dev

If that fails, what is your output for:

gem install json -v '1.8.6'

(please copy and paste all the output).

Similar issue

I'm not sure what will fix it for Mac, but people had positive experiences with brew install ruby.


问:
Twitter share button opens in full window
I have this code https://codepen.io/anon/pen/YQLdLg and I want to give the popup share window the size I want, be smaller and centered. Right now it opens in a full window.

I have tried with onclick="window.open(this.href,width=400,height=250);return false; but couldn't make it to work.

答:
Demo: https://codepen.io/kumarrishikesh12/pen/VWxgbY

Facebook

```<code><a href="https://www.facebook.com/sharer/sharer.php?u=http://www.example.com/" id="facebookurl" name="fb_url" target="_blank" onclick="javascript:window.open(this.href,'', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');return false;">
</code>```

Linkdin

```<code><a href="http://www.linkedin.com/shareArticle?mini=true&url=http://www.example.com/&title=myexample" id="linkedinurl" name="linkedin_url" target="_blank" onclick="javascript:window.open(this.href,'', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');return false;">
</code>```

twitter

```<code><a href="https://twitter.com/intent/tweet?text=Check%20out%20my%20new%20webpage%21&via=example&url=http://www.example.com" id="twitternurl" name="twitter_url" target="_blank" onclick="javascript:window.open(this.href,'', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');return false;">
</code>```

See the Pen Add share popup to links by Rishikesh kumar (@kumarrishikesh12) on CodePen.

```

Body:
Demo: https://codepen.io/kumarrishikesh12/pen/VWxgbY

Facebook

<a href="https://www.facebook.com/sharer/sharer.php?u=http://www.example.com/" id="facebookurl" name="fb_url" target="_blank" onclick="javascript:window.open(this.href,'', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');return false;">

Linkdin

<a href="http://www.linkedin.com/shareArticle?mini=true&url=http://www.example.com/&title=myexample" id="linkedinurl" name="linkedin_url" target="_blank" onclick="javascript:window.open(this.href,'', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');return false;">

twitter

<a href="https://twitter.com/intent/tweet?text=Check%20out%20my%20new%20webpage%21&via=example&url=http://www.example.com" id="twitternurl" name="twitter_url" target="_blank" onclick="javascript:window.open(this.href,'', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');return false;">

<p data-height="265" data-theme-id="0" data-slug-hash="VWxgbY" data-default-tab="js,result" data-user="kumarrishikesh12" data-embed-version="2" data-pen-title="Add share popup to links" class="codepen">See the Pen <a href="https://codepen.io/kumarrishikesh12/pen/VWxgbY/">Add share popup to links</a> by Rishikesh kumar (<a href="https://codepen.io/kumarrishikesh12">@kumarrishikesh12</a>) on <a href="https://codepen.io">CodePen</a>.</p>
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script>


问:
Target most Windows versions for a 2D game?
If one were to code a game for most versions of Windows, which API should be used?

I know DirectDraw works from NT4 and up (although DirectDraw is emulated on NT4 with GDI). However, I am told DirectDraw is deprecated in newer versions of Windows?

I could revert to just GDI, but then it is hard to completely eliminate flicker and tearing, since there is no double buffering with flipping between buffers.

Should I go for Direct3D or DirectDraw? Or is there some way of completely eliminating flicker in GDI?

If Direct3D is the answer, which version of it is supported on most platforms?

答: Unless you are sure you will never want to port your game to any non-Windows platform, I would recommend OpenGL.  It should work on all versions from 2000 upwards, and some lucky NT4 or Win98 users may be able to run it (but don't advertise those versions as "supported.")  Hardware acceleration won't always work, but the impact on performance won't be noticeable for a simple 2D game.  And you will be able to port it reasonably cheaply to other platforms (e.g. iPhone) if necessary.


问:
What would be the Big O notation for this algorithm
Determine whether the string contains at least 1 repeatable character.

(Implying that string can contain only basic ASCII alphabet: 128 characters).

```<code>bool hasRepeatableChar(String str) {
    if (str.length() > 128) {
            return true;
    }
    str = str.sort();
    for (int i = 0; i < str.length()-1; i++) {
        if (str[i] == str[i+1]) {
            return true;
        }
    }
    return false;
}
</code>```

As I can see, it is:

O(n log n) for str.length() <= 128, where n - length of a string

O(1) for str.length() > 128

But what will be an amortized big O value?

P.S.

Instead of sorting it can also be done by using some kind of data structure (map, for example), it will reduce the amount of operations to O(n) but increase memory cost. Anyway, it isn't related to the question.

答:
An amortized analysis of an algorithm should be based on the expected inputs.

In your case - without any prior knowledge about the distribution of the length of expected inputs - there is no much you can say.

In other words - the term "amortized complexity" without assumptions about the inputs doesn't have much meaning for your algorithm.

Body:
Determine whether the string contains at least 1 repeatable character.

(Implying that string can contain only basic ASCII alphabet: 128 characters).

bool hasRepeatableChar(String str) {
    if (str.length() > 128) {
            return true;
    }
    str = str.sort();
    for (int i = 0; i < str.length()-1; i++) {
        if (str[i] == str[i+1]) {
            return true;
        }
    }
    return false;
}

As I can see, it is:

O(n log n) for str.length() <= 128, where n - length of a string

O(1) for str.length() > 128

But what will be an amortized big O value?

P.S.

Instead of sorting it can also be done by using some kind of data structure (map, for example), it will reduce the amount of operations to O(n) but increase memory cost. Anyway, it isn't related to the question.


问:
groupsize vs execution time?
I make a simple program abput a vector adder and want to test the execution time vs the groupsize.
when I change the groupsize from 1024 to 5012 to 256 and to 128. The execution time is very similar. Why? in my view, when I `use smaller groupsizes, we should have more groups and they can work in the cores in parallel which could lead less execution time(for example, if workgroupsize change from 512 to 256, the execution time should reduce half?) but in my experinment in gpu, the execution time is siilar?  is my view wrong?</p>

答: Because number of workitems per group is not a visible bottleneck for vector addition. The global memory performance ise bottleneck. If data comes from host then pci-e performance is also bottleneck.</p>

Title: groupsize vs execution time?


问:
Where is the best place to check for internet connection in MVVM?
I have an apiClass which makes all the network calls
and I was thinking my options are these:

do the check inside the activity/fragment

do the check inside the apiClient class

I'm sure there is a better alternative.

EDIT

This answer suggests my second option. Is there a better approach?

答:
You can add method for internet connection anywhere but as per my understanding,for code/method  method reuse you can create Util class or You can add it into the Application class.
You can also refer below method.</p>

```<code>public static boolean getConnectionStatus(Context context) {
    ConnectivityManager mConnectivityManager;
    NetworkInfo mNetworkInfoMobile, mNetworkInfoWifi;

    mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    mNetworkInfoMobile = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    mNetworkInfoWifi = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    try {
        if (mNetworkInfoMobile.isConnected()) {
            App.connectivityStatus = 1;

            return true;
        }
    } catch (Exception exception) {
        // exception.printStackTrace();
    }

    if (mNetworkInfoWifi.isConnected()) {
        App.connectivityStatus = 1;

        return true;
    } else {
        App.connectivityStatus = 0;
        return false;
    }
}
</code>```

Body:
You can add method for internet connection anywhere but as per my understanding,for code/method  method reuse you can create Util class or You can add it into the Application class.
You can also refer below method.

public static boolean getConnectionStatus(Context context) {
    ConnectivityManager mConnectivityManager;
    NetworkInfo mNetworkInfoMobile, mNetworkInfoWifi;

    mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    mNetworkInfoMobile = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    mNetworkInfoWifi = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    try {
        if (mNetworkInfoMobile.isConnected()) {
            App.connectivityStatus = 1;

            return true;
        }
    } catch (Exception exception) {
        // exception.printStackTrace();
    }

    if (mNetworkInfoWifi.isConnected()) {
        App.connectivityStatus = 1;

        return true;
    } else {
        App.connectivityStatus = 0;
        return false;
    }
}


问:
OrientDB Delete network BigData
I m using orientdb  community version 2.2.20 .
I have import a large dataset of for about 15M edges and 30K vertices
What is the best way to delete a graph is it to delete edges , and then the vertices ? or is there a way to delete the whole graph at once?

Reading the documentation I only  find the DELETE VERTEX, and EDGE commands

答:
It doesn't exist a command that delete the entire graph but you can do :

```<code>DELETE Edge E
DELETE Vertex V
</code>```

It will delete all the Edge and all the Vertex.

Hope it helps.

Title: OrientDB Delete network BigData

Body:
It doesn't exist a command that delete the entire graph but you can do :

DELETE Edge E
DELETE Vertex V

It will delete all the Edge and all the Vertex.

Hope it helps.


问:
CSS HTML animation with input
I'm developing a website and wanted to put an animated search on it ...
I really enjoyed this animation: https://videohive.net/item/search-logo-reveal/19279469?s_rank=149
And I wonder if there's any way I can do it.
My code here: https://jsfiddle.net/4txmdqhx/
With some optimization errors, because I'm still starting.

Thanks!

答:
$('.form-fild input,.form-fild textarea').focus(function() {
    $(this).parent().addClass('open');
});

$('.form-fild input,.form-fild textarea').blur(function() {
    $(this).parent().removeClass('open');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code><style>
.open {
  color:red;
}
.form-fild {
 position: relative;
 margin: 30px 0;
}
.form-fild label {
 position: absolute;
 top: 5px;
 left: 10px;
 padding:5px;
}

.form-fild.open label {
 top: -25px;
 left: 10px;
 /*background: #ffffff;*/
}
.form-fild input[type="text"] {
 padding-left: 80px;
}
.form-fild textarea {
 padding-left: 80px;
}
.form-fild.open textarea,
.form-fild.open input[type="text"] {
 padding-left: 10px;
}
textarea,
input[type="text"] {
 padding: 10px;
 width: 100%;
}
textarea,
input,
.form-fild.open label,
.form-fild label {
 -webkit-transition: all 0.2s ease-in-out;
       -moz-transition: all 0.2s ease-in-out;
         -o-transition: all 0.2s ease-in-out;
            transition: all 0.2s ease-in-out;
}
</style></code>```

     <form>

            Name :
            <input type="text">

            Email :
            <input type="text">

            Number :
            <input type="text">

            Name :
            <input type="text">

            Name :
            <input type="text">

            Message :
            <textarea cols="10" rows="5"></textarea>

    </form>

```

Title: CSS HTML animation with input

Body:
$('.form-fild input,.form-fild textarea').focus(function() {
    $(this).parent().addClass('open');
});

$('.form-fild input,.form-fild textarea').blur(function() {
    $(this).parent().removeClass('open');
});

<style>
.open {
  color:red;
}
.form-fild {
 position: relative;
 margin: 30px 0;
}
.form-fild label {
 position: absolute;
 top: 5px;
 left: 10px;
 padding:5px;
}

.form-fild.open label {
 top: -25px;
 left: 10px;
 /*background: #ffffff;*/
}
.form-fild input[type="text"] {
 padding-left: 80px;
}
.form-fild textarea {
 padding-left: 80px;
}
.form-fild.open textarea,
.form-fild.open input[type="text"] {
 padding-left: 10px;
}
textarea,
input[type="text"] {
 padding: 10px;
 width: 100%;
}
textarea,
input,
.form-fild.open label,
.form-fild label {
 -webkit-transition: all 0.2s ease-in-out;
       -moz-transition: all 0.2s ease-in-out;
         -o-transition: all 0.2s ease-in-out;
            transition: all 0.2s ease-in-out;
}
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
 <div class="row">
     <form>
        <div class="form-fild">
            <label>Name :</label>
            <input type="text">
        </div>
        <div class="form-fild">
            <label>Email :</label>
            <input type="text">
        </div>
        <div class="form-fild">
            <label>Number :</label>
            <input type="text">
        </div>
        <div class="form-fild">
            <label>Name :</label>
            <input type="text">
        </div>
        <div class="form-fild">
            <label>Name :</label>
            <input type="text">
        </div>
        <div class="form-fild">
            <label>Message :</label>
            <textarea cols="10" rows="5"></textarea>
        </div>
    </form>
    </div>
</div>


问:
Boost::Future deferred continuation unwrapping deadlocks
I am using Boost’s promises and futures and encountered an edge case while using continuations. My code uses a continuation that returns a future, and unwraps then()’s result before getting its value.

```<code>#define BOOST_THREAD_VERSION 5

#include <iostream>
#include <boost/thread/future.hpp>

int main(int argc, char* argv[])
{
    boost::promise<int> promise;
    boost::future<int> future = promise.get_future();

    promise.set_value(42);

    int result = future.then(
        boost::launch::async,
        [](boost::future<int> result)
        {
            return boost::make_ready_future(result.get());
        }
    ).unwrap().get();

    std::cout << "Result is: " << result << std::endl;
    return 0;
}
</code>```

In this example, I explicitly used the boost::launch::async policy to launch the continuation in a new thread, and I get the expected result of 42.

However, as soon as I replace that policy with boost::launch::deferred, the program seems to deadlock. What am I doing wrong?

NB: The deferred continuation works correctly as long as I don’t unwrap() its value. The issue is specifically about unwrapped deferred continuations.

答:
I think the future continuation paired with unwrap does not make sense. If you create a future with .then, you will get a valid future. So you can call .get() without blocking. That is why I dont see the need for a nested future. However, the way you wrote it should not cause a deadlock and it is probably a bug.

```<code>#define BOOST_THREAD_VERSION 5

#include <iostream>
#include <boost/thread/future.hpp>

int main(int argc, char* argv[])
{
    boost::promise<int> promise;
    boost::future<int> future = promise.get_future();

    promise.set_value(42);

    int result = future.then(
        boost::launch::deferred,
        [](boost::future<int> result)
        {
            return result.get(); // get is non-blocking, since it is a continuation
        }
    )/*.unwrap()*/.get();

    std::cout << "Result is: " << result << std::endl;
    return 0;
}
</code>```

As of boost 1.64, unwrap is still a experimental function. It would be nice, if you communicate this behaviour to the developer of boost::thread.

Body:
I am using Boost’s promises and futures and encountered an edge case while using continuations. My code uses a continuation that returns a future, and unwraps then()’s result before getting its value.

#define BOOST_THREAD_VERSION 5

#include <iostream>
#include <boost/thread/future.hpp>

int main(int argc, char* argv[])
{
    boost::promise<int> promise;
    boost::future<int> future = promise.get_future();

    promise.set_value(42);

    int result = future.then(
        boost::launch::async,
        [](boost::future<int> result)
        {
            return boost::make_ready_future(result.get());
        }
    ).unwrap().get();

    std::cout << "Result is: " << result << std::endl;
    return 0;
}

In this example, I explicitly used the boost::launch::async policy to launch the continuation in a new thread, and I get the expected result of 42.

However, as soon as I replace that policy with boost::launch::deferred, the program seems to deadlock. What am I doing wrong?

NB: The deferred continuation works correctly as long as I don’t unwrap() its value. The issue is specifically about unwrapped deferred continuations.

Body:
I think the future continuation paired with unwrap does not make sense. If you create a future with .then, you will get a valid future. So you can call .get() without blocking. That is why I dont see the need for a nested future. However, the way you wrote it should not cause a deadlock and it is probably a bug.

#define BOOST_THREAD_VERSION 5

#include <iostream>
#include <boost/thread/future.hpp>

int main(int argc, char* argv[])
{
    boost::promise<int> promise;
    boost::future<int> future = promise.get_future();

    promise.set_value(42);

    int result = future.then(
        boost::launch::deferred,
        [](boost::future<int> result)
        {
            return result.get(); // get is non-blocking, since it is a continuation
        }
    )/*.unwrap()*/.get();

    std::cout << "Result is: " << result << std::endl;
    return 0;
}

As of boost 1.64, unwrap is still a experimental function. It would be nice, if you communicate this behaviour to the developer of boost::thread.


问:
store negative number in char array ( still no requirred/desired solution )
```<code>EDIT:
  platform unix
  type :  ansi c
</code>```

I have data in form ;

```<code>1 2 3 -1 2 -9 1 3 +
-1 2 -3 -4 -
*
</code>```

integer in range between -9 and 9

'+ - *' operator and shows that you should take data which lies at following  line

data is char double pointer

each line must be stored in double pointer char array

```<code>example :   data[0] :=>  1 2 3 -1 2 -9 1 3 +
            more precisely :  data[0][3] must store -1
</code>```

when I take data and store, I could not achieve store -3 ( negative integer ) in data[i][j]
because '-' is a character so 3 is not accepted by data[i][j]

What should I do to handle this problem?

EDIT: MY code ;

```<code>size_t datalen = sizeof( char ) ;

data = ( char ** ) malloc( sizeof (char * ) )
for ( i = 0 ;   ; ++i )
   data[i] = (char * ) malloc ( datalen )
   for ( j = 0 ;  ; ++ j )
         signed char ch;
         if j !=  0
            datalen += 1
            data[i] = ( char * ) realloc ( begin[i], datalen )
         scanf ("%c ", &ch )
         begin[i][j] = ch
         if ch == OP ( op = + , - , * , / )
             break
   if strlen ( begin[i] ) == 1
           break
</code>```

EDIT :
     if you look at ascii table you will be understand why I am not using scanf("%d",&ch)
     http://www.asciitable.com/

答:
I believe the key here is to take advantage of the limited range of your input values.  Since your input numbers will only be single-digit integers, find several impossible input values and reserve them for operators.  For example, you can let 64 be '+', 65 can be '-', etc.  Use strtol() to read in the numbers one at a time, then validate them and make sure they fall in your specified range and cast them down to a char.  If you see an operator without a number attached to it, convert it to the appropriate reserved value (make 'encode_operator' and 'decode_operator' functions for cleaner code) and store it.

The downside to this method is that you cannot blindly use the stored value as a number.  When you extract the data from the array, you will have to check each value to see if it is an operator or a number.  In your case, a simple #IS_OPERATOR(x) ((x < -9) || (x > 9)) macro should be able to do this for you.

Body:
EDIT:
  platform unix
  type :  ansi c

I have data in form ;

1 2 3 -1 2 -9 1 3 +
-1 2 -3 -4 -
*

integer in range between -9 and 9

'+ - *' operator and shows that you should take data which lies at following  line

data is char double pointer

each line must be stored in double pointer char array

example :   data[0] :=>  1 2 3 -1 2 -9 1 3 +
            more precisely :  data[0][3] must store -1

when I take data and store, I could not achieve store -3 ( negative integer ) in data[i][j]
because '-' is a character so 3 is not accepted by data[i][j]

What should I do to handle this problem?

EDIT: MY code ;

size_t datalen = sizeof( char ) ;

data = ( char ** ) malloc( sizeof (char * ) )
for ( i = 0 ;   ; ++i )
   data[i] = (char * ) malloc ( datalen )
   for ( j = 0 ;  ; ++ j )
         signed char ch;
         if j !=  0
            datalen += 1
            data[i] = ( char * ) realloc ( begin[i], datalen )
         scanf ("%c ", &ch )
         begin[i][j] = ch
         if ch == OP ( op = + , - , * , / )
             break
   if strlen ( begin[i] ) == 1
           break

EDIT :
     if you look at ascii table you will be understand why I am not using scanf("%d",&ch)
     http://www.asciitable.com/


问:
Get label of selected AutoHotKey GUI menu item
I want to create small menu for special characters, directly inserting selected character into text.

For example, this small popup menu opens on F9 as a context menu:

```<code>Menu, Ctx1, Add, €, InsertMenuLabel
Menu, Ctx1, Add, ¥, InsertMenuLabel
Menu, Ctx1, Add, ¢, InsertMenuLabel
Menu, Ctx1, Add, £, InsertMenuLabel

F9:
    Menu, Ctx1, Show, %A_GuiX%, %A_GuiY%
    Return
</code>```

How do simply retrieve label of menu item which was selected? In the following code, how can I carry menu item label into %MenuItemLabel%?)

```<code>InsertMenuLabel:
    Send %MenuItemLabel%
    Return
</code>```

I know this can be done using individual branch for each menu item (InsertChar1 ... InsertChar4) but it is not elegant.

答:
I think I found it:</p>

```<code>InsertMenuLabel:
    Send %A_ThisMenuItem%
    Return
</code>```

Body:
I want to create small menu for special characters, directly inserting selected character into text.

For example, this small popup menu opens on F9 as a context menu:

Menu, Ctx1, Add, €, InsertMenuLabel
Menu, Ctx1, Add, ¥, InsertMenuLabel
Menu, Ctx1, Add, ¢, InsertMenuLabel
Menu, Ctx1, Add, £, InsertMenuLabel

F9:
    Menu, Ctx1, Show, %A_GuiX%, %A_GuiY%
    Return

How do simply retrieve label of menu item which was selected? In the following code, how can I carry menu item label into %MenuItemLabel%?)

InsertMenuLabel:
    Send %MenuItemLabel%
    Return

I know this can be done using individual branch for each menu item (InsertChar1 ... InsertChar4) but it is not elegant.

Body:
I think I found it:

InsertMenuLabel:
    Send %A_ThisMenuItem%
    Return


问:
Why can't I change background color of toolbar
I'm changing toolbar color like this:

MainActivity.xml

```<code>    <Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"></Toolbar>
</code>```

styles.xml

```<code>    <style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="android:colorPrimary">#0000ff</item>
    <item name="android:colorPrimaryDark">#ff0000</item>
    <item name="android:textColorPrimary">#fff</item>
    </style>
</code>```

and MainActivity.java

```<code>   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setActionBar(toolbar);
</code>```

I can change color colorPrimaryDark and textColorPrimary but can not change colorPrimary, why?

I can change toolbar color like this:

```<code>toolbar.setBackgroundColor(Color.parseColor("#0000ff"));
</code>```

but cant change using style also why after removing setActionBar(toolbar); the text and title overflow menu gone why?

答:
From XML

```<code>android:background:"your color"
</code>```

From code

```<code>Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ActionBar actionBar = getSupportActionBar();

actionBar.setBackgroundDrawable(Color.parse("your color"));
</code>```

Body:
I'm changing toolbar color like this:

MainActivity.xml

    <Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"></Toolbar>

styles.xml

and MainActivity.java

   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setActionBar(toolbar);

I can change color colorPrimaryDark and textColorPrimary but can not change colorPrimary, why?

I can change toolbar color like this:

toolbar.setBackgroundColor(Color.parseColor("#0000ff"));

but cant change using style also why after removing setActionBar(toolbar); the text and title overflow menu gone why?

Body:
From XML

android:background:"your color"

From code

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ActionBar actionBar = getSupportActionBar();

actionBar.setBackgroundDrawable(Color.parse("your color"));


问:
How to perform debounce?
How do you perform debounce in React.js?

I want to debounce the handleOnChange.

I tried with debounce(this.handleOnChange, 200) but it doesn't work.

```<code>function debounce(fn, delay) {
  var timer = null;
  return function() {
    var context = this,
      args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function() {
      fn.apply(context, args);
    }, delay);
  };
}

var SearchBox = React.createClass({
  render: function() {
    return <input type="search" name="p" onChange={this.handleOnChange} />;
  },

  handleOnChange: function(event) {
    // make ajax call
  }
});
</code>```

答:
for throttle or debounce the best way is to create a function creator so you can use it any where, for example:

```<code>  updateUserProfileField(fieldName) {
    const handler = throttle(value => {
      console.log(fieldName, value);
    }, 400);
    return evt => handler(evt.target.value.trim());
  }
</code>```

and in your render method you can do:

```<code><input onChange={this.updateUserProfileField("givenName").bind(this)}/>
</code>```

the updateUserProfileField method will create a separated function each time you call it.

Note don't try to return the handler directly for example this will not work:

```<code> updateUserProfileField(fieldName) {
    return evt => throttle(value => {
      console.log(fieldName, value);
    }, 400)(evt.target.value.trim());
  }
</code>```

the reason why this will not work because this will generate a new throttle function each time the event called instead of using the same throttle function, so basically the throttle will be useless ;)

Also if you use debounce or throttle you don't need setTimeout or clearTimeout, this is actually why we use them :P

Title: How to perform debounce?

Body:
How do you perform debounce in React.js?

I want to debounce the handleOnChange.

I tried with debounce(this.handleOnChange, 200) but it doesn't work.

function debounce(fn, delay) {
  var timer = null;
  return function() {
    var context = this,
      args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function() {
      fn.apply(context, args);
    }, delay);
  };
}

var SearchBox = React.createClass({
  render: function() {
    return <input type="search" name="p" onChange={this.handleOnChange} />;
  },

  handleOnChange: function(event) {
    // make ajax call
  }
});

Body:
for throttle or debounce the best way is to create a function creator so you can use it any where, for example:

  updateUserProfileField(fieldName) {
    const handler = throttle(value => {
      console.log(fieldName, value);
    }, 400);
    return evt => handler(evt.target.value.trim());
  }

and in your render method you can do:

<input onChange={this.updateUserProfileField("givenName").bind(this)}/>

the updateUserProfileField method will create a separated function each time you call it.

Note don't try to return the handler directly for example this will not work:

 updateUserProfileField(fieldName) {
    return evt => throttle(value => {
      console.log(fieldName, value);
    }, 400)(evt.target.value.trim());
  }

the reason why this will not work because this will generate a new throttle function each time the event called instead of using the same throttle function, so basically the throttle will be useless ;)

Also if you use debounce or throttle you don't need setTimeout or clearTimeout, this is actually why we use them :P


问:
New line character in Notepad++
How can I take the new line characters in the middle of words... below words in Notepad++ (which is on different lines)

where i should remove the new line character from the address value of cust_id- 102140

result should be

答:
You can try the following regex find and replace:

Find:

```<code>(^\d{6} .*?)\r?\n(?!\d{6})(.*?\r?\n)
</code>```

Replace:

```<code>$1 $2
</code>```

Of note, the negative lookahead (?!\d{6}) makes sure that the following line does not begin with six digits.  This ensures that we only combine lines which represent a spillover.

Title: New line character in Notepad++

Body:
You can try the following regex find and replace:

Find:

(^\d{6} .*?)\r?\n(?!\d{6})(.*?\r?\n)

Replace:

$1 $2

Of note, the negative lookahead (?!\d{6}) makes sure that the following line does not begin with six digits.  This ensures that we only combine lines which represent a spillover.


问:
is it possible to close android/ios application webview using java script?
Basically i am opening a web page in Chat bot which is configured over Line messaging application for signup on auth server and after completing signup i tried to close web view using java script but not able to do this below is my code snippet for closing.</p>

```<code><!DOCTYPE html>
<html>
    <head>
      <script>
        function close(){
         window.close();
        }
      </script>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>Test Webview Closing</title>
    </head>
    <body>
         <input type="button" value="test" onclick="close()">
    </body>
</html>
</code>```

答:
you can call java Function from java script in which you can write logic of closing an app..
ref : https://stackoverflow.com/a/10389678/3746306</p>

Body:
Basically i am opening a web page in Chat bot which is configured over Line messaging application for signup on auth server and after completing signup i tried to close web view using java script but not able to do this below is my code snippet for closing.

<!DOCTYPE html>

      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>Test Webview Closing</title>

         <input type="button" value="test" onclick="close()">


问:
How does a websocket know the server was taken down?
I was playing with websocket a bit (using Sails.js with its built-in socket thing, which is based on Socket.io).

I noticed Chrome receives two frames every 25 seconds. I thought this was some kind of polling to tell the connection was still on.

But then, I cancelled the server and Chrome was notified immediately.

Also I closed the Node process by force with the kill command, and still Chrome was notified, so that means it wasn't Node sending a signal before shutting down the server.

How does this happen?

答:
Normal TCP socket connections do this, so it'd be surprising if websockets didn't.

The server kernel is responsible for cleaning up when the server process dies/exits/is killed. This includes releasing memory, closing files, and shutting down sockets. Cleanly shutting down a TCP socket requires sending a message to tell the peer.

Interestingly, on some old versions of Windows with userspace winsock, this didn't happen if the server process crashed. On all OS with compliant TCP support, it should be guaranteed unless the kernel itself hangs, the machine loses power, or the network breaks.


问:
Using GitHub for issue tracking for a local Git repository
My company has a Git repository hosted on our servers. We use TortoiseGit. I would like to integrate it with GitHub Issues.

Is this possible? Note that we do not host our repository on GitHub.

I have tried using the bugtraq settings on TortoiseGit but it doesn't interact with the repository I've set up on GitHub.

答:
I would like to integrate it with GitHub Issues. Is this possible?

Integrate in this context is a very open concept. Which integrations are you looking for? If you're not hosting the code on the repository itself, any kind of integration will be hard, but it really depends on your specific goal with GitHub Issues and which kind of triggers and links you want from your code to your issues.

From experience if I assume that by integration you mean linking Git commits in your local repository to GitHub Issues the clear answer is no.

So if you really want to use GitHub Issues without pushing the Git code upstream, have you considered creating an empty project to just use GitHub Issues and GitHub Projects. You won't be able to reference issues from the commit message, i.e., Fixed issue found in #4 but you can use it as a standalone project management tool.

Trello offers a free tier for project management that you might also want to check out.


问:
Highcharts shared tooltip positioning if single value only
If you see the example below, when you hover on the points, the tooltip will be to the left of the point, except when you hover on the month of 'June', where there is only a single value.

Im trying to get the tooltip to show in the same position when i hover on a point with multiple values on a single point, and also when i hover on a point with just 1 value available. (this is a shared tooltip).

Any idea how i can make the single value tooltip behave the same way as the others?

http://jsfiddle.net/2paj7L0h/ or snippet below:

Highcharts.chart('container', {

    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
                                 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },
  plotOptions: {
    series: {
     connectNulls: true
      }
    },
    tooltip: {
        shared: true,
        crosshairs: true
    },
    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
    }, {
        data: [216.4, 194.1, 95.6, 54.4, 29.9, null, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5]
    }]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.highcharts.com/highcharts.js"></script>

<div id="container" style="height: 400px"></div></code>```

答:
As I have mentioned in my comment, you should be able to use tooltip.positioner for positioning your tooltip near your points:

http://api.highcharts.com/highcharts/tooltip.positioner

```<code>  tooltip: {
    shared: true,
    crosshairs: true,
    positioner: function(labelWidth, labelHeight, point) {
      var x;
      if (point.plotX - labelWidth / 2 > 0) {
        x = point.plotX - labelWidth / 2;
      } else {
        x = 0
      }
      return {
        x: x,
        y: point.plotY
      }
    },
    shape: 'square'
  },
</code>```

Live example: http://jsfiddle.net/2paj7L0h/2/

Body:
As I have mentioned in my comment, you should be able to use tooltip.positioner for positioning your tooltip near your points:

http://api.highcharts.com/highcharts/tooltip.positioner

  tooltip: {
    shared: true,
    crosshairs: true,
    positioner: function(labelWidth, labelHeight, point) {
      var x;
      if (point.plotX - labelWidth / 2 > 0) {
        x = point.plotX - labelWidth / 2;
      } else {
        x = 0
      }
      return {
        x: x,
        y: point.plotY
      }
    },
    shape: 'square'
  },

Live example: http://jsfiddle.net/2paj7L0h/2/


问:
Make section on top of all div
I am trying to make the Country list from drop down to be on top of the page. It going behnid the content.

I did changed the section itself with home page.

It working now.

答: you give overflow:hidden in .header-inner class that is issue if you remove that property then dropdown become proper

Title: Make section on top of all div


问:
cloning javascript event object
Anybody know how to do a deep copy/cloning of a native javascript event object?  I know I can create a new event object and set the appropriate properties manually to match the original event, but it'd be much easier if there's a way to just clone.</p>

答:
Inspired by Kofifus answer I just do that

```<code>function cloneEvent(type, event) {
    var evt = new Event(type);
    return Object.setPrototypeOf(evt,event);
}
</code>```

or just

```<code>function cloneEvent(event){
  return Object.create(event)
}
</code>```

it returns a new object that protects you from edit the original object. but let you read and edit the property. thanks to js prototype chain

Newest js engine  support 'structuredClone' that should do it for you

OwnerDisplayName: paul smith

Title: cloning javascript event object

Body:
Inspired by Kofifus answer I just do that

function cloneEvent(type, event) {
    var evt = new Event(type);
    return Object.setPrototypeOf(evt,event);
}

or just

function cloneEvent(event){
  return Object.create(event)
}

it returns a new object that protects you from edit the original object. but let you read and edit the property. thanks to js prototype chain

Newest js engine  support 'structuredClone' that should do it for you


问:
Scala returns empty list
I've got a function in which I'd like to return a seq of elements like this:

```<code>def getProcessPrerequisites(processTemplateId: Int): Seq[ProcessTemplatesModel] =  {
    var processTemplates: Seq[ProcessTemplatesModel] = Seq()
    //Other function calls...

            processTemplateIds.foreach(processTemplateId => processTemplateDTO.getProcessTemplate(processTemplateId).map {
              case Some(processTemplate) => processTemplates = processTemplates :+ processTemplate
                println("List in foreach: " + processTemplates)
              case None => println("Process template not found: " + processTemplateId)
              case _ => println("Something went wrong processTemplateDTO.getProcessTemplate(" + processTemplateId + ")!")
            })

    println("List in the end: " + processTemplates)
    processTemplates
  }
</code>```

Eventually, I iterate over a list of processTemplateIds in order to get the corresponding elements. However, scala decides, probably due to its asynchronous nature, to return an empty list in the end.
The println within the foreach:

```<code>println("List in foreach: " + processTemplates)
</code>```

reveals that the list is not empty and is properly filled. Problem is, that it happens after this println:

```<code>println("List in the end: " + processTemplates)
</code>```

which is empty.
How can I assure that the list is not empty or waits for the list to be filled? Am I doing something wrong? Thanks!

UPDATE

```<code>var test = ""
    processPrerequisitesDTO.getProcessPrerequisites(processTemplateId).map {
      processPrerequisiteIds => {
        test += " hello "
        processPrerequisiteIds.foreach(processTemplateId => processTemplateDTO.getProcessTemplate(processTemplateId).map {
          case Some(processTemplate) => processTemplates += processTemplate
            test += " hi "
        })
        println("FirstPrint: " + test)
      }
    }
    println("SecondPrint: " + test)
</code>```

The "FirstPrint" says "ha" the "SecondPrint" is empty. Does this have to do with scoping? I don't get it, not even the " hi " is added...

答:
Seq in Scala is immutable.
Every time you do processTemplates :+ processTemplate the new Seq is created and original var processTemplates doesn't change.
You can either

1) use map/fold instead of foreach and create required result without side effects

2) use mutable.Seq collection for val processTemplates and modify it, which is not recommended in scala because of side effects.

Title: Scala returns empty list

Body:
I've got a function in which I'd like to return a seq of elements like this:

def getProcessPrerequisites(processTemplateId: Int): Seq[ProcessTemplatesModel] =  {
    var processTemplates: Seq[ProcessTemplatesModel] = Seq()
    //Other function calls...

            processTemplateIds.foreach(processTemplateId => processTemplateDTO.getProcessTemplate(processTemplateId).map {
              case Some(processTemplate) => processTemplates = processTemplates :+ processTemplate
                println("List in foreach: " + processTemplates)
              case None => println("Process template not found: " + processTemplateId)
              case _ => println("Something went wrong processTemplateDTO.getProcessTemplate(" + processTemplateId + ")!")
            })

    println("List in the end: " + processTemplates)
    processTemplates
  }

Eventually, I iterate over a list of processTemplateIds in order to get the corresponding elements. However, scala decides, probably due to its asynchronous nature, to return an empty list in the end.
The println within the foreach:

println("List in foreach: " + processTemplates)

reveals that the list is not empty and is properly filled. Problem is, that it happens after this println:

println("List in the end: " + processTemplates)

which is empty.
How can I assure that the list is not empty or waits for the list to be filled? Am I doing something wrong? Thanks!

UPDATE

var test = ""
    processPrerequisitesDTO.getProcessPrerequisites(processTemplateId).map {
      processPrerequisiteIds => {
        test += " hello "
        processPrerequisiteIds.foreach(processTemplateId => processTemplateDTO.getProcessTemplate(processTemplateId).map {
          case Some(processTemplate) => processTemplates += processTemplate
            test += " hi "
        })
        println("FirstPrint: " + test)
      }
    }
    println("SecondPrint: " + test)

The "FirstPrint" says "ha" the "SecondPrint" is empty. Does this have to do with scoping? I don't get it, not even the " hi " is added...


问:
Memcache(d) vs. Varnish for speeding up 3 tier web architecture
I'm trying to speed up my benchmark (3 tier web architecture), and I have some general questions related to Memcache(d) and Varnish.

What is the difference?

It seems to me that Varnish is behind the web server, caching web pages and doesn't require change in code, just configuration.

On the other side, Memcached is general purpose caching system and mostly used to cache result from database and does require change in get method (first cache lookup).

Can I use both? Varnish in front web server and Memcached for database caching?

What is a better option?

(scenario 1 - mostly write,

scenario 2 - mostly read,

scenario 3 - read and write are similar)

答:
Varnish is in front of the webserver; it works as a reverse http proxy that caches.

You can use both.

Mostly write -- Varnish will need to have affected pages purged. This will result in an overhead and little benefit for modified pages.

Mostly read -- Varnish will probably cover most of it.

Similar read & write -- Varnish will serve a lot of the pages for you, Memcache will provide info for pages that have a mixture of known and new data allowing you to generate pages faster.

An example that could apply to stackoverflow.com: adding this comment invalidated the page cache, so this page would have to be cleared from Varnish (and also my profile page, which probably isn't worth caching to begin with. Remembering to invalidate all affected pages may be a bit of an issue). All the comments, however, are still in Memcache, so the database only has to write this comment. Nothing else needs to be done by the database to generate the page. All the comments are pulled by Memcache, and the page is recached until somebody affects it again (perhaps by voting my answer up). Again, the database writes the vote, all other data is pulled from Memcache, and life is fast.

Memcache saves your DB from doing a lot of read work, Varnish saves your dynamic web server from CPU load by making you generate pages less frequently (and lightens the db load a bit as well if not for Memcache).


问:
Loop over columns in DF and calculate sum based on condition for every appended column in R or Python
```<code>A B C
1 0 0
0 0 1
0 1 0
1 1 1
</code>```

Here I have 4*3 dataframe (columns A,B,C). I`d like to calculate sum in a combination of columns based on a condition that both rows are 1. In other words, in the output I want to have 1*3 dataframe with A 2 B 1 C 1. So, first I look at column A, it has 2 rows with ones, so the sum is 2, then I look at combination of A and B, there is just one row with BOTH 1, so I get 1. Finally, I get combination of A,B,C and it has one row with all ones, so I get 1 as well. Could you pls help with the best way to do it in R or Python.

答:
Assuming you only have 1's and 0's in the dataframe. You can do this in R using sapply.

```<code>sapply(seq_along(df), function(x)  sum(rowSums(df[1:x]) == x))

#[1] 2 1 1
</code>```

Here we incrementally go on selecting one-one column from the dataframe and count the number of rows which all have 1's in them.

Body:
A B C
1 0 0
0 0 1
0 1 0
1 1 1

Here I have 4*3 dataframe (columns A,B,C). I`d like to calculate sum in a combination of columns based on a condition that both rows are 1. In other words, in the output I want to have 1*3 dataframe with A 2 B 1 C 1. So, first I look at column A, it has 2 rows with ones, so the sum is 2, then I look at combination of A and B, there is just one row with BOTH 1, so I get 1. Finally, I get combination of A,B,C and it has one row with all ones, so I get 1 as well. Could you pls help with the best way to do it in R or Python.

Body:
Assuming you only have 1's and 0's in the dataframe. You can do this in R using sapply.

sapply(seq_along(df), function(x)  sum(rowSums(df[1:x]) == x))

#[1] 2 1 1

Here we incrementally go on selecting one-one column from the dataframe and count the number of rows which all have 1's in them.


问:
DB2 error while loading shared libraries
When i execute 'db2stop' or 'db2start' command on Centos finally 6.4 (Final). I am getting error as follows:

```<code>> error while loading shared libraries: libnuma.so.1: cannot open shared
> object file: No such file or directory
</code>```

I tried as follows commands but it didn't work..

```<code># yum install compat-libstdc++-33
# yum install libaio
</code>```

waiting your solutions.

答:
And also if you get following error

DBT3514W  The db2prereqcheck utility failed to find the following 32-bit library file: "/lib/libpam.so*"
then execute

sudo yum install pam.i686

Body:
When i execute 'db2stop' or 'db2start' command on Centos finally 6.4 (Final). I am getting error as follows:

> error while loading shared libraries: libnuma.so.1: cannot open shared
> object file: No such file or directory

I tried as follows commands but it didn't work..

# yum install compat-libstdc++-33
# yum install libaio

waiting your solutions.


问:
Weird accuracy result in ConvNN Tensorflow
I've built a convNN to classify a bunch of images, First the accuracy was really bad ( bellow 6%), no matter what I've changed in the network. So  I thought that the problem is the way I Read the images. After change  this parts of code, I get a result that I can't explain:

I guess the the way I use the batch is the problem, so is the code I'm using, for that:

```<code>def getImage(filename):
    with tf.device('/cpu:0'):
        # convert filenames to a queue for an input pipeline.
        filenameQ = tf.train.string_input_producer([filename],num_epochs=None)
    # object to read records
    recordReader = tf.TFRecordReader()

    # read the full set of features for a single example
    key, fullExample = recordReader.read(filenameQ)

    # parse the full example into its' component features.
    features = tf.parse_single_example(
        fullExample,
        features={
            'image/height': tf.FixedLenFeature([], tf.int64),
            'image/width': tf.FixedLenFeature([], tf.int64),
            'image/colorspace': tf.FixedLenFeature([], dtype=tf.string,default_value=''),
            'image/channels':  tf.FixedLenFeature([], tf.int64),
            'image/class/label': tf.FixedLenFeature([],tf.int64),
            'image/class/text': tf.FixedLenFeature([], dtype=tf.string,default_value=''),
            'image/format': tf.FixedLenFeature([], dtype=tf.string,default_value=''),
            'image/filename': tf.FixedLenFeature([], dtype=tf.string,default_value=''),
            'image/encoded': tf.FixedLenFeature([], dtype=tf.string, default_value='')
        })

    # now we are going to manipulate the label and image features
    label = features['image/class/label']
    image_buffer = features['image/encoded']
    # Decode the jpeg
    with tf.name_scope('decode_img',[image_buffer], None):
        # decode
        image = tf.image.decode_png( image_buffer, channels=1)

        # and convert to single precision data type
        image = tf.image.convert_image_dtype(image, dtype=tf.float32)
    # cast image into a single array, where each element corresponds to the greyscale
    # value of a single pixel.
    # the "1-.." part inverts the image, so that the background is black.
    image = tf.reshape(image,[img_height*img_width])
    # re-define label as a "one-hot" vector
    # it will be [0,1] or [1,0] here.
    # This approach can easily be extended to more classes.
    label=tf.stack(tf.one_hot(label-1, numberOFclasses))
    return image, label

with tf.device('/cpu:0'):
    train_img,train_label = getImage(TF_Records+"/TrainRecords")
    validation_img,validation_label=getImage(TF_Records+"/TestRecords")
    # associate the "label_batch" and "image_batch" objects with a randomly selected batch---
    # of labels and images respectively
    train_imageBatch, train_labelBatch = tf.train.shuffle_batch([train_img, train_label], batch_size=batchSize,capacity=50,min_after_dequeue=10)

    # and similarly for the validation data
    validation_imageBatch, validation_labelBatch = tf.train.shuffle_batch([validation_img, validation_label],
                                                    batch_size=batchSize,capacity=50,min_after_dequeue=10)

    # feeding function
    def feed_dict(train):
        if True :
            #img_batch, labels_batch= tf.train.shuffle_batch([train_label,train_img],batch_size=batchSize,capacity=500,min_after_dequeue=200)
            img_batch , labels_batch = sess.run([ train_labelBatch ,train_imageBatch])
            dropoutValue = 0.7
        else:
            #   img_batch,labels_batch = tf.train.shuffle_batch([validation_label,validation_img],batch_size=batchSize,capacity=500,min_after_dequeue=200)
            img_batch,labels_batch = sess.run([ validation_labelBatch,validation_imageBatch])
            dropoutValue = 1
        return {x:img_batch,y_:labels_batch,keep_prob:dropoutValue}

    for i  in range(max_numberofiteretion):
        if i%10 == 0:#Run a Test
            summary, acc = sess.run([merged,accuracy],feed_dict=feed_dict(False))
            test_writer.add_summary(summary,i)# Save to TensorBoard
        else: # Training
          if i % 100 == 99:  # Record execution stats
            run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
            run_metadata = tf.RunMetadata()
            summary, _ = sess.run([merged, train_step],
                                  feed_dict=feed_dict(True),
                                  options=run_options,
                                  run_metadata=run_metadata)
            train_writer.add_run_metadata(run_metadata, 'step%03d' % i)
            train_writer.add_summary(summary, i)
            print('Adding run metadata for', i)
          else:  # Record a summary
            summary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True))
            train_writer.add_summary(summary, i)
        # finalise
        coord.request_stop()
        coord.join(threads)
        train_writer.close()
        test_writer.close()
</code>```

Any idea what's the problem here is ?
thanks in advance !
PS: the images are definitely been loaded I can see them in Tensorboard

答:
One thing I picked up is here:

```<code>return label, image

with tf.device('/cpu:0'):
    train_img,train_label = getImage(TF_Records+"/TrainRecords")
    validation_img,validation_label=getImage(TF_Records+"/TestRecords")
</code>```

Looks like in the function get_image() you return label, image but when you call the function you reverse the assignments.

Body:
I've built a convNN to classify a bunch of images, First the accuracy was really bad ( bellow 6%), no matter what I've changed in the network. So  I thought that the problem is the way I Read the images. After change  this parts of code, I get a result that I can't explain:

I guess the the way I use the batch is the problem, so is the code I'm using, for that:

def getImage(filename):
    with tf.device('/cpu:0'):
        # convert filenames to a queue for an input pipeline.
        filenameQ = tf.train.string_input_producer([filename],num_epochs=None)
    # object to read records
    recordReader = tf.TFRecordReader()

    # read the full set of features for a single example
    key, fullExample = recordReader.read(filenameQ)

    # parse the full example into its' component features.
    features = tf.parse_single_example(
        fullExample,
        features={
            'image/height': tf.FixedLenFeature([], tf.int64),
            'image/width': tf.FixedLenFeature([], tf.int64),
            'image/colorspace': tf.FixedLenFeature([], dtype=tf.string,default_value=''),
            'image/channels':  tf.FixedLenFeature([], tf.int64),
            'image/class/label': tf.FixedLenFeature([],tf.int64),
            'image/class/text': tf.FixedLenFeature([], dtype=tf.string,default_value=''),
            'image/format': tf.FixedLenFeature([], dtype=tf.string,default_value=''),
            'image/filename': tf.FixedLenFeature([], dtype=tf.string,default_value=''),
            'image/encoded': tf.FixedLenFeature([], dtype=tf.string, default_value='')
        })

    # now we are going to manipulate the label and image features
    label = features['image/class/label']
    image_buffer = features['image/encoded']
    # Decode the jpeg
    with tf.name_scope('decode_img',[image_buffer], None):
        # decode
        image = tf.image.decode_png( image_buffer, channels=1)

        # and convert to single precision data type
        image = tf.image.convert_image_dtype(image, dtype=tf.float32)
    # cast image into a single array, where each element corresponds to the greyscale
    # value of a single pixel.
    # the "1-.." part inverts the image, so that the background is black.
    image = tf.reshape(image,[img_height*img_width])
    # re-define label as a "one-hot" vector
    # it will be [0,1] or [1,0] here.
    # This approach can easily be extended to more classes.
    label=tf.stack(tf.one_hot(label-1, numberOFclasses))
    return image, label

with tf.device('/cpu:0'):
    train_img,train_label = getImage(TF_Records+"/TrainRecords")
    validation_img,validation_label=getImage(TF_Records+"/TestRecords")
    # associate the "label_batch" and "image_batch" objects with a randomly selected batch---
    # of labels and images respectively
    train_imageBatch, train_labelBatch = tf.train.shuffle_batch([train_img, train_label], batch_size=batchSize,capacity=50,min_after_dequeue=10)

    # and similarly for the validation data
    validation_imageBatch, validation_labelBatch = tf.train.shuffle_batch([validation_img, validation_label],
                                                    batch_size=batchSize,capacity=50,min_after_dequeue=10)

    # feeding function
    def feed_dict(train):
        if True :
            #img_batch, labels_batch= tf.train.shuffle_batch([train_label,train_img],batch_size=batchSize,capacity=500,min_after_dequeue=200)
            img_batch , labels_batch = sess.run([ train_labelBatch ,train_imageBatch])
            dropoutValue = 0.7
        else:
            #   img_batch,labels_batch = tf.train.shuffle_batch([validation_label,validation_img],batch_size=batchSize,capacity=500,min_after_dequeue=200)
            img_batch,labels_batch = sess.run([ validation_labelBatch,validation_imageBatch])
            dropoutValue = 1
        return {x:img_batch,y_:labels_batch,keep_prob:dropoutValue}

    for i  in range(max_numberofiteretion):
        if i%10 == 0:#Run a Test
            summary, acc = sess.run([merged,accuracy],feed_dict=feed_dict(False))
            test_writer.add_summary(summary,i)# Save to TensorBoard
        else: # Training
          if i % 100 == 99:  # Record execution stats
            run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
            run_metadata = tf.RunMetadata()
            summary, _ = sess.run([merged, train_step],
                                  feed_dict=feed_dict(True),
                                  options=run_options,
                                  run_metadata=run_metadata)
            train_writer.add_run_metadata(run_metadata, 'step%03d' % i)
            train_writer.add_summary(summary, i)
            print('Adding run metadata for', i)
          else:  # Record a summary
            summary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True))
            train_writer.add_summary(summary, i)
        # finalise
        coord.request_stop()
        coord.join(threads)
        train_writer.close()
        test_writer.close()

Any idea what's the problem here is ?
thanks in advance !
PS: the images are definitely been loaded I can see them in Tensorboard

Body:
One thing I picked up is here:

return label, image

with tf.device('/cpu:0'):
    train_img,train_label = getImage(TF_Records+"/TrainRecords")
    validation_img,validation_label=getImage(TF_Records+"/TestRecords")

Looks like in the function get_image() you return label, image but when you call the function you reverse the assignments.


问:
Threadpool deadlock with Task.Result
We have a large legacy with asp.net system, we have started using some async methods from an infrastructure library that we cannot change.
The system doesn't use tasks in most places but the infrastructure exposes only async methods.

In the code we use the following pattern to use the async methods:

Task.Run(() => Foo()).Result

We use the Task.Run to prevent a deadlock if somewhere in the code someone didn't use ConfigureAwait(false), There are a lot of places that someone could have missed and it has happened before.
And we use Task.Result to integrate it with the existing sync code base.

After experiencing heavy load We've noticed that that we are getting timeouts but the servers are not doing any work(Low CPU), we've found out that when there are a lot of calls to the server and the thread pool reaches the maximal number of threads the threads reach a deadlock in the Task.Result as it blocks the thread until the task is finished but the task can't run as there are no thread pool threads available to run it.

The best solution would be to change the code to work async all the way, but that is not an option right now.
Also removing the Task.Run could work but it's too risky as there is not enough test coverage to know that we will not cause new deadlocks in untested flows.

I've tried to implement a new task scheduler that will not use the thread pool but a different set of threads to run the Foo task, but internal task are being executed on the default task scheduler that I do not want to replace.

Any ideas how this can be resolved without a huge change to the code base?

This is a small sample app that reproduces the issue, using only 10 threads and not the real limit. In the sample Foo will never be called.

```<code>class Program
{
    static void Main(string[] args)
    {
        ThreadPool.SetMaxThreads(10, 10);
        ThreadPool.SetMinThreads(10, 10);

        for (int i = 0; i < 10; i++)
        {
            ThreadPool.QueueUserWorkItem(CallBack);
        }

        Console.ReadKey();
    }

    private static void CallBack(object state)
    {
        Thread.Sleep(1000);

        var result = Task.Run(() => Foo()).Result;
    }

    public static async Task<string> Foo()
    {
        await Task.Delay(100);
        return "";
    }
}
</code>```

答:
You can safely use short form (Foo().Result) instead of Task.Run(() => Foo()).Result if you disable aspnet:UseTaskFriendlySynchronizationContext setting:

```<code><appSettings>
   <add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
</appSettings>
</code>```

Disabling task-friendly synchronization context means that HttpContext.Current would be null after any await operator - but now it is null inside of Task.Run.

Using Foo().Result instead of Task.Run(() => Foo()).Result will lead to 2 times less thread pool usage, so it can solve your problem.

Also you can use <httpRuntime> and <processModel> to configure minimum free thread pool size:

```<code><system.web>
  <processModel autoConfig="false" maxWorkerThreads="..." maxIoThreads="..." />
  <httpRuntime minFreeThreads="..." />
</system.web>
</code>```

Note that default values are:

maxWorkerThreads = 100 per cpu

maxIoThreads = 100 per cpu

minFreeThreads = 88 per cpu

Title: Threadpool deadlock with Task.Result

Body:
We have a large legacy with asp.net system, we have started using some async methods from an infrastructure library that we cannot change.
The system doesn't use tasks in most places but the infrastructure exposes only async methods.

In the code we use the following pattern to use the async methods:

Task.Run(() => Foo()).Result

We use the Task.Run to prevent a deadlock if somewhere in the code someone didn't use ConfigureAwait(false), There are a lot of places that someone could have missed and it has happened before.
And we use Task.Result to integrate it with the existing sync code base.

After experiencing heavy load We've noticed that that we are getting timeouts but the servers are not doing any work(Low CPU), we've found out that when there are a lot of calls to the server and the thread pool reaches the maximal number of threads the threads reach a deadlock in the Task.Result as it blocks the thread until the task is finished but the task can't run as there are no thread pool threads available to run it.

The best solution would be to change the code to work async all the way, but that is not an option right now.
Also removing the Task.Run could work but it's too risky as there is not enough test coverage to know that we will not cause new deadlocks in untested flows.

I've tried to implement a new task scheduler that will not use the thread pool but a different set of threads to run the Foo task, but internal task are being executed on the default task scheduler that I do not want to replace.

Any ideas how this can be resolved without a huge change to the code base?

This is a small sample app that reproduces the issue, using only 10 threads and not the real limit. In the sample Foo will never be called.

class Program
{
    static void Main(string[] args)
    {
        ThreadPool.SetMaxThreads(10, 10);
        ThreadPool.SetMinThreads(10, 10);

        for (int i = 0; i < 10; i++)
        {
            ThreadPool.QueueUserWorkItem(CallBack);
        }

        Console.ReadKey();
    }

    private static void CallBack(object state)
    {
        Thread.Sleep(1000);

        var result = Task.Run(() => Foo()).Result;
    }

    public static async Task<string> Foo()
    {
        await Task.Delay(100);
        return "";
    }
}

Body:
You can safely use short form (Foo().Result) instead of Task.Run(() => Foo()).Result if you disable aspnet:UseTaskFriendlySynchronizationContext setting:

<appSettings>
   <add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
</appSettings>

Disabling task-friendly synchronization context means that HttpContext.Current would be null after any await operator - but now it is null inside of Task.Run.

Using Foo().Result instead of Task.Run(() => Foo()).Result will lead to 2 times less thread pool usage, so it can solve your problem.

Also you can use <httpRuntime> and <processModel> to configure minimum free thread pool size:

<system.web>
  <processModel autoConfig="false" maxWorkerThreads="..." maxIoThreads="..." />
  <httpRuntime minFreeThreads="..." />
</system.web>

Note that default values are:

maxWorkerThreads = 100 per cpu

maxIoThreads = 100 per cpu

minFreeThreads = 88 per cpu


问:
Application without the `apply` method?
I noticed the following code in org.scalacheck.Properties file:

```<code>  /** Used for specifying properties. Usage:
   *  {{{
   *  property("myProp") = ...
   *  }}}
   */
  class PropertySpecifier() {
    def update(propName: String, p: Prop) = props += ((name+"."+propName, p))
  }

  lazy val property = new PropertySpecifier()
</code>```

I'm not sure what is happening when property("myProp") = ... is invoked. There is no apply method in the class PropertySpecifier. So, what is being called here?

答:
You may notice that the usage does not only show application but rather something else, the = sign. By having your class implement an update method you can let the compiler how the state of this class can be updated and allowing the property("myProp") = syntax.

You can find the same behavior on Arrays, where apply performs read access and update write access.

Here is a small example you can use to understand this:

```<code>final class Box[A](private[this] var item: A) {

  def apply(): A =
    item

  def update(newItem: A): Unit =
    item = newItem

}

val box = new Box(42)
println(box()) // prints 42
box() = 47 // updates box contents
println(box()) // prints 47
</code>```

Title: Application without the `apply` method?

Body:
I noticed the following code in org.scalacheck.Properties file:

  /** Used for specifying properties. Usage:
   *  {{{
   *  property("myProp") = ...
   *  }}}
   */
  class PropertySpecifier() {
    def update(propName: String, p: Prop) = props += ((name+"."+propName, p))
  }

  lazy val property = new PropertySpecifier()

I'm not sure what is happening when property("myProp") = ... is invoked. There is no apply method in the class PropertySpecifier. So, what is being called here?

Body:
You may notice that the usage does not only show application but rather something else, the = sign. By having your class implement an update method you can let the compiler how the state of this class can be updated and allowing the property("myProp") = syntax.

You can find the same behavior on Arrays, where apply performs read access and update write access.

Here is a small example you can use to understand this:

final class Box[A](private[this] var item: A) {

  def apply(): A =
    item

  def update(newItem: A): Unit =
    item = newItem

}

val box = new Box(42)
println(box()) // prints 42
box() = 47 // updates box contents
println(box()) // prints 47


问:
Node.js append a row to xlsx file
I'm just trying to figure out how to append a single row to an xlsx file. For example, append array = [1 2 3 4 5] to the first empty row using columns 1,2,3,4,5. Ideally I'd start with an empty .xlsx file, and repeatedly rerun this program, which appends a new row to the file each time it is ran.

I'm attempting to use exceljs, but any test writes I try to do to a file say corrupted when I attempt to open them.

edited code (still not working):

```<code>var Excel = require('exceljs');
var workbook = new Excel.Workbook();
var sheet = workbook.addWorksheet('rssi');
file = 'testfile.xlsx'
var array = [1,2,3,4,5]
sheet.addRow(array)
workbook.xlsx.writeFile(file)
.then(function() {
    console.log('Array added and file saved.')
});
</code>```

Output is zero bytes and cannot be opened by Microsoft Excel. Says, "The file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."

答:
But it add only one row at a time

```<code>var spread_sheet = require('spread_sheet');

var row = "1,2,Jack,Pirate";
var filePath = '/home/Pranjal/Desktop/test.xlsx';
var sheetName = "Sheet1";

spread_sheet.addRow(row,filePath,sheetName,function(err,result){
console.log(err,result)
})
</code>```

Title: Node.js append a row to xlsx file

Body:
I'm just trying to figure out how to append a single row to an xlsx file. For example, append array = [1 2 3 4 5] to the first empty row using columns 1,2,3,4,5. Ideally I'd start with an empty .xlsx file, and repeatedly rerun this program, which appends a new row to the file each time it is ran.

I'm attempting to use exceljs, but any test writes I try to do to a file say corrupted when I attempt to open them.

edited code (still not working):

var Excel = require('exceljs');
var workbook = new Excel.Workbook();
var sheet = workbook.addWorksheet('rssi');
file = 'testfile.xlsx'
var array = [1,2,3,4,5]
sheet.addRow(array)
workbook.xlsx.writeFile(file)
.then(function() {
    console.log('Array added and file saved.')
});

Output is zero bytes and cannot be opened by Microsoft Excel. Says, "The file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."

Body:
But it add only one row at a time

var spread_sheet = require('spread_sheet');

var row = "1,2,Jack,Pirate";
var filePath = '/home/Pranjal/Desktop/test.xlsx';
var sheetName = "Sheet1";

spread_sheet.addRow(row,filePath,sheetName,function(err,result){
console.log(err,result)
})