问:
My php Scripts is very slow at server
i'm testing an app hosted at: app.promls.net, but there is some mistake on the script execution, on localhost
takes only -> timer: 0.12875008583069 seconds. .
in the execution when is just plain text that are created via php.
and when content is created dinamically and cames from mysql database:
timer: 0.44203495979309 seconds.  /timer: 0.65762710571289 seconds. / timer: 0.48272085189819 seconds.
the times are diferent on the server. takes like 8 seconds on execution.

does anyone could give me a recomendation of how test and optimize my php execution.
i was optimizing the mysql database, cause some querys returns a tons of rows for a simple search, using describe and explain.
but know i have finished, and i would like to explore some new options for php execution.
i know that adding compression to html helps, but it only help on time of trasportation between server and final host when returns an html response. know i want to optimize php execution and if there are some tricks on mysql that could be implemented to help me improve the time response better.

note: i have thinking in use the hiphop for php and memcache or cassandra. but i guess those thinks are not re result for problem, cause i have no activities( means user actions) and no much information on my app.

thanks in advance i'm available for any comments or suggestions.

答:
with such a big difference on execution we would need details on the host configuration (shared? dedicated?).

Is mysql skipping DNS test? if not try using skip-name-resolve setting in my.cnf, or use IP and not DNS in the PRIVILEGE query/user table, the only time I have seen such latency it was because of DNS timeout in the connection between MySQL and PHP.

Title: My php Scripts is very slow at server


来源: stackexchange

问:
Building Abreviations Dictionary from Text file
I would like to build a dictionary of abreviations.

I have a text file with a lot of abreviations. The text file looks like this(after import)

```<code>with open('abreviations.txt') as ab:
    ab_words = ab.read().splitlines()
</code>```

An extract:

```<code>'ACE',
'Access Control Entry',
'ACK',
'Acknowledgement',
'ACORN',
'A Completely Obsessive Really Nutty person',
</code>```

Now I want to build the dictionnary, where I have every uneven line as a dictionary key and every even line as the dictionary value.

Hence I should be able to write at the end:

```<code>ab_dict['ACE']
</code>```

and get the result:

```<code>'Access Control Entry'
</code>```

Also, How can I make it case-insensitive ?

```<code>ab_dict['ace']
</code>```

should yield the same result

```<code>'Access Control Entry'
</code>```

In fact, it would be perfect, if the output would also be lower case:

```<code>'access control entry'
</code>```

Here is a link to the text file: https://www.dropbox.com/s/91afgnupk686p9y/abreviations.txt?dl=0

答:
Here is an answer that also allows sentences to be replaced with words from the dictionary:

```<code>import re
from requests.structures import CaseInsensitiveDict

def read_file_dict(filename):
    """
    Reads file data into CaseInsensitiveDict
    """

    # lists for keys and values
    keys = []
    values = []

    # case sensitive dict
    data = CaseInsensitiveDict()

    # count used for deciding which line we're on
    count = 1

    with open(filename) as file:
        temp = file.read().splitlines()

        for line in temp:

            # if the line count is even, a value is being read
            if count % 2 == 0:
                values.append(line)

            # otherwise, a key is being read
            else:
                keys.append(line)
            count += 1

    # Add to dictionary
    # perhaps some error checking here would be good
    for key, value in zip(keys, values):
        data[key] = value

    return data

def replace_word(ab_dict, sentence):
    """
    Replaces sentence with words found in dictionary
    """

    # not necessarily words, but you get the idea
    words = re.findall(r"[\w']+|[.,!?; ]", sentence)

    new_words = []
    for word in words:

        # if word is in dictionary, replace it and add it to resulting list
        if word in ab_dict:
            new_words.append(ab_dict[word])

        # otherwise add it as normally
        else:
            new_words.append(word)

    # return sentence with replaced words
    return "".join(x for x in new_words)

def main():
    ab_dict = read_file_dict("abreviations.txt")

    print(ab_dict)

    print(ab_dict['ACE'])
    print(ab_dict['Ace'])
    print(ab_dict['ace'])

    print(replace_word(ab_dict, "The ACE is not easy to understand"))

if __name__ == '__main__':
    main()
</code>```

Which outputs:

```<code>{'ACE': 'Access Control Entry', 'ACK': 'Acknowledgement', 'ACORN': 'A Completely Obsessive Really Nutty person'}
Access Control Entry
Access Control Entry
Access Control Entry
The Access Control Entry is not easy to understand
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to build a dictionary of abreviations.

I have a text file with a lot of abreviations. The text file looks like this(after import)

with open('abreviations.txt') as ab:
    ab_words = ab.read().splitlines()

An extract:

'ACE',
'Access Control Entry',
'ACK',
'Acknowledgement',
'ACORN',
'A Completely Obsessive Really Nutty person',

Now I want to build the dictionnary, where I have every uneven line as a dictionary key and every even line as the dictionary value.

Hence I should be able to write at the end:

ab_dict['ACE']

and get the result:

'Access Control Entry'

Also, How can I make it case-insensitive ?

ab_dict['ace']

should yield the same result

'Access Control Entry'

In fact, it would be perfect, if the output would also be lower case:

'access control entry'

Here is a link to the text file: https://www.dropbox.com/s/91afgnupk686p9y/abreviations.txt?dl=0

Body:
Here is an answer that also allows sentences to be replaced with words from the dictionary:

import re
from requests.structures import CaseInsensitiveDict

def read_file_dict(filename):
    """
    Reads file data into CaseInsensitiveDict
    """

    # lists for keys and values
    keys = []
    values = []

    # case sensitive dict
    data = CaseInsensitiveDict()

    # count used for deciding which line we're on
    count = 1

    with open(filename) as file:
        temp = file.read().splitlines()

        for line in temp:

            # if the line count is even, a value is being read
            if count % 2 == 0:
                values.append(line)

            # otherwise, a key is being read
            else:
                keys.append(line)
            count += 1

    # Add to dictionary
    # perhaps some error checking here would be good
    for key, value in zip(keys, values):
        data[key] = value

    return data

def replace_word(ab_dict, sentence):
    """
    Replaces sentence with words found in dictionary
    """

    # not necessarily words, but you get the idea
    words = re.findall(r"[\w']+|[.,!?; ]", sentence)

    new_words = []
    for word in words:

        # if word is in dictionary, replace it and add it to resulting list
        if word in ab_dict:
            new_words.append(ab_dict[word])

        # otherwise add it as normally
        else:
            new_words.append(word)

    # return sentence with replaced words
    return "".join(x for x in new_words)

def main():
    ab_dict = read_file_dict("abreviations.txt")

    print(ab_dict)

    print(ab_dict['ACE'])
    print(ab_dict['Ace'])
    print(ab_dict['ace'])

    print(replace_word(ab_dict, "The ACE is not easy to understand"))

if __name__ == '__main__':
    main()

Which outputs:

{'ACE': 'Access Control Entry', 'ACK': 'Acknowledgement', 'ACORN': 'A Completely Obsessive Really Nutty person'}
Access Control Entry
Access Control Entry
Access Control Entry
The Access Control Entry is not easy to understand


问:
How to make a Gpars Actor to read from console
I have a simple GPars actor:

```<code>class ConsoleActor extends DefaultActor {

    protected void act() {
        loop {
            react { Msg msg ->
                switch (msg.type) {
                    case MsgType.Read:
                        sender.send(System.console().readLine())
                        break
                }
            }
        }
    }
}
</code>```

But when I try to send a message to force the actor to read from Console, i get a NPE:

An exception occurred in the Actor thread Actor Thread 3
  java.lang.NullPointerException: Cannot invoke method readLine() on
  null object

Why this happens and how to read from console in a GPars Actor?

答:
I found the answer here:
StackOverflow - System Console returns null

```<code>class ConsoleActor extends DefaultActor {

    protected void act() {
        loop {
            react { Msg msg ->
                switch (msg.type) {
                    case MsgType.Read:
                        Scanner input = new Scanner(System.in);
                        String str = input.nextLine();
                        sender.send(str)
                        break
                }
            }
        }
    }
}
</code>```

It works for me.

Body:
I have a simple GPars actor:

class ConsoleActor extends DefaultActor {

    protected void act() {
        loop {
            react { Msg msg ->
                switch (msg.type) {
                    case MsgType.Read:
                        sender.send(System.console().readLine())
                        break
                }
            }
        }
    }
}

But when I try to send a message to force the actor to read from Console, i get a NPE:

An exception occurred in the Actor thread Actor Thread 3
  java.lang.NullPointerException: Cannot invoke method readLine() on
  null object

Why this happens and how to read from console in a GPars Actor?

Body:
I found the answer here:
StackOverflow - System Console returns null

class ConsoleActor extends DefaultActor {

    protected void act() {
        loop {
            react { Msg msg ->
                switch (msg.type) {
                    case MsgType.Read:
                        Scanner input = new Scanner(System.in);
                        String str = input.nextLine();
                        sender.send(str)
                        break
                }
            }
        }
    }
}

It works for me.


问:
ASP.NET MVC passing string to JSON.parse with quote escaping issue
I hit a problem with JSON.
I want to pass serialized object to a JSON.parse method in JS.
Everything works fine until one of string values does not have quotes, like for example HTML code. Then you get JSON parse error in JS.

Simply I get:

```<code>var test = JSON.parse('{"test":"<p>Terms <a href=\"google.pl\"></a></p>"}');
</code>```

But what works is:

```<code>var test = JSON.parse('{"test":"<p>Terms <a href=\\"google.pl\\"></a></p>"}');
</code>```

Here is my test view code, any thoughts?
How to pass this object properly?

```<code>@{
    Layout = null;
}

@{
    string args = Newtonsoft.Json.JsonConvert.SerializeObject(new
    {
        test = @"<p>Terms <a href=""google.pl""></a></p>"
    }, new Newtonsoft.Json.JsonSerializerSettings
    {
        ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),
    });
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <script>
        var test = JSON.parse('@Html.Raw(args)');
    </script>
    <div>
    </div>
</body>
</html>
</code>```

答:
You don't need to parse it, as it is already a JSON object.
Just use:

```<code><script>
    var test = @Html.Raw(args);
</script>
</code>```

JSON.parse is used to parse string to object.

Body:
I hit a problem with JSON.
I want to pass serialized object to a JSON.parse method in JS.
Everything works fine until one of string values does not have quotes, like for example HTML code. Then you get JSON parse error in JS.

Simply I get:

var test = JSON.parse('{"test":"
Terms
"}');

But what works is:

var test = JSON.parse('{"test":"
Terms
"}');

Here is my test view code, any thoughts?
How to pass this object properly?

@{
    Layout = null;
}

@{
    string args = Newtonsoft.Json.JsonConvert.SerializeObject(new
    {
        test = @"
Terms
"
    }, new Newtonsoft.Json.JsonSerializerSettings
    {
        ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),
    });
}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

Body:
You don't need to parse it, as it is already a JSON object.
Just use:

<script>
    var test = @Html.Raw(args);
</script>

JSON.parse is used to parse string to object.


问:
How can I make this code shorter? Is it possible to create this in one loop?
```<code>var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

var rw = 50;
var rh = 50;
var x = 10;
var y = 10;

for (x=10, y=10; y<240; x=x+60, y=y+57) {
  ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}
  for (x=10, y=67; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=124; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=181; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=238; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}
</code>```

It's a javascript code. In my html is this

```<code><canvas id="myCanvas" height="300" width="450" style="border: 1px solid black"></canvas>
</code>```

My task is, come this code together below one loop.

Thank you so much for your help!

答:
This can be shorter. But looks like a nested loop is required as :

```<code>for(row=0;row<5;row++) {
  for(col=0;col < row+1; col++)  {
    ctx.fillStyle = "orange";
    ctx.fillRect(x + col * 60 ,y + row * 57,rw,rh);
  }
}
</code>```

For each row,draw columns
each column object, step x co-ordinate by 60, y co-ordinate by row * 57; This way per row you are painting, x will increment pre column, y will remain same for a row.

Body:
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

var rw = 50;
var rh = 50;
var x = 10;
var y = 10;

for (x=10, y=10; y<240; x=x+60, y=y+57) {
  ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}
  for (x=10, y=67; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=124; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=181; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=238; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

It's a javascript code. In my html is this

<canvas id="myCanvas" height="300" width="450" style="border: 1px solid black"></canvas>

My task is, come this code together below one loop.

Thank you so much for your help!

Body:
This can be shorter. But looks like a nested loop is required as :

for(row=0;row<5;row++) {
  for(col=0;col < row+1; col++)  {
    ctx.fillStyle = "orange";
    ctx.fillRect(x + col * 60 ,y + row * 57,rw,rh);
  }
}

For each row,draw columns
each column object, step x co-ordinate by 60, y co-ordinate by row * 57; This way per row you are painting, x will increment pre column, y will remain same for a row.


问:
Why is `;;` giving me a syntax error in utop?
I'm working on a short project to convert small programs from python to java and visa versa.
I created the following code, and tested it in utop.

```<code>let c =
let x = "for (int i = 0; i<10; i++)"
and y = "for i in range(0,10):"
in function
| x -> y
| y -> x
| _ -> "Oh no!!";;
</code>```

For some reason, x & y are both considered unbound, yet at the same time any parameter seems to match to x.

What order does everything need to be written in to make this work?

答:
Simply to follow up with your answer.

In pattern-matching, matching to a variable doesn't necessarily seem to match to its value.

This is the very reason why it's called pattern-matching and not value-matching.

As the name implies, pattern-matching is used to match things against patterns, not values. In the code you show in the question, you are not actually comparing anything to x or y, you are defining patterns named x and y that can match anything. See the example below:

```<code>match 2 with
| x -> "Hey, I matched!"
| _ -> "Oh, I didn't match.";;

- : string = "Hey, I matched!"
</code>```

Note that this works even if x was previously defined. In the match
  case, the x from the pattern is actually shadowing the other one.

```<code>let x = 42 in
match 1337 with
| x -> Printf.printf "Matched %d\n!" x
| _ -> ();;

Matched 1337!
- : unit = ()
</code>```

On the other hand, the pattern i when i = x is actually matching against the value of the outer variable x, which is why the code in your self-answer works. But this is not what patterns are for anyway.

What you're actually trying to do is not a pattern-matching, it is a simple conditional statement.

```<code>let c argument =
  let x = "for (int i = 0; i<10; i++)"  in
  let y = "for i in range(0,10):" in
  if argument = x then y
  else if argument = y then x
  else "Oh no!";;

val c : string -> string = <fun>
</code>```

And here it is in action:

```<code>c "for (int i = 0; i<10; i++)";;
- : string = "for i in range(0,10):"

c "for i in range(0,10):";;
- : string = "for (int i = 0; i<10; i++)"

c "whatever";;
- : string = "Oh no!"
</code>```

Also, don't use and unless you're defining mutually recursive values.

Body:
I'm working on a short project to convert small programs from python to java and visa versa.
I created the following code, and tested it in utop.

let c =
let x = "for (int i = 0; i<10; i++)"
and y = "for i in range(0,10):"
in function
| x -> y
| y -> x
| _ -> "Oh no!!";;

For some reason, x & y are both considered unbound, yet at the same time any parameter seems to match to x.

What order does everything need to be written in to make this work?

Body:
Simply to follow up with your answer.

In pattern-matching, matching to a variable doesn't necessarily seem to match to its value.

This is the very reason why it's called pattern-matching and not value-matching.

As the name implies, pattern-matching is used to match things against patterns, not values. In the code you show in the question, you are not actually comparing anything to x or y, you are defining patterns named x and y that can match anything. See the example below:

match 2 with
| x -> "Hey, I matched!"
| _ -> "Oh, I didn't match.";;

- : string = "Hey, I matched!"

Note that this works even if x was previously defined. In the match
  case, the x from the pattern is actually shadowing the other one.

let x = 42 in
match 1337 with
| x -> Printf.printf "Matched %d\n!" x
| _ -> ();;

Matched 1337!
- : unit = ()

On the other hand, the pattern i when i = x is actually matching against the value of the outer variable x, which is why the code in your self-answer works. But this is not what patterns are for anyway.

What you're actually trying to do is not a pattern-matching, it is a simple conditional statement.

let c argument =
  let x = "for (int i = 0; i<10; i++)"  in
  let y = "for i in range(0,10):" in
  if argument = x then y
  else if argument = y then x
  else "Oh no!";;

val c : string -> string = <fun>

And here it is in action:

c "for (int i = 0; i<10; i++)";;
- : string = "for i in range(0,10):"

c "for i in range(0,10):";;
- : string = "for (int i = 0; i<10; i++)"

c "whatever";;
- : string = "Oh no!"

Also, don't use and unless you're defining mutually recursive values.


问:
In Python, how do I read the exif data for an image?
I'm using PIL. How do I turn the EXIF data of a picture into a dictionary?</p>

答:
You can use the _getexif() protected method of a PIL Image.

```<code>import PIL.Image
img = PIL.Image.open('img.jpg')
exif_data = img._getexif()
</code>```

This should give you a dictionary indexed by EXIF numeric tags.  If you want the dictionary indexed by the actual EXIF tag name strings, try something like:

```<code>import PIL.ExifTags
exif = {
    PIL.ExifTags.TAGS[k]: v
    for k, v in img._getexif().items()
    if k in PIL.ExifTags.TAGS
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can use the _getexif() protected method of a PIL Image.

import PIL.Image
img = PIL.Image.open('img.jpg')
exif_data = img._getexif()

This should give you a dictionary indexed by EXIF numeric tags.  If you want the dictionary indexed by the actual EXIF tag name strings, try something like:

import PIL.ExifTags
exif = {
    PIL.ExifTags.TAGS[k]: v
    for k, v in img._getexif().items()
    if k in PIL.ExifTags.TAGS
}


问:
Angularjs save variables $routeProvider
There's a way to save variables inside the $routeProvider?

Ex: I was trying to set the aside menu when a reach a certain page.
The idea is do like this:

```<code>$routeProvider.when('/', {
    title: 'Home',
    controller: 'Home',
    variable: 'active'
});
</code>```

And in the HTML:

```<code><a href="/Home" class="{{$route.variable}}">
</code>```

Thanks!

答:
Route provider

```<code>$routeProvider.
  when('/', {
    title: 'test.html',
    controller: 'Home',
    resolve: {
         setParams: function ($route) { $route.current.params.variable = 'active'; }
    }
})
</code>```

Controller

Use $routeParams dependency

```<code>app.controller('HomeController', ['$scope', '$routeParams', function ($scope, $routeParams) {
     $scope.variable = $routeParams.variable;
}
</code>```

HTML

```<code><a href="/Home" ng-class="variable">
</code>```

Title: Angularjs save variables $routeProvider

Body:
There's a way to save variables inside the $routeProvider?

Ex: I was trying to set the aside menu when a reach a certain page.
The idea is do like this:

$routeProvider.when('/', {
    title: 'Home',
    controller: 'Home',
    variable: 'active'
});

And in the HTML:

Thanks!

Body:
Route provider

$routeProvider.
  when('/', {
    title: 'test.html',
    controller: 'Home',
    resolve: {
         setParams: function ($route) { $route.current.params.variable = 'active'; }
    }
})

Controller

Use $routeParams dependency

app.controller('HomeController', ['$scope', '$routeParams', function ($scope, $routeParams) {
     $scope.variable = $routeParams.variable;
}

HTML

<a href="/Home" ng-class="variable">


问:
How seeking ffplay or pipe from ffmpeg to ffplay
my goal is to check the file 10 minutes after the start. This is my script.

```<code>ffplay.exe -f lavfi "amovie=input.mov,showvolume=b=4:w=640:h=96"
</code>```

If I add seeking, something like -ss 600, the file always starts from the beginning,

anyone know workaround? thanks.

答:
Two ways of doing this:

```<code>ffplay -f lavfi "amovie=input.mov:sp=600,showvolume=b=4:w=640:h=96"
</code>```

sp is option seek_point - will seek from nearest keyframe before seek point.

```<code>ffplay -f lavfi "amovie=input.mov,atrim=600,showvolume=b=4:w=640:h=96"
</code>```

Apply a (a)trim filter.

Body:
my goal is to check the file 10 minutes after the start. This is my script.

ffplay.exe -f lavfi "amovie=input.mov,showvolume=b=4:w=640:h=96"

If I add seeking, something like -ss 600, the file always starts from the beginning,

anyone know workaround? thanks.

Body:
Two ways of doing this:

ffplay -f lavfi "amovie=input.mov:sp=600,showvolume=b=4:w=640:h=96"

sp is option seek_point - will seek from nearest keyframe before seek point.

ffplay -f lavfi "amovie=input.mov,atrim=600,showvolume=b=4:w=640:h=96"

Apply a (a)trim filter.


问:
Limiting the results by sql query
I have a ranking system, and when I pass the player_ID it will return 2 values above and below my player_id. But the problem is if the above or below player rankings are same it's returning all the values, But I need exactly five values.

My Code:

```<code> SET @rank = 1, @seq = 1, @last = null;

select ranks.rank , ranks.id, ranks.scores from (
SELECT *, @rank := if(@last = scores, @rank, @seq) AS rank, @seq := @seq + 1, @last := scores FROM testingleaderboard ORDER BY scores DESC) as ranks JOIN (

  -- find the rank of the user we want similarly
  SELECT @sd:=COUNT(id) rank
  FROM   testingleaderboard JOIN (
    -- our user's highest score
    SELECT MAX(scores) maxscore FROM testingleaderboard WHERE id = 46818
  ) userscore ON testingleaderboard.scores > userscore.maxscore

-- filter for only those who are within given range from our user's rank
) userrank ON ranks.rank BETWEEN  userrank.rank - 2  AND  userrank.rank + 3

-- sort the results
ORDER BY ranks.rank
</code>```

INPUT :

```<code>id = 46818
</code>```

RECEIVED OUTPUT:

```<code>"rank"  "id"    "scores"

"426688"    "1032909"   "6138"
"426688"    "1094298"   "6138"
"426688"    "1081638"   "6138"
"426688"    "1016393"   "6138"
"426688"    "1016503"   "6138"
"426688"    "1020950"   "6138"
"426688"    "39479" "6138"
**"426688"  "46818" "6138"**
"426688"    "29181" "6138"
"426688"    "31458" "6138"
"426688"    "33779" "6138"
"426688"    "23640" "6138"
"426688"    "4852"  "6138"
</code>```

REQUIRED OUTPUT:

```<code>"426688"    "1020950"   "6138"
"426688"    "39479" "6138"
**"426688"  "46818" "6138"**
"426688"    "29181" "6138"
"426688"    "31458" "6138"
</code>```

答:
just add limit 5 at the end of your query.

```<code>query limit 5;
</code>```

e.g.
      select * from whatever where something order by some limit 5;

Title: Limiting the results by sql query

Body:
I have a ranking system, and when I pass the player_ID it will return 2 values above and below my player_id. But the problem is if the above or below player rankings are same it's returning all the values, But I need exactly five values.

My Code:

 SET @rank = 1, @seq = 1, @last = null;

select ranks.rank , ranks.id, ranks.scores from (
SELECT *, @rank := if(@last = scores, @rank, @seq) AS rank, @seq := @seq + 1, @last := scores FROM testingleaderboard ORDER BY scores DESC) as ranks JOIN (

  -- find the rank of the user we want similarly
  SELECT @sd:=COUNT(id) rank
  FROM   testingleaderboard JOIN (
    -- our user's highest score
    SELECT MAX(scores) maxscore FROM testingleaderboard WHERE id = 46818
  ) userscore ON testingleaderboard.scores > userscore.maxscore

-- filter for only those who are within given range from our user's rank
) userrank ON ranks.rank BETWEEN  userrank.rank - 2  AND  userrank.rank + 3

-- sort the results
ORDER BY ranks.rank

INPUT :

id = 46818

RECEIVED OUTPUT:

"rank"  "id"    "scores"

"426688"    "1032909"   "6138"
"426688"    "1094298"   "6138"
"426688"    "1081638"   "6138"
"426688"    "1016393"   "6138"
"426688"    "1016503"   "6138"
"426688"    "1020950"   "6138"
"426688"    "39479" "6138"
**"426688"  "46818" "6138"**
"426688"    "29181" "6138"
"426688"    "31458" "6138"
"426688"    "33779" "6138"
"426688"    "23640" "6138"
"426688"    "4852"  "6138"

REQUIRED OUTPUT:

"426688"    "1020950"   "6138"
"426688"    "39479" "6138"
**"426688"  "46818" "6138"**
"426688"    "29181" "6138"
"426688"    "31458" "6138"

Body:
just add limit 5 at the end of your query.

query limit 5;

e.g.
      select * from whatever where something order by some limit 5;


问:
Can't have access to admin console in glassfish 3
I have started glassfish server in netbeans, but cant't have access to admin console through web brouser on localhost:4848
The log of start up process:

```<code>21.01.2011 18:48:34 com.sun.enterprise.glassfish.bootstrap.ASMain main
INFO: Launching GlassFish on Felix platform
Welcome to Felix
================
INFO: Perform lazy SSL initialization for the listener 'http-listener-1'
INFO: Perform lazy SSL initialization for the listener 'http-listener-2'
INFO: Perform lazy SSL initialization for the listener 'admin-listener'
INFO: Starting Grizzly Framework 1.9.18-k - Fri Jan 21 18:48:37 EET 2011
INFO: The Admin Console is already installed, but not yet loaded.
INFO: Grizzly Framework 1.9.18-k started in: 219ms listening on port 8181
INFO: Grizzly Framework 1.9.18-k started in: 203ms listening on port 4848
INFO: Grizzly Framework 1.9.18-k started in: 235ms listening on port 8080
INFO: Starting Grizzly Framework 1.9.18-k - Fri Jan 21 18:48:37 EET 2011
INFO: Grizzly Framework 1.9.18-k started in: 906ms listening on port 3700
INFO: Grizzly Framework 1.9.18-k started in: 891ms listening on port 7676
INFO: GlassFish v3 (74.2) startup time : Felix(2422ms) startup services(1890ms) total(4312ms)
INFO: javassist.util.proxy.ProxyFactory.classLoaderProvider = org.glassfish.weld.WeldActivator$GlassFishClassLoaderProvider@1fa2b3e
INFO: Hibernate Validator bean-validator-3.0-JBoss-4.0.2
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Binding RMI port to *:8686
INFO: JMXStartupService: Started JMXConnector, JMXService URL = service:jmx:rmi://localhost:8686/jndi/rmi://localhost:8686/jmxrmi
INFO: Using com.sun.enterprise.transaction.jts.JavaEETransactionManagerJTSDelegate as the delegate
INFO: Perform lazy SSL initialization for the listener 'http-listener-1'
INFO: Grizzly Framework 1.9.18-k started in: 0ms listening on port 8080
INFO: [Thread[GlassFish Kernel Main Thread,5,main]] started
INFO: {felix.fileinstall.poll (ms) = 5000, felix.fileinstall.dir = C:\Program Files\sges-v3\glassfish\modules\autostart, felix.fileinstall.debug = 1, felix.fileinstall.bundles.new.start = true, felix.fileinstall.tmpdir = C:\DOCUME~1\Admin\LOCALS~1\Temp\fileinstall-6018388012782185995, felix.fileinstall.filter = null}
INFO: Perform lazy SSL initialization for the listener 'http-listener-2'
INFO: {felix.fileinstall.poll (ms) = 5000, felix.fileinstall.dir = C:\Program Files\sges-v3\glassfish\domains\domain1\autodeploy\bundles, felix.fileinstall.debug = 1, felix.fileinstall.bundles.new.start = true, felix.fileinstall.tmpdir = C:\DOCUME~1\Admin\LOCALS~1\Temp\fileinstall-570365091622749624, felix.fileinstall.filter = null}
INFO: Grizzly Framework 1.9.18-k started in: 16ms listening on port 8181
INFO: Updating configuration from org.apache.felix.fileinstall-autodeploy-bundles.cfg
INFO: Installed C:\Program Files\sges-v3\glassfish\modules\autostart\org.apache.felix.fileinstall-autodeploy-bundles.cfg
INFO: {felix.fileinstall.poll (ms) = 5000, felix.fileinstall.dir = C:\Program Files\sges-v3\glassfish\domains\domain1\autodeploy\bundles, felix.fileinstall.debug = 1, felix.fileinstall.bundles.new.start = true, felix.fileinstall.tmpdir = C:\DOCUME~1\Admin\LOCALS~1\Temp\fileinstall--7403987252271825379, felix.fileinstall.filter = null}
</code>```

How can i have access to console?

edited:
It is available on https://localhost:4848
How i can change it to http://localhost:4848

答: Here is a thousand words... and then some...

ContentLicense: CC BY-SA 2.5

Body:
I have started glassfish server in netbeans, but cant't have access to admin console through web brouser on localhost:4848
The log of start up process:

21.01.2011 18:48:34 com.sun.enterprise.glassfish.bootstrap.ASMain main
INFO: Launching GlassFish on Felix platform
Welcome to Felix
================
INFO: Perform lazy SSL initialization for the listener 'http-listener-1'
INFO: Perform lazy SSL initialization for the listener 'http-listener-2'
INFO: Perform lazy SSL initialization for the listener 'admin-listener'
INFO: Starting Grizzly Framework 1.9.18-k - Fri Jan 21 18:48:37 EET 2011
INFO: The Admin Console is already installed, but not yet loaded.
INFO: Grizzly Framework 1.9.18-k started in: 219ms listening on port 8181
INFO: Grizzly Framework 1.9.18-k started in: 203ms listening on port 4848
INFO: Grizzly Framework 1.9.18-k started in: 235ms listening on port 8080
INFO: Starting Grizzly Framework 1.9.18-k - Fri Jan 21 18:48:37 EET 2011
INFO: Grizzly Framework 1.9.18-k started in: 906ms listening on port 3700
INFO: Grizzly Framework 1.9.18-k started in: 891ms listening on port 7676
INFO: GlassFish v3 (74.2) startup time : Felix(2422ms) startup services(1890ms) total(4312ms)
INFO: javassist.util.proxy.ProxyFactory.classLoaderProvider = org.glassfish.weld.WeldActivator$GlassFishClassLoaderProvider@1fa2b3e
INFO: Hibernate Validator bean-validator-3.0-JBoss-4.0.2
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: Binding RMI port to *:8686
INFO: JMXStartupService: Started JMXConnector, JMXService URL = service:jmx:rmi://localhost:8686/jndi/rmi://localhost:8686/jmxrmi
INFO: Using com.sun.enterprise.transaction.jts.JavaEETransactionManagerJTSDelegate as the delegate
INFO: Perform lazy SSL initialization for the listener 'http-listener-1'
INFO: Grizzly Framework 1.9.18-k started in: 0ms listening on port 8080
INFO: [Thread[GlassFish Kernel Main Thread,5,main]] started
INFO: {felix.fileinstall.poll (ms) = 5000, felix.fileinstall.dir = C:\Program Files\sges-v3\glassfish\modules\autostart, felix.fileinstall.debug = 1, felix.fileinstall.bundles.new.start = true, felix.fileinstall.tmpdir = C:\DOCUME~1\Admin\LOCALS~1\Temp\fileinstall-6018388012782185995, felix.fileinstall.filter = null}
INFO: Perform lazy SSL initialization for the listener 'http-listener-2'
INFO: {felix.fileinstall.poll (ms) = 5000, felix.fileinstall.dir = C:\Program Files\sges-v3\glassfish\domains\domain1\autodeploy\bundles, felix.fileinstall.debug = 1, felix.fileinstall.bundles.new.start = true, felix.fileinstall.tmpdir = C:\DOCUME~1\Admin\LOCALS~1\Temp\fileinstall-570365091622749624, felix.fileinstall.filter = null}
INFO: Grizzly Framework 1.9.18-k started in: 16ms listening on port 8181
INFO: Updating configuration from org.apache.felix.fileinstall-autodeploy-bundles.cfg
INFO: Installed C:\Program Files\sges-v3\glassfish\modules\autostart\org.apache.felix.fileinstall-autodeploy-bundles.cfg
INFO: {felix.fileinstall.poll (ms) = 5000, felix.fileinstall.dir = C:\Program Files\sges-v3\glassfish\domains\domain1\autodeploy\bundles, felix.fileinstall.debug = 1, felix.fileinstall.bundles.new.start = true, felix.fileinstall.tmpdir = C:\DOCUME~1\Admin\LOCALS~1\Temp\fileinstall--7403987252271825379, felix.fileinstall.filter = null}

How can i have access to console?

edited:
It is available on https://localhost:4848
How i can change it to http://localhost:4848


问:
SQL max() with JOIN
Would like ask you for a little help

Have Sql query where i list all orders, but there i need add last OrderStatus throught OrderStatusID

```<code>SELECT DISTINCT
    a.OrderNr,
    a.CompanyName,
    max(a.OrderStatusID) AS 'xxx'

FROM [NB].[dbo].[Npos] as a
INNER JOIN [NB].[dbo].[Npos_Order_Status_Name] as b
ON
a.OrderStatusID = b.OrderStatusID

GROUP BY  OrderNr, CompanyName
</code>```

in [NB].[dbo].[Npos_Order_Status_Name] are

```<code>OrderStatusID | OrderStatusName
--------------------------------
            0 | Start
            1 | Stop
            2 | Pause
</code>```

I tried it with inner join but i make something wrong.

Thank you

答:
I believe this query will do what you want

```<code>SELECT t.OrderNr, t.CompanyName, b.OrderStatusName
FROM
(
   SELECT
    OrderNr,
    CompanyName,
    max(OrderStatusID) AS 'maxOrderStatus'
  FROM [NB].[dbo].[Npos]
  GROUP BY  OrderNr, CompanyName
) t
JOIN [NB].[dbo].[Npos_Order_Status_Name] as b
  ON  t.maxOrderStatus = b.OrderStatusID
</code>```

or using window functions

```<code>SELECT t.*
FROM
(
    SELECT
        a.*,
        row_number() over (partition by OrderNr, CompanyName order by OrderStatusID desc) rn
    FROM [NB].[dbo].[Npos] as a
    INNER JOIN [NB].[dbo].[Npos_Order_Status_Name] as b
      ON a.OrderStatusID = b.OrderStatusID
) t
WHERE rn = 1
</code>```

However, from my experience, the second variant can be slightly slower in certain cases.

Title: SQL max() with JOIN

Body:
Would like ask you for a little help

Have Sql query where i list all orders, but there i need add last OrderStatus throught OrderStatusID

SELECT DISTINCT
    a.OrderNr,
    a.CompanyName,
    max(a.OrderStatusID) AS 'xxx'

FROM [NB].[dbo].[Npos] as a
INNER JOIN [NB].[dbo].[Npos_Order_Status_Name] as b
ON
a.OrderStatusID = b.OrderStatusID

GROUP BY  OrderNr, CompanyName

in [NB].[dbo].[Npos_Order_Status_Name] are

OrderStatusID | OrderStatusName
--------------------------------
            0 | Start
            1 | Stop
            2 | Pause

I tried it with inner join but i make something wrong.

Thank you

Body:
I believe this query will do what you want

SELECT t.OrderNr, t.CompanyName, b.OrderStatusName
FROM
(
   SELECT
    OrderNr,
    CompanyName,
    max(OrderStatusID) AS 'maxOrderStatus'
  FROM [NB].[dbo].[Npos]
  GROUP BY  OrderNr, CompanyName
) t
JOIN [NB].[dbo].[Npos_Order_Status_Name] as b
  ON  t.maxOrderStatus = b.OrderStatusID

or using window functions

SELECT t.*
FROM
(
    SELECT
        a.*,
        row_number() over (partition by OrderNr, CompanyName order by OrderStatusID desc) rn
    FROM [NB].[dbo].[Npos] as a
    INNER JOIN [NB].[dbo].[Npos_Order_Status_Name] as b
      ON a.OrderStatusID = b.OrderStatusID
) t
WHERE rn = 1

However, from my experience, the second variant can be slightly slower in certain cases.


问:
(Node J.S.) SyntaxError: Unexpected token function on an async function
So I'm trying to use async/await but i get this error:

```<code>async function something(options) {
  ^^^^^^^^
SyntaxError: Unexpected token function
</code>```

Here's the code:

```<code>var request = require('superagent');

async function something(options) {
    let response = await request.get("apiurlblabla");
    if(response) {
      .query(({'queryqeureur}))
      .query(({'uqeryqery'}))
      var jsonString = JSON.parse(res.text)
      console.log(jsonString.propertyblabla);
      console.log(jsonString.propertyblabla)
    }
}
</code>```

答:
Install node version manager:

```<code>curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bash
</code>```

Install new version of node:

```<code>nvm install 8.0
</code>```

Update verion which uses:

```<code>nvm use 8.0
</code>```

Body:
So I'm trying to use async/await but i get this error:

async function something(options) {
  ^^^^^^^^
SyntaxError: Unexpected token function

Here's the code:

var request = require('superagent');

async function something(options) {
    let response = await request.get("apiurlblabla");
    if(response) {
      .query(({'queryqeureur}))
      .query(({'uqeryqery'}))
      var jsonString = JSON.parse(res.text)
      console.log(jsonString.propertyblabla);
      console.log(jsonString.propertyblabla)
    }
}

Body:
Install node version manager:

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bash

Install new version of node:

nvm install 8.0

Update verion which uses:

nvm use 8.0


问:
Trivial query with if statements
How to achieve this simple logic?

```<code>void IRQHandler(void)
{
   if(update_variable == 0)
    {
        if(CONDITION1)
         {

            /* MORE CODE */
            update_variable = 1;
          }
    } /* Here i want to exit the loop */

    if(update_variable == 1) /* execute in next loop */
     {
         if(CONDITION1)
          {
            /* MORE CODE */
            /*UPDATE SOME ARRAY */
            update_variable = 0; /* reset variable for next loop */
          }
      }
  }
</code>```

Essentially, I want to check for the same CONDITION1 over two consecutive interrupts. For 1st interrupt, I want to update the variable value to 1 and exit the loop (precisely do not execute the following if condition).  As I see, I cannot use break condition with "if"! I am struck here for a while! Please help me!

答:
You are mentioning loops and you are not using any.

As from what I understand about your question, and you do not want to enter the second condition EVER, just use an elsecondition.

```<code>void IRQHandler(void)
{
   if(update_variable == 0)
    {
        if(CONDITION1)
         {

            /* MORE CODE */
            update_variable = 1;
          }
    } /* Here i want to exit the loop */

    else if(update_variable == 1) /* execute in next loop */
     {
         if(CONDITION1)
          {
            /* MORE CODE */
            /*UPDATE SOME ARRAY */
            update_variable = 0; /* reset variable for next loop */
          }
      }
  }
</code>```

Title: Trivial query with if statements

Body:
How to achieve this simple logic?

void IRQHandler(void)
{
   if(update_variable == 0)
    {
        if(CONDITION1)
         {

            /* MORE CODE */
            update_variable = 1;
          }
    } /* Here i want to exit the loop */

    if(update_variable == 1) /* execute in next loop */
     {
         if(CONDITION1)
          {
            /* MORE CODE */
            /*UPDATE SOME ARRAY */
            update_variable = 0; /* reset variable for next loop */
          }
      }
  }

Essentially, I want to check for the same CONDITION1 over two consecutive interrupts. For 1st interrupt, I want to update the variable value to 1 and exit the loop (precisely do not execute the following if condition).  As I see, I cannot use break condition with "if"! I am struck here for a while! Please help me!

Body:
You are mentioning loops and you are not using any.

As from what I understand about your question, and you do not want to enter the second condition EVER, just use an elsecondition.

void IRQHandler(void)
{
   if(update_variable == 0)
    {
        if(CONDITION1)
         {

            /* MORE CODE */
            update_variable = 1;
          }
    } /* Here i want to exit the loop */

    else if(update_variable == 1) /* execute in next loop */
     {
         if(CONDITION1)
          {
            /* MORE CODE */
            /*UPDATE SOME ARRAY */
            update_variable = 0; /* reset variable for next loop */
          }
      }
  }


问:
sass variables right way
I'm creating multiple themes with scss in ionic. I ended up with 2 ways, but which one is better and why?

First way

```<code> $colors: (
  primary:    #bdc3c7,
  secondary:  #444444,
  danger:     #7f8c8d,
  light:      #34495e,
  dark:       #e74c3c
);
.light-theme {
  // main style for all the commi themes app
  ion-content {
      background-color: color($colors, light);
     }
  @import "main";

}// light-theme
</code>```

second way

```<code>.light-theme {
   $colors: (
  primary:    #bdc3c7,
  secondary:  #444444,
  danger:     #7f8c8d,
  light:      #34495e,
  dark:       #e74c3c
);
  // main style for all the commi themes app
  ion-content {
      background-color: color($colors, light);
     }
  @import "main";

}//
</code>```

The first way I have the colors outside the class and the second way the colors are inside the class and the both ways are working. I'm thinking about what would happen if we have at least three themes?

答:
Thank you for opening sass way , here is my end code

```<code>    $themes:(
   theme:(
        primary:    #032838,
        secondary:  #868a6f,
        danger:     #ed4039,
        light:      #f3f2f2,
        dark:       #37aad9
    ),
    light:(
        primary:    #34495e,
        secondary:  #e74c3c,
        danger:     #7f8c8d,
        light:      #bdc3c7,
        dark:       #444444
    ),
    dark:(
        primary:    #f3f2f2,
        secondary:  #3D8EB9,
        danger:     #e74c3c,
        light:      #303030,
        dark:       #212121
    ),
    main:(
        black:    #000000,
        white:    #ffffff,
        wisteria:   #8e44ad,
        pomegranate:#c0392b,
        orange:   #f39c12,
        green:    #03A678,
    )
);

$color-key: primary !default;

@function color(
    $theme-name: commi,
    $color-key: $color-key,
    $opacity: 1
){
    $color: null;
    $theme: map-get($themes, $theme-name);

    @if $theme{
        $color: map-get($theme, $color-key );
    }

    @return $color;
}

@import "light";
@import "dark";
</code>```

and in my theme i call it like this

```<code>.dark-theme{
  $theme : dark;
  @import "main";
}
</code>```

in scss style file

```<code> ion-content {
      color: color($theme, light);
      background-color:color($theme, light);
      @if($theme == 'dark'){
        background-color:color($theme, primary);
      }
  }
</code>```

Title: sass variables right way

Body:
I'm creating multiple themes with scss in ionic. I ended up with 2 ways, but which one is better and why?

First way

 $colors: (
  primary:    #bdc3c7,
  secondary:  #444444,
  danger:     #7f8c8d,
  light:      #34495e,
  dark:       #e74c3c
);
.light-theme {
  // main style for all the commi themes app
  ion-content {
      background-color: color($colors, light);
     }
  @import "main";

}// light-theme

second way

.light-theme {
   $colors: (
  primary:    #bdc3c7,
  secondary:  #444444,
  danger:     #7f8c8d,
  light:      #34495e,
  dark:       #e74c3c
);
  // main style for all the commi themes app
  ion-content {
      background-color: color($colors, light);
     }
  @import "main";

}//

The first way I have the colors outside the class and the second way the colors are inside the class and the both ways are working. I'm thinking about what would happen if we have at least three themes?

Body:
Thank you for opening sass way , here is my end code

    $themes:(
   theme:(
        primary:    #032838,
        secondary:  #868a6f,
        danger:     #ed4039,
        light:      #f3f2f2,
        dark:       #37aad9
    ),
    light:(
        primary:    #34495e,
        secondary:  #e74c3c,
        danger:     #7f8c8d,
        light:      #bdc3c7,
        dark:       #444444
    ),
    dark:(
        primary:    #f3f2f2,
        secondary:  #3D8EB9,
        danger:     #e74c3c,
        light:      #303030,
        dark:       #212121
    ),
    main:(
        black:    #000000,
        white:    #ffffff,
        wisteria:   #8e44ad,
        pomegranate:#c0392b,
        orange:   #f39c12,
        green:    #03A678,
    )
);

$color-key: primary !default;

@function color(
    $theme-name: commi,
    $color-key: $color-key,
    $opacity: 1
){
    $color: null;
    $theme: map-get($themes, $theme-name);

    @if $theme{
        $color: map-get($theme, $color-key );
    }

    @return $color;
}

@import "light";
@import "dark";

and in my theme i call it like this

.dark-theme{
  $theme : dark;
  @import "main";
}

in scss style file

 ion-content {
      color: color($theme, light);
      background-color:color($theme, light);
      @if($theme == 'dark'){
        background-color:color($theme, primary);
      }
  }


问:
Symfony 3: How to redirect from within InteractiveLoginEvent listener
In Symfony 3.4.0, from an event listener that listens to the InteractiveLoginEvent I would like to redirect to another route, so I would like to respond a redirect.

But the InteractiveLoginEvent object has no "setResponse" method. So which is the preferred way to use the InteractiveLoginEvent to modify the response so that a redirect is sent to the user?

答:
Since you asked in the comment, instead of just implementing the entire interface yourself, you can extend the default success handler, override the success method, do what you want with it, and then call the parent method to allow symfony to do its normal thing

Click below for a full example of how to override the handler
https://www.codereviewvideos.com/course/symfony-3-for-beginners/video/bonus-how-to-show-a-flash-message-on-successful-login-or-failed-login-attempt


问:
Stop DecimalFormat with percentage sign from moving the decimal
Is there a way to prevent a DecimalFormat object from automatically moving the decimal place two places to the right?

This code:

```<code>double d = 65.87;
DecimalFormat df1 = new DecimalFormat(" #,##0.00");
DecimalFormat df2 = new DecimalFormat(" #,##0.00 %");
System.out.println(df1.format(d));
System.out.println(df2.format(d));
</code>```

produces:

```<code>65.87
6,587.00 %
</code>```

But I'd like it to produce:

```<code>65.87
65.87 %
</code>```

答:
This is how I do it:

```<code>// your double in percentage:
double percentage = 0.6587;

// how I get the number in as many decimal places as I need:
double doub = (100*10^n*percentage);
System.out.println("TEST:   " + doub/10^n + "%");
</code>```

Where n is the number of decimal places you need.

I know this isn't the cleanest way but it works.

Hope this helps.

Body:
Is there a way to prevent a DecimalFormat object from automatically moving the decimal place two places to the right?

This code:

double d = 65.87;
DecimalFormat df1 = new DecimalFormat(" #,##0.00");
DecimalFormat df2 = new DecimalFormat(" #,##0.00 %");
System.out.println(df1.format(d));
System.out.println(df2.format(d));

produces:

65.87
6,587.00 %

But I'd like it to produce:

65.87
65.87 %

Body:
This is how I do it:

// your double in percentage:
double percentage = 0.6587;

// how I get the number in as many decimal places as I need:
double doub = (100*10^n*percentage);
System.out.println("TEST:   " + doub/10^n + "%");

Where n is the number of decimal places you need.

I know this isn't the cleanest way but it works.

Hope this helps.


问:
Difference between 'connection reset' exception and -1 return value on read when a Java socket is closed
I have a Java socket that connects to a server and receives a sequence of buffers from that server. The transfer stops when the server closes the connection, i.e. closes the accepting socket on its side.

Most of the time, when the servers closes the connection, the client gets a -1 return code on the read method on the InputStream associated with the socket:

```<code>Socket sSocket   = new Socket(ServerAddress ,acceptorPort);
InputStream  isr = sSocket.getInputStream();

byte[] buf              = new byte[3200];
int    rr               = 1;

while (rr != -1) {
    try {
        rr     = isr.read(buffer);
    } catch (IOException e) {
        e.printStackTrace();
        break;
    }
}
</code>```

But sometimes the read raises a java.net.SocketException: Connection reset.
In that case, I have the following stack trace:

```<code>java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:210)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.net.SocketInputStream.read(SocketInputStream.java:127)
at com.testing.sockets.SimpleReadTest.main(SimpleReadTest.java:149)
</code>```

What is the difference and why?

答:
The difference according to Javadoc is this:

-1 if there is no more data because the end of the stream has been reached.

java.net.IOException - if an I/O error occurs.

java.net.SocketException extends java.io.IOException, so it is caught by your catch-block.

Body:
I have a Java socket that connects to a server and receives a sequence of buffers from that server. The transfer stops when the server closes the connection, i.e. closes the accepting socket on its side.

Most of the time, when the servers closes the connection, the client gets a -1 return code on the read method on the InputStream associated with the socket:

Socket sSocket   = new Socket(ServerAddress ,acceptorPort);
InputStream  isr = sSocket.getInputStream();

byte[] buf              = new byte[3200];
int    rr               = 1;

while (rr != -1) {
    try {
        rr     = isr.read(buffer);
    } catch (IOException e) {
        e.printStackTrace();
        break;
    }
}

But sometimes the read raises a java.net.SocketException: Connection reset.
In that case, I have the following stack trace:

java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:210)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.net.SocketInputStream.read(SocketInputStream.java:127)
at com.testing.sockets.SimpleReadTest.main(SimpleReadTest.java:149)

What is the difference and why?


问:
Batch file won't kill process and close console window
Batch is a mystery to me. Here is the situation. I used a mouse macro program to create a .exe that automatically clicks on my screen. I want to automate this by adding it to my task scheduler. Here is the code that the program created:

```<code>@echo off
REM ************ Built by MiniMouseMacro.exe **********
cls
mode con lines=11 cols=115
title=Mini Mouse Macro - Turnssoft.com
color 0A
echo * Mini Mouse Macro *
echo   - "C:\Users\John Doe\Desktop\MiniMouseMacro.exe" /m "C:\Users\John Doe\Desktop\TestKlik.mmmacro"
echo   - Running C:\Users\John Doe\Desktop\TestKlik.mmmacro...
"C:\Users\John Doe\Desktop\MiniMouseMacro.exe" /m "C:\Users\John Doe\Desktop\TestKlik.mmmacro"
</code>```

It opens the Macro program, loads the macro file (.mmmacro) and executes. This works. However, it keeps the console window open + it keeps the Macro program open (the mouse click opens a new program, might the console window lose focus or something?). I tried to fix this by adding this to the script:

```<code>echo   - killing process
taskkill /im "MiniMouseMacro.exe" /f
end
</code>```

But nothing happens. How can I make this script work and also maybe make it look cleaner (I dont need all the text output).

答:
When you run the program, the cmd will wait for the program to finish before it continues. To change this use the start command when starting the mouse program.

```<code>cd "C:\Users\John Doe\Desktop\"
start "" "MiniMouseMacro.exe /m TestKlik.mmmacro"
</code>```

Which will allow you to follow it with a taskkill

Body:
Batch is a mystery to me. Here is the situation. I used a mouse macro program to create a .exe that automatically clicks on my screen. I want to automate this by adding it to my task scheduler. Here is the code that the program created:

@echo off
REM ************ Built by MiniMouseMacro.exe **********
cls
mode con lines=11 cols=115
title=Mini Mouse Macro - Turnssoft.com
color 0A
echo * Mini Mouse Macro *
echo   - "C:\Users\John Doe\Desktop\MiniMouseMacro.exe" /m "C:\Users\John Doe\Desktop\TestKlik.mmmacro"
echo   - Running C:\Users\John Doe\Desktop\TestKlik.mmmacro...
"C:\Users\John Doe\Desktop\MiniMouseMacro.exe" /m "C:\Users\John Doe\Desktop\TestKlik.mmmacro"

It opens the Macro program, loads the macro file (.mmmacro) and executes. This works. However, it keeps the console window open + it keeps the Macro program open (the mouse click opens a new program, might the console window lose focus or something?). I tried to fix this by adding this to the script:

echo   - killing process
taskkill /im "MiniMouseMacro.exe" /f
end

But nothing happens. How can I make this script work and also maybe make it look cleaner (I dont need all the text output).

Body:
When you run the program, the cmd will wait for the program to finish before it continues. To change this use the start command when starting the mouse program.

cd "C:\Users\John Doe\Desktop\"
start "" "MiniMouseMacro.exe /m TestKlik.mmmacro"

Which will allow you to follow it with a taskkill


问:
Pandas Python UnicodeDecodeError
I'm just practicing writing codes for data extraction. I used the following code and it worked before. However, I've recently updated pandas and now it doesn't work and gives me an error.

```<code>import pandas as pd
from pandas_datareader import data
data.DataReader(name = ["MSFT", "GOOG", "AAPL", "YHOO", "AMZN"], data_source = "google",
               start = "2010-01-01", end = "2016-12-31")`
</code>```

Resulting in the following error:

```<code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 46626: invalid start byte'
</code>```

I've tried looking online here and used the .encode('utf-8).strip() at the end of each parameters to see if it works but it's not.

答:
try doing </p>

```<code>.decode('unicode_escape').encode('ascii', 'ignore')
</code>```

<p>instead of </p>

```<code>.encode('utf-8).strip()
</code>```

Title: Pandas Python UnicodeDecodeError

Body:
I'm just practicing writing codes for data extraction. I used the following code and it worked before. However, I've recently updated pandas and now it doesn't work and gives me an error.

import pandas as pd
from pandas_datareader import data
data.DataReader(name = ["MSFT", "GOOG", "AAPL", "YHOO", "AMZN"], data_source = "google",
               start = "2010-01-01", end = "2016-12-31")`

Resulting in the following error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 46626: invalid start byte'

I've tried looking online here and used the .encode('utf-8).strip() at the end of each parameters to see if it works but it's not.

Body:
try doing

.decode('unicode_escape').encode('ascii', 'ignore')

instead of

.encode('utf-8).strip()


问:
What does the agent mean in jenkins?
I am trying to use jenkins. But when I reading the Declarative Pipeline Syntax, I confused by the agent term

https://jenkins.io/doc/book/pipeline/syntax/#scripted-pipeline

What does the agent stand for?

Is that mean I can set the pipeline runtime folder path?

How to create an agent?

How set a label for agent?

答:
I can feel you :-D.
Here are the answers:

The agent section specifies where the entire Pipeline, or a specific stage, will execute in the Jenkins environment depending on where the agent section is placed. The section must be defined at the top-level inside the pipeline block, but stage-level usage is optional. - Content copied from the agent section

NO, this has nothing to do with the pipeline runtime folder path.

You can for example Create an agent/node by the following tutorial:
How to Setup Jenkins Agent/Slave Using Password and ssh Keys. -
But there are many other ways to create an agent e.g. using a Docker-Container (...).

You can Set a label under the Configuration of the Node.
You can use a label in your pipeline like:

```<code> pipeline {
 agent { label 'labelName' }
 (...)
 }
</code>```

Title: What does the agent mean in jenkins?

Body:
I can feel you :-D.
Here are the answers:

The agent section specifies where the entire Pipeline, or a specific stage, will execute in the Jenkins environment depending on where the agent section is placed. The section must be defined at the top-level inside the pipeline block, but stage-level usage is optional. - Content copied from the agent section

NO, this has nothing to do with the pipeline runtime folder path.

You can for example Create an agent/node by the following tutorial:
How to Setup Jenkins Agent/Slave Using Password and ssh Keys. -
But there are many other ways to create an agent e.g. using a Docker-Container (...).

You can Set a label under the Configuration of the Node.
You can use a label in your pipeline like:

 pipeline {
 agent { label 'labelName' }
 (...)
 }


问:
Protractor: More specific feedback to User?
Say I have a page of 10 images and the 3rd and 5th don't load. How can I say something like:

2/5 images didn't load.

Or "image2.jpeg" and image5.jpeg" hasn't loaded.

```<code>browser.waitForAngularEnabled(false);

it('should find all images', function () {
  browser.get('https://popeyes.com/');
  var imagesBrokenCount = browser.executeScript(`
  var elms = document.querySelectorAll("img");
  return [].filter.call(elms, e => e.offsetHeight > 1 && e.naturalHeight <= 1).length;
  `);
browser.sleep(1000);
expect(imagesBrokenCount).toEqual(0);

});
</code>```

答:
You could simply return the source from the broken images and then assert that the returned array is empty:</p>

```<code>browser.get('https://popeyes.com/');
var brokenImages = browser.executeScript(`
  return [].slice.call(document.querySelectorAll("img"))
    .filter(e => e.offsetHeight > 1 && e.naturalHeight < 1)
    .map(e => e.src);
`);
browser.sleep(1000);
expect(brokenImages).toBeEmptyArray();
</code>```

Body:
Say I have a page of 10 images and the 3rd and 5th don't load. How can I say something like:

2/5 images didn't load.

Or "image2.jpeg" and image5.jpeg" hasn't loaded.

browser.waitForAngularEnabled(false);

it('should find all images', function () {
  browser.get('https://popeyes.com/');
  var imagesBrokenCount = browser.executeScript(`
  var elms = document.querySelectorAll("img");
  return [].filter.call(elms, e => e.offsetHeight > 1 && e.naturalHeight <= 1).length;
  `);
browser.sleep(1000);
expect(imagesBrokenCount).toEqual(0);

});

Body:
You could simply return the source from the broken images and then assert that the returned array is empty:

browser.get('https://popeyes.com/');
var brokenImages = browser.executeScript(`
  return [].slice.call(document.querySelectorAll("img"))
    .filter(e => e.offsetHeight > 1 && e.naturalHeight < 1)
    .map(e => e.src);
`);
browser.sleep(1000);
expect(brokenImages).toBeEmptyArray();


问:
TypeError: unhashable type: 'numpy.ndarray' - How to get data from data frame by querying radius from ball tree?
How to get data by querying radius from ball tree? For example

```<code>from sklearn.neighbors import BallTree
import pandas as pd

bt = BallTree(df[['lat','lng']], metric="haversine")

for idx, row in df.iterrow():
    res = df[bt.query_radius(row[['lat','lng']],r=1)]
</code>```

I want to get those rows in df that are in radius r=1. But it throws type error

```<code>TypeError: unhashable type: 'numpy.ndarray'
</code>```

Following the first answer I got index out of range when iterating over the rows

```<code>5183
(5219, 25)
5205
(5219, 25)
5205
(5219, 25)
5221
(5219, 25)
Traceback (most recent call last):
  File "/Users/Chu/Documents/dssg2018/sa4.py", line 45, in <module>
    df.loc[idx,word]=len(df.iloc[indices[idx]][df[word]==1])/\
IndexError: index 5221 is out of bounds for axis 0 with size 5219
</code>```

And the code is

```<code>bag_of_words = ['beautiful','love','fun','sunrise','sunset','waterfall','relax']

for idx,row in df.iterrows():
    for word in bag_of_words:
        if word in row['caption']:
            df.loc[idx, word] = 1
        else:
            df.loc[idx, word] = 0

bt = BallTree(df[['lat','lng']], metric="haversine")
indices = bt.query_radius(df[['lat','lng']],r=(float(10)/40000)*360)

for idx,row in df.iterrows():
    for word in bag_of_words:
        if word in row['caption']:
            print(idx)
            print(df.shape)
            df.loc[idx,word]=len(df.iloc[indices[idx]][df[word]==1])/\
                             np.max([1,len(df.iloc[indices[idx]][df[word]!=1])])
</code>```

答:
The error is not in the BallTree, but the indices returned by it are not used properly for putting it into index.

Do it this way:

```<code>for idx, row in df.iterrows():
    indices = bt.query_radius(row[['lat','lng']].values.reshape(1,-1), r=1)
    res = df.iloc[[x for b in indices for x in b]]
    # Do what you want to do with res
</code>```

This will also do (since we are sending only a single point each time):

```<code>    res = df.iloc[indices[0]]
</code>```

Explanation:

I'm using scikit 0.20. So the code you wrote above:

```<code>df[bt.query_radius(row[['lat','lng']],r=1)]
</code>```

did not work for me. I needed to make it a 2-d array by using reshape().

Now bt.query_radius() returns array of array of indices within the radius r specified as mentioned in the documentation:

ind : array of objects, shape = X.shape[:-1]

each element is a numpy integer array listing the indices of neighbors of the corresponding point. Note that unlike the results of
  a k-neighbors query, the returned neighbors are not sorted by distance
  by default.

So we needed to iterate two arrays to reach the actual indices of the data.

Now once we got the indices, in a pandas Dataframe, iloc is the way to access data with indices.

Update:

You dont need to query the bt each time for individual points. You can send all the df  at once to return a 2-d array containing the indices of points within the radius to the point specified that index.

```<code>indices = bt.query_radius(df, r=1)

for idx, row in df.iterrows():
    nearest_points_index = indices[idx]
    res = df.iloc[nearest_points_index]
    # Do what you want to do with res
</code>```

Body:
How to get data by querying radius from ball tree? For example

from sklearn.neighbors import BallTree
import pandas as pd

bt = BallTree(df[['lat','lng']], metric="haversine")

for idx, row in df.iterrow():
    res = df[bt.query_radius(row[['lat','lng']],r=1)]

I want to get those rows in df that are in radius r=1. But it throws type error

TypeError: unhashable type: 'numpy.ndarray'

Following the first answer I got index out of range when iterating over the rows

5183
(5219, 25)
5205
(5219, 25)
5205
(5219, 25)
5221
(5219, 25)
Traceback (most recent call last):
  File "/Users/Chu/Documents/dssg2018/sa4.py", line 45, in <module>
    df.loc[idx,word]=len(df.iloc[indices[idx]][df[word]==1])/\
IndexError: index 5221 is out of bounds for axis 0 with size 5219

And the code is

bag_of_words = ['beautiful','love','fun','sunrise','sunset','waterfall','relax']

for idx,row in df.iterrows():
    for word in bag_of_words:
        if word in row['caption']:
            df.loc[idx, word] = 1
        else:
            df.loc[idx, word] = 0

bt = BallTree(df[['lat','lng']], metric="haversine")
indices = bt.query_radius(df[['lat','lng']],r=(float(10)/40000)*360)

for idx,row in df.iterrows():
    for word in bag_of_words:
        if word in row['caption']:
            print(idx)
            print(df.shape)
            df.loc[idx,word]=len(df.iloc[indices[idx]][df[word]==1])/\
                             np.max([1,len(df.iloc[indices[idx]][df[word]!=1])])

Body:
The error is not in the BallTree, but the indices returned by it are not used properly for putting it into index.

Do it this way:

for idx, row in df.iterrows():
    indices = bt.query_radius(row[['lat','lng']].values.reshape(1,-1), r=1)
    res = df.iloc[[x for b in indices for x in b]]
    # Do what you want to do with res

This will also do (since we are sending only a single point each time):

    res = df.iloc[indices[0]]

Explanation:

I'm using scikit 0.20. So the code you wrote above:

df[bt.query_radius(row[['lat','lng']],r=1)]

did not work for me. I needed to make it a 2-d array by using reshape().

Now bt.query_radius() returns array of array of indices within the radius r specified as mentioned in the documentation:

ind : array of objects, shape = X.shape[:-1]

each element is a numpy integer array listing the indices of neighbors of the corresponding point. Note that unlike the results of
  a k-neighbors query, the returned neighbors are not sorted by distance
  by default.

So we needed to iterate two arrays to reach the actual indices of the data.

Now once we got the indices, in a pandas Dataframe, iloc is the way to access data with indices.

Update:

You dont need to query the bt each time for individual points. You can send all the df  at once to return a 2-d array containing the indices of points within the radius to the point specified that index.

indices = bt.query_radius(df, r=1)

for idx, row in df.iterrows():
    nearest_points_index = indices[idx]
    res = df.iloc[nearest_points_index]
    # Do what you want to do with res


问:
Can not build Gradle project with Android Studio
I'm using Android Studio 0.3.0 (configured to use gradle wrapper to build), Gradle 1.8. Everytime I build (or rebuild) the project with Android Studio, I get the error:

```<code>Gradle: A problem occurred evaluating project ':MyProject'.
> For input string: ""
</code>```

Clicking on the error, here is the error code in build.gradle:

```<code>def getCommitsCount() {
    return 'git rev-list --count HEAD'.execute().text.toInteger()
}
</code>```

If I remove .toInteger() then the error is gone. Otherwise, I can build the project from console just fine ./gradlew clean check build.

Anyone is getting the same problem? It seems to be a problem of Android Studio. If you know any workaround or fix, that would be cool.

答:
My problem was that I didn't have a Xcode version selected.

You can also try reinstalling Xcode Command Line Tools: xcode-select --install

Body:
I'm using Android Studio 0.3.0 (configured to use gradle wrapper to build), Gradle 1.8. Everytime I build (or rebuild) the project with Android Studio, I get the error:

Gradle: A problem occurred evaluating project ':MyProject'.
> For input string: ""

Clicking on the error, here is the error code in build.gradle:

def getCommitsCount() {
    return 'git rev-list --count HEAD'.execute().text.toInteger()
}

If I remove .toInteger() then the error is gone. Otherwise, I can build the project from console just fine ./gradlew clean check build.

Anyone is getting the same problem? It seems to be a problem of Android Studio. If you know any workaround or fix, that would be cool.


问:
How to check if PayPal app is installed on iPhone from code?
This is how I check if WeChat app is installed:

```<code>static func isWechatAvailable() -> Bool {
    if let url = NSURL(string:"weixin://scanqrcode")?.absoluteURL, UIApplication.shared.canOpenURL(url) {
        return true
    }
    return false
}
</code>```

How do I do it for PayPal? PayPal doesn't seem to have the scheme url. And installing and using PayPal SDK is a huge amount of work. Any suggestions?

Thanks!

答:
First you need to provide a LSApplicationQueriesSchemes entry in plist file, declaring which schemes it attempts to query. In your case its PayPal app.

```<code><key>LSApplicationQueriesSchemes</key>
<array>
    <string>paypal</string>
</array>
</code>```

Then modify your function like this.

```<code>static func isPayPalAvailable() -> Bool {
    if let url = NSURL(string:"paypal:")?.absoluteURL, UIApplication.shared.canOpenURL(url) {
        return true
    }
    return false
}
</code>```

You will get true if device has PayPal app installed. In case if you want to check it for other apps, replace paypal with other app name.

Body:
This is how I check if WeChat app is installed:

static func isWechatAvailable() -> Bool {
    if let url = NSURL(string:"weixin://scanqrcode")?.absoluteURL, UIApplication.shared.canOpenURL(url) {
        return true
    }
    return false
}

How do I do it for PayPal? PayPal doesn't seem to have the scheme url. And installing and using PayPal SDK is a huge amount of work. Any suggestions?

Thanks!

Body:
First you need to provide a LSApplicationQueriesSchemes entry in plist file, declaring which schemes it attempts to query. In your case its PayPal app.

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>paypal</string>
</array>

Then modify your function like this.

static func isPayPalAvailable() -> Bool {
    if let url = NSURL(string:"paypal:")?.absoluteURL, UIApplication.shared.canOpenURL(url) {
        return true
    }
    return false
}

You will get true if device has PayPal app installed. In case if you want to check it for other apps, replace paypal with other app name.


问:
Combine two queries into one and sort them
I am trying to display buildings and circuits in list (only 3 in total, sorted by the column "updated_at"). The problem is that they are not in the same table. I have a table circuits and a table buildings.

I tried to do this:

```<code>$buildings = Building::published()->limit(3)->get();
$circuits = Circuit::published()->limit(3)->get();

$merged = $buildings->merge($circuits);

$this->data['buildingsAndCircuits'] = $merged->all();
</code>```

I get everything right when I'm doing my var_dump and I know how to access the data when I do a foreach. But that does not do what I want.

I would like to sort them (by updated_at) and have only three and not six.

Is there a way to do that?

I tried to make conditions like with the QueryBuilder on $merge but it does not work

```<code>$this->data['buildingsAndCircuits'] = $merged->orderBy('updated_at', 'DESC')->limit(3)->all();
</code>```

thank you very much

答:
Once you've called get on each query then the query is executed and the result is returned. orderBy will not longer work after that since what you have in $buildings, $circuits and $merged is a collection.

You can however do this:

```<code>$buildings = Building::published()->limit(3)->get();
$circuits = Circuit::published()->limit(3)->get();

$merged = $buildings->merge($circuits)->sortByDesc('updated_at');

$this->data['buildingsAndCircuits'] = $merged->all();
</code>```

Check what else you can do on collections in the documentation

Body:
I am trying to display buildings and circuits in list (only 3 in total, sorted by the column "updated_at"). The problem is that they are not in the same table. I have a table circuits and a table buildings.

I tried to do this:

$buildings = Building::published()->limit(3)->get();
$circuits = Circuit::published()->limit(3)->get();

$merged = $buildings->merge($circuits);

$this->data['buildingsAndCircuits'] = $merged->all();

I get everything right when I'm doing my var_dump and I know how to access the data when I do a foreach. But that does not do what I want.

I would like to sort them (by updated_at) and have only three and not six.

Is there a way to do that?

I tried to make conditions like with the QueryBuilder on $merge but it does not work

$this->data['buildingsAndCircuits'] = $merged->orderBy('updated_at', 'DESC')->limit(3)->all();

thank you very much

Body:
Once you've called get on each query then the query is executed and the result is returned. orderBy will not longer work after that since what you have in $buildings, $circuits and $merged is a collection.

You can however do this:

$buildings = Building::published()->limit(3)->get();
$circuits = Circuit::published()->limit(3)->get();

$merged = $buildings->merge($circuits)->sortByDesc('updated_at');

$this->data['buildingsAndCircuits'] = $merged->all();

Check what else you can do on collections in the documentation


问:
Calling a C++ dll (unmanaged code) from a C# windows service (written in managed code)
I am working on a C++ project that has different components. We need to start the application as a windows service. The project is unmanaged C++ code. I wrote a C# windows service, and a C-style dll that will have a function to start the different components, and another to stop them. The dll has two files, a header and a .cpp file:
RTSS.h:

```<code>namespace PFDS
{
  extern "C" __declspec(dllexport) int runRTS(char*);
}
</code>```

RTSS.cpp:

```<code>using namespace PFDS;
/* ... includes and declarations */
extern "C" __declspec(dllexport) int runRTS(char* service_name)
{
   g_reserved_memory = (char*) malloc(sizeof(char) * RESERVED_MEMORY_SIZE);
   _set_new_handler(memory_depletion_handler);
   // this function is from a C++ .lib which is included in
   // the linker input for the RTSS dll project setting.
   // SetUnhandledExceptionHandler("RTS");
   return 0;
}
</code>```

In the ServiceBase subclass of the windows service, I have the following:

```<code>[DllImport("RTSSd.dll")]
public static extern int runRTS(string serviceName);

protected override void OnStart(string[] args)
{
  try
  {
    // the bin directory has all dependencies (dlls needed)
    Environment.CurrentDirectory = "D:/work/projects/bin";
    eventLog1.WriteEntry("RTSWinService: Starting " + this.ServiceName);
    int result = runRTS(this.ServiceName);
    eventLog1.WriteEntry("Result of invoking runRTS = " + result);
  }
  catch (Exception e)
  {
    eventLog1.WriteEntry("Exception caught: " + e.ToString());
  }
}
</code>```

Furthermore I have a console test application with code inside main similar to that inside OnStart. Both the application and the windows service runs with no problem when the SetUnhandledException function is commented. But when I uncomment that function, the windows console application runs ok, but the windows service outputs the following exception:

System.DllNotFoundException: Unable to load DLL 'RTSSd.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
     at RTSWS.RTSWinService.runRTS(String serviceName)
     at RTSWS.RTSWinService.OnStart(String[] args) in D:\work\project\ ...\RTSWinService.cs:line 39

I have read in some threads in different forums that the windows services start in C:\WINDOWS\System32, and it is true since initializing a DirectoryInfo and printing its full name shows so. I tried to change the default start directory with Environment.CurrentDirectory = "directory where the windows service executable and dlls are", but that didn't work. I also tried to change the Process directory, but that failed too. Other threads lead to this conclusion link text, but is it really that? Could it be something simpler?
I should note that the SetUnhandledException function is written in C++, not C, and so are many other functions that I need to call. All the needed dlls are placed next to the service executable. Your feedback is much appreciated.

Thanks.

答:
When something works at the console but not as a service, I aways suspect access permissions.  Make sure the user the service is running as, has read/execute access to d:\work\projects\bin.

The other suggestion is to call SetDllDirectory, which is a more direct way to say where DLLs are than to use the current directory.  See this SO thread on the pinvoke dll search path

You can also use SysInternal's ProcMon to watch the system try and locate your DLL.  Sometimes it's not the DLL, but a DLL your DLL depends on that has the problem and ProcMon is good for finding these issues.

Body:
I am working on a C++ project that has different components. We need to start the application as a windows service. The project is unmanaged C++ code. I wrote a C# windows service, and a C-style dll that will have a function to start the different components, and another to stop them. The dll has two files, a header and a .cpp file:
RTSS.h:

namespace PFDS
{
  extern "C" __declspec(dllexport) int runRTS(char*);
}

RTSS.cpp:

using namespace PFDS;
/* ... includes and declarations */
extern "C" __declspec(dllexport) int runRTS(char* service_name)
{
   g_reserved_memory = (char*) malloc(sizeof(char) * RESERVED_MEMORY_SIZE);
   _set_new_handler(memory_depletion_handler);
   // this function is from a C++ .lib which is included in
   // the linker input for the RTSS dll project setting.
   // SetUnhandledExceptionHandler("RTS");
   return 0;
}

In the ServiceBase subclass of the windows service, I have the following:

[DllImport("RTSSd.dll")]
public static extern int runRTS(string serviceName);

protected override void OnStart(string[] args)
{
  try
  {
    // the bin directory has all dependencies (dlls needed)
    Environment.CurrentDirectory = "D:/work/projects/bin";
    eventLog1.WriteEntry("RTSWinService: Starting " + this.ServiceName);
    int result = runRTS(this.ServiceName);
    eventLog1.WriteEntry("Result of invoking runRTS = " + result);
  }
  catch (Exception e)
  {
    eventLog1.WriteEntry("Exception caught: " + e.ToString());
  }
}

Furthermore I have a console test application with code inside main similar to that inside OnStart. Both the application and the windows service runs with no problem when the SetUnhandledException function is commented. But when I uncomment that function, the windows console application runs ok, but the windows service outputs the following exception:

System.DllNotFoundException: Unable to load DLL 'RTSSd.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
     at RTSWS.RTSWinService.runRTS(String serviceName)
     at RTSWS.RTSWinService.OnStart(String[] args) in D:\work\project\ ...\RTSWinService.cs:line 39

I have read in some threads in different forums that the windows services start in C:\WINDOWS\System32, and it is true since initializing a DirectoryInfo and printing its full name shows so. I tried to change the default start directory with Environment.CurrentDirectory = "directory where the windows service executable and dlls are", but that didn't work. I also tried to change the Process directory, but that failed too. Other threads lead to this conclusion link text, but is it really that? Could it be something simpler?
I should note that the SetUnhandledException function is written in C++, not C, and so are many other functions that I need to call. All the needed dlls are placed next to the service executable. Your feedback is much appreciated.

Thanks.


问:
Make sure the same ID is not affected to multiple tables
I want to restrict the number of the ID between multiple tables. Let's say I have 4 tables with products. Each table will have an ID, but I want to restrict the number of ID so I can't duplicate it that number already exists on one of these tables. Let's say I have the ID 43 in one table, I want to "deny" it on another table so I can't use it anymore because it's already created on that one.
Thanks!</p>

答:
When you INSERT new row, you should, LOCK all four tables (for data insert), start transaction, read max value of ID of each table and choose maximum, add 1 to that maximum and INSERT new row, then finish transaction and unlock tables.

This is basic solution, you can try to optimize it by saving in some place last maximum ID. The table locking ensure that ID will be unique when many concurrent threads (e.g. from php) will insert rows.

May be you will able to do it using triggers (so no on application side but on DB side).


问:
How can I find a variable with prompt in javascript?
with the function zoekAuto I want to if I say in the Prompt Maikel it says Maikel - 0. if you add fgvhj I want it to say thet it doesn't exist.

there is an error in this code but I cant find it.

```<code>var vrienden = ["Maikel", "Anna", "Peter", "Savannah"];

function toon() {
    document.getElementById("p7").innerHTML = vrienden + "  " + vrienden.length;
}

document.getElementById("p7").innerHTML = vrienden;
var vrienden = [" Maikel", " Anna", " Peter", " Savannah"];

function voegToe() {
    var vriend = prompt("Please enter your name:")

    vrienden.push(vriend);
    toon();

    document.getElementById("but").innerHTML = "toon lijst " + vrienden.length;
}

function toonFor() {
    document.getElementById("p6").innerHTML = "";

    lengteLijst = vrienden.length;
    for (i = 0; i < lengteLijst; i++) {
        document.getElementById("p6").innerHTML += i + " --- " + vrienden[i] + "<br>";
    }
}

function zoekauto() {
    var zoekString = prompt("welke naam zoek je???")
    var nr = vrienden.indexOf(zoekString);

    lengteLijst = vrienden.length;
    for (i = 0; i < lengteLijst; i++) {
        if (zoekString == vrienden[i]) {
            document.getElementById("p5").innerHTML += i + " -- gevonden " + nr + "<br>";
        } else {
            document.getElementById("p5").innerHTML = zoekString + " is niet gevonden";
        }
    }
}
</code>```

答:
You can try the below function . There are some spaces in your array elements so you have to remove them to match with the actual value supplied in prompt

var vrienden = ["Maikel", "Anna", "Peter", "Savannah"];

function zoekauto(){
            var zoekString = prompt ("welke naam zoek je???")
            var nr = vrienden.indexOf(zoekString);

            if(nr > -1){
              document.getElementById("p5").innerHTML += " -- gevonden " + nr + "
";
            }
             else{
               document.getElementById("p5").innerHTML = zoekString + " is niet gevonden";
             }
        }

 zoekauto();     ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="p5"></p></code>```

Body:
with the function zoekAuto I want to if I say in the Prompt Maikel it says Maikel - 0. if you add fgvhj I want it to say thet it doesn't exist.

there is an error in this code but I cant find it.

var vrienden = ["Maikel", "Anna", "Peter", "Savannah"];

function toon() {
    document.getElementById("p7").innerHTML = vrienden + "  " + vrienden.length;
}

document.getElementById("p7").innerHTML = vrienden;
var vrienden = [" Maikel", " Anna", " Peter", " Savannah"];

function voegToe() {
    var vriend = prompt("Please enter your name:")

    vrienden.push(vriend);
    toon();

    document.getElementById("but").innerHTML = "toon lijst " + vrienden.length;
}

function toonFor() {
    document.getElementById("p6").innerHTML = "";

    lengteLijst = vrienden.length;
    for (i = 0; i < lengteLijst; i++) {
        document.getElementById("p6").innerHTML += i + " --- " + vrienden[i] + "
";
    }
}

function zoekauto() {
    var zoekString = prompt("welke naam zoek je???")
    var nr = vrienden.indexOf(zoekString);

    lengteLijst = vrienden.length;
    for (i = 0; i < lengteLijst; i++) {
        if (zoekString == vrienden[i]) {
            document.getElementById("p5").innerHTML += i + " -- gevonden " + nr + "
";
        } else {
            document.getElementById("p5").innerHTML = zoekString + " is niet gevonden";
        }
    }
}

Body:
You can try the below function . There are some spaces in your array elements so you have to remove them to match with the actual value supplied in prompt

var vrienden = ["Maikel", "Anna", "Peter", "Savannah"];

function zoekauto(){
            var zoekString = prompt ("welke naam zoek je???")
            var nr = vrienden.indexOf(zoekString);

            if(nr > -1){
              document.getElementById("p5").innerHTML += " -- gevonden " + nr + "<br>";
            }
             else{
               document.getElementById("p5").innerHTML = zoekString + " is niet gevonden";
             }
        }

 zoekauto();

<p id="p5"></p>


问:
how to parsing json var inside script tag
I'm trying to scrape the data shown in the scatter plot in https://www.proteinatlas.org/ENSG00000167286-CD3D/pathology/tissue/renal+cancer

The javascript is in

```<code>'<script> var plot = $('#scatter6001').scatterPlot({"Alive (n=651)":{"symbol":"circle","data":[{"x":0.407889650408,"y":12.811,"tooltip":"TCGA-KL-8324-01A<br>Female\/ Stage ii \/ Alive<br>FPKM: 0.4<br>Living days: 4676 (12.8 years)","class":"stage_ii sex_f best_low median_low"},{"x":0.587835812523,"y":8.0795,"tooltip":"TCGA-KL-8334-01A<br>Female\/ Stage iii \/ Alive<br>FPKM: 0.6<br>Living days: 2949 (8.1years)","class":"stage_iii sex_f best_low median_low"}'...});
</code>```

My question is how to parse the information in TCGA-XX-XXXX-XXX, gender,stage, living or dead, FPKM and Living days? And how to save those information in the csv file?

This is the code I have done.

```<code>page = urlopen("https://www.proteinatlas.org/ENSG00000167286-CD3D/pathology/tissue/prostate+cancer#imid_3605750")
content = page.read()
soup = BeautifulSoup(content,'lxml')

table = soup.find('div', {'id':'scatter6001'})
print(table)

p = re.search(r"var plot = (.*?);",soup).group(1)
print(p)
</code>```

The code has some error, which is

Traceback (most recent call last):   File "scrap2.py", line 24, in

      p = re.search(r"var plot = (.*?);",soup).group(1)   File "C:\Python34\lib\re.py", line 170, in search
      return _compile(pattern, flags).search(string) TypeError: expected string or buffer

How to solve this problem and scrap the data I want?

Thanks

答:
It's definitely not a good idea to comply but it will fetch you the data you are after.

```<code>import requests
from bs4 import BeautifulSoup

page = requests.get("https://www.proteinatlas.org/ENSG00000167286-CD3D/pathology/tissue/prostate+cancer#imid_3605750")
soup = BeautifulSoup(page.text,'lxml')
item_text = soup.select('#scatter6001 script')[0].text
for x in range(1,100):            #be sure to put the highest range in place of 100
    item = item_text.split('tooltip')[x].split("class")[0].replace('"','').replace(',','').replace(':','').replace("<br>"," ").replace("/","").replace("\\","")
    print(item)
</code>```

Partial output:

```<code>TCGA-KK-A7B3-01A Male  Stage not reported  Alive FPKM 5.5 Living days 899 (2.5 years)
TCGA-G9-6347-01A Male  Stage not reported  Alive FPKM 14.2 Living days 2089 (5.7 years)
TCGA-KC-A4BL-01A Male  Stage not reported  Alive FPKM 3.8 Living days 934 (2.6 years)
TCGA-KK-A7AQ-01A Male  Stage not reported  Alive FPKM 2.6 Living days 1610 (4.4 years)
</code>```

Body:
I'm trying to scrape the data shown in the scatter plot in https://www.proteinatlas.org/ENSG00000167286-CD3D/pathology/tissue/renal+cancer

The javascript is in

'

Body:
It's definitely not a good idea to comply but it will fetch you the data you are after.

import requests
from bs4 import BeautifulSoup

page = requests.get("https://www.proteinatlas.org/ENSG00000167286-CD3D/pathology/tissue/prostate+cancer#imid_3605750")
soup = BeautifulSoup(page.text,'lxml')
item_text = soup.select('#scatter6001 script')[0].text
for x in range(1,100):            #be sure to put the highest range in place of 100
    item = item_text.split('tooltip')[x].split("class")[0].replace('"','').replace(',','').replace(':','').replace("<br>"," ").replace("/","").replace("\\","")
    print(item)

Partial output:

TCGA-KK-A7B3-01A Male  Stage not reported  Alive FPKM 5.5 Living days 899 (2.5 years)
TCGA-G9-6347-01A Male  Stage not reported  Alive FPKM 14.2 Living days 2089 (5.7 years)
TCGA-KC-A4BL-01A Male  Stage not reported  Alive FPKM 3.8 Living days 934 (2.6 years)
TCGA-KK-A7AQ-01A Male  Stage not reported  Alive FPKM 2.6 Living days 1610 (4.4 years)


问:
Making a string by accessing dictionary values
years, months, days, hours, minutes these values accessed from a dict. now I want to create a string like years = 12 months= 1 if there is only years and months. Consider a case only minutes and second. then the string should be minutes=1 seconds= 1 . how can I do this in an effective way??
The sample data may look like this

I tried to do something like this. But not working

```<code>    years, months, days, hours, minutes = self.initial_data["months"], \
                                            self.initial_data["years"], \
                                            self.initial_data["days"], \
                                            self.initial_data["hours"], \
                                            self.initial_data["minutes"],
    duration = if years: "years= {}".format(years) + \
            if months "months={}".format(months) +\
            and so on
</code>```

So the string change by if there is value or not

答:
Apart from bad syntax (you cannot use if in such a way), you're making this more complicated than it needs to be. Just create an ordered map and loop through it to extract existing fields from self.initial_data:

```<code>fields = ["years", "months", "days", "hours", "minutes", "seconds"]  # ordered list
data = self.initial_data  # a shorthand for readability sake
duration = " ".join("{}={}".format(f, data[f]) for f in fields if f in data)
</code>```

You can add an additional data[f] check in the duration list build up if you want to ignore fields whose values evaluate to False (e.g. 0, None etc.).

Body:
years, months, days, hours, minutes these values accessed from a dict. now I want to create a string like years = 12 months= 1 if there is only years and months. Consider a case only minutes and second. then the string should be minutes=1 seconds= 1 . how can I do this in an effective way??
The sample data may look like this

I tried to do something like this. But not working

    years, months, days, hours, minutes = self.initial_data["months"], \
                                            self.initial_data["years"], \
                                            self.initial_data["days"], \
                                            self.initial_data["hours"], \
                                            self.initial_data["minutes"],
    duration = if years: "years= {}".format(years) + \
            if months "months={}".format(months) +\
            and so on

So the string change by if there is value or not

Body:
Apart from bad syntax (you cannot use if in such a way), you're making this more complicated than it needs to be. Just create an ordered map and loop through it to extract existing fields from self.initial_data:

fields = ["years", "months", "days", "hours", "minutes", "seconds"]  # ordered list
data = self.initial_data  # a shorthand for readability sake
duration = " ".join("{}={}".format(f, data[f]) for f in fields if f in data)

You can add an additional data[f] check in the duration list build up if you want to ignore fields whose values evaluate to False (e.g. 0, None etc.).


问:
How can I call emergency number programmatically
I can call general phone number by following codes:

```<code>Intent intent = new Intent(Intent.ACTION_CALL);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("tel:" + phoneNumber));
startActivity(intent);
</code>```

in manifest file, I add permission like below:

```<code><uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.CALL_PRIVILEGED"/>
</code>```

as android's doc explain CALL_PRIVILEGED like this:Allows an application to call any phone number, including emergency numbers, without going through the Dialer user interface for the user to confirm the call being placed.Not for use by third-party applications.

And my app is located at packages/apps, so it is not a third-party application, right? So, why I still go straight to dial pad not the dialing user interface every time I call emergency number like '112'?

答:
No permission required in manifest. Call emergency dialer intent:</p>

```<code>try {
    Intent callIntent = new Intent("com.android.phone.EmergencyDialer.DIAL");
    callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
        Intent.FLAG_ACTIVITY_NO_USER_ACTION);
    callIntent.setData(Uri.parse("tel:112")); // < Optional, will prompt number for user
    startActivity(callIntent);
} catch (Exception e) {
    // in case something went wrong ...
}
</code>```

Body:
I can call general phone number by following codes:

Intent intent = new Intent(Intent.ACTION_CALL);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("tel:" + phoneNumber));
startActivity(intent);

in manifest file, I add permission like below:

<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.CALL_PRIVILEGED"/>

as android's doc explain CALL_PRIVILEGED like this:Allows an application to call any phone number, including emergency numbers, without going through the Dialer user interface for the user to confirm the call being placed.Not for use by third-party applications.

And my app is located at packages/apps, so it is not a third-party application, right? So, why I still go straight to dial pad not the dialing user interface every time I call emergency number like '112'?

Body:
No permission required in manifest. Call emergency dialer intent:

try {
    Intent callIntent = new Intent("com.android.phone.EmergencyDialer.DIAL");
    callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
        Intent.FLAG_ACTIVITY_NO_USER_ACTION);
    callIntent.setData(Uri.parse("tel:112")); // < Optional, will prompt number for user
    startActivity(callIntent);
} catch (Exception e) {
    // in case something went wrong ...
}


问:
Change UIButton border color on highlight
I've got a simple custom UIButton, to which I added:

```<code>button.layer.bordercolor = [[UIColor blueColor]CGColor];
</code>```

However, I want to change the .bordercolor when the button is highlighted. I tried adding an action to the button's touchDown action that changes the .bordercolor to red, but when the user lifts their finger, it stays red rather than returning to blue. Any ideas?

答:
For a solution that doesn't involve subclassing, you could always add an extension method to UIButton. E.g.</p>

```<code>func setBackgroundColor(_ backgroundColor: UIColor,
                        borderColor: UIColor,
                        borderWidth: CGFloat,
                        cornerRadius: CGFloat,
                        forState state: UIControlState) {

    UIGraphicsBeginImageContext(bounds.size)
    guard let context = UIGraphicsGetCurrentContext() else { return }

    if borderWidth > 0 {
        layer.borderWidth = 0 // hide the layer's border if we're going to draw a border
    }

    context.addPath(UIBezierPath(roundedRect: bounds.insetBy(dx: borderWidth, dy: borderWidth), cornerRadius: cornerRadius).cgPath)
    context.setStrokeColor(borderColor.cgColor)
    context.setFillColor(backgroundColor.cgColor)
    context.setLineWidth(borderWidth)

    context.closePath()
    context.strokePath()
    context.fillPath()

    let buttonImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    setBackgroundImage(buttonImage, for: state)
}
</code>```

Body:
I've got a simple custom UIButton, to which I added:

button.layer.bordercolor = [[UIColor blueColor]CGColor];

However, I want to change the .bordercolor when the button is highlighted. I tried adding an action to the button's touchDown action that changes the .bordercolor to red, but when the user lifts their finger, it stays red rather than returning to blue. Any ideas?

Body:
For a solution that doesn't involve subclassing, you could always add an extension method to UIButton. E.g.

func setBackgroundColor(_ backgroundColor: UIColor,
                        borderColor: UIColor,
                        borderWidth: CGFloat,
                        cornerRadius: CGFloat,
                        forState state: UIControlState) {

    UIGraphicsBeginImageContext(bounds.size)
    guard let context = UIGraphicsGetCurrentContext() else { return }

    if borderWidth > 0 {
        layer.borderWidth = 0 // hide the layer's border if we're going to draw a border
    }

    context.addPath(UIBezierPath(roundedRect: bounds.insetBy(dx: borderWidth, dy: borderWidth), cornerRadius: cornerRadius).cgPath)
    context.setStrokeColor(borderColor.cgColor)
    context.setFillColor(backgroundColor.cgColor)
    context.setLineWidth(borderWidth)

    context.closePath()
    context.strokePath()
    context.fillPath()

    let buttonImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    setBackgroundImage(buttonImage, for: state)
}