问:
convert all factor columns to character in a data.frame without affecting non-factor columns
For example I have a data.frame with both integer column and factor columns.

```<code>data <- data.frame(
    a = 1:5,
    b = factor(c("a", "b", "c", "d", "e")),
    c = factor(c("f", "g", "h", "i", "j")))`
</code>```

And I want to convert b and c factor columns into character, with keeping column a as integer.

I tried the follwing code :

sapply(data, function(x) {if_else(is.factor(x), as.character(x), x)})

Instead of getting the result, it throws an error:

Error: true must be length 1 (length of condition), not 5

I knew this can be done by mutate_if function in dplyr. But I still wonder why my code does not work for this case.

Thank you very much for any suggestions!

答:
You can try:

```<code>library(tidyverse)
d <- data.frame(a = 1:5,
                b = factor(c("a", "b", "c", "d", "e")),
                c = factor(c("f", "g", "h", "i", "j")))
d %>% glimpse()
Observations: 5
Variables: 3
$ a <int> 1, 2, 3, 4, 5
$ b <fctr> a, b, c, d, e
$ c <fctr> f, g, h, i, j

d %>%
  mutate_if(is.factor, as.character) %>%
  glimpse()
Observations: 5
Variables: 3
$ a <int> 1, 2, 3, 4, 5
$ b <chr> "a", "b", "c", "d", "e"
$ c <chr> "f", "g", "h", "i", "j"
</code>```

Using base R you can try

```<code>d[] <- lapply(d, function(x) if(is.factor(x)) as.character(x) else x)
</code>```

Body:
For example I have a data.frame with both integer column and factor columns.

data <- data.frame(
    a = 1:5,
    b = factor(c("a", "b", "c", "d", "e")),
    c = factor(c("f", "g", "h", "i", "j")))`

And I want to convert b and c factor columns into character, with keeping column a as integer.

I tried the follwing code :

sapply(data, function(x) {if_else(is.factor(x), as.character(x), x)})

Instead of getting the result, it throws an error:

Error: true must be length 1 (length of condition), not 5

I knew this can be done by mutate_if function in dplyr. But I still wonder why my code does not work for this case.

Thank you very much for any suggestions!

Body:
You can try:

library(tidyverse)
d <- data.frame(a = 1:5,
                b = factor(c("a", "b", "c", "d", "e")),
                c = factor(c("f", "g", "h", "i", "j")))
d %>% glimpse()
Observations: 5
Variables: 3
$ a <int> 1, 2, 3, 4, 5
$ b <fctr> a, b, c, d, e
$ c <fctr> f, g, h, i, j

d %>%
  mutate_if(is.factor, as.character) %>%
  glimpse()
Observations: 5
Variables: 3
$ a <int> 1, 2, 3, 4, 5
$ b <chr> "a", "b", "c", "d", "e"
$ c <chr> "f", "g", "h", "i", "j"

Using base R you can try

d[] <- lapply(d, function(x) if(is.factor(x)) as.character(x) else x)


来源: stackexchange

问:
Changing optimizer in keras during training
I am developing a model using nadam optimizer. I was wondering if there is a way to switch to sgd during training if validation loss does not reduce for two epochs.

答:
You can create an EarlyStopping callback that will stop the training, and in this callback, you create a function to change your optimizer and fit again.

The following callback will monitor the validation loss (val_loss) and stop training after two epochs (patience) without an improvement greater than min_delta.

```<code>min_delta = 0.000000000001

stopper = EarlyStopping(monitor='val_loss',min_delta=min_delta,patience=2)
</code>```

But for adding an extra action after the training is finished, we can extend this callback and change the on_train_end method:

```<code>class OptimizerChanger(EarlyStopping):

    def __init__(self, on_train_end, **kwargs):

        self.do_on_train_end = on_train_end
        super(OptimizerChanger,self).__init__(**kwargs)

    def on_train_end(self, logs=None):
        super(OptimizerChanger,self).on_train_end(self,logs)
        self.do_on_train_end()
</code>```

For the custom function to call when the model ends training:

```<code>def do_after_training():

    #warining, this creates a new optimizer and,
    #at the beginning, it might give you a worse training performance than before
    model.compile(optimizer = 'SGD', loss=...., metrics = ...)
    model.fit(.....)
</code>```

Now let's use the callbacks:

```<code>changer = OptimizerChanger(on_train_end= do_after_training,
                           monitor='val_loss',
                           min_delta=min_delta,
                           patience=2)

model.fit(..., ..., callbacks = [changer])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can create an EarlyStopping callback that will stop the training, and in this callback, you create a function to change your optimizer and fit again.

The following callback will monitor the validation loss (val_loss) and stop training after two epochs (patience) without an improvement greater than min_delta.

min_delta = 0.000000000001

stopper = EarlyStopping(monitor='val_loss',min_delta=min_delta,patience=2)

But for adding an extra action after the training is finished, we can extend this callback and change the on_train_end method:

class OptimizerChanger(EarlyStopping):

    def __init__(self, on_train_end, **kwargs):

        self.do_on_train_end = on_train_end
        super(OptimizerChanger,self).__init__(**kwargs)

    def on_train_end(self, logs=None):
        super(OptimizerChanger,self).on_train_end(self,logs)
        self.do_on_train_end()

For the custom function to call when the model ends training:

def do_after_training():

    #warining, this creates a new optimizer and,
    #at the beginning, it might give you a worse training performance than before
    model.compile(optimizer = 'SGD', loss=...., metrics = ...)
    model.fit(.....)

Now let's use the callbacks:

changer = OptimizerChanger(on_train_end= do_after_training,
                           monitor='val_loss',
                           min_delta=min_delta,
                           patience=2)

model.fit(..., ..., callbacks = [changer])


问:
502 Whoops, GitLab is taking too much time to respond
I installed Gitlab on Raspberry Pi2, and it had worked well for a couple of months. But since shutting down the power of RPi, it doesn't work anymore. The webpage returns 502 error.

502 Whoops, GitLab is taking too much time to respond.

So I tried reconfigure (sudo gitlab-ctl reconfigure) but, it failed with the error message:

```<code>FATAL: Errono::EAFNOSUPPORT: Address family not supported by protocol - socket(2)
</code>```

I don't know how to resolve this problem.

答:
Need to set nginx['listen_port'] and unicorn['port'].
For example:

```<code>nginx['listen_port'] = 8081
unicorn['port'] = 8082 #the ports should be different
</code>```

Then:

```<code>sudo gitlab-ctl reconfigure
sudo gitlab-ctl restart
</code>```

Body:
I installed Gitlab on Raspberry Pi2, and it had worked well for a couple of months. But since shutting down the power of RPi, it doesn't work anymore. The webpage returns 502 error.

502 Whoops, GitLab is taking too much time to respond.

So I tried reconfigure (sudo gitlab-ctl reconfigure) but, it failed with the error message:

FATAL: Errono::EAFNOSUPPORT: Address family not supported by protocol - socket(2)

I don't know how to resolve this problem.

Body:
Need to set nginx['listen_port'] and unicorn['port'].
For example:

nginx['listen_port'] = 8081
unicorn['port'] = 8082 #the ports should be different

Then:

sudo gitlab-ctl reconfigure
sudo gitlab-ctl restart


问:
Why is it string.join(list) instead of list.join(string)?
This has always confused me. It seems like this would be nicer:

```<code>["Hello", "world"].join("-")
</code>```

Than this:

```<code>"-".join(["Hello", "world"])
</code>```

Is there a specific reason it is like this?

答:
- in "-".join(my_list) declares that you are converting to a string from joining elements a list.It's result-oriented. (just for easy memory and understanding)

I made an exhaustive cheatsheet of methods_of_string for your reference.

```<code>string_methods_44 = {
    'convert': ['join','split', 'rsplit','splitlines', 'partition', 'rpartition'],
    'edit': ['replace', 'lstrip', 'rstrip', 'strip'],
    'search': ['endswith', 'startswith', 'count', 'index', 'find','rindex', 'rfind',],
    'condition': ['isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isnumeric','isidentifier',
                  'islower','istitle', 'isupper','isprintable', 'isspace', ],
    'text': ['lower', 'upper', 'capitalize', 'title', 'swapcase',
             'center', 'ljust', 'rjust', 'zfill', 'expandtabs','casefold'],
    'encode': ['translate', 'maketrans', 'encode'],
    'format': ['format', 'format_map']}
</code>```

OwnerDisplayName: Evan Fosmark

ContentLicense: CC BY-SA 4.0

Body:
This has always confused me. It seems like this would be nicer:

["Hello", "world"].join("-")

Than this:

"-".join(["Hello", "world"])

Is there a specific reason it is like this?

Body:
- in "-".join(my_list) declares that you are converting to a string from joining elements a list.It's result-oriented. (just for easy memory and understanding)

I made an exhaustive cheatsheet of methods_of_string for your reference.

string_methods_44 = {
    'convert': ['join','split', 'rsplit','splitlines', 'partition', 'rpartition'],
    'edit': ['replace', 'lstrip', 'rstrip', 'strip'],
    'search': ['endswith', 'startswith', 'count', 'index', 'find','rindex', 'rfind',],
    'condition': ['isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isnumeric','isidentifier',
                  'islower','istitle', 'isupper','isprintable', 'isspace', ],
    'text': ['lower', 'upper', 'capitalize', 'title', 'swapcase',
             'center', 'ljust', 'rjust', 'zfill', 'expandtabs','casefold'],
    'encode': ['translate', 'maketrans', 'encode'],
    'format': ['format', 'format_map']}


问:
Clashing global and local variable name
Here is the code snippet in question:

package main

import (
    "fmt"
)

var a string = "hello"

func main() {
    b := "world"

    fmt.Println(a, b)

    a := "bye"

    fmt.Println(a, b)
}
```

<p>Output:</p>

```hello world
bye world
```

My question is, how do I resolve name clash between the "global" and "local" variables a?

More specifically, how do I tell Go which a to use?

答:
Well, this is not really a solution but a workaround. Before creating a shadowning variable, you can make a pointer to an outside variable.</p>

```<code>var a string = "hello"

func main() {
    b := "world"

    fmt.Println(a, b)

    pa := &a
    a := "bye"

    fmt.Println(*pa, b, a)
}
</code>```

Title: Clashing global and local variable name

Body:
Here is the code snippet in question:

package main

import (
    "fmt"
)

var a string = "hello"

func main() {
    b := "world"

    fmt.Println(a, b)

    a := "bye"

    fmt.Println(a, b)
}

Output:

hello world
bye world

My question is, how do I resolve name clash between the "global" and "local" variables a?

More specifically, how do I tell Go which a to use?

Body:
Well, this is not really a solution but a workaround. Before creating a shadowning variable, you can make a pointer to an outside variable.

var a string = "hello"

func main() {
    b := "world"

    fmt.Println(a, b)

    pa := &a
    a := "bye"

    fmt.Println(*pa, b, a)
}


问:
tableView misplaced when running iOS 9 simulator
I am trying to lower the deployment target of my app from iOS 11 to iOS 9 but for some reason, some of my layout is misplaced, the most significant one is a tableview.

How it looks on iOS 11.0:

How it looks on iOS lower than 11.0 (Notice the space between the navigationBar and the tableView)

The constraints I use are:

Align trailing to Safe Area

Align Leading to Safe Area

Align Bottom to Safe Area

Align Top to Safe Area

I have tried implementing layoutIfNeeded() but to no success, any ideas why this happens?

答:
As per Documentation

You need to disable following property.

```<code>self.automaticallyAdjustsScrollViewInsets = false
</code>```

or

select viewcontroller from stoaryborad and go to attribute inspecter then disable Adjusts ScrollView Insets

Body:
As per Documentation

You need to disable following property.

self.automaticallyAdjustsScrollViewInsets = false

or

select viewcontroller from stoaryborad and go to attribute inspecter then disable Adjusts ScrollView Insets


问:
Why the error only be reported on the second element and how can I solve it?
I try to build a char array.

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

using namespace std;

int main(){

    static const char array1[] = {"green", "red","red", "green", "green"};

}
</code>```

I would expect this to work, but I get the following error:

答:
You are trying to initialize the char array with multiple string literals which decay to const char*. So either use characters in your list initialization:

```<code>const char array1[] = { 'g', 'r', 'r', 'g', 'g' };
</code>```

or change the array signature to const char*:

```<code>const char* array1[] = { "green", "red", "red", "green", "green" };
</code>```

or simply use a std::string type:

```<code>std::string array1[] = { "green", "red","red", "green", "green" };
</code>```

or even better, a vector of strings:

```<code>std::vector<std::string> v = { "green", "red", "red", "green", "green" };
</code>```

Body:
I try to build a char array.

#include <iostream>
#include <vector>

using namespace std;

int main(){

    static const char array1[] = {"green", "red","red", "green", "green"};

}

I would expect this to work, but I get the following error:

Body:
You are trying to initialize the char array with multiple string literals which decay to const char*. So either use characters in your list initialization:

const char array1[] = { 'g', 'r', 'r', 'g', 'g' };

or change the array signature to const char*:

const char* array1[] = { "green", "red", "red", "green", "green" };

or simply use a std::string type:

std::string array1[] = { "green", "red","red", "green", "green" };

or even better, a vector of strings:

std::vector<std::string> v = { "green", "red", "red", "green", "green" };


问:
javascript: replace classList that is into a conditional
I want change the class of a div any time, no mater what class it has. If the div has the class "mystyle" I want it to change into "mystyle1", and vice versa. My code is this:

<!DOCTYPE html>

Click the button to change the style class from DIV.

<button onclick="myFunction()">Try it</button>

I am a DIV element

```

When we press the buttom it has to change the css style any time. But it doesn't.
I think that the problem has something to be with the mixed of the conditional (classList.contains) and the classList.replace, because I did it separately and it worked.

Do you know what it is my problem? Thank you.

答:
Here is your code..</p>

```<code>    <!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
    width: 300px;
    height: 50px;
    background-color: coral;
    color: white;
    font-size: 25px;
}

.mystyle1 {
    width: 100px;
    height: 100px;
    background-color: black;
    color: coral;
    font-size: 30px;
}
</style>
</head>
<body>

<p>Click the button to change the style class from DIV.</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV" class="mystyle">
I am a DIV element
</div>

<script>
function myFunction() {
    var x = document.getElementById("myDIV");

    /*Here you missspelled "mystyle"*/
    if (x.classList.contains("mystyle")) {
        x.classList.replace("mystyle", "mystyle1");
    } else if (x.classList.contains("mystyle1")) {
        x.classList.replace("mystyle1", "mystyle");
    }
}
</script>

</body>
</html>
</code>```

Body:
I want change the class of a div any time, no mater what class it has. If the div has the class "mystyle" I want it to change into "mystyle1", and vice versa. My code is this:

<!DOCTYPE html>

Click the button to change the style class from DIV.

<button onclick="myFunction()">Try it</button>

I am a DIV element

When we press the buttom it has to change the css style any time. But it doesn't.
I think that the problem has something to be with the mixed of the conditional (classList.contains) and the classList.replace, because I did it separately and it worked.

Do you know what it is my problem? Thank you.

Body:
Here is your code..

    <!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
    width: 300px;
    height: 50px;
    background-color: coral;
    color: white;
    font-size: 25px;
}

.mystyle1 {
    width: 100px;
    height: 100px;
    background-color: black;
    color: coral;
    font-size: 30px;
}
</style>
</head>
<body>

<p>Click the button to change the style class from DIV.</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV" class="mystyle">
I am a DIV element
</div>

<script>
function myFunction() {
    var x = document.getElementById("myDIV");

    /*Here you missspelled "mystyle"*/
    if (x.classList.contains("mystyle")) {
        x.classList.replace("mystyle", "mystyle1");
    } else if (x.classList.contains("mystyle1")) {
        x.classList.replace("mystyle1", "mystyle");
    }
}
</script>

</body>
</html>


问:
eclipse error, "Cannot switch on a value of type String for source level below 1.7"
I am new for eclipse, and could not find the solution for

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot switch on a value of type String for source level below 1.7.

I changed the Java Compiler from 1.6 to 1.8, but I still have this error.
The code is as below:

```<code>package learning;

import java.util.Scanner;

public class Switch {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Insert a command:");
        String text = input.nextLine();

        switch (text) {
            case "start":
                System.out.println("Game Started");
            case "stop":
                System.out.println("Game Stopped");
            default:
                System.out.println("Invalid Input");
        }
        input.close();
    }
}
</code>```

I just downloaded the latest eclipse and Java SED kit 8 yesterday. Can anyone help me?

答:
I have java 1.8, the following steps worked for me.

1) in eclipse.ini Change  java version = 1.7 and launch eclipse, change java compiler settings as 1.7

2) right click on the error, click change compilation settings.

Body:
I am new for eclipse, and could not find the solution for

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot switch on a value of type String for source level below 1.7.

I changed the Java Compiler from 1.6 to 1.8, but I still have this error.
The code is as below:

package learning;

import java.util.Scanner;

public class Switch {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Insert a command:");
        String text = input.nextLine();

        switch (text) {
            case "start":
                System.out.println("Game Started");
            case "stop":
                System.out.println("Game Stopped");
            default:
                System.out.println("Invalid Input");
        }
        input.close();
    }
}

I just downloaded the latest eclipse and Java SED kit 8 yesterday. Can anyone help me?


问:
Number of Google Results from Excel
Given a column of strings in Excel, is there an easy way to return the number of results from a Google search for each of the strings? I am looking for a way to convert a list of text data from Excel into Google search results.</p>

答:
Idea From here (but modified):

```<code>Public Sub ExcelGoogleSearch()

Dim searchWords As String

With Sheets("Sheet1")
RowCount = 1
Do While .Range("A" & RowCount) <> ""
searchWords = .Range("A" & RowCount).Value

' Get keywords and validate by adding + for spaces between
searchWords = Replace$(searchWords, " ", "+")

' Obtain the source code for the Google-searchterm webpage
search_url = "http://www.google.com/search?hl=en&q=" & searchWords & "&meta="""
Set search_http = CreateObject("MSXML2.XMLHTTP")
search_http.Open "GET", search_url, False
search_http.send
results_var = search_http.responsetext
Set search_http = Nothing

' Find the number of results and post to sheet
pos_1 = InStr(1, results_var, "resultStats>", vbTextCompare)
pos_2 = InStr(3 + pos_1, results_var, ">", vbTextCompare)
pos_3 = InStr(pos_2, results_var, "<nobr>", vbTextCompare)
NumberofResults = Mid(results_var, 1 + pos_2, (-1 + pos_3 - pos_2))
Range("B" & RowCount) = NumberofResults
RowCount = RowCount + 1
Loop
End With
End Sub
</code>```

HTH

ContentLicense: CC BY-SA 2.5

Title: Number of Google Results from Excel

Body:
Idea From here (but modified):

Public Sub ExcelGoogleSearch()

Dim searchWords As String

With Sheets("Sheet1")
RowCount = 1
Do While .Range("A" & RowCount) <> ""
searchWords = .Range("A" & RowCount).Value

' Get keywords and validate by adding + for spaces between
searchWords = Replace$(searchWords, " ", "+")

' Obtain the source code for the Google-searchterm webpage
search_url = "http://www.google.com/search?hl=en&q=" & searchWords & "&meta="""
Set search_http = CreateObject("MSXML2.XMLHTTP")
search_http.Open "GET", search_url, False
search_http.send
results_var = search_http.responsetext
Set search_http = Nothing

' Find the number of results and post to sheet
pos_1 = InStr(1, results_var, "resultStats>", vbTextCompare)
pos_2 = InStr(3 + pos_1, results_var, ">", vbTextCompare)
pos_3 = InStr(pos_2, results_var, "<nobr>", vbTextCompare)
NumberofResults = Mid(results_var, 1 + pos_2, (-1 + pos_3 - pos_2))
Range("B" & RowCount) = NumberofResults
RowCount = RowCount + 1
Loop
End With
End Sub

HTH


问:
Regex: How to capture second part of the url by regex and jQuery
so these is my url which I need to split into two part.

```<code>1) http://localhost:8800/gb/

2) http://localhost:8800/gb/About.aspx

3) http://localhost:8800/gb/product.aspx?id=1&vref=201

4) http://localhost:8800/gb/Contact.aspx
</code>```

now tell me which regex I should use to split the above url.
the second part will hold the url after from country code

suppose this is my url http://localhost:8800/gb/About.aspx
so second part will be About.aspx

I got one regex (https?:\/\/[^\/]+)\/(.*) which split url into two part but I want to get after from country code. thanks

答:
You can use split on 2 digit country code with / on either side:

var url = 'http://localhost:8800/gb/About.aspx?id=2&vref=3';
var arr = url.split(/\/[a-z]{2}\//);

console.log(arr[0]); //=> http://localhost:8800
console.log(arr[1]); //=> About.aspx?id=2&vref=3```

RegEx Demo

Body:
so these is my url which I need to split into two part.

1) http://localhost:8800/gb/

2) http://localhost:8800/gb/About.aspx

3) http://localhost:8800/gb/product.aspx?id=1&vref=201

4) http://localhost:8800/gb/Contact.aspx

now tell me which regex I should use to split the above url.
the second part will hold the url after from country code

suppose this is my url http://localhost:8800/gb/About.aspx
so second part will be About.aspx

I got one regex (https?:\/\/[^\/]+)\/(.*) which split url into two part but I want to get after from country code. thanks

Body:
You can use split on 2 digit country code with / on either side:

var url = 'http://localhost:8800/gb/About.aspx?id=2&vref=3';
var arr = url.split(/\/[a-z]{2}\//);

console.log(arr[0]); //=> http://localhost:8800
console.log(arr[1]); //=> About.aspx?id=2&vref=3

RegEx Demo


问:
Passing arguments from a file to shell in Pipeline
Basically I'm trying to pass properties to shell from a file.

I have a file "docker_info" with following content in workspace

```<code>IMAGE_NAME='Docker-image'

IMAGE_VERIONS='Docker-1.3.5'
</code>```

Here is my pipeline script:

```<code>node
{

load "${WORKSPACE}/docker_info"

sh " echo ${IMAGE_NAME}" // here getting expected output: Docker-image

stage('Executing SHELL SCRIPING TO CHECK DOCKER IMAGE')

        sh '''

         echo "$DOCKER_IMAGE"

            if [ -z "${IMAGE_NAME}" ]     //(also tried "$IMAGE_NAME")
            then
            echo "Docker image not found."
            exit 0
            fi

             echo "${IMAGE_NAME}:started pushing image"

         '''
}
</code>```

OUTPUT:

```<code>[Test_BUILD_PIPELINE] Running shell script

+ echo Docker-image

Docker-image

**Entering stage Executing SHELL SCRIPTING TO CHECK DOCKER IMAGE**

Proceeding

[Pipeline] sh

[Test_BUILD_PIPELINE] Running shell script

+  echo ''
+ '[' -z '' ']'

+ echo 'Docker image not found. Skip pushing Docker image'

Docker image not found. Skip pushing Docker image

+ exit 0
</code>```

Kindly note after entering into the stage I Won't see the expected value(Docker-image)instead displaying:   echo ' '

I tried with several ways but that haven't worked.

答:
sh '''

. /path/to/the/docker_info

if [ -z "$IMAGE_NAME" ]

then

echo "Docker image not found"

exit 0

fi

echo "$IMAGE_NAME:started pushing image"

'''

Body:
Basically I'm trying to pass properties to shell from a file.

I have a file "docker_info" with following content in workspace

IMAGE_NAME='Docker-image'

IMAGE_VERIONS='Docker-1.3.5'

Here is my pipeline script:

node
{

load "${WORKSPACE}/docker_info"

sh " echo ${IMAGE_NAME}" // here getting expected output: Docker-image

stage('Executing SHELL SCRIPING TO CHECK DOCKER IMAGE')

        sh '''

         echo "$DOCKER_IMAGE"

            if [ -z "${IMAGE_NAME}" ]     //(also tried "$IMAGE_NAME")
            then
            echo "Docker image not found."
            exit 0
            fi

             echo "${IMAGE_NAME}:started pushing image"

         '''
}

OUTPUT:

[Test_BUILD_PIPELINE] Running shell script

+ echo Docker-image

Docker-image

**Entering stage Executing SHELL SCRIPTING TO CHECK DOCKER IMAGE**

Proceeding

[Pipeline] sh

[Test_BUILD_PIPELINE] Running shell script

+  echo ''
+ '[' -z '' ']'

+ echo 'Docker image not found. Skip pushing Docker image'

Docker image not found. Skip pushing Docker image

+ exit 0

Kindly note after entering into the stage I Won't see the expected value(Docker-image)instead displaying:   echo ' '

I tried with several ways but that haven't worked.


问:
How to stream videos from multiple IP cameras using Python
```<code>url='http://192.168.0.103:8080/shot.jpg'
url2='http://192.168.0.102:8080/shot.jpg'
url3='http://192.168.0.3:8080/shot.jpg'

while True:
 imgResp=urllib.urlopen(url)
 imgNp=np.array(bytearray(imgResp.read()),dtype=np.uint8)
 img=cv2.imdecode(imgNp,-1)

 imgResp2=urllib.urlopen(url2)
 imgNp2=np.array(bytearray(imgResp2.read()),dtype=np.uint8)
 img2=cv2.imdecode(imgNp2,-1)

 imgResp3=urllib.urlopen(url3)
 imgNp3=np.array(bytearray(imgResp3.read()),dtype=np.uint8)
 img3=cv2.imdecode(imgNp3,-1)

 cv2.imshow('IPWebcam',img)
 cv2.imshow('IPWebcam2',img2)
 cv2.imshow('IPWebcam3',img3)
 if cv2.waitKey(1) & 0xFF == ord('q'):
    break
</code>```

this is the code i am running.but the result is lagging. i want a faster way to read multiple video streams at a time.

答:
Try this out :

```<code>def ShowCam(url,CameraNumber =1):
    imgResp = urllib.urlopen(url)
    imgNp = np.array(bytearray(imgResp.read()), dtype=np.uint8)
    img = cv2.imdecode(imgNp, -1)
    camName = 'IPWebcam' + str(CameraNumber)
    return camName,img
result = True

from multiprocessing.pool import ThreadPool

# do some other stuff in the main process

while result:
    pool = ThreadPool(processes=3)
    async_result1 = pool.apply_async(ShowCam, (url, 1))  # tuple of args for     foo
    rval1 = async_result1.get()
    cv2.imshow(rval1[0],rval1[1])
    async_result2 = pool.apply_async(ShowCam, (url2, 2))  # tuple of args for foo
    rval2 = async_result2.get()
    cv2.imshow(rval2[0],rval2[1])
    async_result3 = pool.apply_async(ShowCam, (url3, 3))  # tuple of args for foo
    rval3 = async_result3.get()
    cv2.imshow(rval3[0],rval3[1])
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
</code>```

Note : Code is not tested , please ignore any typos , but this should solve the purpose . Happy coding :)

Body:
url='http://192.168.0.103:8080/shot.jpg'
url2='http://192.168.0.102:8080/shot.jpg'
url3='http://192.168.0.3:8080/shot.jpg'

while True:
 imgResp=urllib.urlopen(url)
 imgNp=np.array(bytearray(imgResp.read()),dtype=np.uint8)
 img=cv2.imdecode(imgNp,-1)

 imgResp2=urllib.urlopen(url2)
 imgNp2=np.array(bytearray(imgResp2.read()),dtype=np.uint8)
 img2=cv2.imdecode(imgNp2,-1)

 imgResp3=urllib.urlopen(url3)
 imgNp3=np.array(bytearray(imgResp3.read()),dtype=np.uint8)
 img3=cv2.imdecode(imgNp3,-1)

 cv2.imshow('IPWebcam',img)
 cv2.imshow('IPWebcam2',img2)
 cv2.imshow('IPWebcam3',img3)
 if cv2.waitKey(1) & 0xFF == ord('q'):
    break

this is the code i am running.but the result is lagging. i want a faster way to read multiple video streams at a time.

Body:
Try this out :

def ShowCam(url,CameraNumber =1):
    imgResp = urllib.urlopen(url)
    imgNp = np.array(bytearray(imgResp.read()), dtype=np.uint8)
    img = cv2.imdecode(imgNp, -1)
    camName = 'IPWebcam' + str(CameraNumber)
    return camName,img
result = True

from multiprocessing.pool import ThreadPool

# do some other stuff in the main process

while result:
    pool = ThreadPool(processes=3)
    async_result1 = pool.apply_async(ShowCam, (url, 1))  # tuple of args for     foo
    rval1 = async_result1.get()
    cv2.imshow(rval1[0],rval1[1])
    async_result2 = pool.apply_async(ShowCam, (url2, 2))  # tuple of args for foo
    rval2 = async_result2.get()
    cv2.imshow(rval2[0],rval2[1])
    async_result3 = pool.apply_async(ShowCam, (url3, 3))  # tuple of args for foo
    rval3 = async_result3.get()
    cv2.imshow(rval3[0],rval3[1])
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

Note : Code is not tested , please ignore any typos , but this should solve the purpose . Happy coding :)


问:
Python Pygame - updating displays
I'm working with pygame to try and produce a visual Blackjack game. I'va had a look around for past hour or so, and I can't seem to find anything that does what I'm looking for. I need to update the display (named screen in my code) so that the user can navigate through the menu with ease. the function below is the product of all that I've read up on and, when applied and ran with the necessary button, it only changes the colour of the "Blackjack Blast" text whilst the mouse button is being held down.

```<code>def update_window():
      textsurface = Font1.render('BlackJack Blast!', True, e_m_lighter)
      screen.blit(textsurface,(106,100))
      pygame.display.update()
</code>```

Could anyone offer any assistance as to how I can get the display to permanently update with a single button press?

答:
I can't see your code so I will improvise.

You have to use variable which will remeber that you clicked buttom (ie. clicked = False) and split code into two part - one will change clicked, second will draw different button depend on value in clicked

```<code># set on start (before mainloop)

clicked = False

# executed when you click in button

def update_window():
  global clicked
  clicked = True

# in main loop when you draw button

if clicked
  textsurface = Font1.render('BlackJack Blast!', True, e_m_lighter)
else:
  textsurface = Font1.render('BlackJack Blast!', True, NORMAL_COLOR)

screen.blit(textsurface,(106,100))
pygame.display.update()
</code>```

Or you can use variable to keep current image

```<code># set on start (before mainloop)

normal_text = Font1.render('BlackJack Blast!', True, NORMAL_COLOR)
clicked_text = Font1.render('BlackJack Blast!', True, e_m_lighter)

current_text = normal_text

# executed when you click in button

def update_window():
  global current_text
  current_text = clicked_text

# in main loop when you draw button

screen.blit(current_text, (106,100))
pygame.display.update()
</code>```

Title: Python Pygame - updating displays

Body:
I'm working with pygame to try and produce a visual Blackjack game. I'va had a look around for past hour or so, and I can't seem to find anything that does what I'm looking for. I need to update the display (named screen in my code) so that the user can navigate through the menu with ease. the function below is the product of all that I've read up on and, when applied and ran with the necessary button, it only changes the colour of the "Blackjack Blast" text whilst the mouse button is being held down.

def update_window():
      textsurface = Font1.render('BlackJack Blast!', True, e_m_lighter)
      screen.blit(textsurface,(106,100))
      pygame.display.update()

Could anyone offer any assistance as to how I can get the display to permanently update with a single button press?

Body:
I can't see your code so I will improvise.

You have to use variable which will remeber that you clicked buttom (ie. clicked = False) and split code into two part - one will change clicked, second will draw different button depend on value in clicked

# set on start (before mainloop)

clicked = False

# executed when you click in button

def update_window():
  global clicked
  clicked = True

# in main loop when you draw button

if clicked
  textsurface = Font1.render('BlackJack Blast!', True, e_m_lighter)
else:
  textsurface = Font1.render('BlackJack Blast!', True, NORMAL_COLOR)

screen.blit(textsurface,(106,100))
pygame.display.update()

Or you can use variable to keep current image

# set on start (before mainloop)

normal_text = Font1.render('BlackJack Blast!', True, NORMAL_COLOR)
clicked_text = Font1.render('BlackJack Blast!', True, e_m_lighter)

current_text = normal_text

# executed when you click in button

def update_window():
  global current_text
  current_text = clicked_text

# in main loop when you draw button

screen.blit(current_text, (106,100))
pygame.display.update()


问:
PHP Codeception instantiating Tester Class
I am new to PHP, so please forgive me. I did not write the whole code for brevity.

I want to to use JSWaiter function to be called before every step.

```<code><?php
class Tester extends \Codeception\Actor
{
    public function JSWaiter() {
        $this->waitForJS("return document.readyState == 'complete'", 20);
    }
}
</code>```

So I tried to call instance of Tester, the error says "required parameter $scenario missing"

```<code><?php
namespace Helper;
use Tester;

class EventListener extends \Codeception\Module
{
    public function _beforeStep(\Codeception\Step $step) {
        $this->tester = new Tester();
    }
}
</code>```

What exactly is the $scenario that I have to pass in?

Or how do I call Webdriver methods inside a class that extends \Codeception\Module?

答:
Use getModule method to get instance of WebDriver module.</p>

```<code>$webdriver = $this->getModule('WebDriver');
</code>```

Body:
I am new to PHP, so please forgive me. I did not write the whole code for brevity.

I want to to use JSWaiter function to be called before every step.

<?php
class Tester extends \Codeception\Actor
{
    public function JSWaiter() {
        $this->waitForJS("return document.readyState == 'complete'", 20);
    }
}

So I tried to call instance of Tester, the error says "required parameter $scenario missing"

<?php
namespace Helper;
use Tester;

class EventListener extends \Codeception\Module
{
    public function _beforeStep(\Codeception\Step $step) {
        $this->tester = new Tester();
    }
}

What exactly is the $scenario that I have to pass in?

Or how do I call Webdriver methods inside a class that extends \Codeception\Module?

Body:
Use getModule method to get instance of WebDriver module.

$webdriver = $this->getModule('WebDriver');


问:
Ldd show different version of library on the same c++ executable between different Ubuntu machines
I have created a c++ app that needs libboost_iostreams.so.1.63.0  library. In a Ubuntu 16.04 VM I have built the library and the ldd command on my executable gives the following:

```<code>ldd ./c++_app | grep boost

libboost_iostreams.so.1.63.0 => /usr/local/lib/libboost_iostreams.so.1.63.0 (0x00007f7a52e62000)
</code>```

Then I zip the app with the relevant shared lib in order to install it on new VM which has not the boost 1.63 library built.

I install the c++ on /usr/bin and the library on a folder lib in /usr/share-data and then update the /etc/ld.so.conf so that it can find the new library

However when I give:

```<code> sudo ldconfig -p | grep boost
</code>```

I get

```<code> libboost_iostreams.so.1.63.0 (libc6,x86-64) => /usr/share/lib/libboost_iostreams.so.1.63.0
</code>```

but when I give ldd on the binary file in /usr/bin I get

```<code>ldd c++_app | grep boost
libboost_iostreams.so.1.62.0 => not found
</code>```

What I have done wrong here?

答: Try export LD_LIBRARY_PATH=/usr/share/lib. This should help you

Body:
I have created a c++ app that needs libboost_iostreams.so.1.63.0  library. In a Ubuntu 16.04 VM I have built the library and the ldd command on my executable gives the following:

ldd ./c++_app | grep boost

libboost_iostreams.so.1.63.0 => /usr/local/lib/libboost_iostreams.so.1.63.0 (0x00007f7a52e62000)

Then I zip the app with the relevant shared lib in order to install it on new VM which has not the boost 1.63 library built.

I install the c++ on /usr/bin and the library on a folder lib in /usr/share-data and then update the /etc/ld.so.conf so that it can find the new library

However when I give:

 sudo ldconfig -p | grep boost

I get

 libboost_iostreams.so.1.63.0 (libc6,x86-64) => /usr/share/lib/libboost_iostreams.so.1.63.0

but when I give ldd on the binary file in /usr/bin I get

ldd c++_app | grep boost
libboost_iostreams.so.1.62.0 => not found

What I have done wrong here?


问:
Specifying thread pool size in executor doesn't work
I have a spring boot project. I am trying to call some method asynchronously. I followed this documentation: https://spring.io/guides/gs/async-method/. In Application.java, I have added following method:

```<code>    @Bean
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(500);
        executor.setThreadNamePrefix("Rules-");
        executor.initialize();
        return executor;
    }
</code>```

Please note that I have set pool size to 2. But when I call the async method 5 times, five different threads get created with different ThreadNamePrefix.

```<code>2017-12-01 19:16:00.901  INFO 32000 --- [cTaskExecutor-5] hello world
2017-12-01 19:16:00.930  INFO 32000 --- [cTaskExecutor-4] hello world
2017-12-01 19:16:01.372  INFO 32000 --- [cTaskExecutor-1] hello world
2017-12-01 19:16:01.376  INFO 32000 --- [cTaskExecutor-2] hello world
2017-12-01 19:16:01.985  INFO 32000 --- [cTaskExecutor-3] hello world
</code>```

I am not sure from where it's getting configured. Can someone please help?

Update:

Here is the code from where I am submitting the tasks:

```<code>@Component
public class MyClass {
    @Autowired
    private Async2 async;

    public void someMethod()
    {
        try {
            async.anotherMethod(1);
            async.anotherMethod(2);
            async.anotherMethod(3);
            async.anotherMethod(4);
            async.anotherMethod(5);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

@Service
public class Async2 {
    private static final Logger LOGGER = Logger.getLogger(Async2.class);
    @Async
    public CompletableFuture<Void> anotherMethod(int i) {
        LOGGER.info("hello world");
        return CompletableFuture.completedFuture(null);
    }
}
</code>```

Update2

```<code>@Controller
@RequestMapping("/a")
public class WebController {
    @Autowired
    private MyClass c;

    @RequestMapping(value="/b", method =RequestMethod.POST)
    @ResponseBody Response getResponseForRequest(@RequestBody Request request)
    {
        c.someMethod();
        return new Response();
    }
}
</code>```

答:
Finally, I got the solution. First of all, I had to specify the name of the bean and use the bean-name in Async2 class.</p>

```<code>@Bean(name="rulesThreadExecutor")
public Executor asyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(2);
    executor.setQueueCapacity(500);
    executor.setThreadNamePrefix("Rules-");
    executor.initialize();
    return executor;
}

@Async("rulesThreadExecutor")
public CompletableFuture<Void> anotherMethod(int i) {
    LOGGER.info("hello world");
    return CompletableFuture.completedFuture(null);
}
</code>```

Body:
I have a spring boot project. I am trying to call some method asynchronously. I followed this documentation: https://spring.io/guides/gs/async-method/. In Application.java, I have added following method:

    @Bean
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(500);
        executor.setThreadNamePrefix("Rules-");
        executor.initialize();
        return executor;
    }

Please note that I have set pool size to 2. But when I call the async method 5 times, five different threads get created with different ThreadNamePrefix.

2017-12-01 19:16:00.901  INFO 32000 --- [cTaskExecutor-5] hello world
2017-12-01 19:16:00.930  INFO 32000 --- [cTaskExecutor-4] hello world
2017-12-01 19:16:01.372  INFO 32000 --- [cTaskExecutor-1] hello world
2017-12-01 19:16:01.376  INFO 32000 --- [cTaskExecutor-2] hello world
2017-12-01 19:16:01.985  INFO 32000 --- [cTaskExecutor-3] hello world

I am not sure from where it's getting configured. Can someone please help?

Update:

Here is the code from where I am submitting the tasks:

@Component
public class MyClass {
    @Autowired
    private Async2 async;

    public void someMethod()
    {
        try {
            async.anotherMethod(1);
            async.anotherMethod(2);
            async.anotherMethod(3);
            async.anotherMethod(4);
            async.anotherMethod(5);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

@Service
public class Async2 {
    private static final Logger LOGGER = Logger.getLogger(Async2.class);
    @Async
    public CompletableFuture<Void> anotherMethod(int i) {
        LOGGER.info("hello world");
        return CompletableFuture.completedFuture(null);
    }
}

Update2

@Controller
@RequestMapping("/a")
public class WebController {
    @Autowired
    private MyClass c;

    @RequestMapping(value="/b", method =RequestMethod.POST)
    @ResponseBody Response getResponseForRequest(@RequestBody Request request)
    {
        c.someMethod();
        return new Response();
    }
}

Body:
Finally, I got the solution. First of all, I had to specify the name of the bean and use the bean-name in Async2 class.

@Bean(name="rulesThreadExecutor")
public Executor asyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(2);
    executor.setQueueCapacity(500);
    executor.setThreadNamePrefix("Rules-");
    executor.initialize();
    return executor;
}

@Async("rulesThreadExecutor")
public CompletableFuture<Void> anotherMethod(int i) {
    LOGGER.info("hello world");
    return CompletableFuture.completedFuture(null);
}


问:
Creating a scheduled reboot task every Saturday of the week
I have no issues setting up a scheduled task every week (Saturday) at 3pm, however there is a requirement that if the last day of the month falls on a Saturday, the reboot has to be rolled over to Sunday at 3pm.

This is the part I am unsure of, as task scheduler doesn't appear to have an exclude option, so wondering what my options are?

答:
One approach is to run a script and check if the current date is the last day of the month.

If yes, wait 24 hours with reboot, if no reboot immediately.

The following Powershell-script will do what you want. Run it every Saturday at 3pm.

```<code>#Get the last day of the current month
$lastDayOfMonth = ((Get-Date).AddMonths(1)).
                   AddDays(-(Get-Date ((Get-Date).AddMonths(1)) -format dd)).Date

if ((Get-Date).Date -eq $lastDayOfMonth)
{
    #It's the last day of this month, reboot in 24 hours (86400 seconds)
    shutdown -r -t 86400
}
else
{
    #Reboot immediately
    shutdown -r -t 0
}
</code>```

Another solution may be a third-party task scheduler software.

Body:
One approach is to run a script and check if the current date is the last day of the month.

If yes, wait 24 hours with reboot, if no reboot immediately.

The following Powershell-script will do what you want. Run it every Saturday at 3pm.

#Get the last day of the current month
$lastDayOfMonth = ((Get-Date).AddMonths(1)).
                   AddDays(-(Get-Date ((Get-Date).AddMonths(1)) -format dd)).Date

if ((Get-Date).Date -eq $lastDayOfMonth)
{
    #It's the last day of this month, reboot in 24 hours (86400 seconds)
    shutdown -r -t 86400
}
else
{
    #Reboot immediately
    shutdown -r -t 0
}

Another solution may be a third-party task scheduler software.


问:
libtorrent and tcp::acceptor crashes with access violation on Windows
libtorrent version (or branch):
master / libtorrent-1_1_5

platform/architecture:
Win32

compiler and compiler version:
msvc-14.0

boost version:
boost-1.65.1

The code below always leads to crash.

```<code>#include "libtorrent/session.hpp"

#include <chrono>
#include <thread>

using namespace std;
int main()
{
    libtorrent::session session;

    boost::asio::io_service io_service;
        boost::asio::ip::tcp::acceptor acceptor(io_service);

    std::this_thread::sleep_for(chrono::seconds(15));
    return 0;
}
</code>```

Call stack:

```<code>>   test-crow-libtorrent.exe!boost::asio::detail::win_iocp_socket_service_base::do_open(struct boost::asio::detail::win_iocp_socket_service_base::base_implementation_type &,int,int,int,class boost::system::error_code &) C++
    test-crow-libtorrent.exe!libtorrent::aux::session_impl::setup_listener(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,class boost::asio::ip::tcp const &,int,int,class boost::system::error_code &)    C++
    test-crow-libtorrent.exe!libtorrent::aux::session_impl::open_listen_port(void)  C++
    test-crow-libtorrent.exe!libtorrent::aux::session_impl::init(class boost::shared_ptr<struct libtorrent::settings_pack>) C++
    test-crow-libtorrent.exe!boost::_mfi::mf1<void,struct libtorrent::aux::session_impl,class boost::shared_ptr<struct libtorrent::settings_pack> >::operator()(struct libtorrent::aux::session_impl *,class boost::shared_ptr<struct libtorrent::settings_pack>)   C++
    test-crow-libtorrent.exe!boost::asio::asio_handler_invoke<class boost::_bi::bind_t<void,class boost::_mfi::mf1<void,struct libtorrent::aux::session_impl,class boost::shared_ptr<struct libtorrent::settings_pack> >,class boost::_bi::list2<class boost::_bi::value<struct libtorrent::aux::session_impl *>,class boost::_bi::value<class boost::shared_ptr<struct libtorrent::settings_pack> > > > >(class boost::_bi::bind_t<void,class boost::_mfi::mf1<void,struct libtorrent::aux::session_impl,class boost::shared_ptr<struct libtorrent::settings_pack> >,class boost::_bi::list2<class boost::_bi::value<struct libtorrent::aux::session_impl *>,class boost::_bi::value<class boost::shared_ptr<struct libtorrent::settings_pack> > > > &,...)    C++
    test-crow-libtorrent.exe!boost::asio::detail::completion_handler<class boost::_bi::bind_t<void,class boost::_mfi::mf1<void,struct libtorrent::aux::session_impl,class boost::shared_ptr<struct libtorrent::settings_pack> >,class boost::_bi::list2<class boost::_bi::value<struct libtorrent::aux::session_impl *>,class boost::_bi::value<class boost::shared_ptr<struct libtorrent::settings_pack> > > > >::do_complete(class boost::asio::detail::win_iocp_io_service *,class boost::asio::detail::win_iocp_operation *,class boost::system::error_code const &,unsigned int)   C++
    test-crow-libtorrent.exe!boost::asio::detail::win_iocp_io_service::do_one(bool,class boost::system::error_code &)   C++
    test-crow-libtorrent.exe!boost::asio::detail::win_iocp_io_service::run(class boost::system::error_code &)   C++
    test-crow-libtorrent.exe!boost::asio::io_service::run(void) C++
    test-crow-libtorrent.exe!thread_start<unsigned int (__stdcall*)(void *)>(void * const parameter) Line 115   C++
    kernel32.dll!@BaseThreadInitThunk@12�() Unknown
    ntdll.dll!__RtlUserThreadStart()    Unknown
    ntdll.dll!__RtlUserThreadStart@8�() Unknown
</code>```

libtorrent compile options:

```<code>toolset=msvc-14.0 boost-link=static dht=on encryption=on mutable-torrents=on crypto=openssl openssl-version=1.1 link=static runtime-link=static variant=debug,release i2p=on
</code>```

Crash occurs only on release builds.

Could anyone help me?

答:
The problem was in preprocessor. Need to add BOOST_ASIO_ENABLE_CANCELIO when you build app (which uses libtorrent) with a tool other than boost-build.

Here  you can find more information on this issue.

Body:
libtorrent version (or branch):
master / libtorrent-1_1_5

platform/architecture:
Win32

compiler and compiler version:
msvc-14.0

boost version:
boost-1.65.1

The code below always leads to crash.

#include "libtorrent/session.hpp"

#include <chrono>
#include <thread>

using namespace std;
int main()
{
    libtorrent::session session;

    boost::asio::io_service io_service;
        boost::asio::ip::tcp::acceptor acceptor(io_service);

    std::this_thread::sleep_for(chrono::seconds(15));
    return 0;
}

Call stack:

>   test-crow-libtorrent.exe!boost::asio::detail::win_iocp_socket_service_base::do_open(struct boost::asio::detail::win_iocp_socket_service_base::base_implementation_type &,int,int,int,class boost::system::error_code &) C++
    test-crow-libtorrent.exe!libtorrent::aux::session_impl::setup_listener(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,class boost::asio::ip::tcp const &,int,int,class boost::system::error_code &)    C++
    test-crow-libtorrent.exe!libtorrent::aux::session_impl::open_listen_port(void)  C++
    test-crow-libtorrent.exe!libtorrent::aux::session_impl::init(class boost::shared_ptr<struct libtorrent::settings_pack>) C++
    test-crow-libtorrent.exe!boost::_mfi::mf1<void,struct libtorrent::aux::session_impl,class boost::shared_ptr<struct libtorrent::settings_pack> >::operator()(struct libtorrent::aux::session_impl *,class boost::shared_ptr<struct libtorrent::settings_pack>)   C++
    test-crow-libtorrent.exe!boost::asio::asio_handler_invoke<class boost::_bi::bind_t<void,class boost::_mfi::mf1<void,struct libtorrent::aux::session_impl,class boost::shared_ptr<struct libtorrent::settings_pack> >,class boost::_bi::list2<class boost::_bi::value<struct libtorrent::aux::session_impl *>,class boost::_bi::value<class boost::shared_ptr<struct libtorrent::settings_pack> > > > >(class boost::_bi::bind_t<void,class boost::_mfi::mf1<void,struct libtorrent::aux::session_impl,class boost::shared_ptr<struct libtorrent::settings_pack> >,class boost::_bi::list2<class boost::_bi::value<struct libtorrent::aux::session_impl *>,class boost::_bi::value<class boost::shared_ptr<struct libtorrent::settings_pack> > > > &,...)    C++
    test-crow-libtorrent.exe!boost::asio::detail::completion_handler<class boost::_bi::bind_t<void,class boost::_mfi::mf1<void,struct libtorrent::aux::session_impl,class boost::shared_ptr<struct libtorrent::settings_pack> >,class boost::_bi::list2<class boost::_bi::value<struct libtorrent::aux::session_impl *>,class boost::_bi::value<class boost::shared_ptr<struct libtorrent::settings_pack> > > > >::do_complete(class boost::asio::detail::win_iocp_io_service *,class boost::asio::detail::win_iocp_operation *,class boost::system::error_code const &,unsigned int)   C++
    test-crow-libtorrent.exe!boost::asio::detail::win_iocp_io_service::do_one(bool,class boost::system::error_code &)   C++
    test-crow-libtorrent.exe!boost::asio::detail::win_iocp_io_service::run(class boost::system::error_code &)   C++
    test-crow-libtorrent.exe!boost::asio::io_service::run(void) C++
    test-crow-libtorrent.exe!thread_start<unsigned int (__stdcall*)(void *)>(void * const parameter) Line 115   C++
    kernel32.dll!@BaseThreadInitThunk@12�() Unknown
    ntdll.dll!__RtlUserThreadStart()    Unknown
    ntdll.dll!__RtlUserThreadStart@8�() Unknown

libtorrent compile options:

toolset=msvc-14.0 boost-link=static dht=on encryption=on mutable-torrents=on crypto=openssl openssl-version=1.1 link=static runtime-link=static variant=debug,release i2p=on

Crash occurs only on release builds.

Could anyone help me?


问:
Repeat background with fixed background attachment and rotated container?
Is it possible to get seamless pattern repeat with following conditions?

Idea is to have one rotated background with fixed attachment. I think this is how is supposed to be working, but are there any ways of achieving that?

body {
  padding: 50px;
  margin: 0;
  height: 10000px;
}

.main {
  width: 100%;
  height: 1300px;
  box-sizing: border-box;
  overflow: hidden;
  border: 5px solid #7cb7b7;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.background {
  background-image: url('https://thumbs.dreamstime.com/b/circles-seamless-pattern-10032830.jpg');
  background-attachment: fixed;
  background-repeat: repeat;
  position: absolute;
  top: -1000%;
  left: -1000%;
  right: -1000%;
  bottom: -1000%;
  transform: rotate(-15deg);
}

.text {
  background: white;
  border: 2px solid black;
  width: 200px;
  height: 70px;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">
  <div class="background"></div>
  <div class="text">
   <p>Flex</p>
  </div>
</div></code>```

答:
```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        body {
  padding: 50px;
  margin: 0;
  height: 1000px;
}

.main {
  width: 100%;
  height: 1000px;
  box-sizing: border-box;
  overflow: hidden;
  border: 5px solid #7cb7b7;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.image {
  background-image: url('images/attractions01.jpg');
  background-attachment: fixed;
  background-repeat: repeat;
  position: absolute;
  top: -1000%;
  left: -1000%;
  right: -1000%;
  bottom: -1000%;

}

.text {
  background: white;
  border: 2px solid black;
  width: 200px;
  height: 70px;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1;
}
    </style>
</head>
<body>
<div class="main">
  <div class="image"></div>
  <div class="text">
   <p>Flex</p>
  </div>
</div>
</body>
</html>
</code>```

Body:
Is it possible to get seamless pattern repeat with following conditions?

Idea is to have one rotated background with fixed attachment. I think this is how is supposed to be working, but are there any ways of achieving that?

body {
  padding: 50px;
  margin: 0;
  height: 10000px;
}

.main {
  width: 100%;
  height: 1300px;
  box-sizing: border-box;
  overflow: hidden;
  border: 5px solid #7cb7b7;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.background {
  background-image: url('https://thumbs.dreamstime.com/b/circles-seamless-pattern-10032830.jpg');
  background-attachment: fixed;
  background-repeat: repeat;
  position: absolute;
  top: -1000%;
  left: -1000%;
  right: -1000%;
  bottom: -1000%;
  transform: rotate(-15deg);
}

.text {
  background: white;
  border: 2px solid black;
  width: 200px;
  height: 70px;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1;
}

Flex


问:
HTML won't display 2 images
I want to display 2 images on the same row like this:

```<code>Image  Same Text  Image
</code>```

If I put one image it works, but if I put both of them I get 404.
I think I am doing something wrong in the code I don't have much experience with HTML and don't know what I am missing.
The files are in same folder.
Here is the code:

```<code><td colspan="8" >
<h1>
<img src="/home/apps/myapp/dynamic/img/myimage1.png" style="float:left; " alt="This is my mage" height="130" width="455">
<b>Same text</b>
<img src="/home/apps/myapp/dynamic/img/myimage2.png" style="float:right; vertical-align:middle;" alt="My second image" height="130" width="454"></h1>
</td>
</code>```

答:
simply you can use bootstrap..
divide the page into 2 halves using col-md-6 and put your data in its individual divs</p>

```<code>   <div class="container">
    <div class="row">
     <div class="col-md-6">
      <img src="/path1">
     </div>
    <div class="col-md-6">
     <img src="/path2">
    </div>
   </div>
  </div>
</code>```

Title: HTML won't display 2 images

Body:
I want to display 2 images on the same row like this:

Image  Same Text  Image

If I put one image it works, but if I put both of them I get 404.
I think I am doing something wrong in the code I don't have much experience with HTML and don't know what I am missing.
The files are in same folder.
Here is the code:

Same text

Body:
simply you can use bootstrap..
divide the page into 2 halves using col-md-6 and put your data in its individual divs

   <div class="container">
    <div class="row">
     <div class="col-md-6">
      <img src="/path1">
     </div>
    <div class="col-md-6">
     <img src="/path2">
    </div>
   </div>
  </div>


问:
WinForms ComboBox SelectedIndexChanged not firing when typing few chars followed by Alt+Down
In short

When I type a character in a ComboBox, press Alt+Down followed by Enter or Tab, the SelectedIndexChanged event doesn't fire, even though the SelectedIndex value does change!  Why doesn't the event fire?

Update
The same error occurs if you type a character, press Alt+Down and then type Esc. You would expect the Esc to cancel the change. However, the SelectedIndex does change, and the SelectedIndexChanged event doesn't fire.

What should happen if you just type Alt+Down, use the arrow keys to browse to an entry, and then type Esc? Should the selected index be set back to its original value?

Not so short

I have a WinForm application with a ComboBox on it. The ComboBox' SelectedIndexChanged event is wired up to a event handler that shows the SelectedItem in a Label control. The ComboBox' Items collection has three values: "One", "Two", and "Three".

When I select an item with the mouse, the event fires.

When I scroll the mouse, the event fires.

When I use Alt+Down to expand the combobox and walk through the items with Up and Down, the event fires.

But... When I type in the first character of a value, then press Alt+Down, followed by Enter or Tab, the value does get selected and is shown in the combobox, but the event doesn't fire.

I've also added a button that shows the SelectedIndex. It shows the SelectedIndex has changed. So even though the SelectedIndex does change, the SelectedIndexChanged event does not fire!

If I just type in a valid value like One the event doesn't fire either, but in that case a click on the button reveals the SelectedIndex indeed hasn't changed. So in that case the behavior is normal.

To reproduce, create a Form and add a ComboBox, a Label and a Button. Place the following code in the Form1.cs:

```<code>using System;
using System.Windows.Forms;

namespace ComboBoxSelectedIndexChanged
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            comboBox1.Items.AddRange(new object[] {
                "One",
                "Two",
                "Three"
            });
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            label1.Text = "Selected index: " + comboBox1.SelectedIndex;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Selected item: " + comboBox1.SelectedItem +
                "\nSelected index: " + comboBox1.SelectedIndex);
        }
    }
}
</code>```

答:
I've tried several google searches in order to find a definitive answer on this but didn't find one before. Just now I found a thread that actually refers to a Microsoft knowledge base article about the problem. Article KB948869 describes the problem.

The knowledge base article suggest to create your own combobox and override the ProcessDialogKey method.

```<code>using System.Windows.Forms;

public class MyComboBox : ComboBox
{
    protected override bool ProcessDialogKey(Keys keyData)
    {
        if (keyData == Keys.Tab)
            this.DroppedDown = false;
        return base.ProcessDialogKey(keyData);
    }
}
</code>```

I've tried it, but unfortunately, it doesn't seem to have any effect. Which is a bit strange. I would expect a workaround described in a knowledge base article to be accurate.

I found another workaround though, which is to use the DropDownClosed event in stead.

```<code>private void comboBox1_DropDownClosed(object sender, EventArgs e)
{
    label1.Text = "DroDownClosed Selected index: " + comboBox1.SelectedIndex;
}
</code>```

This does seem to work, but only when using DropDownStyle.DropDown. When you set the DropDownStyle to DropDownList, typing a character does not fire the DropDownClosed (as there is no actual drop down in that case). Only if you actually open up the drop down list and select a value the DropDownClosed event is fired.

So, both options are not really a good answer.

Update
I've even tried overriding property SelectedIndex in MyComboBox, having it call OnSelectedIndexChanged(EventArgs.Empty). After typing a character and pressing Alt+Down, the setter is executed, but it's setting the value to -1, which it already is. After pressing Tab, the setter isn't executed again, although somehow the SelectedIndex value does change. It looks like the ComboBox is directly changing the backing field for SelectedIndex, bypassing the setting. I believe something like this probably also happens in the real ComboBox.

Body:
In short

When I type a character in a ComboBox, press Alt+Down followed by Enter or Tab, the SelectedIndexChanged event doesn't fire, even though the SelectedIndex value does change!  Why doesn't the event fire?

Update
The same error occurs if you type a character, press Alt+Down and then type Esc. You would expect the Esc to cancel the change. However, the SelectedIndex does change, and the SelectedIndexChanged event doesn't fire.

What should happen if you just type Alt+Down, use the arrow keys to browse to an entry, and then type Esc? Should the selected index be set back to its original value?

Not so short

I have a WinForm application with a ComboBox on it. The ComboBox' SelectedIndexChanged event is wired up to a event handler that shows the SelectedItem in a Label control. The ComboBox' Items collection has three values: "One", "Two", and "Three".

When I select an item with the mouse, the event fires.

When I scroll the mouse, the event fires.

When I use Alt+Down to expand the combobox and walk through the items with Up and Down, the event fires.

But... When I type in the first character of a value, then press Alt+Down, followed by Enter or Tab, the value does get selected and is shown in the combobox, but the event doesn't fire.

I've also added a button that shows the SelectedIndex. It shows the SelectedIndex has changed. So even though the SelectedIndex does change, the SelectedIndexChanged event does not fire!

If I just type in a valid value like One the event doesn't fire either, but in that case a click on the button reveals the SelectedIndex indeed hasn't changed. So in that case the behavior is normal.

To reproduce, create a Form and add a ComboBox, a Label and a Button. Place the following code in the Form1.cs:

using System;
using System.Windows.Forms;

namespace ComboBoxSelectedIndexChanged
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            comboBox1.Items.AddRange(new object[] {
                "One",
                "Two",
                "Three"
            });
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            label1.Text = "Selected index: " + comboBox1.SelectedIndex;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Selected item: " + comboBox1.SelectedItem +
                "\nSelected index: " + comboBox1.SelectedIndex);
        }
    }
}

Body:
I've tried several google searches in order to find a definitive answer on this but didn't find one before. Just now I found a thread that actually refers to a Microsoft knowledge base article about the problem. Article KB948869 describes the problem.

The knowledge base article suggest to create your own combobox and override the ProcessDialogKey method.

using System.Windows.Forms;

public class MyComboBox : ComboBox
{
    protected override bool ProcessDialogKey(Keys keyData)
    {
        if (keyData == Keys.Tab)
            this.DroppedDown = false;
        return base.ProcessDialogKey(keyData);
    }
}

I've tried it, but unfortunately, it doesn't seem to have any effect. Which is a bit strange. I would expect a workaround described in a knowledge base article to be accurate.

I found another workaround though, which is to use the DropDownClosed event in stead.

private void comboBox1_DropDownClosed(object sender, EventArgs e)
{
    label1.Text = "DroDownClosed Selected index: " + comboBox1.SelectedIndex;
}

This does seem to work, but only when using DropDownStyle.DropDown. When you set the DropDownStyle to DropDownList, typing a character does not fire the DropDownClosed (as there is no actual drop down in that case). Only if you actually open up the drop down list and select a value the DropDownClosed event is fired.

So, both options are not really a good answer.

Update
I've even tried overriding property SelectedIndex in MyComboBox, having it call OnSelectedIndexChanged(EventArgs.Empty). After typing a character and pressing Alt+Down, the setter is executed, but it's setting the value to -1, which it already is. After pressing Tab, the setter isn't executed again, although somehow the SelectedIndex value does change. It looks like the ComboBox is directly changing the backing field for SelectedIndex, bypassing the setting. I believe something like this probably also happens in the real ComboBox.


问:
Is there a way to search a String of lyrics then substring out the matching phrases
I need to search lyrics for a matching phrase.

For example:

I have song lyrics like these.

"She is the one that I love, I know it something something something something something she loves you and me something something something."

Given this search term below, search the lyrics for the closest match and count the characters in the sub string. My issue is finding the closest match using indexOf returns the first SHE. I need the to be able to sub string out the closes matching phrase.

The results should print :

The closest matching search for 'she loves me' is "she loves you and me".

Index Length: 20

答: You could implement your own sophisticated algorithm in Java because in JDK we don't have an appropriate solution out of the box. But in Java world are a lot of suitable solution you could try to solve your issue by using Apache Lucene.</p>


问:
App. Server gets down while running test using latest Jmeter 3.3
My app server gets down during load test using latest 3.3 version of jmeter, however works fine in older jmeter 2.13

Any idea, I'm not figuring out since I'm using the the same script in both of the versions.

I can notice, there is huge difference in response time.

The other thing, I notice is the Server Memory gets piled up, not gets free up eventually while running using latest 3.3 version of Jmeter.

Please throw some light on this issue.

答:
Are you testing the exact same application with the 2 versions ?
Is it the exact same script ?

If yes, This can be explained by lot of improvements on performances done in JMeter between 2.13 and 3.3 particularly on embedded resources download.

If you’re using it then it’s the explanation:

https://jmeter.apache.org/changes.html


问:
Microsoft.Solutions/applicationDefinitions internal server error
I'm trying to create a Service catalog managed application definition and get the following error :{
  "error": {
    "code": "InternalServerError",
    "message": "Encountered an internal server error. The tracking id is '5d5bf382-f101-48d7-bd89-72c72536a4a9'."
  }
}

Is there anyway to find out what causes this? I did come across before. And believe it might be something to do with the template. I've tested the following using visual studio and the deployments works correctly. Just uploading the app.zip with the templates causes this error.

答: You can either look at the Azure Portal and go to Event Monitor and find error records and discern from the text there what went wrong or use Get-AzureRmLog -CorrelationId GUID_goes_here and look from there.


问:
Neo4j-shell not working on Mac Community edition 3.3.0
I'm new to Neo4j and have installed the Community Edition (3.3.0).  I'm working through tutorials that reference neo4j-shell.  However, every time I try to run it I get:

```<code>-bash: /usr/local/bin/neo4j-shell: No such file or directory
</code>```

I tried to run the Desktop version and use its terminal, but get the same thing.  I even installed it with Homebrew (have since uninstalled) and it seemed to respond but could not connect to anything even when I used the appropriate switches.  I've also tried things I've found searching here and within the Google Group to no avail.

Could anyone please let me know how to get this running with Community Edition, or if not possible, please let me know how to otherwise.  I'm running on a Mac and installed using the .dmg file.

Thanks in advance for your help.

Greg

答:
Apparently, cypher-shell is the command to use now.

It only seems to work for me with the Desktop edition.  I'm going to close this topic out and likely post the issue, unless I can find a solution, as a cypher-shell topic.

Body:
I'm new to Neo4j and have installed the Community Edition (3.3.0).  I'm working through tutorials that reference neo4j-shell.  However, every time I try to run it I get:

-bash: /usr/local/bin/neo4j-shell: No such file or directory

I tried to run the Desktop version and use its terminal, but get the same thing.  I even installed it with Homebrew (have since uninstalled) and it seemed to respond but could not connect to anything even when I used the appropriate switches.  I've also tried things I've found searching here and within the Google Group to no avail.

Could anyone please let me know how to get this running with Community Edition, or if not possible, please let me know how to otherwise.  I'm running on a Mac and installed using the .dmg file.

Thanks in advance for your help.

Greg


问:
What happens if I send longer key to mysql AES_ENCRYPT than allowed
In mysql 5.7.10 I am using AES_Encrypt with cbc 256 bit mode so I have to use 32-byte key. But I I use longer key, the result is different, so how does MYSQL takes longer key into account?

Because I wanted to use 64-byte (512 bit) key and this kind of "works" in MYSQL, but using Chilkasoft crypt2library the 64-byte key is not working, I mean result is not the same as from MySQL.

Any ideas, can I use longer key than 32-byte (I use SHA512 to generate the key, that is why I have 64-byte key).

答:
```<code>bzero((char*) rkey,AES_KEY_LENGTH/8);
for (ptr= rkey, sptr= key; sptr < key_end; ptr++,sptr++)
{
    if (ptr == rkey_end)
    ptr= rkey;  /*  Just loop over tmp_key until we used all key */
    *ptr^= (uint8) *sptr;
}
</code>```

I found the answer here. Basically it creates an array of zeros and foreach the key and just xors it. No matter how long is the key, the array will be always 32/16 bytes.

Body:
bzero((char*) rkey,AES_KEY_LENGTH/8);
for (ptr= rkey, sptr= key; sptr < key_end; ptr++,sptr++)
{
    if (ptr == rkey_end)
    ptr= rkey;  /*  Just loop over tmp_key until we used all key */
    *ptr^= (uint8) *sptr;
}

I found the answer here. Basically it creates an array of zeros and foreach the key and just xors it. No matter how long is the key, the array will be always 32/16 bytes.


问:
How to check whether scrollview / recyclerview is scrolling to up or down android
I am working on android app and using recyclerview and scrollview in some activities. Now I want to show some layout when recyclerview/scrollview scrolls in up direction and hide the layout when it scrolls in down direction.
I want a function which can tell that recyclerview/scrollview is scrolling in up or down direction.

Please help if anyone know how to do this for both recyclerview and scrollview.

Thanks a lot in advanced.

答:
A sure short answer for this issue

```<code>scroll.setOnScrollChangeListener(new View.OnScrollChangeListener() {
        @Override
        public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                    int x = scrollY - oldScrollY;
                    if (x > 0) {
                        //scroll up
                    } else if (x < 0) {
                       //scroll down
                    } else {

                    }

        }
    });
</code>```

Body:
A sure short answer for this issue

scroll.setOnScrollChangeListener(new View.OnScrollChangeListener() {
        @Override
        public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                    int x = scrollY - oldScrollY;
                    if (x > 0) {
                        //scroll up
                    } else if (x < 0) {
                       //scroll down
                    } else {

                    }

        }
    });


问:
Index python dict by object or two floats
I have a number of objects which I need to link to an integer number. These objects are ArcGIS Point objects (exactly what they are isn't relevant), which store an X and a Y value for a point, as floating point numbers.

I need to record that, for example:

```<code>Point(X = 2.765, Y = 3.982) -> 2
Point(X = 33.9, Y = 98.45) -> 7
Point(X = 1.23, Y = 2.43) -> 9
Point(X = 8.342, Y = 6.754) -> 5
</code>```

I then need to be able to look up the resulting value by the X and Y values. I've tried using the Point objects as the dictionary's key, but this doesn't work as when I recreate the point object from the X and Y values it doesn't look it up properly anymore (presumably because the object ID has changed).

How should I go about linking these point values to the integers. Is there another way that I can use a dictionary?

答:
Add a hash method to your Point class:

```<code>...
def __hash__(self):
    return hash(self.x) ^ hash(self.y)
...
</code>```

In other words, the hash of a point is a munging of the hash of the x and y coordinates.

EDIT:  a better hash function (based on comments here) is:

```<code>...
def __hash__(self):
    return hash((self.x, self.y))
...
</code>```

Because Python hashes tuples in a way that hash((p,q)) does not equal hash((q,p)), this will avoid hash collisions for points symmetric about the diagonal.

Then, you can use your Point object as keys for dictionaries, put them in sets, etc.

Body:
I have a number of objects which I need to link to an integer number. These objects are ArcGIS Point objects (exactly what they are isn't relevant), which store an X and a Y value for a point, as floating point numbers.

I need to record that, for example:

Point(X = 2.765, Y = 3.982) -> 2
Point(X = 33.9, Y = 98.45) -> 7
Point(X = 1.23, Y = 2.43) -> 9
Point(X = 8.342, Y = 6.754) -> 5

I then need to be able to look up the resulting value by the X and Y values. I've tried using the Point objects as the dictionary's key, but this doesn't work as when I recreate the point object from the X and Y values it doesn't look it up properly anymore (presumably because the object ID has changed).

How should I go about linking these point values to the integers. Is there another way that I can use a dictionary?

Body:
Add a hash method to your Point class:

...
def __hash__(self):
    return hash(self.x) ^ hash(self.y)
...

In other words, the hash of a point is a munging of the hash of the x and y coordinates.

EDIT:  a better hash function (based on comments here) is:

...
def __hash__(self):
    return hash((self.x, self.y))
...

Because Python hashes tuples in a way that hash((p,q)) does not equal hash((q,p)), this will avoid hash collisions for points symmetric about the diagonal.

Then, you can use your Point object as keys for dictionaries, put them in sets, etc.


问:
An error building Qt libraries for the raspberry pi
I am trying to compile the Qt 5 libraries for my RPI, but it always crashes.

These are the guides I have tried to follow:

http://qt-project.org/wiki/RaspberryPi_Beginners_guide

http://qt-project.org/wiki/RaspberryPi

I have downloaded the cross-compiler and sysroot-image according to the guide and pulled the Qt5 sources from the git repo.

After following one of the guides I am now stuck at make.

This is the error I am receiving:

```<code>.obj/release-shared/qlibrary_unix.o: In function `QLibraryPrivate::load_sys()':
qlibrary_unix.cpp:(.text+0xf84): warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
/home/esa/qtonpi/rpi_image/usr/lib/arm-linux-gnueabihf/libdl.a(dlopen.o): In function `dlopen':
(.text+0xc): undefined reference to `__dlopen'
/home/esa/qtonpi/rpi_image/usr/lib/arm-linux-gnueabihf/libdl.a(dlclose.o): In function `dlclose':
(.text+0x0): undefined reference to `__dlclose'
/home/esa/qtonpi/rpi_image/usr/lib/arm-linux-gnueabihf/libdl.a(dlsym.o): In function `dlsym':
(.text+0xc): undefined reference to `__dlsym'
/home/esa/qtonpi/rpi_image/usr/lib/arm-linux-gnueabihf/libdl.a(dlerror.o): In function `dlerror':
(.text+0x0): undefined reference to `__dlerror'
/home/esa/qtonpi/rpi_image/usr/lib/arm-linux-gnueabihf/libm.a(feholdexcpt.o): In function `feholdexcept':
(.text+0x48): undefined reference to `_dl_hwcap'
/home/esa/qtonpi/rpi_image/usr/lib/arm-linux-gnueabihf/libm.a(fesetenv.o): In function `fesetenv':
(.text+0x64): undefined reference to `_dl_hwcap'
collect2: virhe: ld:n paluuarvo oli 1                                           # collect2: error: ld returnvalue was 1
make[2]: *** [../../lib/libQt5Core.so.5.0.0] Virhe 1                            # Error 1
make[2]: Poistutaan hakemistosta "/home/esa/qtonpi/qt5/qtbase/src/corelib"      # Leaving directory
make[1]: *** [sub-corelib-make_first] Virhe 2                                   # Error 2
make[1]: Poistutaan hakemistosta "/home/esa/qtonpi/qt5/qtbase/src"              # Leaving directory
make: *** [sub-src-make_first] Virhe 2                                          # Error 2
</code>```

答:
instead of fixQualifiedLibraryPaths use:</p>

```<code>cd <folder-with-sysroot-subfolder>
wget https://raw.githubusercontent.com/riscv/riscv-poky/master/script/sysroot-relativelinks.py
chmod +x sysroot-relativelinks.py
./sysroot-relativelinks.py sysroot
</code>```

Body:
I am trying to compile the Qt 5 libraries for my RPI, but it always crashes.

These are the guides I have tried to follow:

http://qt-project.org/wiki/RaspberryPi_Beginners_guide

http://qt-project.org/wiki/RaspberryPi

I have downloaded the cross-compiler and sysroot-image according to the guide and pulled the Qt5 sources from the git repo.

After following one of the guides I am now stuck at make.

This is the error I am receiving:

.obj/release-shared/qlibrary_unix.o: In function `QLibraryPrivate::load_sys()':
qlibrary_unix.cpp:(.text+0xf84): warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
/home/esa/qtonpi/rpi_image/usr/lib/arm-linux-gnueabihf/libdl.a(dlopen.o): In function `dlopen':
(.text+0xc): undefined reference to `__dlopen'
/home/esa/qtonpi/rpi_image/usr/lib/arm-linux-gnueabihf/libdl.a(dlclose.o): In function `dlclose':
(.text+0x0): undefined reference to `__dlclose'
/home/esa/qtonpi/rpi_image/usr/lib/arm-linux-gnueabihf/libdl.a(dlsym.o): In function `dlsym':
(.text+0xc): undefined reference to `__dlsym'
/home/esa/qtonpi/rpi_image/usr/lib/arm-linux-gnueabihf/libdl.a(dlerror.o): In function `dlerror':
(.text+0x0): undefined reference to `__dlerror'
/home/esa/qtonpi/rpi_image/usr/lib/arm-linux-gnueabihf/libm.a(feholdexcpt.o): In function `feholdexcept':
(.text+0x48): undefined reference to `_dl_hwcap'
/home/esa/qtonpi/rpi_image/usr/lib/arm-linux-gnueabihf/libm.a(fesetenv.o): In function `fesetenv':
(.text+0x64): undefined reference to `_dl_hwcap'
collect2: virhe: ld:n paluuarvo oli 1                                           # collect2: error: ld returnvalue was 1
make[2]: *** [../../lib/libQt5Core.so.5.0.0] Virhe 1                            # Error 1
make[2]: Poistutaan hakemistosta "/home/esa/qtonpi/qt5/qtbase/src/corelib"      # Leaving directory
make[1]: *** [sub-corelib-make_first] Virhe 2                                   # Error 2
make[1]: Poistutaan hakemistosta "/home/esa/qtonpi/qt5/qtbase/src"              # Leaving directory
make: *** [sub-src-make_first] Virhe 2                                          # Error 2

Body:
instead of fixQualifiedLibraryPaths use:

cd <folder-with-sysroot-subfolder>
wget https://raw.githubusercontent.com/riscv/riscv-poky/master/script/sysroot-relativelinks.py
chmod +x sysroot-relativelinks.py
./sysroot-relativelinks.py sysroot


问:
Arduino Micro pro not uploading any code
I have been programming the arduino micro pro board for a a few weeks now, recently (on all devices I try on) when I upload my code, any code, via Arduino IDE, I get the following error:

```<code>avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = ""; type =
Software Version = .; Hardware Version = .
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: exit bootloader
</code>```

when I disconnect and re-connect the board, it runs the last code I uploaded to it before this problem occurred.

Anyone know how to fix this?

答:
I had the same issue when trying to upload code into Arduino Micro ( Chinese clone ). Spending hours on Google, flashing new bootloader - still nothing. Physical reset and opening COM port with boundrate 1200 doesn't work. Why?

I HAVE ATMEGA168 INSTEAD OF ATMEGA32u4!

Google is telling, that Arduino Micro got Atmega32u4, but my clone got Atmega168! First of all, check what atmega type do you have by lookup on black soldered chip on Arduino. So instead of choose "Arduino Micro" on Arduino IDE menu, i choose Arduino Nano and everything works!

Body:
I have been programming the arduino micro pro board for a a few weeks now, recently (on all devices I try on) when I upload my code, any code, via Arduino IDE, I get the following error:

avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = ""; type =
Software Version = .; Hardware Version = .
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: exit bootloader

when I disconnect and re-connect the board, it runs the last code I uploaded to it before this problem occurred.

Anyone know how to fix this?


问:
Hibernate unable to add foreign key constraint
I have already created database and all tables with all foreign key constraints. But when I run the spring boot application hibernate is throwing error

Unable to execute schema management to JDBC target [alter table
  tlp_client add constraint FKfd2km387c8s4oou769dmw5t94 foreign key
  (u_frn_address_id) references tlp_address (a_id)]

Entity

```<code>@Entity
@Table(name = "tlp_client")
public class ClientModel {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   @Column(name = "c_id")
   private Long id;

   @Column(name = "c_name")
   private String name;

   @Column(name = "c_description")
   private String description;

   @Column(name = "c_web_url")
   private String webUrl;

   @Column(name = "c_created_at")
   private Calendar createdAt;

   @Column(name = "c_is_active")
   private Boolean isActive;

   @OneToOne
   @JoinColumn(name = "u_frn_created_by", referencedColumnName = "u_id")
   private UserModel createdBy;

   @OneToOne
   @JoinColumn(name = "u_frn_address_id", referencedColumnName = "a_id")
   private AddressModel address;

    }
   // getters and setters ...
}
</code>```

SQL for ClientModel

```<code>create table tlp_client (
   c_id INT(11) AUTO_INCREMENT,
   c_name varchar(255) NOT NULL,
   c_description varchar(255),
   c_web_url varchar(255),
   c_created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
   c_is_active TINYINT(1) DEFAULT 1,

   c_frn_created_by INT(11),
   c_frn_address_id INT(11),

   PRIMARY KEY (c_id),
   FOREIGN KEY (c_frn_address_id) REFERENCES tlp_address (a_id),
   FOREIGN KEY (c_frn_created_by) REFERENCES tlp_user (u_id)
);
</code>```

SQL forAddressModel

```<code>create table tlp_address (
   a_id INT(11) AUTO_INCREMENT,
   a_address varchar(255),
   a_city varchar(255),
   a_state varchar(255),
   a_country varchar(255),
   a_zip varchar(8),

   PRIMARY KEY (a_id)
);
</code>```

My Question is, I have already created all the tables and still why hibernate is trying to create tables?

application.properties

```<code>spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/dbName?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.pool.size=20
server.port=8090
</code>```

UPDATE
I ran the application by setting spring.jpa.hibernate.ddl-auto=validate in application.properties, now it is throwing the error

Schema-validation: wrong column type encountered in column [a_id] in
  table [tlp_address]; found [int (Types#INTEGER)], but expecting
  [bigint (Types#BIGINT)]

答: The error was due to a simple mistake I made. In the sql scripts, I have field c_frn_addres_id, but in the entity class, I was mapping it to u_frn_address_id. So after changing u_frn_address_id to c_frn_address_id, it is working fine

Body:
I have already created database and all tables with all foreign key constraints. But when I run the spring boot application hibernate is throwing error

Unable to execute schema management to JDBC target [alter table
  tlp_client add constraint FKfd2km387c8s4oou769dmw5t94 foreign key
  (u_frn_address_id) references tlp_address (a_id)]

Entity

@Entity
@Table(name = "tlp_client")
public class ClientModel {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   @Column(name = "c_id")
   private Long id;

   @Column(name = "c_name")
   private String name;

   @Column(name = "c_description")
   private String description;

   @Column(name = "c_web_url")
   private String webUrl;

   @Column(name = "c_created_at")
   private Calendar createdAt;

   @Column(name = "c_is_active")
   private Boolean isActive;

   @OneToOne
   @JoinColumn(name = "u_frn_created_by", referencedColumnName = "u_id")
   private UserModel createdBy;

   @OneToOne
   @JoinColumn(name = "u_frn_address_id", referencedColumnName = "a_id")
   private AddressModel address;

    }
   // getters and setters ...
}

SQL for ClientModel

create table tlp_client (
   c_id INT(11) AUTO_INCREMENT,
   c_name varchar(255) NOT NULL,
   c_description varchar(255),
   c_web_url varchar(255),
   c_created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
   c_is_active TINYINT(1) DEFAULT 1,

   c_frn_created_by INT(11),
   c_frn_address_id INT(11),

   PRIMARY KEY (c_id),
   FOREIGN KEY (c_frn_address_id) REFERENCES tlp_address (a_id),
   FOREIGN KEY (c_frn_created_by) REFERENCES tlp_user (u_id)
);

SQL forAddressModel

create table tlp_address (
   a_id INT(11) AUTO_INCREMENT,
   a_address varchar(255),
   a_city varchar(255),
   a_state varchar(255),
   a_country varchar(255),
   a_zip varchar(8),

   PRIMARY KEY (a_id)
);

My Question is, I have already created all the tables and still why hibernate is trying to create tables?

application.properties

spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/dbName?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.pool.size=20
server.port=8090

UPDATE
I ran the application by setting spring.jpa.hibernate.ddl-auto=validate in application.properties, now it is throwing the error

Schema-validation: wrong column type encountered in column [a_id] in
  table [tlp_address]; found [int (Types#INTEGER)], but expecting
  [bigint (Types#BIGINT)]


问:
how disable button if app not install in phone
I have button and i want disable this button if app by Package not installed and user can click if app install in phone ..

my code

```<code>    Button start = (Button) findViewById(R.id.bt_start);
    boolean isAppInstalled = appInstalledOrNot("com.check.application");
    if(isAppInstalled) {
        Intent Start_screen = new Intent(SplashScreen.this, MainActivity.class);
        startActivity(Start_screen);

    } else {

        start.setEnabled(false);

    }
}

private boolean appInstalledOrNot(String uri) {
    PackageManager pm = getPackageManager();
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
    }

    return false;
}
</code>```

I use this code but the button is disabled at all times .. if app install the button disable and if not install the button disable

答:
Why don't you try below method to check for existence of package in android

```<code>public boolean isPackageExisted(String targetPackage){
    List<ApplicationInfo> packages;
    PackageManager pm;

    pm = getPackageManager();
    packages = pm.getInstalledApplications(0);
    for (ApplicationInfo packageInfo : packages) {
        if(packageInfo.packageName.equals(targetPackage))
            return true;
    }
    return false;
}
</code>```

Call method isPackageExisted with targetPacket.

Body:
I have button and i want disable this button if app by Package not installed and user can click if app install in phone ..

my code

    Button start = (Button) findViewById(R.id.bt_start);
    boolean isAppInstalled = appInstalledOrNot("com.check.application");
    if(isAppInstalled) {
        Intent Start_screen = new Intent(SplashScreen.this, MainActivity.class);
        startActivity(Start_screen);

    } else {

        start.setEnabled(false);

    }
}

private boolean appInstalledOrNot(String uri) {
    PackageManager pm = getPackageManager();
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
    }

    return false;
}

I use this code but the button is disabled at all times .. if app install the button disable and if not install the button disable

Body:
Why don't you try below method to check for existence of package in android

public boolean isPackageExisted(String targetPackage){
    List<ApplicationInfo> packages;
    PackageManager pm;

    pm = getPackageManager();
    packages = pm.getInstalledApplications(0);
    for (ApplicationInfo packageInfo : packages) {
        if(packageInfo.packageName.equals(targetPackage))
            return true;
    }
    return false;
}

Call method isPackageExisted with targetPacket.


问:
ruby file locking error Errno::EBADF in solaris
Am trying to lock one executable script to make sure it doesn't run second time when there is another process running. Here is my code,

```<code>if $0 == __FILE__
  if File.new(__FILE__).flock(File::LOCK_EX | File::LOCK_NB)
    main()
  end
end
</code>```

and getting below error,

```<code># ruby /tmp/test.rb
/tmp/test.rb:397:in `flock': Bad file number - /tmp/test.rb (Errno::EBADF)
        from /tmp/test.rb:397:in `<main>'
#
</code>```

Am using ruby version 1.9.3,

```<code># ruby --version
ruby 1.9.3p551 (2014-11-13 revision 48407) [sparc-solaris2.11]
#
</code>```

But its working perfect in Linux environments.

答:
Found the solution. In Solaris we need to open file with read/write mode only then the exclusive lock will happen. </p>

```<code>if $0 == __FILE__
  if File.new(__FILE__, 'r+').flock(File::LOCK_EX | File::LOCK_NB)
    main()
  end
end
</code>```

Body:
Am trying to lock one executable script to make sure it doesn't run second time when there is another process running. Here is my code,

if $0 == __FILE__
  if File.new(__FILE__).flock(File::LOCK_EX | File::LOCK_NB)
    main()
  end
end

and getting below error,

# ruby /tmp/test.rb
/tmp/test.rb:397:in `flock': Bad file number - /tmp/test.rb (Errno::EBADF)
        from /tmp/test.rb:397:in `'
#

Am using ruby version 1.9.3,

# ruby --version
ruby 1.9.3p551 (2014-11-13 revision 48407) [sparc-solaris2.11]
#

But its working perfect in Linux environments.

Body:
Found the solution. In Solaris we need to open file with read/write mode only then the exclusive lock will happen.

if $0 == __FILE__
  if File.new(__FILE__, 'r+').flock(File::LOCK_EX | File::LOCK_NB)
    main()
  end
end