问:
Understanding a line of R code
There is a blog post on R bloggers how to transform stock prices in R to returns. It will transform the first row to 1 and then track the returns going forward. So they have this example of stock data:

```<code>##            AAPL.Close MSFT.Close GOOG.Close
## 2016-01-04     105.35      54.80     741.84
## 2016-01-05     102.71      55.05     742.58
## 2016-01-06     100.70      54.05     743.62
## 2016-01-07      96.45      52.17     726.39
## 2016-01-08      96.96      52.33     714.47
## 2016-01-11      98.53      52.30     716.03
</code>```

When you load a library magittr (which apparently is for a "pipe" operator) and you run this line of code:

```<code>stock_return <- apply(stocks, 1, function(x) {x / stocks[1,]}) %>% t %>% as.xts
</code>```

you get this:

```<code>           AAPL.Close MSFT.Close GOOG.Close
2016-01-04  1.0000000  1.0000000  1.0000000
2016-01-05  0.9749407  1.0045620  1.0009975
2016-01-06  0.9558614  0.9863139  1.0023994
2016-01-07  0.9155197  0.9520073  0.9791734
2016-01-08  0.9203607  0.9549271  0.9631052
2016-01-11  0.9352634  0.9543796  0.9652081
</code>```

I don't understand how this line of code works. I know the apply function will operate on each row (the parameter 1 accomplishes that). I know that in theory I want to divide the first row by itself (which will give 1 for that row) and then divide each succeeding row by the first row which will show how the 1.00 investment changes over time.

So this part of the code is the function:

```<code>{x / stocks[1,]}) %>% t %>%
</code>```

It has something to do with a "pipe operator" and the operations working left to right instead of inside out. Can someone help me understand the syntax of this function and how it accomplishes what it is supposed to? I can just use it but I would rather not have it be a black box. Thanks!

答:
First thing to note is that this code only works if the input is a matrix.
To make it reproducible read in the data as follows:

```<code>library(magrittr)
library(xts)
df <- read.table(text =" ,AAPL.Close, MSFT.Close, GOOG.Close
            2016-01-04,     105.35,      54.80,     741.84
            2016-01-05,     102.71,      55.05,     742.58
            2016-01-06,     100.70,      54.05,     743.62
            2016-01-07,      96.45,      52.17,     726.39
            2016-01-08,      96.96,      52.33,     714.47
            2016-01-11,      98.53,      52.30,     716.03",
            sep = ",", header = TRUE, row.names = 1)
stock <- as.matrix(df)
</code>```

If you struggle to understand how the whole pipe works at once just split it into its components.

The first part is the apply function.

```<code>apply(df, 1, function(x) {x / df[1,]})
</code>```

As you correctly stated it works on the rows of the matrix meaning

it takes each row of the martix and passes them seperatly to the provided function (there is actually a for loop working in the background). An easy case for a function would be mean.

```<code>apply(stock, 1, mean)
</code>```

This would simply compute the mean of each row. The author of the blog did something slightly more complicated and provided the anonymous function (a function just written for this special task)  function(x) {x / stock[1,]}.

So sequentially each row of the matrix is passed as the first argument to the provided  function. The function has only one argument x. So you can think of x as a vector representing one row of your original matrix. To figure out what the function is doing look at its body x / stock[1,].

x represents a row of the original matrix and stock[1, ] is the first row of the original matrix. Hence each row of the matrix is one after another devided by the first row of the matrix and the results are added as columns to a new matrix which looks like this

```<code>                       2016-01-04             2016-01-05             2016-01-06
AAPL.Close                      1              0.9749407              0.9558614
MSFT.Close                      1              1.0045620              0.9863139
GOOG.Close                      1              1.0009975              1.0023994
                       2016-01-07             2016-01-08             2016-01-11
AAPL.Close              0.9155197              0.9203607              0.9352634
MSFT.Close              0.9520073              0.9549270              0.9543796
GOOG.Close              0.9791734              0.9631053              0.9652081
</code>```

Compared to the final output here rows and columns are transposed.
If you transopse this matrix using t (the second function in the pipe) you get the desired output matrix. The last function as.xts simply transforms the matrix to a special type of time series object, a xts object.

OwnerDisplayName: Matt Papes

Title: Understanding a line of R code

Body:
There is a blog post on R bloggers how to transform stock prices in R to returns. It will transform the first row to 1 and then track the returns going forward. So they have this example of stock data:

##            AAPL.Close MSFT.Close GOOG.Close
## 2016-01-04     105.35      54.80     741.84
## 2016-01-05     102.71      55.05     742.58
## 2016-01-06     100.70      54.05     743.62
## 2016-01-07      96.45      52.17     726.39
## 2016-01-08      96.96      52.33     714.47
## 2016-01-11      98.53      52.30     716.03

When you load a library magittr (which apparently is for a "pipe" operator) and you run this line of code:

stock_return <- apply(stocks, 1, function(x) {x / stocks[1,]}) %>% t %>% as.xts

you get this:

           AAPL.Close MSFT.Close GOOG.Close
2016-01-04  1.0000000  1.0000000  1.0000000
2016-01-05  0.9749407  1.0045620  1.0009975
2016-01-06  0.9558614  0.9863139  1.0023994
2016-01-07  0.9155197  0.9520073  0.9791734
2016-01-08  0.9203607  0.9549271  0.9631052
2016-01-11  0.9352634  0.9543796  0.9652081

I don't understand how this line of code works. I know the apply function will operate on each row (the parameter 1 accomplishes that). I know that in theory I want to divide the first row by itself (which will give 1 for that row) and then divide each succeeding row by the first row which will show how the 1.00 investment changes over time.

So this part of the code is the function:

{x / stocks[1,]}) %>% t %>%

It has something to do with a "pipe operator" and the operations working left to right instead of inside out. Can someone help me understand the syntax of this function and how it accomplishes what it is supposed to? I can just use it but I would rather not have it be a black box. Thanks!

Body:
First thing to note is that this code only works if the input is a matrix.
To make it reproducible read in the data as follows:

library(magrittr)
library(xts)
df <- read.table(text =" ,AAPL.Close, MSFT.Close, GOOG.Close
            2016-01-04,     105.35,      54.80,     741.84
            2016-01-05,     102.71,      55.05,     742.58
            2016-01-06,     100.70,      54.05,     743.62
            2016-01-07,      96.45,      52.17,     726.39
            2016-01-08,      96.96,      52.33,     714.47
            2016-01-11,      98.53,      52.30,     716.03",
            sep = ",", header = TRUE, row.names = 1)
stock <- as.matrix(df)

If you struggle to understand how the whole pipe works at once just split it into its components.

The first part is the apply function.

apply(df, 1, function(x) {x / df[1,]})

As you correctly stated it works on the rows of the matrix meaning

it takes each row of the martix and passes them seperatly to the provided function (there is actually a for loop working in the background). An easy case for a function would be mean.

apply(stock, 1, mean)

This would simply compute the mean of each row. The author of the blog did something slightly more complicated and provided the anonymous function (a function just written for this special task)  function(x) {x / stock[1,]}.

So sequentially each row of the matrix is passed as the first argument to the provided  function. The function has only one argument x. So you can think of x as a vector representing one row of your original matrix. To figure out what the function is doing look at its body x / stock[1,].

x represents a row of the original matrix and stock[1, ] is the first row of the original matrix. Hence each row of the matrix is one after another devided by the first row of the matrix and the results are added as columns to a new matrix which looks like this

                       2016-01-04             2016-01-05             2016-01-06
AAPL.Close                      1              0.9749407              0.9558614
MSFT.Close                      1              1.0045620              0.9863139
GOOG.Close                      1              1.0009975              1.0023994
                       2016-01-07             2016-01-08             2016-01-11
AAPL.Close              0.9155197              0.9203607              0.9352634
MSFT.Close              0.9520073              0.9549270              0.9543796
GOOG.Close              0.9791734              0.9631053              0.9652081

Compared to the final output here rows and columns are transposed.
If you transopse this matrix using t (the second function in the pipe) you get the desired output matrix. The last function as.xts simply transforms the matrix to a special type of time series object, a xts object.

OwnerDisplayName: Alex


来源: stackexchange

问:
Loading old bootloader in assembly x86
I am writing my own bootloader in NASM x86 on x86_64 architechture, for starters I am just trying to copy the existing bootloader into second sector by using dd, then copy it back and run it from assembly.

file.asm

```<code>org 0x7c00

jmp 0:start

start:
mov ax, cs
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x8000

mov           ah, 0x02
mov           al, 1
mov           dl, 0x80
mov           ch, 0
mov           dh, 0
mov           cl, 3
mov           bx, 0x7e00
int           0x13

jmp 0x7e00
times 510-($-$$) db 0
dw 0xaa55

times (1024 - ($ - $$)) db 0x00
third_sector:
mov           ah, 0x02
mov           al, 1
mov           dl, 0x80
mov           ch, 0
mov           dh, 0
mov           cl, 2
mov           bx, 0x7c00
int           0x13

jmp           0x7c00
</code>```

The code sets up the stack, then pats itself to 1024 bytes with zeroes to have the last bit of code in third sector of the disk, then it loads the second sector from the disk into the first one and jumps to the first sector.

src.sh

```<code>#!/bin/bash
dd bs=1 count=512 if=/dev/c0d0 of=tmp
nasm -f bin file.asm -o file
dd bs=1 count=1200 if=file of=/dev/c0d0
dd bs=1 count=512 seek=512 if=tmp of=/dev/c0d0
</code>```

What I am doing is copying the original bootloader into temporary file called tmp, then compiling my programme and putting it into old bootloader's place (/dev/c0d0 since I am working on MINIX 3.3.0), then moving old bootloader into second sector.

The result is "Booting from hard disk" string, which is fine, and then I get "NetBSD MBR boot
 Error P" which corresponds to "no netBSD partition".

Edit: Pasted the wrong asm file.
Second edit: Error changed, but still persists.

答:
The NetBSD volume boot record (called a partition boot record or PBR by NetBSD) reads the first block of the disk it was booted from and checks to see if its the same as itself. If it's not then it assumes the disk has an MBR and tries to find the NetBSD boot partition in the MBR. It does this check by a simple comparison of the first 4 bytes of itself as loaded in memory, and the first four bytes of the first sector on disk.

Since your replacement boot sector doesn't start with the exact same 4 bytes its interpreted as an MBR with a partition table. Since your boot sector doesn't actually have an MBR partition table the NetBSD VBR isn't able to find the NetBSD partition and so prints error P (maybe or error no slice, depending on how it was configured).

To solve this problem you'll need to copy your disk's partition table into your replacement MBR. Note this also necessary because NetBSD itself (or whatever you're booting) will also want to read the partition table.

If your disk doesn't have an MBR with a partition table, and instead starts with the NetBSD VBR (PBR) then there isn't much you can do to fix the problem. In that case when the NetBSD VBR boots normally, it loads the first 15 sectors into memory at 0000:1000, checks that the first four bytes match itself as described above, and if so jumps to the code loaded at 0000:1000. Since you're changing the first 3 sectors of the disk you're also overwriting the NetBSD disk label at sector 2 and the start of what NetBSD calls the phase 1 bootstrap (bootxx) at sector 3.

ContentLicense: CC BY-SA 3.0

Title: Loading old bootloader in assembly x86

Body:
I am writing my own bootloader in NASM x86 on x86_64 architechture, for starters I am just trying to copy the existing bootloader into second sector by using dd, then copy it back and run it from assembly.

file.asm

org 0x7c00

jmp 0:start

start:
mov ax, cs
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x8000

mov           ah, 0x02
mov           al, 1
mov           dl, 0x80
mov           ch, 0
mov           dh, 0
mov           cl, 3
mov           bx, 0x7e00
int           0x13

jmp 0x7e00
times 510-($-$$) db 0
dw 0xaa55

times (1024 - ($ - $$)) db 0x00
third_sector:
mov           ah, 0x02
mov           al, 1
mov           dl, 0x80
mov           ch, 0
mov           dh, 0
mov           cl, 2
mov           bx, 0x7c00
int           0x13

jmp           0x7c00

The code sets up the stack, then pats itself to 1024 bytes with zeroes to have the last bit of code in third sector of the disk, then it loads the second sector from the disk into the first one and jumps to the first sector.

src.sh

#!/bin/bash
dd bs=1 count=512 if=/dev/c0d0 of=tmp
nasm -f bin file.asm -o file
dd bs=1 count=1200 if=file of=/dev/c0d0
dd bs=1 count=512 seek=512 if=tmp of=/dev/c0d0

What I am doing is copying the original bootloader into temporary file called tmp, then compiling my programme and putting it into old bootloader's place (/dev/c0d0 since I am working on MINIX 3.3.0), then moving old bootloader into second sector.

The result is "Booting from hard disk" string, which is fine, and then I get "NetBSD MBR boot
 Error P" which corresponds to "no netBSD partition".

Edit: Pasted the wrong asm file.
Second edit: Error changed, but still persists.


问:
graph in plotly R
Im new with plotly and i have question for you.

I have a dataset with date and value like this:

```<code>date             value
 01/01/2001     5
 ....
 01/01/2010     25
</code>```

and im plotting it with this code:

```<code>   plotr<- plot_ly(data,x = ~date, y = ~var,name='X',
                      type="scatter",mode='lines',
                      line = list(color = 'rgb(0, 0, 102)', width = 2 )) %>%
  layout(title = "My first graph",
         xaxis = list(title = "date"),
         yaxis = list (title = "number"))
  plotr
</code>```

It works fine but i want to put a note in one date for example in 2013 with his value... I searched in plotly website and i found it but i cant view my note...

https://plot.ly/r/line-charts/

anyone could help?

答:
Does the code below help you?

```<code>library(plotly)

x <- as.Date(c('2011-01-01','2012-01-01', '2013-01-01', '2014-01-01'))
y <- c(34, 24, 39, 15)
data <- data.frame(x, y)

annotation <- list(
x = data$x[2],
y = data$y[2],
text = 'My annotation',
showarrow = TRUE)

p <- plot_ly(data, x=~x) %>%
  add_trace(y=y, mode='lines')  %>%
  add_trace(x=~c(x[1], x[4]), y=~c(y[1], y[4]), type='scatter') %>%
  layout(title='My graph', annotations=annotation)
</code>```

Title: graph in plotly R

Body:
Im new with plotly and i have question for you.

I have a dataset with date and value like this:

date             value
 01/01/2001     5
 ....
 01/01/2010     25

and im plotting it with this code:

   plotr<- plot_ly(data,x = ~date, y = ~var,name='X',
                      type="scatter",mode='lines',
                      line = list(color = 'rgb(0, 0, 102)', width = 2 )) %>%
  layout(title = "My first graph",
         xaxis = list(title = "date"),
         yaxis = list (title = "number"))
  plotr

It works fine but i want to put a note in one date for example in 2013 with his value... I searched in plotly website and i found it but i cant view my note...

https://plot.ly/r/line-charts/

anyone could help?

Body:
Does the code below help you?

library(plotly)

x <- as.Date(c('2011-01-01','2012-01-01', '2013-01-01', '2014-01-01'))
y <- c(34, 24, 39, 15)
data <- data.frame(x, y)

annotation <- list(
x = data$x[2],
y = data$y[2],
text = 'My annotation',
showarrow = TRUE)

p <- plot_ly(data, x=~x) %>%
  add_trace(y=y, mode='lines')  %>%
  add_trace(x=~c(x[1], x[4]), y=~c(y[1], y[4]), type='scatter') %>%
  layout(title='My graph', annotations=annotation)


问:
Python print adds new line and 0
Here's my issue. I'm trying to ssh to Cisco devices and pull information off. When I run my code, the print statement adds a new line with a 0 in it to the bottom of the output. Here is the output of the code followed by the output of the plink CLI input:

```<code>C:\Python30>python PLINKSSHtest.py
Enter your username: josh
Password:
plink -pw nowayjose -ssh nope@1.1.1.1 "show run | inc hostname"
hostname net-R2
0  <------------MY ISSUE

C:\Python30>plink -pw nowayjose -ssh nope@1.1.1.1 "show run | inc hostname"
hostname net-R2
  <------------WHAT I EXPECT
</code>```

Here is my code:

```<code>def read_dev():
    # Print statement here for debugging
    print ("plink -pw " + password + " -ssh " + user + "@" + HOST + " " + command)
    cur_dev = os.system("plink -pw " + password + " -ssh " + user + "@" + HOST + " " + command)
    return(cur_dev)

HOST = None
user = input("Enter your username: ")
password = getpass.getpass()
command = '"show run | inc hostname"'
HOST = '1.1.1.1'
print (read_dev())
</code>```

答: It doesn't "print zero". It prints cur_dev which is returned by read_dev function, which happens to be zero. And it does so, because you told it to. Remove print function and it won't print anything."

ContentLicense: CC BY-SA 2.5

Title: Python print adds new line and 0

Body:
Here's my issue. I'm trying to ssh to Cisco devices and pull information off. When I run my code, the print statement adds a new line with a 0 in it to the bottom of the output. Here is the output of the code followed by the output of the plink CLI input:

C:\Python30>python PLINKSSHtest.py
Enter your username: josh
Password:
plink -pw nowayjose -ssh nope@1.1.1.1 "show run | inc hostname"
hostname net-R2
0  <------------MY ISSUE

C:\Python30>plink -pw nowayjose -ssh nope@1.1.1.1 "show run | inc hostname"
hostname net-R2
  <------------WHAT I EXPECT

Here is my code:

def read_dev():
    # Print statement here for debugging
    print ("plink -pw " + password + " -ssh " + user + "@" + HOST + " " + command)
    cur_dev = os.system("plink -pw " + password + " -ssh " + user + "@" + HOST + " " + command)
    return(cur_dev)

HOST = None
user = input("Enter your username: ")
password = getpass.getpass()
command = '"show run | inc hostname"'
HOST = '1.1.1.1'
print (read_dev())


问:
Adding a new column to each element in a list of tables or data frames
I have a list of files. I also have a list of "names" which I substr() from the actual filenames of these files. I would like to add a new column to each of the files in the list. This column will contain the corresponding element in "names" repeated times the number of rows in the file.

For example:

```<code>df1 <- data.frame(x = 1:3, y=letters[1:3])
df2 <- data.frame(x = 4:6, y=letters[4:6])
filelist <- list(df1,df2)
ID <- c("1A","IB")
</code>```

Pseudocode

```<code>  for( i in length(filelist)){

       filelist[i]$SampleID <- rep(ID[i],nrow(filelist[i])

  }
</code>```

// basically create a new column in each of the dataframes in filelist, and fill the column with repeted corresponding values of ID

my output should be like:

filelist[1] should be:

```<code>   x y SAmpleID
 1 1 a       1A
 2 2 b       1A
 3 3 c       1A
</code>```

fileList[2]

```<code>   x y SampleID
 1 4 d       IB
 2 5 e       IB
 3 6 f       IB
</code>```

and so on.....

Any Idea how it could be done.

答:
A tricky way: </p>

```<code>library(plyr)

names(filelist) <- ID
result <- ldply(filelist, data.frame)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a list of files. I also have a list of "names" which I substr() from the actual filenames of these files. I would like to add a new column to each of the files in the list. This column will contain the corresponding element in "names" repeated times the number of rows in the file.

For example:

df1 <- data.frame(x = 1:3, y=letters[1:3])
df2 <- data.frame(x = 4:6, y=letters[4:6])
filelist <- list(df1,df2)
ID <- c("1A","IB")

Pseudocode

  for( i in length(filelist)){

       filelist[i]$SampleID <- rep(ID[i],nrow(filelist[i])

  }

// basically create a new column in each of the dataframes in filelist, and fill the column with repeted corresponding values of ID

my output should be like:

filelist[1] should be:

   x y SAmpleID
 1 1 a       1A
 2 2 b       1A
 3 3 c       1A

fileList[2]

   x y SampleID
 1 4 d       IB
 2 5 e       IB
 3 6 f       IB

and so on.....

Any Idea how it could be done.

Body:
A tricky way:

library(plyr)

names(filelist) <- ID
result <- ldply(filelist, data.frame)


问:
Reset AutoIncrement in SQL Server after Delete
I've deleted some records from a table in a SQL Server database.

The IDs in the table look like this:

99
100
101
1200
1201...

I want to delete the later records (IDs >1200), then I want to reset the auto increment so the next autogenerated ID will be 102. So my records are sequential, Is there a way to do this in SQL Server?

答:
Several answers recommend using a statement something like this:

```<code>DBCC CHECKIDENT (mytable, RESEED, 0)
</code>```

But the OP said "deleted some records", which may not be all of them, so a value of 0 is not always the right one. Another answer suggested automatically finding the maximum current value and reseeding to that one, but that runs into trouble if there are no records in the table, and thus max() will return NULL. A comment suggested using simply

```<code>DBCC CHECKIDENT (mytable)
</code>```

to reset the value, but another comment correctly stated that this only increases the value to the maximum already in the table; this will not reduce the value if it is already higher than the maximum in the table, which is what the OP wanted to do.

A better solution combines these ideas. The first CHECKIDENT resets the value to 0, and the second resets it to the highest value currently in the table, in case there are records in the table:

```<code>DBCC CHECKIDENT (mytable, RESEED, 0)
DBCC CHECKIDENT (mytable)
</code>```

As multiple comments have indicated, make sure there are no foreign keys in other tables pointing to the deleted records. Otherwise those foreign keys will point at records you create after reseeding the table, which is almost certainly not what you had in mind.

Body:
Several answers recommend using a statement something like this:

DBCC CHECKIDENT (mytable, RESEED, 0)

But the OP said "deleted some records", which may not be all of them, so a value of 0 is not always the right one. Another answer suggested automatically finding the maximum current value and reseeding to that one, but that runs into trouble if there are no records in the table, and thus max() will return NULL. A comment suggested using simply

DBCC CHECKIDENT (mytable)

to reset the value, but another comment correctly stated that this only increases the value to the maximum already in the table; this will not reduce the value if it is already higher than the maximum in the table, which is what the OP wanted to do.

A better solution combines these ideas. The first CHECKIDENT resets the value to 0, and the second resets it to the highest value currently in the table, in case there are records in the table:

DBCC CHECKIDENT (mytable, RESEED, 0)
DBCC CHECKIDENT (mytable)

As multiple comments have indicated, make sure there are no foreign keys in other tables pointing to the deleted records. Otherwise those foreign keys will point at records you create after reseeding the table, which is almost certainly not what you had in mind.


问:
Confused by example code to check endianness
Hi I'm confused by the example code given here to check if a machine is little or big endian:

Little Endian or Big Endian?

```<code>int isLittleEndian( void )
{
    unsigned int temp = 0x12345678;
    char * tempAddress = &temp;
    if( *tempAddress == 0x12 )
    {
        return 0; // Indicating False
    } else {
        return 1; // Indicating True
    }
}
</code>```

Versus this description of little and big endianness given here:

http://support.microsoft.com/kb/102025

The second link says on an LE machine 0x1234 is stored in memory as 0x34 0x12, however the isLittleEndian() function in the first link is returning true if the first byte is 0x12. Isn't that a contradiction of the 2nd link? If not then what is it I've misunderstood?

答: No, the function returns false if the first byte is 0x12. Which is as it should be, and jives with the description of endianness.

Body:
Hi I'm confused by the example code given here to check if a machine is little or big endian:

Little Endian or Big Endian?

int isLittleEndian( void )
{
    unsigned int temp = 0x12345678;
    char * tempAddress = &temp;
    if( *tempAddress == 0x12 )
    {
        return 0; // Indicating False
    } else {
        return 1; // Indicating True
    }
}

Versus this description of little and big endianness given here:

http://support.microsoft.com/kb/102025

The second link says on an LE machine 0x1234 is stored in memory as 0x34 0x12, however the isLittleEndian() function in the first link is returning true if the first byte is 0x12. Isn't that a contradiction of the 2nd link? If not then what is it I've misunderstood?


问:
How do I call a function in Swift?
I'm unsure why my label will not change to the question string.

```<code>func GenerateQuestion(){
    let FirstNo = Int(arc4random_uniform(10))+1 // first number in sum
    let SecondNo = Int(arc4random_uniform(10))+1 // second number in sum
    let SymbolNo = Int(arc4random_uniform(4))+1 // number which decides the operator in sum
    var OperatorSymbol = ""
    var Question = "" // the question
    var Answer = Int() // holds answer of the sum
    var ButtonNo = Int(arc4random_uniform(4))+1 // number which chooses button to hold correct answer

    switch SymbolNo{
    case 1 : OperatorSymbol = "+";
    Question = "\(FirstNo) + \(SecondNo) = ?";
    self.Lbl.text = Question
    case 2 : OperatorSymbol = "-";
        Question = "\(FirstNo) - \(SecondNo) = ?";
        self.Lbl.text = Question
    case 3 : OperatorSymbol = "/";
        Question = "\(FirstNo) / \(SecondNo) = ?";
        self.Lbl.text = Question
    case 4 : OperatorSymbol = "x";
        Question = "\(FirstNo) x \(SecondNo) = ?;";
        self.Lbl.text = Question
    default : Question = ""
    }
</code>```

I haven't called func generateQuestion as I don't know how to. What should I do?

答:
To call an instance of a function you type the function name followed by a pair of parentheses with or without an argument.

```<code>generateQuestion()
</code>```

If you want something to be executed as soon as the app loads up you should type it into the viewDidLoad function.

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    generateQuestion()
}
</code>```

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html

This is a good resource, as mentioned above.

Again, as mentioned above it is better to use lowerCamelCase for functions and variables and reserve UpperCamelCase for classes and structures. More can be found on that in the Swift guide.

Good luck!

Title: How do I call a function in Swift?

Body:
I'm unsure why my label will not change to the question string.

func GenerateQuestion(){
    let FirstNo = Int(arc4random_uniform(10))+1 // first number in sum
    let SecondNo = Int(arc4random_uniform(10))+1 // second number in sum
    let SymbolNo = Int(arc4random_uniform(4))+1 // number which decides the operator in sum
    var OperatorSymbol = ""
    var Question = "" // the question
    var Answer = Int() // holds answer of the sum
    var ButtonNo = Int(arc4random_uniform(4))+1 // number which chooses button to hold correct answer

    switch SymbolNo{
    case 1 : OperatorSymbol = "+";
    Question = "\(FirstNo) + \(SecondNo) = ?";
    self.Lbl.text = Question
    case 2 : OperatorSymbol = "-";
        Question = "\(FirstNo) - \(SecondNo) = ?";
        self.Lbl.text = Question
    case 3 : OperatorSymbol = "/";
        Question = "\(FirstNo) / \(SecondNo) = ?";
        self.Lbl.text = Question
    case 4 : OperatorSymbol = "x";
        Question = "\(FirstNo) x \(SecondNo) = ?;";
        self.Lbl.text = Question
    default : Question = ""
    }

I haven't called func generateQuestion as I don't know how to. What should I do?

Body:
To call an instance of a function you type the function name followed by a pair of parentheses with or without an argument.

generateQuestion()

If you want something to be executed as soon as the app loads up you should type it into the viewDidLoad function.

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    generateQuestion()
}

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html

This is a good resource, as mentioned above.

Again, as mentioned above it is better to use lowerCamelCase for functions and variables and reserve UpperCamelCase for classes and structures. More can be found on that in the Swift guide.

Good luck!


问:
Script not showing properly inside a div tabbertab
I have added an Instagram Widget inside a div tabbertab. The widget is not shown properly, it is like cutted in the middle. If I put the widget code outside the div tab it works fine, but I need it inside.

Here is a link to my page code:
http://thebestwineriesoftheworld.com/chateausmithhautlafitte/chateausmithhautlafitte.htm

Please let me know what can I do. You can see the widget inside the "Social Networks" title of the tab.

答:
I don't know how you included this widget, but if you can, you should increase the height of the ifream to sth like height: 435px; !

If you don't have access to ifream tag, you can do it with js simply :)


问:
Chart.js - Styling Legend
I'm making a chart with chart.js and I'm trying to figure out how I can change the label/legend styling.
I want to remove the rectangle part and instead use a circle. I've read that you can make your custom legend (using legendCallback), but for the life of me I cannot figure out how to do it. This is how my chart looks now - image.

This is my HTML:

```<code><div class="container">
<canvas id="myChart"></canvas>
</div>
</code>```

And this is my JS:

```<code>var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: 'Link One',
            data: [1, 2, 3, 2, 1, 1.5, 1],
            backgroundColor: [
                '#D3E4F3'
            ],
            borderColor: [
                '#D3E4F3',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        legend: {
            display: true,
          position: 'bottom',
            labels: {
                fontColor: '#333',
            }
        }
}
});
</code>```

I'm new to JS in general, so please be as specific as possible with your answers. Thank you so much!

答:
No need to use legendCallback function. You can set  usePointStyle = true to turn that rectangle into a circle.

Chart.defaults.global.legend.labels.usePointStyle = true;

var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: 'Link One',
            data: [1, 2, 3, 2, 1, 1.5, 1],
            backgroundColor: [
                '#D3E4F3'
            ],
            borderColor: [
                '#D3E4F3',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        legend: {
            display: true,
            position: 'bottom',
            labels: {
                fontColor: '#333'
            }
        }
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<div class="container">
  <canvas id="myChart"></canvas>
</div></code>```

Title: Chart.js - Styling Legend

Body:
I'm making a chart with chart.js and I'm trying to figure out how I can change the label/legend styling.
I want to remove the rectangle part and instead use a circle. I've read that you can make your custom legend (using legendCallback), but for the life of me I cannot figure out how to do it. This is how my chart looks now - image.

This is my HTML:

<canvas id="myChart"></canvas>

And this is my JS:

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: 'Link One',
            data: [1, 2, 3, 2, 1, 1.5, 1],
            backgroundColor: [
                '#D3E4F3'
            ],
            borderColor: [
                '#D3E4F3',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        legend: {
            display: true,
          position: 'bottom',
            labels: {
                fontColor: '#333',
            }
        }
}
});

I'm new to JS in general, so please be as specific as possible with your answers. Thank you so much!

Body:
No need to use legendCallback function. You can set  usePointStyle = true to turn that rectangle into a circle.

Chart.defaults.global.legend.labels.usePointStyle = true;

var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: 'Link One',
            data: [1, 2, 3, 2, 1, 1.5, 1],
            backgroundColor: [
                '#D3E4F3'
            ],
            borderColor: [
                '#D3E4F3',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        legend: {
            display: true,
            position: 'bottom',
            labels: {
                fontColor: '#333'
            }
        }
    }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<div class="container">
  <canvas id="myChart"></canvas>
</div>


答:
Step 1:

Change options to this:

```<code>options: {
    legend: {
        display: false,
    }
}
</code>```

Step 2:

Append to your canvas this code (just after canvas):

```<code><div id='chartjsLegend' class='chartjsLegend'></div> //Or prepend to show the legend at top, if you append then it will show to bottom.
</code>```

Step 3:

Generate this legend instead of default with this (just after mychart):

```<code>document.getElementById('chartjsLegend').innerHTML = myChart.generateLegend();
</code>```

Step 4:

Make css so it generates as circle:

```<code>.chartjsLegend li span {
    display: inline-block;
    width: 12px;
    height: 12px;
    margin-right: 5px;
    border-radius: 25px;
}
</code>```

Step 5:

Change css with what ever you feel like should be better.

Time for some chimichangas now.

Title: Chart.js - Styling Legend

Body:
Step 1:

Change options to this:

options: {
    legend: {
        display: false,
    }
}

Step 2:

Append to your canvas this code (just after canvas):

<div id='chartjsLegend' class='chartjsLegend'></div> //Or prepend to show the legend at top, if you append then it will show to bottom.

Step 3:

Generate this legend instead of default with this (just after mychart):

document.getElementById('chartjsLegend').innerHTML = myChart.generateLegend();

Step 4:

Make css so it generates as circle:

.chartjsLegend li span {
    display: inline-block;
    width: 12px;
    height: 12px;
    margin-right: 5px;
    border-radius: 25px;
}

Step 5:

Change css with what ever you feel like should be better.

Time for some chimichangas now.


问:
Difficulty passing arguments into function?
I'd like to pass it's value as an argument into my function

```<code>function dostuff($input) {
global $input;

    if ($input == 5) {
        $output = "Success";
    } else {
        $output = "Failure";
    }
echo $output;
}
</code>```

Why does running

```<code>dostuff(5);
</code>```

Not echo the output variable ("Success") like it's supposed to?

答:
You don't need to set global $input;, try this:

```<code>function dostuff($input) {
    if ($input == 5) {
        $output = "Success";
    } else {
        $output = "Failure";
    }
echo $output;
}
</code>```

With this, dostuff(5) return "Success"

Explanation:

global is to used global variable into your function (http://php.net/manual/en/language.variables.scope.php), you don't need it because you passed $input in function parameters.

Body:
I'd like to pass it's value as an argument into my function

function dostuff($input) {
global $input;

    if ($input == 5) {
        $output = "Success";
    } else {
        $output = "Failure";
    }
echo $output;
}

Why does running

dostuff(5);

Not echo the output variable ("Success") like it's supposed to?

Body:
You don't need to set global $input;, try this:

function dostuff($input) {
    if ($input == 5) {
        $output = "Success";
    } else {
        $output = "Failure";
    }
echo $output;
}

With this, dostuff(5) return "Success"

Explanation:

global is to used global variable into your function (http://php.net/manual/en/language.variables.scope.php), you don't need it because you passed $input in function parameters.


问:
Including ~/opt/lib libraries in a Passenger Rails App
I'm having trouble getting a rails app on Dreamhost's Passenger to see compiled libraries in my ~/opt/lib directory.  I have to put them here because I don't have root access.

I can boot up my app in ./script/console and it sees them libraries just fine because I updated my .bash_profile's LD_LIBRARY_PATH environment variable to include ~/opt/lib.

I've tried putting ENV['LD_LIBRARY_PATH'] = '~/opt/lib' in my environment.rb file but it doesn't seem too help.  I get the following error from Passenger when I navigate to my site:
libodbcinst.so.1: cannot open shared object file: No such file or directory - /home/username/opt/lib/odbc.so

Anyone have experience with this?

Thanks

答:
The environment.rb way sounds like the way to go, though you might want to append to LD_LIBRARY_PATH instead.  Also I'd make sure to use the full path to that directory just in case.

Alternatively you might be able to use .htaccess directives, similar to what is described @ http://wiki.rubyonrails.org/rails/pages/HowToUseOracleWithFastCGI

OwnerDisplayName: Kevin Colyar

OwnerDisplayName: revolutiontrigger


问:
Obtain frequency spectrum for four basic signals using simulink blocks
I tried using the 'Spectrum Analyzer' and those signal blocks (sine, pulse generator, triangle generator and sawtooth generator) separately of course, but the spectrum block needs a discrete signal or a non-infinite signal, and there's only a discrete sine block, is there a way to generate the others?</p>

答:
Most input blocks, including those you list, have a Sample Time parameter.  Make it a number greater than 0 to specify a discrete sample time.  For instance 0.001 would give you a milli-second sample rate.

For the few blocks that don't have this, simply use a Zero-Order Hold on the output of the block, and specify a sample time for the ZOH block.


问:
Second array is just random
I need to write a program that produces a single random permutation of the numbers 1 - 10. If possible, no methods or extra include libraries. Simple as can be. Here is what I have so far.</p>

```<code>import java.util.Scanner;
public class SwitchingNum {
public static void main(String[] args) {
    int num = 10;
    Scanner in = new Scanner(System.in);
    int[] tempArray = new int[10];
    int currentSize = tempArray.length;
    System.out.print("First Array: ");
    for(int i = 0; i < num; i++){
        tempArray[i] = i + 1;
        System.out.print(tempArray[i] + " ");
    }
    int[] permArray = new int[tempArray.length];
    System.out.println();
    System.out.print("Second Array: ");
    for (int i = 0; i < permArray.length; i ++){
        permArray[i] = tempArray[(int) (Math.random() * currentSize -1)];
        for (int j = i; j < currentSize -1; j++){
            tempArray[i] = tempArray[i+1];
        }
        currentSize--;
        System.out.print(permArray[i] + " ");
    }
}
}
</code>```

答:
An easy way to shuffle an array is the Fisher–Yates shuffle. Just copy the original array into your permArray and then do:

```<code>Random rand = new Random();
for(int i = 0;  i < permArray.length - 1; i++) {
    int swapPosition = rand.nextInt(permArray.length - i) + i;
    int tmp = permArray[i];
    permArray[i] = permArray[swapPosition]
    permArray[swapPosition] = tmp;
}
</code>```

Don't forget to import java.util.Random. For more info, you can take a look at this question.

Title: Second array is just random

Body:
I need to write a program that produces a single random permutation of the numbers 1 - 10. If possible, no methods or extra include libraries. Simple as can be. Here is what I have so far.

import java.util.Scanner;
public class SwitchingNum {
public static void main(String[] args) {
    int num = 10;
    Scanner in = new Scanner(System.in);
    int[] tempArray = new int[10];
    int currentSize = tempArray.length;
    System.out.print("First Array: ");
    for(int i = 0; i < num; i++){
        tempArray[i] = i + 1;
        System.out.print(tempArray[i] + " ");
    }
    int[] permArray = new int[tempArray.length];
    System.out.println();
    System.out.print("Second Array: ");
    for (int i = 0; i < permArray.length; i ++){
        permArray[i] = tempArray[(int) (Math.random() * currentSize -1)];
        for (int j = i; j < currentSize -1; j++){
            tempArray[i] = tempArray[i+1];
        }
        currentSize--;
        System.out.print(permArray[i] + " ");
    }
}
}

Body:
An easy way to shuffle an array is the Fisher–Yates shuffle. Just copy the original array into your permArray and then do:

Random rand = new Random();
for(int i = 0;  i < permArray.length - 1; i++) {
    int swapPosition = rand.nextInt(permArray.length - i) + i;
    int tmp = permArray[i];
    permArray[i] = permArray[swapPosition]
    permArray[swapPosition] = tmp;
}

Don't forget to import java.util.Random. For more info, you can take a look at this question.


问:
Make component a property so that I can access its methods
Currently creating a TypeScript/React app and I've run into an issue. What I want to do is store a component as a property in a another component, so that I can access it's methods and properties directly (because I need to get to it's children's methods). Basically what I want to do is something like this:

```<code>class FooContainer extends React.component<FooContainerProps,FooContainerState> {
    bar: Bar;

    constructor(props: FooContainerProps) {
        super(props);
        this.bar = new Barcontainer({bar_prop1: asdf, ...});
    }
    aThing() {
        this.bar.doSomething();
    }

    render() {
        return <Foo bar={this.bar} />;
    }
}

class Foo extends React.component<FooProps,undefined> {
    render() {
        return ( ... {this.props.bar} ...);
    }
}

class BarContainer extends React.component<BarContainerProps,BarcontainerState>{
    doSomething() {
    }
    render() {
        return <div>...</div>;
}
</code>```

I also need bar to update whenever I set the state of foo, since bar's props rely on foo's state. Any ideas?

Edit: Thank you very much for the help. Using what was given, I found a way to make it so that the Component won't have any object properties and so it now looks like this:

```<code>class FooContainer extends React.component<FooContainerProps,FooContainerState> {
    bar: Bar;

    registerBar(bar: Bar) {
        this.bar = Bar;
    }

    aThing() {
        this.bar.doSomething();
    }

    render() {
        return <Foo
            registerBar={this.registerBar.bind(this)}
            bar={this.bar} />;
    }
}

class Foo extends React.component<FooProps,undefined> {
    render() {
        return (
            ...
            <Bar ref={(el) => {this.props.registerBar(el)}} />
            ...
        );
    }
}

class BarContainer extends React.component<BarContainerProps,BarcontainerState>{
    doSomething() {
    }

    render() {
        return <div>...</div>;
}
</code>```

Again, thanks for the help!

答:
This is the "react way":

```<code>class Foo extends React.Component<{}, {}> {
    private bar: Bar;

    render() {
        return <div><Bar ref={ el => this.bar = el } /></div>
    }
}

class Bar extends React.Component<{}, {}> {
    render() {
        ...
    }
}
</code>```

More on refs in: Refs and the DOM

Body:
Currently creating a TypeScript/React app and I've run into an issue. What I want to do is store a component as a property in a another component, so that I can access it's methods and properties directly (because I need to get to it's children's methods). Basically what I want to do is something like this:

class FooContainer extends React.component<FooContainerProps,FooContainerState> {
    bar: Bar;

    constructor(props: FooContainerProps) {
        super(props);
        this.bar = new Barcontainer({bar_prop1: asdf, ...});
    }
    aThing() {
        this.bar.doSomething();
    }

    render() {
        return <Foo bar={this.bar} />;
    }
}

class Foo extends React.component<FooProps,undefined> {
    render() {
        return ( ... {this.props.bar} ...);
    }
}

class BarContainer extends React.component<BarContainerProps,BarcontainerState>{
    doSomething() {
    }
    render() {
        return
...
;
}

I also need bar to update whenever I set the state of foo, since bar's props rely on foo's state. Any ideas?

Edit: Thank you very much for the help. Using what was given, I found a way to make it so that the Component won't have any object properties and so it now looks like this:

class FooContainer extends React.component<FooContainerProps,FooContainerState> {
    bar: Bar;

    registerBar(bar: Bar) {
        this.bar = Bar;
    }

    aThing() {
        this.bar.doSomething();
    }

    render() {
        return <Foo
            registerBar={this.registerBar.bind(this)}
            bar={this.bar} />;
    }
}

class Foo extends React.component<FooProps,undefined> {
    render() {
        return (
            ...
            <Bar ref={(el) => {this.props.registerBar(el)}} />
            ...
        );
    }
}

class BarContainer extends React.component<BarContainerProps,BarcontainerState>{
    doSomething() {
    }

    render() {
        return
...
;
}

Again, thanks for the help!

Body:
This is the "react way":

class Foo extends React.Component<{}, {}> {
    private bar: Bar;

    render() {
        return <div><Bar ref={ el => this.bar = el } /></div>
    }
}

class Bar extends React.Component<{}, {}> {
    render() {
        ...
    }
}

More on refs in: Refs and the DOM


问:
JavaScript will not run from Chrome extension context menu
Disclaimer: I am new to JavaScript and I have never developed a Chrome extension before.

I am trying to develop a Chrome extension that runs some JavaScript when the user selects some text on a page, right-clicks, then clicks a context menu button. I have determined (based on running it from the Chrome console) that the JavaScript I've written runs as expected. Now all is left is to make an extension.

I can get the extension to load, and I can get it to appear on the page and to appear to run. However, it doesn't seem to do anything, and the console doesn't return any output. (I read that I can't run inline JavaScript with event pages, hence using addListener.) Have I set up the context menu incorrectly? Is there an error (or several) in my script?

manifest.json

```<code>{
  "name": "My Extension",
  "description": "sample",
  "version": "0.0.1",
  "permissions": ["contextMenus"],
  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "manifest_version": 2
}
</code>```

background.js

```<code>chrome.runtime.onInstalled.addListener(function() {
  var context = "selection";
  var title = "My Extension";
  var id = chrome.contextMenus.create({"title": title, "contexts":[context],
                                         "id": "context" + context});
});

chrome.contextMenus.onClicked.addListener(getSHA);

// Get file path of file to be staged
// Get SHA
function getSHA(){
    stagedFile = window.getSelection().toString()
    console.log(stagedFile)
    baseURL = window.location.href.slice(0, -6);
    prNumber = baseURL.slice(-4);
    xhr = new XMLHttpRequest();
    xhr.open("GET", "https://api.github.com/repos/kubernetes/kubernetes.github.io/pulls/"+prNumber, false);
    xhr.send();
    json_data = JSON.parse(xhr.responseText);
    shaValue = (json_data.head.sha)
    console.log("SHA: "+shaValue)
    getNetlify;
};

// Get Netlify URL
function getNetlify(){
    xhr2 = new XMLHttpRequest();
    xhr2.open("GET", "https://api.github.com/repos/kubernetes/kubernetes.github.io/commits/"+shaValue+"/status", false);
    xhr2.send();
    json_data2 = JSON.parse(xhr2.responseText, function(key, value) { if (key == "target_url" && value.includes("netlify")) { netlifyURL = value; }});
    openStaging
};

// Stage file
function openStaging(){
    window.open(netlifyURL+"/"+stagedFile)
};
</code>```

答:
You need to add a "content script" to your manifest.json. That is the kind of code that gets injected into the page to run. The background script didn't have access to the page at all. So, check out the documentation on content scripts. https://developer.chrome.com/extensions/content_scripts

You need to add the following piece to your code to your manifest.json:

```<code>"content_scripts": [
  {
    "matches": ["http://www.google.com/*"],
    "css": ["mystyles.css"],
    "js": ["myscript.js"]
  }
]
</code>```

With this code, any time the user goes to a site that "matches" the url I provided, then the extension will inject into that page mystyles.css and myscript.js. So... your pattern would be something like http*://*/* . That will inject the script onto any page that the user will go to.

Next, to accomplish what you are trying to accomplish, you don't need a background script. So you can remove that from your manifest.json.

So your manifest.json would look like this:

```<code>{
  "name": "My Extension",
  "description": "sample",
  "version": "0.0.1",
  "permissions": ["contextMenus"],
  "content_scripts": [
    {
      "matches": ["http://www.google.com/*"],
      "css": ["mystyles.css"],
      "js": ["myscript.js"]
    }
  ],
  "manifest_version": 2
}
</code>```

Then put your code into the myscript.js file (or whatever you want to call yours), and you should see this start to run on the page.

Body:
Disclaimer: I am new to JavaScript and I have never developed a Chrome extension before.

I am trying to develop a Chrome extension that runs some JavaScript when the user selects some text on a page, right-clicks, then clicks a context menu button. I have determined (based on running it from the Chrome console) that the JavaScript I've written runs as expected. Now all is left is to make an extension.

I can get the extension to load, and I can get it to appear on the page and to appear to run. However, it doesn't seem to do anything, and the console doesn't return any output. (I read that I can't run inline JavaScript with event pages, hence using addListener.) Have I set up the context menu incorrectly? Is there an error (or several) in my script?

manifest.json

{
  "name": "My Extension",
  "description": "sample",
  "version": "0.0.1",
  "permissions": ["contextMenus"],
  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "manifest_version": 2
}

background.js

chrome.runtime.onInstalled.addListener(function() {
  var context = "selection";
  var title = "My Extension";
  var id = chrome.contextMenus.create({"title": title, "contexts":[context],
                                         "id": "context" + context});
});

chrome.contextMenus.onClicked.addListener(getSHA);

// Get file path of file to be staged
// Get SHA
function getSHA(){
    stagedFile = window.getSelection().toString()
    console.log(stagedFile)
    baseURL = window.location.href.slice(0, -6);
    prNumber = baseURL.slice(-4);
    xhr = new XMLHttpRequest();
    xhr.open("GET", "https://api.github.com/repos/kubernetes/kubernetes.github.io/pulls/"+prNumber, false);
    xhr.send();
    json_data = JSON.parse(xhr.responseText);
    shaValue = (json_data.head.sha)
    console.log("SHA: "+shaValue)
    getNetlify;
};

// Get Netlify URL
function getNetlify(){
    xhr2 = new XMLHttpRequest();
    xhr2.open("GET", "https://api.github.com/repos/kubernetes/kubernetes.github.io/commits/"+shaValue+"/status", false);
    xhr2.send();
    json_data2 = JSON.parse(xhr2.responseText, function(key, value) { if (key == "target_url" && value.includes("netlify")) { netlifyURL = value; }});
    openStaging
};

// Stage file
function openStaging(){
    window.open(netlifyURL+"/"+stagedFile)
};

Body:
You need to add a "content script" to your manifest.json. That is the kind of code that gets injected into the page to run. The background script didn't have access to the page at all. So, check out the documentation on content scripts. https://developer.chrome.com/extensions/content_scripts

You need to add the following piece to your code to your manifest.json:

"content_scripts": [
  {
    "matches": ["http://www.google.com/*"],
    "css": ["mystyles.css"],
    "js": ["myscript.js"]
  }
]

With this code, any time the user goes to a site that "matches" the url I provided, then the extension will inject into that page mystyles.css and myscript.js. So... your pattern would be something like http*://*/* . That will inject the script onto any page that the user will go to.

Next, to accomplish what you are trying to accomplish, you don't need a background script. So you can remove that from your manifest.json.

So your manifest.json would look like this:

{
  "name": "My Extension",
  "description": "sample",
  "version": "0.0.1",
  "permissions": ["contextMenus"],
  "content_scripts": [
    {
      "matches": ["http://www.google.com/*"],
      "css": ["mystyles.css"],
      "js": ["myscript.js"]
    }
  ],
  "manifest_version": 2
}

Then put your code into the myscript.js file (or whatever you want to call yours), and you should see this start to run on the page.


问:
$_POST is empty when using AJAX (Prototype)
I am fairly new to PHP and I am experiencing a problem that I can't find an answer to anywhere!!
It really bugs me...
I want to post data to a PHP script using AJAX. I am using the JS framework Prototype to do AJAX communication.

Here is the JS code:

```<code>new Ajax.Request("/ondemand/Radio.php", {
          method: 'POST',
          parameters: {programID: id},
          onSuccess: function(transport) {
                window.alert("Success, " + id);

          },
          onFailure: function() {
              window.alert("Communication problem");
          },
          onComplete: function() {
              window.alert("Complete");
          }
});
</code>```

All JS is in the  element...The function is called when choosing an option from a  box

PHP code:

```<code><?php
       //Selects all programs that have a podcast
       $QUERY_SELECT_ALL_PROGRAMS   = "SELECT DISTINCT d.defnr, d.name
                       FROM definition d, podcast p
                   WHERE p.program = d.defnr";
       //Select podcasts that belongs to a given program
       $QUERY_SELECT_PODCASTS_FOR_PROGRAM   = "SELECT p.title, p.refnr, p.filename
                           FROM podcast p
                       WHERE program =  ?";
       //Selects all podcasts
       $QUERY_SELECT_ALL_PODCASTS = "SELECT p.refnr, p.title, p.filename, p.filename
                            FROM podcast";

        $BROADCAST_PATH = "";

        $programID = $_POST["programID"];

/* Returns true if DB connection to server and database is OK
 * Takes mysqli as parameter
 * Connect to the database using the MySQLi API in PHP 5.x
 * This is the prefered way*/
 function DBconnection($connection) {
   $result = false;
   //Refering to $con declared eralier
   //global $connection;
   //Check DB connection
 if ($connection->connect_error) {
           die('Connect Error: '.$connection- >connect_error); }
else {
    //Refering to $DB_NAME declared earlier
    //Select DB
      global $DB_NAME;
       $DB_selected = $connection->select_db($DB_NAME);
      if (!$DB_selected) { die ('Can\'t use : ' . $connection->connect_error); }
       else { $result = true; }
  }
  return $result;
   }

   ?>

<?php
  echo "<form>";
  echo "<select>";
  //The MySQL connection object, must be created before connection
  $con = new mysqli($MYSQL_SERVER, $MYSQL_USER_NAME, $MYSQL_PASSWORD, $DB_NAME);
if (DBconnection($con)) {
    if ($stmt = $con->prepare($QUERY_SELECT_PODCASTS_FOR_PROGRAM)) {
        $stmt->bind_param("i", $program);
        //$stmt->bind_param("i", $program);
        //$program = $_POST["programs"];
        $program = $_POST["programID"];
        $stmt->execute();
        $stmt->bind_result($title, $refnr, $filepath);
    }
    if (is_null($_POST["programs"])) {
        echo "<option>Choose a program first...</option>";
        //echo "<option>".$file."</option>";
    }
    else {
        if (is_numeric($_POST["programs"])) {
            while($stmt->fetch()) {
                print_r($title);
                //$filepath holds the value of only the name of the broadcast without the entire path
                //40 is the starposition of the name
                $filename = substr($filepath, 40);
                echo "<option value=\"".$refnr."\" id=\"".$refnr."\" onclick=\"play('".$filename."')\">".utf8_encode($title).utf8_encode($filename)."</option>";
            }
        }
    }
     $con->close();
}
echo "</select>";
echo "</form>";
  ?>
</code>```

Here is my problem...The value of $_POST is allways "Array ()".
When using a regular form that posts, everything is OK, I get the value, but when using AJAX (not only Prototype), I dont.

What i want to do simply put is: Post data with AJAX -> use recieved data in sql query -> make a HTML lement based on the result from the sql wuery..

This is kind of difficult when I don't get the POST'ed variabel

I also took a lokk at what was being sent, and POSTDATA was correct.
Please, I really need someones help on this...been looking for days now for an answer..

Read this post to get a better understanding.. Same problem

答:
If you directly post data and the result is what you're expecting, then it's the generated HTML that's the source of your problem. This line:

```<code> echo "<option value=\"".$refnr."\" id=\"".$refnr."\" onclick=\"play('".$filename."')\">".utf8_encode($title).utf8_encode($filename)."</option>";
</code>```

is the cause of your problem. "Array()" is kind of the "toString()" version of what PHP does when arrays are concatenated to a string. $refnr is obviously an array here and Prototype simply picks up that value.

A hint: use printf('<option value="%d">%s</option>', ...) to save your eyes the sore of the leaning slash syndrome ;-)

Body:
I am fairly new to PHP and I am experiencing a problem that I can't find an answer to anywhere!!
It really bugs me...
I want to post data to a PHP script using AJAX. I am using the JS framework Prototype to do AJAX communication.

Here is the JS code:

new Ajax.Request("/ondemand/Radio.php", {
          method: 'POST',
          parameters: {programID: id},
          onSuccess: function(transport) {
                window.alert("Success, " + id);

          },
          onFailure: function() {
              window.alert("Communication problem");
          },
          onComplete: function() {
              window.alert("Complete");
          }
});

All JS is in the  element...The function is called when choosing an option from a  box

PHP code:

<?php
       //Selects all programs that have a podcast
       $QUERY_SELECT_ALL_PROGRAMS   = "SELECT DISTINCT d.defnr, d.name
                       FROM definition d, podcast p
                   WHERE p.program = d.defnr";
       //Select podcasts that belongs to a given program
       $QUERY_SELECT_PODCASTS_FOR_PROGRAM   = "SELECT p.title, p.refnr, p.filename
                           FROM podcast p
                       WHERE program =  ?";
       //Selects all podcasts
       $QUERY_SELECT_ALL_PODCASTS = "SELECT p.refnr, p.title, p.filename, p.filename
                            FROM podcast";

        $BROADCAST_PATH = "";

        $programID = $_POST["programID"];

/* Returns true if DB connection to server and database is OK
 * Takes mysqli as parameter
 * Connect to the database using the MySQLi API in PHP 5.x
 * This is the prefered way*/
 function DBconnection($connection) {
   $result = false;
   //Refering to $con declared eralier
   //global $connection;
   //Check DB connection
 if ($connection->connect_error) {
           die('Connect Error: '.$connection- >connect_error); }
else {
    //Refering to $DB_NAME declared earlier
    //Select DB
      global $DB_NAME;
       $DB_selected = $connection->select_db($DB_NAME);
      if (!$DB_selected) { die ('Can\'t use : ' . $connection->connect_error); }
       else { $result = true; }
  }
  return $result;
   }

   ?>

<?php
  echo "<form>";
  echo "<select>";
  //The MySQL connection object, must be created before connection
  $con = new mysqli($MYSQL_SERVER, $MYSQL_USER_NAME, $MYSQL_PASSWORD, $DB_NAME);
if (DBconnection($con)) {
    if ($stmt = $con->prepare($QUERY_SELECT_PODCASTS_FOR_PROGRAM)) {
        $stmt->bind_param("i", $program);
        //$stmt->bind_param("i", $program);
        //$program = $_POST["programs"];
        $program = $_POST["programID"];
        $stmt->execute();
        $stmt->bind_result($title, $refnr, $filepath);
    }
    if (is_null($_POST["programs"])) {
        echo "<option>Choose a program first...</option>";
        //echo "<option>".$file."</option>";
    }
    else {
        if (is_numeric($_POST["programs"])) {
            while($stmt->fetch()) {
                print_r($title);
                //$filepath holds the value of only the name of the broadcast without the entire path
                //40 is the starposition of the name
                $filename = substr($filepath, 40);
                echo "<option value=\"".$refnr."\" id=\"".$refnr."\" onclick=\"play('".$filename."')\">".utf8_encode($title).utf8_encode($filename)."</option>";
            }
        }
    }
     $con->close();
}
echo "</select>";
echo "</form>";
  ?>

Here is my problem...The value of $_POST is allways "Array ()".
When using a regular form that posts, everything is OK, I get the value, but when using AJAX (not only Prototype), I dont.

What i want to do simply put is: Post data with AJAX -> use recieved data in sql query -> make a HTML lement based on the result from the sql wuery..

This is kind of difficult when I don't get the POST'ed variabel

I also took a lokk at what was being sent, and POSTDATA was correct.
Please, I really need someones help on this...been looking for days now for an answer..

Read this post to get a better understanding.. Same problem

Body:
If you directly post data and the result is what you're expecting, then it's the generated HTML that's the source of your problem. This line:

 echo "<option value=\"".$refnr."\" id=\"".$refnr."\" onclick=\"play('".$filename."')\">".utf8_encode($title).utf8_encode($filename)."</option>";

is the cause of your problem. "Array()" is kind of the "toString()" version of what PHP does when arrays are concatenated to a string. $refnr is obviously an array here and Prototype simply picks up that value.

A hint: use printf('<option value="%d">%s</option>', ...) to save your eyes the sore of the leaning slash syndrome ;-)


问:
Design system for a given Article class with states
Having the following problem. Article goes through several stages before being published by several different Roles.

```<code>Writer -> writes
Approver -> approves
Admin -> Publishes
</code>```

Design a program that allow for maximum extensibility:
This is what I have. Can someone please let me know if this is the right approach? is there a better one?

```<code>public interface IRole
{
    IRole Write();
    IRole Approve();
    IRole Publish();
}

internal class Writer : IRole
{
    public IRole Write()
    {
        return new Approver(); // next needs approval
    }

    public IRole Approve()
    {
        return this;
    }

    public IRole Publish()
    {
        return this;
    }
}

internal class Approver : IRole
{
    public IRole Write()
    {
        return new Writer();
    }

    public IRole Approve()
    {
        // publish
        return new Admin();
    }

    public IRole Publish()
    {
        return this;
    }
}

internal class Admin : IRole
{
    public IRole Write()
    {
        return new Writer();
    }

    public IRole Approve()
    {
        return new Approver();
    }

    public IRole Publish()
    {
        return this;
    }
}

internal class Article
{
    public Article()
    {
        role = new Writer();
    }

    private IRole role { get; set; }

    public void Write()
    {
        role = role.Write();
    }

    public void Approve()
    {
        role = role.Approve();
    }

    public void Publish()
    {
        role = role.Publish();
    }
}

    private static void Main(string[] args)
    {
        var article = new Article();
        article.Approve(); // can't do - write first
        article.Write();
        article.Publish(); // can't do
        article.Approve(); // can
        article.Write(); // can go back
        article.Approve(); // can
        article.Publish();
    }
</code>```

答: What you are looking for is called "Chain of Responsibility". It is a design pattern that allows operations to be chained one after the other. Your use case will perfectly fit with this pattern. https://www.codeproject.com/Articles/594974/Chain-of-Responsibility-Pattern

Body:
Having the following problem. Article goes through several stages before being published by several different Roles.

Writer -> writes
Approver -> approves
Admin -> Publishes

Design a program that allow for maximum extensibility:
This is what I have. Can someone please let me know if this is the right approach? is there a better one?

public interface IRole
{
    IRole Write();
    IRole Approve();
    IRole Publish();
}

internal class Writer : IRole
{
    public IRole Write()
    {
        return new Approver(); // next needs approval
    }

    public IRole Approve()
    {
        return this;
    }

    public IRole Publish()
    {
        return this;
    }
}

internal class Approver : IRole
{
    public IRole Write()
    {
        return new Writer();
    }

    public IRole Approve()
    {
        // publish
        return new Admin();
    }

    public IRole Publish()
    {
        return this;
    }
}

internal class Admin : IRole
{
    public IRole Write()
    {
        return new Writer();
    }

    public IRole Approve()
    {
        return new Approver();
    }

    public IRole Publish()
    {
        return this;
    }
}

internal class Article
{
    public Article()
    {
        role = new Writer();
    }

    private IRole role { get; set; }

    public void Write()
    {
        role = role.Write();
    }

    public void Approve()
    {
        role = role.Approve();
    }

    public void Publish()
    {
        role = role.Publish();
    }
}

    private static void Main(string[] args)
    {
        var article = new Article();
        article.Approve(); // can't do - write first
        article.Write();
        article.Publish(); // can't do
        article.Approve(); // can
        article.Write(); // can go back
        article.Approve(); // can
        article.Publish();
    }


问:
How can I create a 2D array with 1 to n in one column and zeros in the other - Python
I tried creating two arrays and then adding them together

```<code>array_nmax = np.arange (100)
array_zeros = np.zeros (100, dtype = np.int)
array_final = np.append (array_nmax,np.zeros, axis = 0)
</code>```

but it says that they're not the same dimensions even though they should be both 100 by 1 arrays.

答:
Maybe something like this? </p>

```<code>a = np.zeros((100, 10), dtype=np.int)
a[:, 0] = np.arange(0, 100)
</code>```

Body:
I tried creating two arrays and then adding them together

array_nmax = np.arange (100)
array_zeros = np.zeros (100, dtype = np.int)
array_final = np.append (array_nmax,np.zeros, axis = 0)

but it says that they're not the same dimensions even though they should be both 100 by 1 arrays.

Body:
Maybe something like this?

a = np.zeros((100, 10), dtype=np.int)
a[:, 0] = np.arange(0, 100)


问:
How to stop more than one being removed from an integer?
I know the title may seem fairly confusing, was just unsure on how to ask this...
So, I'm working on a basic sample game (not going to be a complete game or anything), where you can move around and are chased by an enemy character that attacks you. The problem is that when the attack function is called, instead of only removing one heart/hitpoint, they continue to be 'spam removed'. Here's what I'm working with...

```<code>void Enemy::attackPlayer()
{
    if (distance < 50)
    {
        Player::health--;
        return;
    }
}
</code>```

Pretty simple, right? Well the problem is that I need some way of I guess 'sleeping' the single function so that instead of continuing to remove health, it stops after one, then after let's say, 3 seconds, allows another attack to occur.

答: I think you can create two global time variables that are passed to your attack function. startTime is initiated once you call your attack function (outside). endTime is initiated right after removing one health from player (inside your function). Then you simply add a if statement before the distance if statement to check the delta time between these two and if they are more than 3 seconds then do the rest to remove another health. </p>

Body:
I know the title may seem fairly confusing, was just unsure on how to ask this...
So, I'm working on a basic sample game (not going to be a complete game or anything), where you can move around and are chased by an enemy character that attacks you. The problem is that when the attack function is called, instead of only removing one heart/hitpoint, they continue to be 'spam removed'. Here's what I'm working with...

void Enemy::attackPlayer()
{
    if (distance < 50)
    {
        Player::health--;
        return;
    }
}

Pretty simple, right? Well the problem is that I need some way of I guess 'sleeping' the single function so that instead of continuing to remove health, it stops after one, then after let's say, 3 seconds, allows another attack to occur.


问:
Syntax error : end of file unexpected (expecting "fi")
I am writing a makefile in bash and I have a target in which I try to find if a file exists and even though I think the syntax is correct, i still gives me an error.

Here is the script that I am trying to run

```<code>read:
        if [ -e testFile] ; then \
        cat testFile\
        fi
</code>```

I am using tabs so that is not a problem.

The error is (when I type in: "make read")

```<code>if [ -e testFile] ; then \
        cat testFile \
        fi
/bin/sh: Syntax error: end of file unexpected (expecting "fi")
make: *** [read] Error 2
</code>```

答:
Since GNU Make 3.82, you can add .ONESHELL: to the top of the file to tell make to run all the lines within a target in a single shell.

```<code>.ONESHELL:
SHELL := /bin/bash

foobar:
    if true
    then
        echo hello there
    fi
</code>```

See the documentation.

Prepend lines with @ or add the .SILENT: option beneath .ONESHELL: to suppress echoing lines.

Body:
I am writing a makefile in bash and I have a target in which I try to find if a file exists and even though I think the syntax is correct, i still gives me an error.

Here is the script that I am trying to run

read:
        if [ -e testFile] ; then \
        cat testFile\
        fi

I am using tabs so that is not a problem.

The error is (when I type in: "make read")

if [ -e testFile] ; then \
        cat testFile \
        fi
/bin/sh: Syntax error: end of file unexpected (expecting "fi")
make: *** [read] Error 2

Body:
Since GNU Make 3.82, you can add .ONESHELL: to the top of the file to tell make to run all the lines within a target in a single shell.

.ONESHELL:
SHELL := /bin/bash

foobar:
    if true
    then
        echo hello there
    fi

See the documentation.

Prepend lines with @ or add the .SILENT: option beneath .ONESHELL: to suppress echoing lines.


问:
Can you use es6 import alias syntax for React Components?
I'm trying to do something like the following, however it returns null:

```<code>import { Button as styledButton } from 'component-library'
</code>```

then attempting to render it as:

```<code>import React, { PropTypes } from "react";
import cx from 'classNames';

import { Button as styledButton } from 'component-library';

export default class Button extends React.Component {
    constructor(props){
        super(props)
    }
    render() {
        return (
                <styledButton {...this.props}></styledButton>
        )
    }
}
</code>```

The reason is, I need to import the Button component from a library, and also export a wrapper component with the same name but maintaining the functionality from the imported component.  If I leave it at import { Button } from component library then of course, I get a multiple declaration error.

Any ideas?

答:
No idea why I am not able to alias the import;

As a work around, I ended up doing this:

```<code>import React, { PropTypes } from "react";
import * as StyledLibrary from 'component-library';

export default class Button extends React.Component {
    constructor(props){
        super(props)
    }
    render() {
        return (
            <StyledLibrary.Button {...this.props}></StyledLibrary.Button>
        )
    }
}
</code>```

Thanks all

Body:
I'm trying to do something like the following, however it returns null:

import { Button as styledButton } from 'component-library'

then attempting to render it as:

import React, { PropTypes } from "react";
import cx from 'classNames';

import { Button as styledButton } from 'component-library';

export default class Button extends React.Component {
    constructor(props){
        super(props)
    }
    render() {
        return (

        )
    }
}

The reason is, I need to import the Button component from a library, and also export a wrapper component with the same name but maintaining the functionality from the imported component.  If I leave it at import { Button } from component library then of course, I get a multiple declaration error.

Any ideas?

Body:
No idea why I am not able to alias the import;

As a work around, I ended up doing this:

import React, { PropTypes } from "react";
import * as StyledLibrary from 'component-library';

export default class Button extends React.Component {
    constructor(props){
        super(props)
    }
    render() {
        return (
            <StyledLibrary.Button {...this.props}></StyledLibrary.Button>
        )
    }
}

Thanks all


问:
Is the percentage of CPU utlized by the .NET garbage collector an indicator of anything?
As an explanation for the slowness of an application, someone reported that the garbage collector, during collection, was taking up 17% of the CPU. To me, that statistic sounded irrelevant since 17% is not too much to worry anyway. Besides, it is an arbitrary metric that tells me nothing about the constitution of the process' memory.

What would be more relevant data to me would be things like:

How many Gen 2 collections did we have?

Show me the memory dump and let me party with it and come back to you. Let me look at the heapstat (!dumpheap -stat from psscorX), syncblocks, etc.

Show me the CPU utilization during a heavy period of slowness so I know it's not an I/O bound issue that's begging the introduction of asynchrony into the desgin.

How many garbage collections did we have since we launched suspect operation and how many of them were full collections?

Show me the LOH heap fragmentation.

Show me the unmanaged heap, the free space in the process and the total space occupied by the managed heap.

Profile the code and see what's taking time. Then zero in on the operation that's taking the most amount of time.

But the CPU utilization held by a run of garbage collection? That doesn't seem like a relevant metric to me at all.

So, I ask for a confirmation.

Is that metric of CPU utilized by the GC, esp. when it is only 17%, a relevant indicator of problems in the application?

Is there an expected threshold CPU utilization that the GC should normally fit within so as to be considered a normal collection of a nice and healthy application?

We're talking about a process run on a workstation version of the CLR.

答:
After some searching, I found some information on this topic here.

It appears that checking the CPU utilization during a collection may give one some insight into whether too many or too frequent a number of collections are taking place. This could mean that objects are being allocated too quickly and/or are not being freed up, i.e. are living too long (for example too many class level objects), and therefore it is taking the garbage collector longer as there is not much to collect in every collection.

I reproduce the relevant snippet from the article:

Garbage Collection and Performance -> Issue: CPU Usage During a Garbage Collection Is Too High

CPU usage will be high during a garbage collection. If a significant
  amount of process time is spent in a garbage collection, the number of
  collections is too frequent or the collection is lasting too long. An
  increased allocation rate of objects on the managed heap causes
  garbage collection to occur more frequently. Decreasing the allocation
  rate reduces the frequency of garbage collections.

You can monitor allocation rates by using the Allocated Bytes/second
  performance counter. For more information, see Performance Counters in
  the .NET Framework.

This, however, makes no comment on whether or not the 17% CPU utilization is high, as it shouldn't. It does provide a lead with the suggestion that we look into the allocation per second performance metric and the % Time counter.


问:
OAuth authentication through Owin Facebook stopped working since yesterday
This code was working fine for a year or so, this problem is related to facebook changing their API response to JSON (instead of regular query string)

It's a MVC5 project, I updated to https://www.nuget.org/packages/Microsoft.Owin.Security.Facebook/3.1.0-rc1
as suggested here:
ASP.NET MVC5 OWIN Facebook authentication suddenly not working and also try to simplify my call as suggested here: https://github.com/aspnet/AspNetKatana/issues/38

In addition I tried adding the BackchannelHttpHandler class (but removed it as it was not working for me), Also, I deleted my facebook web app (it was API 2.4) and created a new one (2.8) that is not approved yet, but I think test app should be working regardless.

I keep getting 302 error=access_denied

This is the code I'm using:

```<code>var facebookAuthOptions = new FacebookAuthenticationOptions();
facebookAuthOptions.AppId = "xxx";
facebookAuthOptions.AppSecret = "yyy";
facebookAuthOptions.SendAppSecretProof = true;
facebookAuthOptions.CallbackPath = new PathString("/signin-facebook");

facebookAuthOptions.Scope.Add("public_profile");
facebookAuthOptions.Scope.Add("email");
facebookAuthOptions.Scope.Add("user_birthday");

// added for Microsoft.Owin.Security.Facebook/3.1.0-rc1
facebookAuthOptions.Fields.Add("email");
facebookAuthOptions.Fields.Add("birthday");
facebookAuthOptions.Fields.Add("gender");
facebookAuthOptions.Fields.Add("locale");
facebookAuthOptions.Fields.Add("location");
facebookAuthOptions.Fields.Add("timezone");

facebookAuthOptions.Provider = new FacebookAuthenticationProvider()
{
    OnAuthenticated = (context) =>
    {
        context.Identity.AddClaim(new Claim("FacebookAccessToken", context.AccessToken));

        var expiryDuration = context.ExpiresIn ?? new TimeSpan();
        context.Identity.AddClaim(new Claim("urn:facebook:expires_in", DateTime.UtcNow.Add(expiryDuration).ToString(CultureInfo.InvariantCulture)));

    // Add all other available claims
    foreach (var claim in context.User)
    {
        var claimType = string.Format("urn:facebook:{0}", claim.Key);
        var claimValue = claim.Value.ToString();
        if (!context.Identity.HasClaim(claimType, claimValue))
            context.Identity.AddClaim(new Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
    }

    return Task.FromResult(0);
}
};
app.UseFacebookAuthentication(facebookAuthOptions);
</code>```

The net traffic looks like this:

https://localhost:44300/external-providers
  (302)

https://www.facebook.com/v2.8/dialog/oauth?response_type=code&client_id=1897713540512505&redirect_uri=https%3A%2F%2Flocalhost%3A44300%2Fsignin-facebook&scope=&state=OXOiCtOJPEK5WCQkEJt-mH3lxEnTCXG3YcGFtW7j_dyuPd_9LevphavHobpB6EH3Wfb8BpbhqST13SacFMB3OnddsgnslzcAX7KnMpzpnEcfFI3KErmByenV9xn1IEt7PhY4TjXi5KHFNUp1PVu_ikUBnvf0hJpY2IK0fczvQLVmGKplJV-g6qsEMYXfKHNYoqjDiu9cA-iGIPXfRxPxZg
  (302)

https://localhost:44300/signin-facebook?code=AQDrGJ9sqk0ENVw_7RW3zmauzV1Gf6rWXBotgAKf6uBbdryamL5RMHiOgIrBiPYdy8CA9HC9hq2sahu2bt-VwznOJ8PNFTxRmLCe0PRrwxSsffscHSdNzjz16jjavuupse087mB_2KhZeKKWeS2Rlwabcfa-n4FGIcyDizpOKTWJl_J6PFAjWv3XfPy1zkbLz0cAsTdQ8t8pOARPhP5nKwUIGN5GuS4fzuGhgPCerlPyHknK0BWcFrRC0fa_n3X2d0-zANu6nzhRspssDTWmIAr9PZCLOlpSMlJeb1NrebECNbw4YqGzScCWxBRVL8YAfQ4&state=OXOiCtOJPEK5WCQkEJt-mH3lxEnTCXG3YcGFtW7j_dyuPd_9LevphavHobpB6EH3Wfb8BpbhqST13SacFMB3OnddsgnslzcAX7KnMpzpnEcfFI3KErmByenV9xn1IEt7PhY4TjXi5KHFNUp1PVu_ikUBnvf0hJpY2IK0fczvQLVmGKplJV-g6qsEMYXfKHNYoqjDiu9cA-iGIPXfRxPxZg
  (302)

https://localhost:44300/signup-connect?error=access_denied
  (302)

https://localhost:44300/signout
  (200)

答:
Ok, I finally found the problem, this cost me 3 days, definitely the most annoying bug of 2017.

So, the new Owin RC1 update is working. also, in my case, no need to specify anything in facebookAuthOptions.Fields nor changing anything else with the provider etc. (see https://github.com/aspnet/AspNetKatana/issues/38)

The problem I had (and still do) is that the facebook page SETTING : Advanced : Require App Secret - was always set to YES, now, as part of the mass confusion after Facebook changed their APIs, I also deleted my facebook app and created a new one using the latest 2.8 APIs.

I also have this in my code: facebookAuthOptions.SendAppSecretProof = true;
So that should have been working, but for now I set Require App Secret to NO.

I'm thinking facebook did something on their end to the Require App Secret option and broke it, OR maybe the new Owin RC1 update does not pass SendAppSecretProof = true in the FacebookAuthenticationOptions

Anyway, that was a tough one, hope someone finds this before spending whole 3-4 days on it.

This is the current facebook settings that works:

PRODUCTS: Facebook Login:

Client OAuth Login: NO

Web OAuth Login: YES

Embedded Browser OAuth Login: NO

Force Web OAuth Reauthentication: NO

Login from Devices: NO

Valid OAuth redirect URIs: https://localhost:44300/signin-facebook

Deauthorize Callback URL: https://localhost:44300/signout

SETTINGS: Advanced:

Require App Secret: NO

Allow API Access to App Settings: YES

Require 2-Factor Reauthorization: NO

UPDATE: the appsecret_proof was not passed correctly to the query string, this will be fixed in the new Owin version very soon, the Require App Secret can be set back to YES.

Body:
This code was working fine for a year or so, this problem is related to facebook changing their API response to JSON (instead of regular query string)

It's a MVC5 project, I updated to https://www.nuget.org/packages/Microsoft.Owin.Security.Facebook/3.1.0-rc1
as suggested here:
ASP.NET MVC5 OWIN Facebook authentication suddenly not working and also try to simplify my call as suggested here: https://github.com/aspnet/AspNetKatana/issues/38

In addition I tried adding the BackchannelHttpHandler class (but removed it as it was not working for me), Also, I deleted my facebook web app (it was API 2.4) and created a new one (2.8) that is not approved yet, but I think test app should be working regardless.

I keep getting 302 error=access_denied

This is the code I'm using:

var facebookAuthOptions = new FacebookAuthenticationOptions();
facebookAuthOptions.AppId = "xxx";
facebookAuthOptions.AppSecret = "yyy";
facebookAuthOptions.SendAppSecretProof = true;
facebookAuthOptions.CallbackPath = new PathString("/signin-facebook");

facebookAuthOptions.Scope.Add("public_profile");
facebookAuthOptions.Scope.Add("email");
facebookAuthOptions.Scope.Add("user_birthday");

// added for Microsoft.Owin.Security.Facebook/3.1.0-rc1
facebookAuthOptions.Fields.Add("email");
facebookAuthOptions.Fields.Add("birthday");
facebookAuthOptions.Fields.Add("gender");
facebookAuthOptions.Fields.Add("locale");
facebookAuthOptions.Fields.Add("location");
facebookAuthOptions.Fields.Add("timezone");

facebookAuthOptions.Provider = new FacebookAuthenticationProvider()
{
    OnAuthenticated = (context) =>
    {
        context.Identity.AddClaim(new Claim("FacebookAccessToken", context.AccessToken));

        var expiryDuration = context.ExpiresIn ?? new TimeSpan();
        context.Identity.AddClaim(new Claim("urn:facebook:expires_in", DateTime.UtcNow.Add(expiryDuration).ToString(CultureInfo.InvariantCulture)));

    // Add all other available claims
    foreach (var claim in context.User)
    {
        var claimType = string.Format("urn:facebook:{0}", claim.Key);
        var claimValue = claim.Value.ToString();
        if (!context.Identity.HasClaim(claimType, claimValue))
            context.Identity.AddClaim(new Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
    }

    return Task.FromResult(0);
}
};
app.UseFacebookAuthentication(facebookAuthOptions);

The net traffic looks like this:

https://localhost:44300/external-providers
  (302)

https://www.facebook.com/v2.8/dialog/oauth?response_type=code&client_id=1897713540512505&redirect_uri=https%3A%2F%2Flocalhost%3A44300%2Fsignin-facebook&scope=&state=OXOiCtOJPEK5WCQkEJt-mH3lxEnTCXG3YcGFtW7j_dyuPd_9LevphavHobpB6EH3Wfb8BpbhqST13SacFMB3OnddsgnslzcAX7KnMpzpnEcfFI3KErmByenV9xn1IEt7PhY4TjXi5KHFNUp1PVu_ikUBnvf0hJpY2IK0fczvQLVmGKplJV-g6qsEMYXfKHNYoqjDiu9cA-iGIPXfRxPxZg
  (302)

<a href="https://localhost:44300/signin-facebook?code=AQDrGJ9sqk0ENVw_7RW3zmauzV1Gf6rWXBotgAKf6uBbdryamL5RMHiOgIrBiPYdy8CA9HC9hq2sahu2bt-VwznOJ8PNFTxRmLCe0PRrwxSsffscHSdNzjz16jjavuupse087mB_2KhZeKKWeS2Rlwabcfa-n4FGIcyDizpOKTWJl_J6PFAjWv3XfPy1zkbLz0cAsTdQ8t8pOARPhP5nKwUIGN5GuS4fzuGhgPCerlPyHknK0BWcFrRC0fa_n3X2d0-zANu6nzhRspssDTWmIAr9PZCLOlpSMlJeb1NrebECNbw4YqGzScCWxBRVL8YAfQ4&state=OXOiCtOJPEK5WCQkEJt-mH3lxEnTCXG3YcGFtW7j_dyuPd_9LevphavHobpB6EH3Wfb8BpbhqST13SacFMB3OnddsgnslzcAX7KnMpzpnEcfFI3KErmByenV9xn1IEt7PhY4TjXi5KHFNUp1PVu_ikUBnvf0hJpY2IK0fczvQLVmGKplJV-g6qsEMYXfKHNYoqjDiu9cA-iGIPXfRxPxZg" rel="nofollow noreferrer">https://localhost:44300/signin-facebook?code=AQDrGJ9sqk0ENVw_7RW3zmauzV1Gf6rWXBotgAKf6uBbdryamL5RMHiOgIrBiPYdy8CA9HC9hq2sahu2bt-VwznOJ8PNFTxRmLCe0PRrwxSsffscHSdNzjz16jjavuupse087mB_2KhZeKKWeS2Rlwabcfa-n4FGIcyDizpOKTWJl_J6PFAjWv3XfPy1zkbLz0cAsTdQ8t8pOARPhP5nKwUIGN5GuS4fzuGhgPCerlPyHknK0BWcFrRC0fa_n3X2d0-zANu6nzhRspssDTWmIAr9PZCLOlpSMlJeb1NrebECNbw4YqGzScCWxBRVL8YAfQ4&state=OXOiCtOJPEK5WCQkEJt-mH3lxEnTCXG3YcGFtW7j_dyuPd_9LevphavHobpB6EH3Wfb8BpbhqST13SacFMB3OnddsgnslzcAX7KnMpzpnEcfFI3KErmByenV9xn1IEt7PhY4TjXi5KHFNUp1PVu_ikUBnvf0hJpY2IK0fczvQLVmGKplJV-g6qsEMYXfKHNYoqjDiu9cA-iGIPXfRxPxZg
  (302)

https://localhost:44300/signup-connect?error=access_denied
  (302)

https://localhost:44300/signout
  (200)


问:
Changing reference types(strings) inside methods
I am passing a string variable to a method. I know strings are reference types but the value that I assign inside the method is lost. </p>

```<code>public static void TestMethod(string myString)
{
    myString = "world";
}

static void Main(string[] args)
{
    string s = "hello";
    Console.WriteLine(s); // output is "hello"
    TestMethod(s);
    Console.WriteLine(s); // output is also "hello" not "world" !?
}
</code>```

<p>Anyway this does not happen with an array for example. Can someone explain why might be the cause? </p>

答:
Yes, because without a ref (or out) you can't assign a new object to a parameter. Since you didn't pass it in through a ref, the variable outside the method still references the original string which didn't change.  Consequently, strings are immutable, so you can't do anything to it without create a new string once it is instantiated.

The array can be altered (or the contents of the array can be altered), because the references inside the array are not immutable (you can say reassign my_object1 to equal "BLAH").  You can replace a value in the array and have it accessible outside of the array, because the reference to the array outside of the method hasn't changed.

Link to String in MSDN (talks about immutability)

Body:
I am passing a string variable to a method. I know strings are reference types but the value that I assign inside the method is lost.

public static void TestMethod(string myString)
{
    myString = "world";
}

static void Main(string[] args)
{
    string s = "hello";
    Console.WriteLine(s); // output is "hello"
    TestMethod(s);
    Console.WriteLine(s); // output is also "hello" not "world" !?
}

Anyway this does not happen with an array for example. Can someone explain why might be the cause?


问:
R how to get the third and last row for each user
I have a table that has information about certain users. What I'm trying to do is extract the third and last row of each user...How would I do that? So for example:

```<code>User | num |

use1 | 3 |

use1 | 2 |

use1 | 5 |

use1 | 8 |

use1 | 6 |

use2 | 1 |

..
</code>```

So in this example, I'd want the row with num = 5 and num = 6 and this would continue for each different user in the table.

答:
How about this?</p>

```<code>library(dplyr)

# Assuming df is your sample data
df %>% group_by(User) %>% filter(row_number() %in% c(3, n()))
</code>```

Body:
I have a table that has information about certain users. What I'm trying to do is extract the third and last row of each user...How would I do that? So for example:

User | num |

use1 | 3 |

use1 | 2 |

use1 | 5 |

use1 | 8 |

use1 | 6 |

use2 | 1 |

..

So in this example, I'd want the row with num = 5 and num = 6 and this would continue for each different user in the table.

Body:
How about this?

library(dplyr)

# Assuming df is your sample data
df %>% group_by(User) %>% filter(row_number() %in% c(3, n()))


问:
Has .txt file been closed?
I have a slight problem. I have a project that I'm working on and that requires two programs to read/write into some .txt files.

Python writes into one .txt file, C++ reads from it. C++ does what it needs to do and then writes its own information into another .txt file that Python has to read.

What I want to know is how can I check with C++ if Python has closed the .txt file before opening the same file, as Python may still be writing stuff into it and vice versa?

If you need any extra information about this conundrum, feel free to contact me.

答:
You might consider having each "writer" process write its output to a temporary file, close the file, then rename it to the filename that the "reader" process is looking for.

If the file is present, then the respective reader process knows that it can read from it.

Title: Has .txt file been closed?


问:
My decrypted password is 1 character to short
So I have this encryption / decryption code:

```<code>private string Crypt(string strData, string strPassword, bool bEncrypt)
{
    byte[] u8_Salt = new byte[] { xxx };

    PasswordDeriveBytes i_Pass = new PasswordDeriveBytes(strPassword, u8_Salt);

    Rijndael i_Alg = Rijndael.Create();
    i_Alg.Key = i_Pass.GetBytes(32);
    i_Alg.IV = i_Pass.GetBytes(16);

    ICryptoTransform i_Trans = (bEncrypt) ? i_Alg.CreateEncryptor() : i_Alg.CreateDecryptor();

    MemoryStream i_Mem = new MemoryStream();
    CryptoStream i_Crypt = new CryptoStream(i_Mem, i_Trans, CryptoStreamMode.Write);

    byte[] u8_Data;
    if (bEncrypt) u8_Data = Encoding.Unicode.GetBytes(strData);
    else u8_Data = Convert.FromBase64String(strData);

    try
    {
        i_Crypt.Write(u8_Data, 0, u8_Data.Length);
        i_Crypt.Close();
    }
    catch { return null; }

    if (bEncrypt) return Convert.ToBase64String(i_Mem.ToArray());
    else return Encoding.Unicode.GetString(i_Mem.ToArray());

}
</code>```

I tried to improve it:

```<code>private string Crypt(string strData, string strPassword, bool bEncrypt)
{
    byte[] u8Salt = new byte[] { xxx };

    PasswordDeriveBytes iPass = new PasswordDeriveBytes(strPassword, u8Salt);

    Rijndael iAlg = Rijndael.Create();
    iAlg.Key = iPass.GetBytes(32);
    iAlg.IV = iPass.GetBytes(16);

    ICryptoTransform iTrans = (bEncrypt) ? iAlg.CreateEncryptor() : iAlg.CreateDecryptor();

    MemoryStream iMem = new MemoryStream();
    using (CryptoStream iCrypt = new CryptoStream(iMem, iTrans, CryptoStreamMode.Write))
    {
        byte[] u8Data;
        try
        {
             if (bEncrypt)
                u8Data = Encoding.Unicode.GetBytes(strData);
             else
                u8Data = Convert.FromBase64String(strData);

             iCrypt.Write(u8Data, 0, u8Data.Length);
             if (bEncrypt)
                return Convert.ToBase64String(iMem.ToArray());
             else
                return Encoding.Unicode.GetString(iMem.ToArray());
        }
        catch (Exception e)
        {
            return null;
        }
    }
}
</code>```

But what I am finding is that the returned decrypted password is 1 character too short. I can't see how this new code is wrong to the former.

答:
Your using statement will make sure that the stream gets closed and therefore flushed automatically. Unfortunately you retrieve the ciphertext / plaintext from the MemoryStream before that.

Don't use PasswordDeriveBytes, especially not for more than 20 bytes, it's insecure. Rather use `Rfc2898DeriveBytes.

Body:
So I have this encryption / decryption code:

private string Crypt(string strData, string strPassword, bool bEncrypt)
{
    byte[] u8_Salt = new byte[] { xxx };

    PasswordDeriveBytes i_Pass = new PasswordDeriveBytes(strPassword, u8_Salt);

    Rijndael i_Alg = Rijndael.Create();
    i_Alg.Key = i_Pass.GetBytes(32);
    i_Alg.IV = i_Pass.GetBytes(16);

    ICryptoTransform i_Trans = (bEncrypt) ? i_Alg.CreateEncryptor() : i_Alg.CreateDecryptor();

    MemoryStream i_Mem = new MemoryStream();
    CryptoStream i_Crypt = new CryptoStream(i_Mem, i_Trans, CryptoStreamMode.Write);

    byte[] u8_Data;
    if (bEncrypt) u8_Data = Encoding.Unicode.GetBytes(strData);
    else u8_Data = Convert.FromBase64String(strData);

    try
    {
        i_Crypt.Write(u8_Data, 0, u8_Data.Length);
        i_Crypt.Close();
    }
    catch { return null; }

    if (bEncrypt) return Convert.ToBase64String(i_Mem.ToArray());
    else return Encoding.Unicode.GetString(i_Mem.ToArray());

}

I tried to improve it:

private string Crypt(string strData, string strPassword, bool bEncrypt)
{
    byte[] u8Salt = new byte[] { xxx };

    PasswordDeriveBytes iPass = new PasswordDeriveBytes(strPassword, u8Salt);

    Rijndael iAlg = Rijndael.Create();
    iAlg.Key = iPass.GetBytes(32);
    iAlg.IV = iPass.GetBytes(16);

    ICryptoTransform iTrans = (bEncrypt) ? iAlg.CreateEncryptor() : iAlg.CreateDecryptor();

    MemoryStream iMem = new MemoryStream();
    using (CryptoStream iCrypt = new CryptoStream(iMem, iTrans, CryptoStreamMode.Write))
    {
        byte[] u8Data;
        try
        {
             if (bEncrypt)
                u8Data = Encoding.Unicode.GetBytes(strData);
             else
                u8Data = Convert.FromBase64String(strData);

             iCrypt.Write(u8Data, 0, u8Data.Length);
             if (bEncrypt)
                return Convert.ToBase64String(iMem.ToArray());
             else
                return Encoding.Unicode.GetString(iMem.ToArray());
        }
        catch (Exception e)
        {
            return null;
        }
    }
}

But what I am finding is that the returned decrypted password is 1 character too short. I can't see how this new code is wrong to the former.