问:
how convert locations: [CLLocation] to Coordinate2D?
how cat get coordinate location of didUpdateLocation delegate ?

```<code>func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
</code>```

Please Help me.Thanks

答:
```<code> func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

 location = locations.last!
}
</code>```

Body:
how cat get coordinate location of didUpdateLocation delegate ?

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

Please Help me.Thanks


来源: stackexchange

问:
How to implement MeshNormalMaterial in THREE.js by GLSL?
I want to implement a shader like MeshNormalMaterial, but I have no idea how to convert normal to color.

In THREE.js:

My test1:

```<code>varying vec3 vNormal;

void main(void) {
    vNormal = abs(normal);
    gl_Position = matrix_viewProjection * matrix_model * vec4(position, 1.0);
}

varying vec3 vNormal;

void main(void) {
    gl_FragColor = vec4(vNormal, 1.0);
}
</code>```

My test2:

```<code>varying vec3 vNormal;

void main(void) {
    vNormal = normalize(normal) * 0.5 + 0.5;
    gl_Position = matrix_viewProjection * matrix_model * vec4(position, 1.0);
}

varying vec3 vNormal;

void main(void) {
    gl_FragColor = vec4(vNormal, 1.0);
}
</code>```

These are just test, I can't find any resources about how to calculate the color...

Can anyone help me ?

Thanks.

答:
If you want to see the normal vector in view space, the you have to transform the normal vector from the model space to the world space and from the world space to the view space. This can be done in one step by transforming the normal vector with the normalMatrix.

```<code>varying vec3 vNormal;

void main(void)
{
    vNormal      = normalMatrix * normalize(normal);
    gl_Position  = matrix_viewProjection * matrix_model * vec4(position, 1.0);
}
</code>```

Since a varying variable is interpolated when it is passed from the vertex shader to the fragment shader, according to its Barycentric coordinates,  the transformation to the color should be done in the fragment shader. Note, after the interpolation the normal vector has to be normalized again

```<code>varying vec3 vNormal;

void main(void)
{
    vec3 view_nv  = normalize(vNormal);
    vec3 nv_color = view_nv * 0.5 + 0.5;
    gl_FragColor  = vec4(nv_color, 1.0);
}
</code>```

Since the normal vector is normalized, its component are in the range [-1.0, 1.0]. How to represent it as a color is up to you.

If you use the abs value, then a positive and negative value with the same size have the same color representation. The intensity of the color increases with the grad of the value.

With the formula normal * 0.5 + 0.5 the intensity increases from 0 to 1.

In common the x component is represented red, the y component is green and the z component is blue.

The colors can be saturated, by dividing with the maximum value of its components:

```<code>varying vec3 vNormal;

void main(void)
{
    vec3 view_nv  = normalize(vNormal);
    vec3 nv_color = abs(view_nv);
    nv_color     /= max(nv_color.x, max(nv_color.y, nv_color.z));
    gl_FragColor  = vec4(nv_color, 1.0);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to implement a shader like MeshNormalMaterial, but I have no idea how to convert normal to color.

In THREE.js:

My test1:

varying vec3 vNormal;

void main(void) {
    vNormal = abs(normal);
    gl_Position = matrix_viewProjection * matrix_model * vec4(position, 1.0);
}

varying vec3 vNormal;

void main(void) {
    gl_FragColor = vec4(vNormal, 1.0);
}

My test2:

varying vec3 vNormal;

void main(void) {
    vNormal = normalize(normal) * 0.5 + 0.5;
    gl_Position = matrix_viewProjection * matrix_model * vec4(position, 1.0);
}

varying vec3 vNormal;

void main(void) {
    gl_FragColor = vec4(vNormal, 1.0);
}

These are just test, I can't find any resources about how to calculate the color...

Can anyone help me ?

Thanks.

Body:
If you want to see the normal vector in view space, the you have to transform the normal vector from the model space to the world space and from the world space to the view space. This can be done in one step by transforming the normal vector with the normalMatrix.

varying vec3 vNormal;

void main(void)
{
    vNormal      = normalMatrix * normalize(normal);
    gl_Position  = matrix_viewProjection * matrix_model * vec4(position, 1.0);
}

Since a varying variable is interpolated when it is passed from the vertex shader to the fragment shader, according to its Barycentric coordinates,  the transformation to the color should be done in the fragment shader. Note, after the interpolation the normal vector has to be normalized again

varying vec3 vNormal;

void main(void)
{
    vec3 view_nv  = normalize(vNormal);
    vec3 nv_color = view_nv * 0.5 + 0.5;
    gl_FragColor  = vec4(nv_color, 1.0);
}

Since the normal vector is normalized, its component are in the range [-1.0, 1.0]. How to represent it as a color is up to you.

If you use the abs value, then a positive and negative value with the same size have the same color representation. The intensity of the color increases with the grad of the value.

With the formula normal * 0.5 + 0.5 the intensity increases from 0 to 1.

In common the x component is represented red, the y component is green and the z component is blue.

The colors can be saturated, by dividing with the maximum value of its components:

varying vec3 vNormal;

void main(void)
{
    vec3 view_nv  = normalize(vNormal);
    vec3 nv_color = abs(view_nv);
    nv_color     /= max(nv_color.x, max(nv_color.y, nv_color.z));
    gl_FragColor  = vec4(nv_color, 1.0);
}

ContentLicense: CC BY-SA 4.0


答:
Please do some research before posting.

```<code>func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let coordinate = locations.first?.coordinate
}
</code>```

CLLocation Documentation

The location manager gives you an array of locations, just get the first one and then access the coordinate property.

Title: how convert locations: [CLLocation] to Coordinate2D?

Body:
Please do some research before posting.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let coordinate = locations.first?.coordinate
}

CLLocation Documentation

The location manager gives you an array of locations, just get the first one and then access the coordinate property.


问:
Twitch api freecodecamp loop issue
I am trying to complete the twitch api at freecodecamp.

I have an allTotalUsers array with the users I am looping through.

My loop appears to grabbing the info I need for each user in my allTotalUsers list correctly.
I tested this by displaying data from the offline users and it showed(multiple).

The issue is on my if(streamInfo==null) statement, the streamerName is showing duplicates only.

For example, If there is 2 offline users, Bob and John.

It will show
Bob
Bob

```<code>function showOfflineUsers() {

var onlinePeople = $('#displayInfo');
onlinePeople.html('');

//allTotalUsers is an array list that is loaded when the page loads and stored globally.
for (var i = 0; i < allTotalUsers.length; i++) {

    var streamerName = allTotalUsers[i];
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {

        if (this.readyState === 4 && this.status == 200) {
            var json = JSON.parse(this.responseText);

            // gets the status of stream(null etc)
            var streamInfo = json['stream'];

            if (streamInfo == null) {
                onlinePeople.append("<li>" + "<a href = 'https://www.twitch.tv/" + streamerName + "'>" + streamerName + "</a>" + "</li>" + "<br>");

            }

        }

    }

    xmlhttp.open("GET", "https://api.twitch.tv/kraken/streams/" + streamerName + "?client_id=" + clientId, true);
    xmlhttp.send();

};
}
</code>```

答:
As per spec

let and const declarations define variables that are scoped to the
  running execution context’s LexicalEnvironment. The variables are
  created when their containing Lexical Environment is instantiated but
  may not be accessed in any way until the variable’s LexicalBinding is
  evaluated.

So, as opposed to var which is scoped to VariableEnvironment (of execution's context), let is scoped to LexicalEnvironment.

Replace

```<code>var streamerName = allTotalUsers[i];
</code>```

with

```<code>let streamerName = allTotalUsers[i];
</code>```

Title: Twitch api freecodecamp loop issue

Body:
I am trying to complete the twitch api at freecodecamp.

I have an allTotalUsers array with the users I am looping through.

My loop appears to grabbing the info I need for each user in my allTotalUsers list correctly.
I tested this by displaying data from the offline users and it showed(multiple).

The issue is on my if(streamInfo==null) statement, the streamerName is showing duplicates only.

For example, If there is 2 offline users, Bob and John.

It will show
Bob
Bob

function showOfflineUsers() {

var onlinePeople = $('#displayInfo');
onlinePeople.html('');

//allTotalUsers is an array list that is loaded when the page loads and stored globally.
for (var i = 0; i < allTotalUsers.length; i++) {

    var streamerName = allTotalUsers[i];
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {

        if (this.readyState === 4 && this.status == 200) {
            var json = JSON.parse(this.responseText);

            // gets the status of stream(null etc)
            var streamInfo = json['stream'];

            if (streamInfo == null) {
                onlinePeople.append("
" + "" + streamerName + "" + "
" + "
");

            }

        }

    }

    xmlhttp.open("GET", "https://api.twitch.tv/kraken/streams/" + streamerName + "?client_id=" + clientId, true);
    xmlhttp.send();

};
}

Body:
As per spec

let and const declarations define variables that are scoped to the
  running execution context’s LexicalEnvironment. The variables are
  created when their containing Lexical Environment is instantiated but
  may not be accessed in any way until the variable’s LexicalBinding is
  evaluated.

So, as opposed to var which is scoped to VariableEnvironment (of execution's context), let is scoped to LexicalEnvironment.

Replace

var streamerName = allTotalUsers[i];

with

let streamerName = allTotalUsers[i];


问:
ARM Assembly: Loop will only iterate once, then inferior error
I'm doing a blackjack game for my final project for an assembly course. I have an array of words that represents 52 cards in a deck. My game wont be exactly like blackjack, but I need to demonstrate the basic concept of the game.

I'm trying to loop my deal function twice, but no matter what value I put into r4 (the loop counter) it only prints the output of the deal function once. I've looked at this in GDB and after the first iteration of deal I get an error:

[Inferior 1 (process 1585) exited with code 04]

```<code>mov r4, #0
cmp r4, #4
beq display_2
add r4, r4, #1
bal deal
</code>```

Whole source code:

```<code>.equ INPUT, 0
.equ OUTPUT, 1
.equ LOW, 0
.equ HIGH, 1

.equ PIN0, 0    // wipi pin 0 - bcm 17
.equ PIN1, 1    // wipi pin 1 - bcm 18
.equ PIN2, 2    // wipi pin 2 - bcm 27
.equ PIN3, 3    // wipi pin 3 - bcm 22
.equ PIN4, 4    // wipi pin 4 - bcm 23
.equ PIN5, 5    // wipi pin 5 - bcm 24
.equ PIN6, 6    // wipi pin 6 - bcm 25
.equ PIN7, 7    // wipi pin 7 - bcm 4

.global main
.data
format: .asciz "r1=%d\n"
.balign 4
// Create a deck of 52 cards
deck:
.word 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10
.word 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10
.word 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10
.word 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10

.text
// ripped from C++ compiler's assembly output
.align 2
.L3: .word 1321528399

main:
push {lr}
bl wiringPiSetup

mov r0, #PIN0
mov r1, #OUTPUT
bl pinMode

mov r0, #PIN1
mov r1, #OUTPUT
bl pinMode

mov r0, #PIN2
mov r1, #OUTPUT
bl pinMode

mov r0, #PIN3
mov r1, #OUTPUT
bl pinMode

mov r0, #PIN4
mov r1, #OUTPUT
bl pinMode

deal:
// the following code was disassembled from the C++ compiler's
// rand function
mov     r0, #0
bl      time
mov     r3, r0
mov     r0, r3
bl      srand
bl      rand

mov     r2, r0
ldr     r3, .L3
smull   r1, r3, r3, r2
mov     r1, r3, asr #4
mov     r3, r2, asr #31
rsb     r3, r3, r1
mov     r1, #52
mul     r3, r1, r3
rsb     r3, r3, r2
// end of C++ compiler's code
ldr r0, =format
// mov the random number generated (r3) into r1 for printing
mov r1, r3
// take the same value and store it also into r7 to preserve it
mov r7, r1
bl printf
ldr r0, =format
ldr r1, =deck
// setup r9 as the increment value leading to the next index
// of the array
mov r9, #4
// multiply into r8 the random number times the increment value
// of the array (4 bytes)
mul r8, r7, r9
// r8 now holds the randomized card just dealt to the player
// add this to the players score and get the actual value
// at from the address
add r1, r1, r8
ldr r1, [r1]
// mov into r7 the players score to preserve it
mov r7, r1
bl printf

display_2:
mov r4, #0
l:
cmp r4, #2
bne deal
add r4, r4, #1

bal l
// write the players score to the led display
mov r0, r7
bl digitalWriteByte
</code>```

Sample output:

```<code>pi@raspberrypi:~ $ ./6leds.out
r1=50 // the random index chosen
r1=10 // the value stored at that array index
pi@raspberrypi:~ $ ./6leds.out
r1=6
r1=7
pi@raspberrypi:~ $ ./6leds.out
r1=6
r1=7
</code>```

^ I would like it to do this twice instead of once

答:
A loop might be structured like so:

```<code>    // Initialize loop counter. Note this is outside the loop body.
    mov #r4, 0
loop_entry:
    // Test if the loop is done. This is a "while (...) { }" or for style loop
    cmp #r4, <loop_limt>
    bge loop_exit
    // code that you want to execute multiple times.
    // In the above this would be everything between deal: and display_2:
    <...>
    add r4, r4, #1
    bal loop_entry

loop_exit:
    // Do stuff after the loop.
</code>```

In the code you posted, the initialization to zero effectively happens inside of the loop. I would expect this to produce an infinite loop, not one which terminates after one execution. (E.g. I don't see how the bal l ever gets executed. You can verify this by stepping through in the debugger.)

The only simple thing I can think of that you might be getting hung up on is the difference between labels and functions. In the code you posted, the only label that identifies a function is main:. Elsewhere, the code just keeps executing past a label in a straight line. (There is of course nothing special about the main: label either, it is how it is used.) So after the second printf following deal:, the move r4, #0 under display_2: gets executed.

Body:
I'm doing a blackjack game for my final project for an assembly course. I have an array of words that represents 52 cards in a deck. My game wont be exactly like blackjack, but I need to demonstrate the basic concept of the game.

I'm trying to loop my deal function twice, but no matter what value I put into r4 (the loop counter) it only prints the output of the deal function once. I've looked at this in GDB and after the first iteration of deal I get an error:

[Inferior 1 (process 1585) exited with code 04]

mov r4, #0
cmp r4, #4
beq display_2
add r4, r4, #1
bal deal

Whole source code:

.equ INPUT, 0
.equ OUTPUT, 1
.equ LOW, 0
.equ HIGH, 1

.equ PIN0, 0    // wipi pin 0 - bcm 17
.equ PIN1, 1    // wipi pin 1 - bcm 18
.equ PIN2, 2    // wipi pin 2 - bcm 27
.equ PIN3, 3    // wipi pin 3 - bcm 22
.equ PIN4, 4    // wipi pin 4 - bcm 23
.equ PIN5, 5    // wipi pin 5 - bcm 24
.equ PIN6, 6    // wipi pin 6 - bcm 25
.equ PIN7, 7    // wipi pin 7 - bcm 4

.global main
.data
format: .asciz "r1=%d\n"
.balign 4
// Create a deck of 52 cards
deck:
.word 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10
.word 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10
.word 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10
.word 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10

.text
// ripped from C++ compiler's assembly output
.align 2
.L3: .word 1321528399

main:
push {lr}
bl wiringPiSetup

mov r0, #PIN0
mov r1, #OUTPUT
bl pinMode

mov r0, #PIN1
mov r1, #OUTPUT
bl pinMode

mov r0, #PIN2
mov r1, #OUTPUT
bl pinMode

mov r0, #PIN3
mov r1, #OUTPUT
bl pinMode

mov r0, #PIN4
mov r1, #OUTPUT
bl pinMode

deal:
// the following code was disassembled from the C++ compiler's
// rand function
mov     r0, #0
bl      time
mov     r3, r0
mov     r0, r3
bl      srand
bl      rand

mov     r2, r0
ldr     r3, .L3
smull   r1, r3, r3, r2
mov     r1, r3, asr #4
mov     r3, r2, asr #31
rsb     r3, r3, r1
mov     r1, #52
mul     r3, r1, r3
rsb     r3, r3, r2
// end of C++ compiler's code
ldr r0, =format
// mov the random number generated (r3) into r1 for printing
mov r1, r3
// take the same value and store it also into r7 to preserve it
mov r7, r1
bl printf
ldr r0, =format
ldr r1, =deck
// setup r9 as the increment value leading to the next index
// of the array
mov r9, #4
// multiply into r8 the random number times the increment value
// of the array (4 bytes)
mul r8, r7, r9
// r8 now holds the randomized card just dealt to the player
// add this to the players score and get the actual value
// at from the address
add r1, r1, r8
ldr r1, [r1]
// mov into r7 the players score to preserve it
mov r7, r1
bl printf

display_2:
mov r4, #0
l:
cmp r4, #2
bne deal
add r4, r4, #1

bal l
// write the players score to the led display
mov r0, r7
bl digitalWriteByte

Sample output:

pi@raspberrypi:~ $ ./6leds.out
r1=50 // the random index chosen
r1=10 // the value stored at that array index
pi@raspberrypi:~ $ ./6leds.out
r1=6
r1=7
pi@raspberrypi:~ $ ./6leds.out
r1=6
r1=7

^ I would like it to do this twice instead of once

Body:
A loop might be structured like so:

    // Initialize loop counter. Note this is outside the loop body.
    mov #r4, 0
loop_entry:
    // Test if the loop is done. This is a "while (...) { }" or for style loop
    cmp #r4, <loop_limt>
    bge loop_exit
    // code that you want to execute multiple times.
    // In the above this would be everything between deal: and display_2:
    <...>
    add r4, r4, #1
    bal loop_entry

loop_exit:
    // Do stuff after the loop.

In the code you posted, the initialization to zero effectively happens inside of the loop. I would expect this to produce an infinite loop, not one which terminates after one execution. (E.g. I don't see how the bal l ever gets executed. You can verify this by stepping through in the debugger.)

The only simple thing I can think of that you might be getting hung up on is the difference between labels and functions. In the code you posted, the only label that identifies a function is main:. Elsewhere, the code just keeps executing past a label in a straight line. (There is of course nothing special about the main: label either, it is how it is used.) So after the second printf following deal:, the move r4, #0 under display_2: gets executed.


问:
connect to mqtt broker after disconnecting from another broker using nodejs lib
The scenario that i want to implement is , first my service will connect to a mqtt broker , when i receive a message from a will topic , i want to disconnect it from the broker my mqtt client was connected and connect to some other broker.is it possible to do this using nodejs library??

var mqtt = require('mqtt')
var client  = mqtt.connect('mqtt://192.168.100.3')

client.on('connect', function () {
  console.log("connected to broker")
  client.subscribe('mqtt_node_subscribe')
  client.publish('mqtt_node_publish', 'Hello mqtt')
})
client.on('close',function(){
  console.log("connection closed")
})
client.on('message', function (topic, message) {
  // message is Buffer
  console.log("message arrived")

    client.end()
    client = mqtt.connect('mqtt://192.168.100.14')
  }})```
</div>
</div>
</p>

<p>I was able to disconnect from the current broker , but unable to connect to the other one, after disconnection Console messages are: </p>

```connected to broker
message arrived
connection closed
```

答:
You are replacing the client object so you need to recreate all the event handlers

e.g.

```<code>client.on('message', function (topic, message) {
  // message is Buffer
  console.log("message arrived")

  client.end()

  client = mqtt.connect('mqtt://192.168.100.14');
  client.on('connect', function () {
  ...
   });
   client.on('close',function(){
   ...
   })
}})
</code>```

Body:
The scenario that i want to implement is , first my service will connect to a mqtt broker , when i receive a message from a will topic , i want to disconnect it from the broker my mqtt client was connected and connect to some other broker.is it possible to do this using nodejs library??

var mqtt = require('mqtt')
var client  = mqtt.connect('mqtt://192.168.100.3')

client.on('connect', function () {
  console.log("connected to broker")
  client.subscribe('mqtt_node_subscribe')
  client.publish('mqtt_node_publish', 'Hello mqtt')
})
client.on('close',function(){
  console.log("connection closed")
})
client.on('message', function (topic, message) {
  // message is Buffer
  console.log("message arrived")

    client.end()
    client = mqtt.connect('mqtt://192.168.100.14')
  }})

I was able to disconnect from the current broker , but unable to connect to the other one, after disconnection Console messages are:

connected to broker
message arrived
connection closed

Body:
You are replacing the client object so you need to recreate all the event handlers

e.g.

client.on('message', function (topic, message) {
  // message is Buffer
  console.log("message arrived")

  client.end()

  client = mqtt.connect('mqtt://192.168.100.14');
  client.on('connect', function () {
  ...
   });
   client.on('close',function(){
   ...
   })
}})


答:
the simple answer for this question in swift : </p>

```<code>(locations.first?.coordinate)!
</code>```

Body:
the simple answer for this question in swift :

(locations.first?.coordinate)!


问:
Efficient string searching in Java
I am working with two big lists of data and I need to efficiently check for matches between the two. This is the scenario:

Reading from a file line by line (this file has 1 million lines)

For each line, check within an ArrayList of strings whether it has a match (this ArrayList also has a huge number of elements)

If a match is found, replace the line from the file with a new value

Any ideas what would be a good way to tackle this problem in terms of efficiency? Obviously looping through that number of records is hopelessly inefficient and process heavy.

Thanks for any help!

UPDATE
It's worth noting, I'm not specifically saying I need to use an ArrayList, that is just something I was using for testing. Any suggestions of more efficient Collections would be welcome.

答:
Without more details (such as the nature of the keys) it is difficult to be certain but you may find using a Bloom filter useful to minimise the number of times you do check within an ArrayList of strings whether it has a match.

Obviously this would not help much if the lookup list changes over time.

You would use the Bloom filter to do a pre-check before searching the list because it can very quickly give you a straight no answer if the key does not exist in the list. You will still need to search you list if the bloom filter says maybe.

Title: Efficient string searching in Java


问:
Fuse-box (VueJS + Font-Awesome + Bootstrap) - not watching scss
I'm trying to create a demo project with :

Fuse-Box

VueJS

Font-Awesome

Bootstrap (css/js/icons)

Jquery

I forked on GitHub fuse-box-seed

My problems:

When I'm running dev node fuse, I have to save several times my .scss files to display the new version in my browser.

When I build the project node fuse dist the ./dist/ressources folder is empty. I expect to have my fonts (Font-Awesome, bootstrap)

I have no error, just missing font files ...

Thank you very much for  your help !

答:
When you bundle bootstrap with FuseBox make sure it's bundled through javascript, not via import in sass.

```<code>import "boostrap/dist/bootstrap.css"
</code>```

The thing is when you bundle it using SASS imports (or any other CSS pre-preprocessor) the actual root folder is lost, the structure if flattened, and FuseBox fails to resolve the paths.

Body:
When you bundle bootstrap with FuseBox make sure it's bundled through javascript, not via import in sass.

import "boostrap/dist/bootstrap.css"

The thing is when you bundle it using SASS imports (or any other CSS pre-preprocessor) the actual root folder is lost, the structure if flattened, and FuseBox fails to resolve the paths.


答:
```<code>func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!) {
        var locationArray = locations as NSArray
        var locationObj = locationArray.lastObject as CLLocation
        var coord = locationObj.coordinate

        println(coord.latitude)
        println(coord.longitude)
}
</code>```


问:
How to use Angular 5 like the old school of web?
I'm trying to develop a web application using Angular. Based on our architecture, I need to include Angular and Material as we do with Bootstrap or jQuery or previous versions of Angular JS.

Yet I can't find a way to use Angular that way. All is cli which is not conformant to our platform's requirements and team rules.

Is there a way that I can use Angular and Material like the old days, by referencing them in head section of my HTML file?

答: No, you can't call Angular like before. You have to install Angular from CLI and then start your project but you can call Materialize in the head. Also, you can install it from npm and import it in .angular.cli.json</p>


问:
Sum of specific elements of a list based on indexes from another list in python

I am trying to find the durations of all the notes with the same name in a music piece (from .xml), in python. I have 3 lists:

```<code>scales = ['A', 'B', 'C'] #scales names
notesAll = ['B', 'A', 'C', 'A', 'C', 'C']  #note names of the piece
durationsAll = [1, 1.5, 1.5, 1, 1, 2]  #duration of each note from notesAll list
</code>```

I want to sum all the durations from durationsAll list for all the notes with the same name. For example for all the 'A's from notesAll list, which equals to scales[0], I want something like: durationsAll[1] + durationsAll[3]= 1.5 + 1 = 2.5. I need a better solution than my attempt:

```<code>for sc in scales:
  for ntPosition, nt in enumerate(notesAll):
    dtOfEach = 0
    for dtPosition, dt in enumerate(durationsAll):
      if sc == nt:
        dtPosotion = ntPosition  #I guess here is the problem
        dtOfEach = dtOfEach + dt
</code>```

The result I want would be: dtOfEach: 2.5  1  4.5

答:
defaultdict is perfect here (assuming note and note's duration are in corresponding lists of course)

```<code>from collections import defaultdict

duration_total = defaultdict(int)
for note in list(zip(notesAll, durationsAll)):
    duration_total[note[0]] += note[1]

print(duration_total)
</code>```

{'B': 1, 'A': 2.5, 'C': 4.5})

I think A:3.5 in your question was a typo ?

EDIT

Updated code with Chris' suggestion:

```<code>for note, duration in zip(notesAll, durationsAll):
    duration_total[note] += duration
</code>```

Body:
I am trying to find the durations of all the notes with the same name in a music piece (from .xml), in python. I have 3 lists:

scales = ['A', 'B', 'C'] #scales names
notesAll = ['B', 'A', 'C', 'A', 'C', 'C']  #note names of the piece
durationsAll = [1, 1.5, 1.5, 1, 1, 2]  #duration of each note from notesAll list

I want to sum all the durations from durationsAll list for all the notes with the same name. For example for all the 'A's from notesAll list, which equals to scales[0], I want something like: durationsAll[1] + durationsAll[3]= 1.5 + 1 = 2.5. I need a better solution than my attempt:

for sc in scales:
  for ntPosition, nt in enumerate(notesAll):
    dtOfEach = 0
    for dtPosition, dt in enumerate(durationsAll):
      if sc == nt:
        dtPosotion = ntPosition  #I guess here is the problem
        dtOfEach = dtOfEach + dt

The result I want would be: dtOfEach: 2.5  1  4.5

Body:
defaultdict is perfect here (assuming note and note's duration are in corresponding lists of course)

from collections import defaultdict

duration_total = defaultdict(int)
for note in list(zip(notesAll, durationsAll)):
    duration_total[note[0]] += note[1]

print(duration_total)

{'B': 1, 'A': 2.5, 'C': 4.5})

I think A:3.5 in your question was a typo ?

EDIT

Updated code with Chris' suggestion:

for note, duration in zip(notesAll, durationsAll):
    duration_total[note] += duration


问:
How to play a sound on iOS 11 with swift 4? And where i place The mp3 file?
I saw a lot of tutorials but when i click button (that actvivate The func playsound) The sound doesn’t play. I saw the code reccomended by stackoverflow but nothing.
I put The mp3 file info asset.xcasset. It’s right?</p>

答:
SWIFT 4 / XCODE 9.1

```<code>import AVFoundation

var objPlayer: AVAudioPlayer?

func playAudioFile() {
    guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)

        // For iOS 11
        objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

        // For iOS versions < 11
        objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3)

        guard let aPlayer = objPlayer else { return }
        aPlayer.play()

    } catch let error {
        print(error.localizedDescription)
    }
}
</code>```

Body:
SWIFT 4 / XCODE 9.1

import AVFoundation

var objPlayer: AVAudioPlayer?

func playAudioFile() {
    guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)

        // For iOS 11
        objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

        // For iOS versions < 11
        objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3)

        guard let aPlayer = objPlayer else { return }
        aPlayer.play()

    } catch let error {
        print(error.localizedDescription)
    }
}


问:
Does this qualify as recursion?
I am aware that a function calling itself is recursive. But, is an object creating objects of it's own type recursive? Additionally, I have no intention of using this code as it will quite obviously cause problems, I'm only interested in whether or not it qualifies as recursion.</p>

```<code>class Cell
{
    Cell()
    {
        Cell c = new Cell();
    }
}
</code>```

答:
Indeed it does. The Cell constructor will be called by itself, assuming that some calling code sets off the construction of a Cell instance.

Unless you block the recursion somehow (perhaps with a maximum instance limit), your program will eventually crash.

Title: Does this qualify as recursion?

Body:
I am aware that a function calling itself is recursive. But, is an object creating objects of it's own type recursive? Additionally, I have no intention of using this code as it will quite obviously cause problems, I'm only interested in whether or not it qualifies as recursion.

class Cell
{
    Cell()
    {
        Cell c = new Cell();
    }
}


问:
C# Merge two Lists of the same values
this is my Clients class:

```<code>public class Clients
{
    public string Email { get; set; }
    public string Name { get; set; }

    public Clients(string e, string n)
    {
        Email = e;
        Name = n;
    }
</code>```

I want to make a new list which contains the same clients from List A and List B .
For example:
List A - John, Jonathan, James ....
List B - Martha, Jane, Jonathan ....
Unsubscribers - Jonathan

```<code>    public static List<Clients> SameClients(List<Clients> A, List<Clients> B)
    {
        List<Clients> Unsubscribers = new List<Clients>();
        Unsubscribers = A.Intersect(B).ToList();
        return Unsubscribers;
    }
</code>```

However for some reasons I get empty list and I have no idea what's wrong.

答:
The problem is that when you are comparing objects Equals and Gethashcode are used to compare them. You can override these two methods and provide your own implementation based on your needs...there is already an answer below covering how to override these two methods

However, normally I prefer to keep my entities/models (or whatever you want to call them) very simple and keep comparison implementation details away from my models. In that case, you can implement an IEqualityComparer<TSource> and use an overload of Intersects that takes in an IEqualityComparer

Here's an example implementation of IEqualityComprarer based on only the Name property...

```<code>public class ClientNameEqualityComparer : IEqualityComparer<Clients>
{
    public bool Equals(Clients c1, Clients c2)
    {
        if (c2 == null && c1 == null)
           return true;
        else if (c1 == null | c2 == null)
           return false;
        else if(c1.Name == c2.Name)
            return true;
        else
            return false;
    }

    public int GetHashCode(Client c)
    {
        return c.Name.GetHashCode();
    }
}
</code>```

Basically, the implementation above only cares about the Name property, if two instances of Clients have the same value for the Name property, then they are considered equal.

Now you can do the followig...

```<code>A.Intersect(B, new ClientNameEqualityComparer()).ToList();
</code>```

And that will produce the results you are expecting...

Title: C# Merge two Lists of the same values

Body:
this is my Clients class:

public class Clients
{
    public string Email { get; set; }
    public string Name { get; set; }

    public Clients(string e, string n)
    {
        Email = e;
        Name = n;
    }

I want to make a new list which contains the same clients from List A and List B .
For example:
List A - John, Jonathan, James ....
List B - Martha, Jane, Jonathan ....
Unsubscribers - Jonathan

    public static List<Clients> SameClients(List<Clients> A, List<Clients> B)
    {
        List<Clients> Unsubscribers = new List<Clients>();
        Unsubscribers = A.Intersect(B).ToList();
        return Unsubscribers;
    }

However for some reasons I get empty list and I have no idea what's wrong.

Body:
The problem is that when you are comparing objects Equals and Gethashcode are used to compare them. You can override these two methods and provide your own implementation based on your needs...there is already an answer below covering how to override these two methods

However, normally I prefer to keep my entities/models (or whatever you want to call them) very simple and keep comparison implementation details away from my models. In that case, you can implement an IEqualityComparer<TSource> and use an overload of Intersects that takes in an IEqualityComparer

Here's an example implementation of IEqualityComprarer based on only the Name property...

public class ClientNameEqualityComparer : IEqualityComparer<Clients>
{
    public bool Equals(Clients c1, Clients c2)
    {
        if (c2 == null && c1 == null)
           return true;
        else if (c1 == null | c2 == null)
           return false;
        else if(c1.Name == c2.Name)
            return true;
        else
            return false;
    }

    public int GetHashCode(Client c)
    {
        return c.Name.GetHashCode();
    }
}

Basically, the implementation above only cares about the Name property, if two instances of Clients have the same value for the Name property, then they are considered equal.

Now you can do the followig...

A.Intersect(B, new ClientNameEqualityComparer()).ToList();

And that will produce the results you are expecting...


问:
Does inheritance via unwinding violate strict aliasing rule?
I have a struct X which inherits from struct Base. However, in my current setup, due to alignment, size of X is 24B:

```<code>typedef struct {
    double_t a;
    int8_t b;
} Base;

typedef struct {
    Base base;
    int8_t c;
} X;
</code>```

In order to save the memory, I'd like to unwind the Base struct, so I created struct Y which contains fields from Base (in the same order, always at the beginning of the struct), so the size of the struct is 16B:

```<code>typedef struct {
    double_t base_a;
    int8_t base_b;
    int8_t c;
} Y;
</code>```

Then I'm going to use instance of struct Y in a method which expects a pointer to Base struct:

```<code>void print_base(Base* b)
{
  printf("%f %d\n", b->a, b->b);
}
// ...
Y data;
print_base((Base*)&data);
</code>```

Does the code above violates the strict aliasing rule, and causes undefined behavior?

答:
First, Base and Y are not compatible types as defined by the standard 6.2.7, all members must match.

To access an Y through a Base* without creating a strict aliasing violation, Y needs to be "an aggregate type" (it is) that contains a Base type among its members. It does not.

So it is a strict aliasing violation and furthermore, since Y and Base are not compatible, they may have different memory layouts. Which is kind of the whole point, you made them different types for that very reason :)

What you can do in situations like this, is to use unions with struct members that share a common initial sequence, which is a special allowed case. Example of valid code from C11 6.5.2.3:

```<code>union {
  struct {
    int alltypes;
  } n;
  struct {
    int type;
    int intnode;
  } ni;
  struct {
    int type;
    double doublenode;
  } nf;
} u;

u.nf.type = 1;
u.nf.doublenode = 3.14;
/* ... */
if (u.n.alltypes == 1)
  if (sin(u.nf.doublenode) == 0.0)
</code>```

Body:
I have a struct X which inherits from struct Base. However, in my current setup, due to alignment, size of X is 24B:

typedef struct {
    double_t a;
    int8_t b;
} Base;

typedef struct {
    Base base;
    int8_t c;
} X;

In order to save the memory, I'd like to unwind the Base struct, so I created struct Y which contains fields from Base (in the same order, always at the beginning of the struct), so the size of the struct is 16B:

typedef struct {
    double_t base_a;
    int8_t base_b;
    int8_t c;
} Y;

Then I'm going to use instance of struct Y in a method which expects a pointer to Base struct:

void print_base(Base* b)
{
  printf("%f %d\n", b->a, b->b);
}
// ...
Y data;
print_base((Base*)&data);

Does the code above violates the strict aliasing rule, and causes undefined behavior?

Body:
First, Base and Y are not compatible types as defined by the standard 6.2.7, all members must match.

To access an Y through a Base* without creating a strict aliasing violation, Y needs to be "an aggregate type" (it is) that contains a Base type among its members. It does not.

So it is a strict aliasing violation and furthermore, since Y and Base are not compatible, they may have different memory layouts. Which is kind of the whole point, you made them different types for that very reason :)

What you can do in situations like this, is to use unions with struct members that share a common initial sequence, which is a special allowed case. Example of valid code from C11 6.5.2.3:

union {
  struct {
    int alltypes;
  } n;
  struct {
    int type;
    int intnode;
  } ni;
  struct {
    int type;
    double doublenode;
  } nf;
} u;

u.nf.type = 1;
u.nf.doublenode = 3.14;
/* ... */
if (u.n.alltypes == 1)
  if (sin(u.nf.doublenode) == 0.0)


问:
Pythonically add header to a csv file
I wrote a Python script merging two csv files, and now I want to add a header to the final csv. I tried following the suggestions reported here and I got the following error: expected string, float found. What is the most pythonic way to fix this?

Here is the code I am using:

```<code>import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])
    writer.writeheader()

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row + [0.0] for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)
</code>```

答:
You just add one additional row before you execute the loop. This row contains
your CSV file header name.</p>

```<code>schema = ['a','b','c','b']
row = 4
generators = ['A','B','C','D']
with open('test.csv','wb') as csvfile:
     writer = csv.writer(csvfile, delimiter=delimiter)
# Gives the header name row into csv
     writer.writerow([g for g in schema])
#Data add in csv file
     for x in xrange(rows):
         writer.writerow([g() for g in generators])
</code>```

Title: Pythonically add header to a csv file

Body:
I wrote a Python script merging two csv files, and now I want to add a header to the final csv. I tried following the suggestions reported here and I got the following error: expected string, float found. What is the most pythonic way to fix this?

Here is the code I am using:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])
    writer.writeheader()

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row + [0.0] for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)

Body:
You just add one additional row before you execute the loop. This row contains
your CSV file header name.

schema = ['a','b','c','b']
row = 4
generators = ['A','B','C','D']
with open('test.csv','wb') as csvfile:
     writer = csv.writer(csvfile, delimiter=delimiter)
# Gives the header name row into csv
     writer.writerow([g for g in schema])
#Data add in csv file
     for x in xrange(rows):
         writer.writerow([g() for g in generators])


问:
Could not resolve all dependencies for configuration ':_debugApkCopy' when using cordova-plugin-facebook4
I installed cordova facebook4 plugin

```<code>cordova plugin add cordova-plugin-facebook4 --save --variable APP_ID="12345678910" --variable APP_NAME="My Application Name"
</code>```

and when I try to build, it shows
this error.

I never got this error till last week, but today when I want to update my app it shows that error. Any suggestion?

答:
In Android Studio, go to SDK Manager and make sure:

Android SDK Platorm 27 is installed

Android SDK Build Tools 27.0.1 is installed

Android SDK Platform Tools is up-to-date (27.0.0 or above)

Android SDK Tools is up-to-date (26.1.1 or above)

Android Support Library is up-to-date (23.2.1 or above)

Android Support Repository is up-to-date (47.0.0 or above)

Body:
I installed cordova facebook4 plugin

cordova plugin add cordova-plugin-facebook4 --save --variable APP_ID="12345678910" --variable APP_NAME="My Application Name"

and when I try to build, it shows
this error.

I never got this error till last week, but today when I want to update my app it shows that error. Any suggestion?


问:
Effect of an asterisk in a jQuery selector
In the DevTools console of Chrome (version 63), I typed the following:

Notice the extra asterisk in the second query.

Both queries find the same element, but the second one is clearly getting a slightly different result. Also I wouldn't have expected the asterisk to be legal.

Can someone explain what effect the asterisk is having?

Note that this is not just asking about the use of an asterisk in a query, but about its effect when immediately next to an identifier.

答:
The asterisk stands for any element.

#right and *#right should both return the same element, since an id is unique.


问:
find the string with maximum number of lower case characters in java 8
I need to find the string with a maximum number of lowercases characters from Given List.

This is how i am currently doing

```<code>public static void main(String[] args) {

        List<String> list  = new ArrayList<>();

        list.add("Strig a with ABDD");
        list.add("STR dfd  BC dsff");

        OptionalLong max = list.stream().map(s->countLowerCase(s)).mapToLong(i->Long.valueOf(i)).max();
        System.out.println(max);

    }

    private static long countLowerCase(String inputString) {
        return inputString.chars().filter((s)->Character.isLowerCase(s)).count();
    }
</code>```

is there any better way of doing this?

答:
Using Stream API, I think there is a slightly easier (one-liner?) way to do it.

```<code>list.stream()
            .flatMap(s -> Stream.of(s.chars()
                    .filter(Character::isLowerCase)
                    .count()))
            .max(Comparator.naturalOrder())
            .ifPresent(System.out::println);
</code>```

Or the obvious much simpler solution:

```<code>long max = list.stream()
            .mapToLong(s -> s.chars().filter(Character::isLowerCase).count())
            .max()
            .getAsLong();
</code>```

Body:
I need to find the string with a maximum number of lowercases characters from Given List.

This is how i am currently doing

public static void main(String[] args) {

        List<String> list  = new ArrayList<>();

        list.add("Strig a with ABDD");
        list.add("STR dfd  BC dsff");

        OptionalLong max = list.stream().map(s->countLowerCase(s)).mapToLong(i->Long.valueOf(i)).max();
        System.out.println(max);

    }

    private static long countLowerCase(String inputString) {
        return inputString.chars().filter((s)->Character.isLowerCase(s)).count();
    }

is there any better way of doing this?

Body:
Using Stream API, I think there is a slightly easier (one-liner?) way to do it.

list.stream()
            .flatMap(s -> Stream.of(s.chars()
                    .filter(Character::isLowerCase)
                    .count()))
            .max(Comparator.naturalOrder())
            .ifPresent(System.out::println);

Or the obvious much simpler solution:

long max = list.stream()
            .mapToLong(s -> s.chars().filter(Character::isLowerCase).count())
            .max()
            .getAsLong();


答:
The problem is that IN is basically treated as a bunch of ORs (e.g.

```<code>col IN (1,2,3)
</code>```

is

```<code>col = 1 OR col = 2 OR col = 3
</code>```

This is a LOT slower than a join.

What you should do is to generate the SQL code which creates the temporary table, populates it with the values in the "IN" clause, and then join with that temp table

```<code>CREATE TEMPORARY TABLE numbers (n INT)
</code>```

Then in a loop, add

```<code>INSERT numbers  VALUES ($next_number)
</code>```

Then at the end

```<code>SELECT * FROM numbers, Recipe_Data
WHERE numbers.n = RHD_No
</code>```

ContentLicense: CC BY-SA 2.5

Title: MySQL Query IN() Clause Slow on Indexed Column

Body:
I Have a MySQL query that is being generated by a PHP script, the query will look something like this:

SELECT * FROM Recipe_Data WHERE 404_Without_200 = 0 AND Failures_Without_Success = 0 AND RHD_No IN (10, 24, 34, 41, 43, 51, 57, 59, 61, 67, 84, 90, 272, 324, 402, 405, 414, 498, 500, 501, 510, 559, 562, 595, 632, 634, 640, 643, 647, 651, 703, 714, 719, 762, 765, 776, 796, 812, 814, 815, 822, 848, 853, 855, 858, 866, 891, 920, 947, 956, 962, 968, 1049, 1054, 1064, 1065, 1070, 1100, 1113, 1119, 1130, 1262, 1287, 1292, 1313, 1320, 1327, 1332, 1333, 1335, 1340, 1343, 1344, 1346, 1349, 1352, 1358, 1362, 1365, 1482, 1495, 1532, 1533, 1537, 1549, 1550, 1569, 1571, 1573, 1574, 1596, 1628, 1691, 1714, 1720, 1735, 1755, 1759, 1829, 1837, 1844, 1881, 1919, 2005, 2022, 2034, 2035, 2039, 2054, 2076, 2079, 2087, 2088, 2089, 2090, 2091, 2092, 2154, 2155, 2156, 2157, 2160, 2162, 2164, 2166, 2169, 2171, 2174, 2176, 2178, 2179, 2183, 2185, 2186, 2187, 2201, 2234, 2236, 2244, 2245, 2250, 2255, 2260, 2272, 2280, 2281, 2282, 2291, 2329, 2357, 2375, 2444, 2451, 2452, 2453, 2454, 2456, 2457, 2460, 2462, 2464, 2465, 2467, 2468, 2469, 2470, 2473, 2474, 2481, 2485, 2487, 2510, 2516, 2519, 2525, 2540, 2545, 2547, 2553, 2571, 2579, 2580, 2587, 2589, 2597, 2602, 2611, 2629, 2660, 2662, 2700, 2756, 2825, 2833, 2835, 2858, 2958, 2963, 2964, 3009, 3090, 3117, 3118, 3120, 3121, 3122, 3123, 3126, 3127, 3129, 3130, 3133, 3135, 3137, 3138, 3139, 3141, 3142, 3145, 3146, 3147, 3151, 3152, 3155, 3193, 3201, 3204, 3219, 3221, 3222, 3223, 3224, 3225, 3226, 3227, 3228, 3229, 3231, 3232, 3233, 3234, 3235, 3237, 3239, 3246, 3250, 3253, 3259, 3261, 3291, 3315, 3328, 3377, 3381, 3383, 3384, 3385, 3387, 3388, 3389, 3390, 3396, 3436, 3463, 3465, 3467, 3470, 3471, 3484, 3507, 3515, 3554, 3572, 3641, 3672, 3683, 3689, 3690, 3692, 3693, 3694, 3697, 3698, 3705, 3711, 3713, 3715, 3716, 3717, 3719, 3720, 3722, 3726, 3727, 3732, 3737, 3763, 3767, 3770, 3771, 3772, 3773, 3803, 3810, 3812, 3816, 3846, 3847, 3848, 3851, 3874, 3882, 3902, 3903, 3906, 3908, 3916, 3924, 3967, 3987, 4006, 4030, 4043, 4045, 4047, 4058, 4067, 4107, 4108, 4114, 4115, 4131, 4132, 4133, 4137, 4138, 4139, 4140, 4141, 4142, 4146, 4150, 4151, 4152, 4153, 4157, 4158, 4160, 4163, 4166, 4167, 4171, 4179, 4183, 4221, 4225, 4242, 4257, 4435, 4437, 4438, 4443, 4446, 4449, 4450, 4451, 4452, 4454, 4460, 4550, 4557, 4618, 4731, 4775, 4804, 4972, 5025, 5026, 5039, 5042, 5294, 5578, 5580, 5599, 5602, 5649, 5726, 5779, 5783, 5931, 5934, 5936, 5939, 5940, 5941, 5978, 6044, 6056, 6113, 6116, 6118, 6122, 6123, 6125, 6127, 6128, 6129, 6130, 6131, 6135, 6141, 6145, 6147, 6150, 6152, 6153, 6154, 6160, 6166, 6169);

The column RHD_No is the primary key for this database, and there are about 400,000 rows total. The problem is, the query is extremely slow, it's often around 2 seconds, but I've seen it get as long as 10.

When I try to explain the query, everything seems like it should be fine:

+----+-------------+-------------+-------+---------------+---------+---------+------+------+-------------+
| id | select_type | table       | type  | possible_keys | key     | key_len | ref  | rows | Extra       |
+----+-------------+-------------+-------+---------------+---------+---------+------+------+-------------+
|  1 | SIMPLE      | Recipe_Data | range | PRIMARY       | PRIMARY | 4       | NULL |  420 | Using where |
+----+-------------+-------------+-------+---------------+---------+---------+------+------+-------------+

When I profile the query I get:

mysql> show profile;
+--------------------------------+----------+
| Status                         | Duration |
+--------------------------------+----------+
| starting                       | 0.000015 |
| checking query cache for query | 0.000266 |
| Opening tables                 | 0.000009 |
| System lock                    | 0.000004 |
| Table lock                     | 0.000006 |
| init                           | 0.000115 |
| optimizing                     | 0.000038 |
| statistics                     | 0.000797 |
| preparing                      | 0.000047 |
| executing                      | 0.000002 |
| Sending data                   | 2.675270 |
| end                            | 0.000007 |
| query end                      | 0.000003 |
| freeing items                  | 0.000071 |
| logging slow query             | 0.000002 |
| logging slow query             | 0.000058 |
| cleaning up                    | 0.000005 |
+--------------------------------+----------+

I've been working on this problem for a long time and I haven't been able to find a solution. Is there anything overtly wrong with this query? I don't see how looking at 420 rows should take 2+ seconds.

Body:
The problem is that IN is basically treated as a bunch of ORs (e.g.

col IN (1,2,3)

is

col = 1 OR col = 2 OR col = 3

This is a LOT slower than a join.

What you should do is to generate the SQL code which creates the temporary table, populates it with the values in the "IN" clause, and then join with that temp table

CREATE TEMPORARY TABLE numbers (n INT)

Then in a loop, add

INSERT numbers  VALUES ($next_number)

Then at the end

SELECT * FROM numbers, Recipe_Data
WHERE numbers.n = RHD_No


问:
jQuery muiltiselect is not working with AngularJS
I'm using jQuery multiple select with checkbox options here is my control

```<code><div id="main-wrapper" ng-app="MyApp">
    <div ng-controller="ngCtrl" style="background:#efefef; border-radius:5px; padding:15px; margin:15px 0px;">
        <label class="col-md-4 control-label" for="rolename">Role Name</label>
        <select id="dates-field2" class="multiselect-ui form-control" multiple="multiple">
            <option value="cheese">Cheese</option>
            <option value="tomatoes">Tomatoes</option>
            <option value="mozarella">Mozzarella</option>
            <option value="mushrooms">Mushrooms</option>
            <option value="pepperoni">Pepperoni</option>
            <option value="onions">Onions</option>
        </select>
    </div>
</div>
</code>```

But the problem is that this control is placed inside the ng-controller and ng-app so of AngularJS. So when I open the controller and checked the checkbox inside it that it is not working like it suppose to work to do.

答:
remove attribute  multiple="multiple" and try with </p>

<p>multiple="true" </p>

Body:
I'm using jQuery multiple select with checkbox options here is my control

        Role Name
        <select id="dates-field2" class="multiselect-ui form-control" multiple="multiple">
            <option value="cheese">Cheese</option>
            <option value="tomatoes">Tomatoes</option>
            <option value="mozarella">Mozzarella</option>
            <option value="mushrooms">Mushrooms</option>
            <option value="pepperoni">Pepperoni</option>
            <option value="onions">Onions</option>
        </select>

But the problem is that this control is placed inside the ng-controller and ng-app so of AngularJS. So when I open the controller and checked the checkbox inside it that it is not working like it suppose to work to do.

Body:
remove attribute  multiple="multiple" and try with

multiple="true"


问:
Django with ModWsgi and Apache not a valid application
This ended up being a OSx MySQL Improperly Configured Reason: unsafe use of relative path issue but I have left original problem incase reader has same breadcrumb trail.

So this is an odd problem - I'm trying to deploy Django to Apache, ModWSGI on a Mac running OSx but am running into the following error message:

Target WSGI script '/Library/WebServer/local_biems/biems/wsgi.py' does not contain WSGI application

Now:

local_biems runs ok with python manage.py runserver with no silenced issues. So I believe my project is error free and ready for deployment.

a test application local_blog runs ok with runserver AND with my virtual host configuration - so I'm assuming from this that Apache and MODWSGI are playing happily together.

local_biems and local_blog are alongside each other in the /Library/WebServer/ and have identical permissions.

If I update the file paths in the virtual host, restart apache and do a hard reload of the site I get the error above.

WSGI files are identical.

What can I try?   I've tried the try/catch statement around get_wsgi_application()

```<code>try:
    application = get_wsgi_application()
    print 'WSGI without exception'
except Exception:
    print 'handling WSGI exception'
    # Error loading applications
    if 'mod_wsgi' in sys.modules:
        traceback.print_exc()
        os.kill(os.getpid(), signal.SIGINT)
        time.sleep(2.5)
</code>```

but same issue.  If I remove this and stick with the standard...

```<code>Fri Dec 08 08:23:15.188440 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348] Traceback (most recent call last):, referer: http://biems.local/
[Fri Dec 08 08:23:15.188471 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348]   File "/Library/WebServer/local_biems/biems/wsgi.py", line 16, in <module>, referer: http://biems.local/
[Fri Dec 08 08:23:15.188521 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348]     application = get_wsgi_application(), referer: http://biems.local/
[Fri Dec 08 08:23:15.188542 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348]   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application, referer: http://biems.local/
[Fri Dec 08 08:23:15.188599 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348]     django.setup(set_prefix=False), referer: http://biems.local/
[Fri Dec 08 08:23:15.188615 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348]   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/__init__.py", line 27, in setup, referer: http://biems.local/
[Fri Dec 08 08:23:15.188637 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348]     apps.populate(settings.INSTALLED_APPS), referer: http://biems.local/
[Fri Dec 08 08:23:15.188650 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348]   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/registry.py", line 78, in populate, referer: http://biems.local/
[Fri Dec 08 08:23:15.188682 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348]     raise RuntimeError("populate() isn't reentrant"), referer: http://biems.local/
[Fri Dec 08 08:23:15.188703 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348] RuntimeError: populate() isn't reentrant, referer: http://biems.local/
</code>```

Although I have just commented out all (but 1) of my apps.    Strange thing is that this same site is working on a remove Ubuntu VPS no problem!

Ok,  so I just copied the database settings from local_biems to the local_blog and I get MYSQL errors.

```<code>daviesc@orion:local_biems [0]$ tail -f /var/log/apache2/local_blog.error.log
[Fri Dec 08 08:42:57.704722 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911]   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/utils.py", line 115, in load_backend, referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704740 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911]     return import_module('%s.base' % backend_name), referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704750 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911]   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module, referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704766 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911]     __import__(name), referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704776 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911]   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 30, in <module>, referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704913 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911]     'Did you install mysqlclient or MySQL-python?' % e, referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704934 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911] ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib, referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704941 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911]   Referenced from: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/_mysql.so, referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704946 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911]   Reason: unsafe use of relative rpath libmysqlclient.18.dylib in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/_mysql.so with restricted binary., referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704951 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911] Did you install mysqlclient or MySQL-python?, referer: http://biems.local/polls/
</code>```

答:
OK.   I traced this to -

MySQL Improperly Configured Reason: unsafe use of relative path

Although needed to update the last arg to reflect the new path.

```<code>sudo install_name_tool -change libmysqlclient.18.dylib /
/usr/local/mysql/lib/libmysqlclient.18.dylib /
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/_mysql.so
</code>```

It is probably a OSx specific issue - This was on 10.12.6.   I'm not sure I would have found it easily because it the SQL error only seems to appear once and then the compiled files report a different error.   I found using

```<code>find . -type f -name '*.pyc' -exec rm {} +
</code>```

to remove all the compiled files helped.

Also have to set Debug to True not to get the less informative 500 Error.

Body:
This ended up being a OSx MySQL Improperly Configured Reason: unsafe use of relative path issue but I have left original problem incase reader has same breadcrumb trail.

So this is an odd problem - I'm trying to deploy Django to Apache, ModWSGI on a Mac running OSx but am running into the following error message:

Target WSGI script '/Library/WebServer/local_biems/biems/wsgi.py' does not contain WSGI application

Now:

local_biems runs ok with python manage.py runserver with no silenced issues. So I believe my project is error free and ready for deployment.

a test application local_blog runs ok with runserver AND with my virtual host configuration - so I'm assuming from this that Apache and MODWSGI are playing happily together.

local_biems and local_blog are alongside each other in the /Library/WebServer/ and have identical permissions.

If I update the file paths in the virtual host, restart apache and do a hard reload of the site I get the error above.

WSGI files are identical.

What can I try?   I've tried the try/catch statement around get_wsgi_application()

try:
    application = get_wsgi_application()
    print 'WSGI without exception'
except Exception:
    print 'handling WSGI exception'
    # Error loading applications
    if 'mod_wsgi' in sys.modules:
        traceback.print_exc()
        os.kill(os.getpid(), signal.SIGINT)
        time.sleep(2.5)

but same issue.  If I remove this and stick with the standard...

Fri Dec 08 08:23:15.188440 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348] Traceback (most recent call last):, referer: http://biems.local/
[Fri Dec 08 08:23:15.188471 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348]   File "/Library/WebServer/local_biems/biems/wsgi.py", line 16, in <module>, referer: http://biems.local/
[Fri Dec 08 08:23:15.188521 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348]     application = get_wsgi_application(), referer: http://biems.local/
[Fri Dec 08 08:23:15.188542 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348]   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application, referer: http://biems.local/
[Fri Dec 08 08:23:15.188599 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348]     django.setup(set_prefix=False), referer: http://biems.local/
[Fri Dec 08 08:23:15.188615 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348]   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/__init__.py", line 27, in setup, referer: http://biems.local/
[Fri Dec 08 08:23:15.188637 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348]     apps.populate(settings.INSTALLED_APPS), referer: http://biems.local/
[Fri Dec 08 08:23:15.188650 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348]   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/registry.py", line 78, in populate, referer: http://biems.local/
[Fri Dec 08 08:23:15.188682 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348]     raise RuntimeError("populate() isn't reentrant"), referer: http://biems.local/
[Fri Dec 08 08:23:15.188703 2017] [wsgi:error] [pid 16734] [client 127.0.0.1:55348] RuntimeError: populate() isn't reentrant, referer: http://biems.local/

Although I have just commented out all (but 1) of my apps.    Strange thing is that this same site is working on a remove Ubuntu VPS no problem!

Ok,  so I just copied the database settings from local_biems to the local_blog and I get MYSQL errors.

daviesc@orion:local_biems [0]$ tail -f /var/log/apache2/local_blog.error.log
[Fri Dec 08 08:42:57.704722 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911]   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/utils.py", line 115, in load_backend, referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704740 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911]     return import_module('%s.base' % backend_name), referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704750 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911]   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module, referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704766 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911]     __import__(name), referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704776 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911]   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 30, in <module>, referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704913 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911]     'Did you install mysqlclient or MySQL-python?' % e, referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704934 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911] ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib, referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704941 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911]   Referenced from: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/_mysql.so, referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704946 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911]   Reason: unsafe use of relative rpath libmysqlclient.18.dylib in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/_mysql.so with restricted binary., referer: http://biems.local/polls/
[Fri Dec 08 08:42:57.704951 2017] [wsgi:error] [pid 16937] [client 127.0.0.1:55911] Did you install mysqlclient or MySQL-python?, referer: http://biems.local/polls/

Body:
OK.   I traced this to -

MySQL Improperly Configured Reason: unsafe use of relative path

Although needed to update the last arg to reflect the new path.

sudo install_name_tool -change libmysqlclient.18.dylib /
/usr/local/mysql/lib/libmysqlclient.18.dylib /
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/_mysql.so

It is probably a OSx specific issue - This was on 10.12.6.   I'm not sure I would have found it easily because it the SQL error only seems to appear once and then the compiled files report a different error.   I found using

find . -type f -name '*.pyc' -exec rm {} +

to remove all the compiled files helped.

Also have to set Debug to True not to get the less informative 500 Error.


问:
How to write logfile in C
I want to write logfile in C program. I also want it to add new logfile with tempstamp on daily basis.

Do you an idea, or is there a libary?

答:
Try this log4cpp.
Here is simple logfile creation written in C.</p>

```<code>/*Write your won logfile in c.*/
#include <stdio.h>
#define LOG(X, Y) fprintf (fp, #X ": Time:%s, File:%s(%d) " #Y  "\n", __TIMESTAMP__, __FILE__, __LINE__)

int main(int args, char **argv)
{
    FILE *fp= fopen("logfile.txt", "w"); //("c:\\temp\\logfile.txt")

    LOG(INFO, "File open success.");
    LOG(WARN, "File path missing.");
    LOG(ERROR, "File close faild.");

    fclose(fp);
return 0;
}
</code>```

Title: How to write logfile in C

Body:
Try this log4cpp.
Here is simple logfile creation written in C.

/*Write your won logfile in c.*/
#include <stdio.h>
#define LOG(X, Y) fprintf (fp, #X ": Time:%s, File:%s(%d) " #Y  "\n", __TIMESTAMP__, __FILE__, __LINE__)

int main(int args, char **argv)
{
    FILE *fp= fopen("logfile.txt", "w"); //("c:\\temp\\logfile.txt")

    LOG(INFO, "File open success.");
    LOG(WARN, "File path missing.");
    LOG(ERROR, "File close faild.");

    fclose(fp);
return 0;
}


问:
What kinds of tests are there?
I've always worked alone and my method of testing is usually compiling very often and making sure the changes I made work well and fix them if they don't. However, I'm starting to feel that that is not enough and I'm curious about the standard kinds of tests there are.

Can someone please tell me about the basic tests, a simple example of each, and why it is used/what it tests?

Thanks.

答:
Firstly there are various tests one can perform. The Question is how does one organize it. Testing is a Vast & enjoying process.

Start Testing with
1.Smoke Testing. Once passed , go ahead with Functionality Testing. This is the Backbone of Testing. If Functionality works fine then 80% of Testing is profitable.

2.Now go with User Interface testing. AS at times User Interface is something that attracts the Client more than functionality. It is the look & feel that a client gets more attracted to it.

3.Now its time to have a look on Cosmetics bugs. Generally these bugs are ignored because of time constraint. But these play a major role depending on the page it is found. A spelling mistake turns to be Major when found on Splash Screen Or Your landing page or the App name itself. Hence these can not be overlooked as well.

4.Do Conduct Compatibility Testing. i,e Testing on Various Browsers & browser Versions. May be devices & OS for Responsive applications.

Happy testing :)

Title: What kinds of tests are there?


问:
detecting a 404 on a http get and quickly handling it
I got this HTTP get request:

```<code>this.httpService.getData ('http://example.com/wp-json/wp/v2/' + 'badReferenceHere').subscribe(
          (response: Response) => {
            let apiResponse = JSON.parse(JSON.stringify(response));
            this.post_content = apiResponse.content.rendered;
            // do something with the this.post_content
          },
          (error: any) => {
            this.post_content = 'An error has occurred.';
        });
</code>```

If the URL is missing, and you already got a Failed to load resource: the server responded with a status of 404 (Not Found) message on the dev tools console.log, but yet, your code still showing the spinner, what are you supposed to do to quickly detect this and stop the wait and handle the 404 to say a message such as "That link does not exist"?

答:
GetMethod(url): Observable<any> {
        return this._http.get(url, { body: "" })
            .map(res => <any>res.json());
    }```

Body:
I got this HTTP get request:

this.httpService.getData ('http://example.com/wp-json/wp/v2/' + 'badReferenceHere').subscribe(
          (response: Response) => {
            let apiResponse = JSON.parse(JSON.stringify(response));
            this.post_content = apiResponse.content.rendered;
            // do something with the this.post_content
          },
          (error: any) => {
            this.post_content = 'An error has occurred.';
        });

If the URL is missing, and you already got a Failed to load resource: the server responded with a status of 404 (Not Found) message on the dev tools console.log, but yet, your code still showing the spinner, what are you supposed to do to quickly detect this and stop the wait and handle the 404 to say a message such as "That link does not exist"?


问:
Jenkins Pipeline Access stage steps variable in power shell execution
I want to access normal variable defined in my steps into power shell execution.
We can access environment variables using $env but, how to access normal step variables?</p>

```<code>stages {
        stage ('sometask') {
                steps{
                     script {
                        def someString = 'Hi'
                        withCredentials(...) {
                        def out = powershell(returnStdout: true, script:
                               '''
                               // Access someString
                         ''')
                         println out
                       }
                }
         }
}
</code>```

答:
Following should work :)

stages {

```<code>    stage ('sometask') {
            steps{
                 script {
                    def someString = 'Hi'
                    withCredentials(...) {
                    def out = powershell(returnStdout: true, script:
                           """
                           // Accessing someString
                           Write-Host $someString
                     """)
                     println out
                   }
            }
     }
</code>```

}

Body:
I want to access normal variable defined in my steps into power shell execution.
We can access environment variables using $env but, how to access normal step variables?

stages {
        stage ('sometask') {
                steps{
                     script {
                        def someString = 'Hi'
                        withCredentials(...) {
                        def out = powershell(returnStdout: true, script:
                               '''
                               // Access someString
                         ''')
                         println out
                       }
                }
         }
}

Body:
Following should work :)

stages {

    stage ('sometask') {
            steps{
                 script {
                    def someString = 'Hi'
                    withCredentials(...) {
                    def out = powershell(returnStdout: true, script:
                           """
                           // Accessing someString
                           Write-Host $someString
                     """)
                     println out
                   }
            }
     }

}


问:
In odoo 10 how can we add new fields to right side by inherting,right side does not have any fileds
I want to add to the right side of product in view

答:
views/stock.xml:

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

<record id="view_production_lot_form_inherit" model="ir.ui.view">
    <field name="model">stock.production.lot</field>
    <field name="inherit_id" ref="stock.view_production_lot_form"/>
    <field name="arch" type="xml">
        <group name="main_group" position="inside">
            <group>

            </group>
        </group>
    </field>
</record>

</odoo>
```

Note: You need to add the stock module the your custom module dependencies
and include the views/stock.xml file in your custom module manifest's data files
list.

Body:
views/stock.xml:

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

<record id="view_production_lot_form_inherit" model="ir.ui.view">
    <field name="model">stock.production.lot</field>
    <field name="inherit_id" ref="stock.view_production_lot_form"/>
    <field name="arch" type="xml">
        <group name="main_group" position="inside">
            <group>
                <!-- Add your fields here. -->
            </group>
        </group>
    </field>
</record>

</odoo>

Note: You need to add the stock module the your custom module dependencies
and include the views/stock.xml file in your custom module manifest's data files
list.


问:
event.preventDefault() vs. return false
When I want to prevent other event handlers from executing after a certain event is fired, I can use one of two techniques. I'll use jQuery in the examples, but this applies to plain-JS as well:

1. event.preventDefault()

```<code>$('a').click(function (e) {
    // custom handling here
    e.preventDefault();
});
</code>```

2. return false

```<code>$('a').click(function () {
    // custom handling here
    return false;
});
</code>```

Is there any significant difference between those two methods of stopping event propagation?

For me, return false; is simpler, shorter and probably less error prone than executing a method. With the method, you have to remember about correct casing, parenthesis, etc.

Also, I have to define the first parameter in callback to be able to call the method. Perhaps, there are some reasons why I should avoid doing it like this and use preventDefault instead? What's the better way?

答:
From my experience, there is at least one clear advantage when using event.preventDefault() over using return false. Suppose you are capturing the click event on an anchor tag, otherwise which it would be a big problem if the user were to be navigated away from the current page. If your click handler uses return false to prevent browser navigation, it opens the possibility that the interpreter will not reach the return statement and the browser will proceed to execute the anchor tag's default behavior.

```<code>$('a').click(function (e) {
  // custom handling here

  // oops...runtime error...where oh where will the href take me?

  return false;
});
</code>```

The benefit to using event.preventDefault() is that you can add this as the first line in the handler, thereby guaranteeing that the anchor's default behavior will not fire, regardless if the last line of the function is not reached (eg. runtime error).

```<code>$('a').click(function (e) {
  e.preventDefault();

  // custom handling here

  // oops...runtime error, but at least the user isn't navigated away.
});
</code>```

Title: event.preventDefault() vs. return false

Body:
When I want to prevent other event handlers from executing after a certain event is fired, I can use one of two techniques. I'll use jQuery in the examples, but this applies to plain-JS as well:

1. event.preventDefault()

$('a').click(function (e) {
    // custom handling here
    e.preventDefault();
});

2. return false

$('a').click(function () {
    // custom handling here
    return false;
});

Is there any significant difference between those two methods of stopping event propagation?

For me, return false; is simpler, shorter and probably less error prone than executing a method. With the method, you have to remember about correct casing, parenthesis, etc.

Also, I have to define the first parameter in callback to be able to call the method. Perhaps, there are some reasons why I should avoid doing it like this and use preventDefault instead? What's the better way?

Body:
From my experience, there is at least one clear advantage when using event.preventDefault() over using return false. Suppose you are capturing the click event on an anchor tag, otherwise which it would be a big problem if the user were to be navigated away from the current page. If your click handler uses return false to prevent browser navigation, it opens the possibility that the interpreter will not reach the return statement and the browser will proceed to execute the anchor tag's default behavior.

$('a').click(function (e) {
  // custom handling here

  // oops...runtime error...where oh where will the href take me?

  return false;
});

The benefit to using event.preventDefault() is that you can add this as the first line in the handler, thereby guaranteeing that the anchor's default behavior will not fire, regardless if the last line of the function is not reached (eg. runtime error).

$('a').click(function (e) {
  e.preventDefault();

  // custom handling here

  // oops...runtime error, but at least the user isn't navigated away.
});


问:
Sum of specific elements of a list based on indexes from another list in python

I am trying to find the durations of all the notes with the same name in a music piece (from .xml), in python. I have 3 lists:

```<code>scales = ['A', 'B', 'C'] #scales names
notesAll = ['B', 'A', 'C', 'A', 'C', 'C']  #note names of the piece
durationsAll = [1, 1.5, 1.5, 1, 1, 2]  #duration of each note from notesAll list
</code>```

I want to sum all the durations from durationsAll list for all the notes with the same name. For example for all the 'A's from notesAll list, which equals to scales[0], I want something like: durationsAll[1] + durationsAll[3]= 1.5 + 1 = 2.5. I need a better solution than my attempt:

```<code>for sc in scales:
  for ntPosition, nt in enumerate(notesAll):
    dtOfEach = 0
    for dtPosition, dt in enumerate(durationsAll):
      if sc == nt:
        dtPosotion = ntPosition  #I guess here is the problem
        dtOfEach = dtOfEach + dt
</code>```

The result I want would be: dtOfEach: 2.5  1  4.5

答:
You could use indices and proceed like this:

```<code>def get_total_duration(note):
    return sum(durationsAll[idx] for idx, nt in enumerate(notesAll) if nt == note)

scales = ['A', 'B', 'C'] #scales names
notesAll = ['B', 'A', 'C', 'A', 'C', 'C']  #note names of the piece
durationsAll = [1, 1.5, 1.5, 1, 1, 2]

get_total_duration('A')
</code>```

output:

```<code>2.5
</code>```

Body:
I am trying to find the durations of all the notes with the same name in a music piece (from .xml), in python. I have 3 lists:

scales = ['A', 'B', 'C'] #scales names
notesAll = ['B', 'A', 'C', 'A', 'C', 'C']  #note names of the piece
durationsAll = [1, 1.5, 1.5, 1, 1, 2]  #duration of each note from notesAll list

I want to sum all the durations from durationsAll list for all the notes with the same name. For example for all the 'A's from notesAll list, which equals to scales[0], I want something like: durationsAll[1] + durationsAll[3]= 1.5 + 1 = 2.5. I need a better solution than my attempt:

for sc in scales:
  for ntPosition, nt in enumerate(notesAll):
    dtOfEach = 0
    for dtPosition, dt in enumerate(durationsAll):
      if sc == nt:
        dtPosotion = ntPosition  #I guess here is the problem
        dtOfEach = dtOfEach + dt

The result I want would be: dtOfEach: 2.5  1  4.5

Body:
You could use indices and proceed like this:

def get_total_duration(note):
    return sum(durationsAll[idx] for idx, nt in enumerate(notesAll) if nt == note)

scales = ['A', 'B', 'C'] #scales names
notesAll = ['B', 'A', 'C', 'A', 'C', 'C']  #note names of the piece
durationsAll = [1, 1.5, 1.5, 1, 1, 2]

get_total_duration('A')

output:

2.5


答:
jQuery extensions causing a lot of problems in interaction with AngularJS. You may going to check this nice article about - “Thinking in AngularJS” if I have a jQuery background?. You need to create a directive or just use a select which is compatible with AngularJS. You may going to use ui-select which based on select2.

```<code><div ng-app="app" ng-controller="myCtrl as vm">
  <ui-select multiple tagging ng-model="vm.selected" theme="bootstrap">
    <ui-select-match placeholder="Pick one...">{{$item.value}}</ui-select-match>
    <ui-select-choices repeat="val in vm.values | filter: $select.search track by val.value">
      <div ng-bind="val.value | highlight: $select.search"></div>
    </ui-select-choices>
  </ui-select>
</div>
</code>```

> Demo fiddle

Title: jQuery muiltiselect is not working with AngularJS

Body:
jQuery extensions causing a lot of problems in interaction with AngularJS. You may going to check this nice article about - “Thinking in AngularJS” if I have a jQuery background?. You need to create a directive or just use a select which is compatible with AngularJS. You may going to use ui-select which based on select2.

<div ng-app="app" ng-controller="myCtrl as vm">
  <ui-select multiple tagging ng-model="vm.selected" theme="bootstrap">
    <ui-select-match placeholder="Pick one...">{{$item.value}}</ui-select-match>
    <ui-select-choices repeat="val in vm.values | filter: $select.search track by val.value">
      <div ng-bind="val.value | highlight: $select.search"></div>
    </ui-select-choices>
  </ui-select>
</div>

> Demo fiddle


问:
FileNotFoundError: [WinError 2] The system cannot find the file specified while trying to use pytesseract
I am trying to write a python script to extract the text from image and i keep getting this error. The script is given below. Error</p>

```<code>from PIL import Image

from pytesseract import image_to_string

print (image_to_string(Image.open('samp.png')))

print (image_to_string(Image.open('test-english.jpg'), lang='eng'))
</code>```

答:
Try the following steps, this worked for me.

1) Download tesseract-OCR from here and install it in the location C:/Program Files

2)write the following code

```<code>from PIL import Image

from pytesseract import image_to_string
</code>```

#pytesseract.pytesseract.tesseract_cmd = '<full_path_to_your_tesseract_executable>'
i.e

```<code>pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe'
</code>```

3)Now run this

```<code>print(pytesseract.image_to_string(Image.open('D:/image_file.jpg')))
</code>```

Hope that help!

Body:
I am trying to write a python script to extract the text from image and i keep getting this error. The script is given below. Error

from PIL import Image

from pytesseract import image_to_string

print (image_to_string(Image.open('samp.png')))

print (image_to_string(Image.open('test-english.jpg'), lang='eng'))

Body:
Try the following steps, this worked for me.

1) Download tesseract-OCR from here and install it in the location C:/Program Files

2)write the following code

from PIL import Image

from pytesseract import image_to_string

#pytesseract.pytesseract.tesseract_cmd = '<full_path_to_your_tesseract_executable>'
i.e

pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe'

3)Now run this

print(pytesseract.image_to_string(Image.open('D:/image_file.jpg')))

Hope that help!


问:
Overcome typescript type error using ramda groupby
I don't know how to fix this typescript error. I'm trying to use ramda's groupBy function:

```<code>245: const groups = R.groupBy((row: Record) => {
246:            return row[this.props.groupBy]
247:        })(this.props.data)
</code>```

Where this.props.groupBy is defined as :

```<code>groupBy?: {[K in keyof Record]}
data: Array<Record>
</code>```

The error that I get is:

```<code>Error:(245, 38) TS2345:Argument of type '(row: Record) => <T>(obj: any) => T' is not assignable to parameter of type '(a: Record) => string'.
  Type '<T>(obj: any) => T' is not assignable to type 'string'.

Error:(246, 31) TS2683:'this' implicitly has type 'any' because it does not have a type annotation.
</code>```

EDIT: I decided not to struggle with the keyof type and just declared it a groupBy as a string. I don't think these were my real errors, but intellij was having trouble updating its error messages, so who knows. They've gone away now.

答:
There are several problems in your question, fixing got the code to work easily:

```<code>namespace X {

    class Record {
        Test: string;
        Bla: string;
        test: number;
    }

    class TT {
        props: {
            groupBy?: keyof Record,
            data: Array<Record>
        }
        name() {
            const groups = R.groupBy((row: Record) => {
                return row[this.props.groupBy].toString();
            })(this.props.data)
        }
    }
}
</code>```

The problems were :

groupBy should be a keyof Record not {[K in keyof Record]}. The first one defines a type that can take any name of the properties of Record. Your version defined a type that has the same structure as Record but with all properties of type any.

groupBy specifically wants the return type to be a string, while the indexing operation on row can return any type of the properties of record (ex string|number in the example above) You should do a .toString to convert everything to string

Note: I used standard compiler settings, you might get other errors with strict but since don't mention the options I assumed standard. I tested with TS 2.6.2, and latest typings for Ramda from npm, other versions may differ in the errors.

Body:
I don't know how to fix this typescript error. I'm trying to use ramda's groupBy function:

245: const groups = R.groupBy((row: Record) => {
246:            return row[this.props.groupBy]
247:        })(this.props.data)

Where this.props.groupBy is defined as :

groupBy?: {[K in keyof Record]}
data: Array<Record>

The error that I get is:

Error:(245, 38) TS2345:Argument of type '(row: Record) => <T>(obj: any) => T' is not assignable to parameter of type '(a: Record) => string'.
  Type '<T>(obj: any) => T' is not assignable to type 'string'.

Error:(246, 31) TS2683:'this' implicitly has type 'any' because it does not have a type annotation.

EDIT: I decided not to struggle with the keyof type and just declared it a groupBy as a string. I don't think these were my real errors, but intellij was having trouble updating its error messages, so who knows. They've gone away now.

Body:
There are several problems in your question, fixing got the code to work easily:

namespace X {

    class Record {
        Test: string;
        Bla: string;
        test: number;
    }

    class TT {
        props: {
            groupBy?: keyof Record,
            data: Array<Record>
        }
        name() {
            const groups = R.groupBy((row: Record) => {
                return row[this.props.groupBy].toString();
            })(this.props.data)
        }
    }
}

The problems were :

groupBy should be a keyof Record not {[K in keyof Record]}. The first one defines a type that can take any name of the properties of Record. Your version defined a type that has the same structure as Record but with all properties of type any.

groupBy specifically wants the return type to be a string, while the indexing operation on row can return any type of the properties of record (ex string|number in the example above) You should do a .toString to convert everything to string

Note: I used standard compiler settings, you might get other errors with strict but since don't mention the options I assumed standard. I tested with TS 2.6.2, and latest typings for Ramda from npm, other versions may differ in the errors.


问:
Change URL without removing history in Angularjs
I'm using 'ui.router' and '$state.go' to redirect page,

'navbar' of my project looks like this.

```<code><ul class="sidebar-menu">
    <li class="active">
        <a ui-sref="root.menu({brand_id:nav.brand_id})">
            <i class="fa fa-building-o"></i>
            <span> {{nav.navInfo.menu.auth_name}}</span>
        </a>
    </li>
    <li>
        <a ui-sref="root.picture({brand_id:nav.brand_id})">
            <i class="fa fa-book"></i>
            <span> {{nav.navInfo.picture.auth_name}}</span>
        </a>
    </li>
    ...
</ul>
</code>```

Each page show table which has list of items first.

Let us supposed a situation.

When I am in 'menu' page, I search a keyword.

Following my code, URL changes including keyword.

For example, this works like

Before searching :

/menu?page=1&offset=0&limit=10

After searching :

/menu?page=1&offset=0&limit=10&searchKey=menu_name&searchString=pizza

.

.

Then, I click 'menu' tab in 'navbar' to get entire list again.

At this time, I wanted to change URL using trigger ui-sref or $(location) or something.

When using $(location).attr('href', url), changing URL successfully

but if I clicked browser back button, browser history did not maintain.

And also I've used window.location.href, window.location.replace but same result.

How can I maintain history in this case?

I'm ready for trying all ways of your suggestions!

.

.

PS.

If this is not enough explanation, please give me feedback.

Actually, I have no idea how to explain this more specifically. :(

And I've tried this in 'js', not 'controller'.

There was no special reason that I've done this in 'js'.

Just I thought that might be more easy way.

Thanks in advance!

.

.

UPDATE

I can change page by clicking each tabs on 'navbar'.

This works using ui-sref and perfect.

My main problem is, for example, when '.active' class is in 'menu' tab,

click 'menu' tab once again, ui-sref did not work.

So I used $location, window or something in 'js',

after this what I've gotten was 'removed history'.

I want to make page in initialized status when I clicked 'menu' tab like.

Before click tab :

/menu?page=1&offset=0&limit=10&searchKey=menu_name&searchString=pizza

After click tab :

/menu?page=1&offset=0&limit=10

One more, I'm putting ?page=1&offset=0&limit=10 into URL manually,

so what I just have to do is firing ui-sref or changing URL without removing history.

答:
Well if you are using Angular routers, don't use window.location or $(location) to change the page url and location. Angular router has its own mechanism of doing that, which is $state.

You need first to inject $state in your controller then you can use:

```<code>$state.go('yourStateHere');
</code>```

This will keep all the tracking the history in your browser.

Note:

Make sure that your states are well defined in your app.js, I mean you need to define a respective state for the serach page taking into considertaion all the search params.

For further details you can check:

ui-router Quick Reference.

StateProvider Reference.

AngularJS Routing Using UI-Router tutorial.

Body:
I'm using 'ui.router' and '$state.go' to redirect page,

'navbar' of my project looks like this.

             {{nav.navInfo.menu.auth_name}}

             {{nav.navInfo.picture.auth_name}}

    ...

Each page show table which has list of items first.

Let us supposed a situation.

When I am in 'menu' page, I search a keyword.

Following my code, URL changes including keyword.

For example, this works like

Before searching :

/menu?page=1&offset=0&limit=10

After searching :

/menu?page=1&offset=0&limit=10&searchKey=menu_name&searchString=pizza

.

.

Then, I click 'menu' tab in 'navbar' to get entire list again.

At this time, I wanted to change URL using trigger ui-sref or $(location) or something.

When using $(location).attr('href', url), changing URL successfully

but if I clicked browser back button, browser history did not maintain.

And also I've used window.location.href, window.location.replace but same result.

How can I maintain history in this case?

I'm ready for trying all ways of your suggestions!

.

.

PS.

If this is not enough explanation, please give me feedback.

Actually, I have no idea how to explain this more specifically. :(

And I've tried this in 'js', not 'controller'.

There was no special reason that I've done this in 'js'.

Just I thought that might be more easy way.

Thanks in advance!

.

.

UPDATE

I can change page by clicking each tabs on 'navbar'.

This works using ui-sref and perfect.

My main problem is, for example, when '.active' class is in 'menu' tab,

click 'menu' tab once again, ui-sref did not work.

So I used $location, window or something in 'js',

after this what I've gotten was 'removed history'.

I want to make page in initialized status when I clicked 'menu' tab like.

Before click tab :

/menu?page=1&offset=0&limit=10&searchKey=menu_name&searchString=pizza

After click tab :

/menu?page=1&offset=0&limit=10

One more, I'm putting ?page=1&offset=0&limit=10 into URL manually,

so what I just have to do is firing ui-sref or changing URL without removing history.

Body:
Well if you are using Angular routers, don't use window.location or $(location) to change the page url and location. Angular router has its own mechanism of doing that, which is $state.

You need first to inject $state in your controller then you can use:

$state.go('yourStateHere');

This will keep all the tracking the history in your browser.

Note:

Make sure that your states are well defined in your app.js, I mean you need to define a respective state for the serach page taking into considertaion all the search params.

For further details you can check:

ui-router Quick Reference.

StateProvider Reference.

AngularJS Routing Using UI-Router tutorial.