问:
gcc -O2 vs. without causes error
When compiling file containing open("FILENAME", O_RDONLY); without -O2 flag everything is fine. But when -O2 is turned on I get:

```<code>/usr/include/x86_64-linux-gnu/bits/fcntl2.h: In function ‘open’:
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:44:7: error: invalid use of ‘__builtin_va_arg_pack_len ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:45:26: error: call to ‘__open_too_many_args’ declared with attribute error: open can be called either with 2 or 3 arguments, not more
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:42:1: error: invalid use of ‘__builtin_va_arg_pack_len ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:60:3: error: invalid use of ‘__builtin_va_arg_pack ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h: In function ‘open64’:
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:76:7: error: invalid use of ‘__builtin_va_arg_pack_len ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:77:28: error: call to ‘__open64_too_many_args’ declared with attribute error: open64 can be called either with 2 or 3 arguments, not more
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:74:1: error: invalid use of ‘__builtin_va_arg_pack_len ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:92:3: error: invalid use of ‘__builtin_va_arg_pack ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h: In function ‘openat’:
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:120:7: error: invalid use of ‘__builtin_va_arg_pack_len ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:121:28: error: call to ‘__openat_too_many_args’ declared with attribute error: openat can be called either with 3 or 4 arguments, not more
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:118:1: error: invalid use of ‘__builtin_va_arg_pack_len ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:136:3: error: invalid use of ‘__builtin_va_arg_pack ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h: In function ‘openat64’:
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:154:7: error: invalid use of ‘__builtin_va_arg_pack_len ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:155:30: error: call to ‘__openat64_too_many_args’ declared with attribute error: openat64 can be called either with 3 or 4 arguments, not more
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:152:1: error: invalid use of ‘__builtin_va_arg_pack_len ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:170:3: error: invalid use of ‘__builtin_va_arg_pack ()’
</code>```

Where can be the problem? It's mixed C/C++ project but this is in the C part. gcc 4.6.1, kernel 3.0.0

Edit: It turns out that commeting out those line gives another "type" of errors like:

```<code>/usr/include/x86_64-linux-gnu/bits/stdio2.h: In function ‘sprintf’:
/usr/include/x86_64-linux-gnu/bits/stdio2.h:34:3: error: invalid use of ‘__builtin_va_arg_pack ()’
</code>```

答:
I hit this when trying to compile https://www.spec.org/cpu2017/Docs/benchmarks/602.gcc_s.html with GCC.

Ironically, the bootstrap process would fail due to GCC apparently not understanding GNU extensions.

Turning on -fgnu89-inline got rid of any problems I was having.
Alternatively, use -std=gnu89.

Title: gcc -O2 vs. without causes error

Body:
When compiling file containing open("FILENAME", O_RDONLY); without -O2 flag everything is fine. But when -O2 is turned on I get:

/usr/include/x86_64-linux-gnu/bits/fcntl2.h: In function ‘open’:
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:44:7: error: invalid use of ‘__builtin_va_arg_pack_len ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:45:26: error: call to ‘__open_too_many_args’ declared with attribute error: open can be called either with 2 or 3 arguments, not more
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:42:1: error: invalid use of ‘__builtin_va_arg_pack_len ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:60:3: error: invalid use of ‘__builtin_va_arg_pack ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h: In function ‘open64’:
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:76:7: error: invalid use of ‘__builtin_va_arg_pack_len ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:77:28: error: call to ‘__open64_too_many_args’ declared with attribute error: open64 can be called either with 2 or 3 arguments, not more
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:74:1: error: invalid use of ‘__builtin_va_arg_pack_len ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:92:3: error: invalid use of ‘__builtin_va_arg_pack ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h: In function ‘openat’:
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:120:7: error: invalid use of ‘__builtin_va_arg_pack_len ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:121:28: error: call to ‘__openat_too_many_args’ declared with attribute error: openat can be called either with 3 or 4 arguments, not more
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:118:1: error: invalid use of ‘__builtin_va_arg_pack_len ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:136:3: error: invalid use of ‘__builtin_va_arg_pack ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h: In function ‘openat64’:
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:154:7: error: invalid use of ‘__builtin_va_arg_pack_len ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:155:30: error: call to ‘__openat64_too_many_args’ declared with attribute error: openat64 can be called either with 3 or 4 arguments, not more
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:152:1: error: invalid use of ‘__builtin_va_arg_pack_len ()’
/usr/include/x86_64-linux-gnu/bits/fcntl2.h:170:3: error: invalid use of ‘__builtin_va_arg_pack ()’

Where can be the problem? It's mixed C/C++ project but this is in the C part. gcc 4.6.1, kernel 3.0.0

Edit: It turns out that commeting out those line gives another "type" of errors like:

/usr/include/x86_64-linux-gnu/bits/stdio2.h: In function ‘sprintf’:
/usr/include/x86_64-linux-gnu/bits/stdio2.h:34:3: error: invalid use of ‘__builtin_va_arg_pack ()’


来源: stackexchange

问:
Master thesis topic - mod_security
Are there any research to be done that could use mod_security?</p>

答:
There's some sentiment out there that tools like mod_security don't actually increase security at all.  Sure, they do "block" common vectors, so they are not useless.  But the thing is, the only way to secure code is to make the code secure.  Everything else is just a band-aid.  That's not to say they are not useful as an extra line of defense.  The best defense is multi-layered.  But my point is that mod_security is not securing any websites.  It's just plugging common holes (which are more than likely not present)...  There's a fine line in there, but it's a line that has to be drawn...

As far as how to make it more research-like, I would simply do your homework.  Go out and look at real world attacks and attack vectors.  Look at the common themes.  If you don't understand how the attacks are happening in the first place, how can you possibly hope to build a tool or create rules to defend against them?!?!?

But that's just my $0.02...

ContentLicense: CC BY-SA 2.5

Title: Master thesis topic - mod_security


问:
How to find evenly divisible values in array javascript?
It sounds like the goal is to find the only two numbers in each row where one evenly divides the other - that is, where the result of the division operation is a whole number. They would like you to find those numbers on each line, divide them, and add up each line's result.

For example, given the following spreadsheet:

[5, 9, 2, 8]

[9, 4, 7, 3]

[3, 8, 6, 5]

In the first row, the only two numbers that evenly divide are 8 and 2; the result of this division is 4.
In the second row, the two numbers are 9 and 3; the result is 3.
In the third row, the result is 2.
In this example, the sum of the results would be 4 + 3 + 2 = 9.

Find the evenly divisible values in next array:

[1224, 926, 1380, 688, 845, 109, 118, 88, 1275, 1306, 91, 796, 102, 1361]
[1928, 2097,138, 1824, 198, 117, 1532, 2000, 1478 ,539, 1982]

how to use for loop or reduce in this case?

https://codepen.io/marinashumeyko/pen/EbreoJ?editors=1011

ContentLicense: CC BY-SA 3.0

Body:
const input =  [1224, 926, 1380, 688, 845, 109, 118, 88, 1275, 1306, 91, 796, 102, 1361];
for (i=0; i<input.length; i++) {
    for (j = i+1; j<input.length; j++) {
        if (input[i] % input[j] == 0) {
            console.log(input[i] / input[j],'\n',i,input[i],'\n',j,input[j]);
        }
        if (input[j] % input[i] ==0) {
            console.log(input[j] / input[i],'\n',i,input[i],'\n',j,input[j]);
        }
    }
}


问:
C Programming - How often should realloc be used?
I have a question about dynamic memory allocation.

Context: I'm writing a program that reads a text file of words and counts the frequency with which each word occurs (one word per line).

This particular function reads the file, counts the lines and characters, then dynamically allocates memory to the array of string pointers, an array storing the count of characters for each line and the strings themselves. (The other parts are less directly relevant to my question).

Question: How often should I reallocate memory if I run out of space? I set a constant ("memstart") for setting the initial memory allocation value. In the below code snippet I realloc for every line over the value of "memstart". Would the program process faster if a reallocated a larger block of memory instead of increasing the memory space by 1 "variable type" each time?

What would be best practice for something like this?

Code Snip:

```<code>int read_alloc(FILE* fin, FILE *tmp, char **wdp, int *sz){
    int line_cnt= 0, chr, let=1;
    do{
        chr=getc(fin);
        let++;
        //count characters

        if(chr!=EOF){
            chr=tolower(chr);
            fputc(chr, tmp);
        }
        //convert to lcase and write to temp file

        if ('\n' == chr || chr==EOF){
            sz[(line_cnt)]=((let)*sizeof(char));            //save size needed to store string in array
            *(wdp+(line_cnt))=malloc((let)*sizeof(char));   //allocate space for the string
            if ((line_cnt-1) >= memstart){
                realloc(wdp, (sizeof(wdp)*(memstart+line_cnt)));    //if more space needed increase size
                realloc(sz, (sizeof(sz)*(memstart+line_cnt)));
            }
            line_cnt++;
            let=1;
        }
    } while (EOF != chr);

    return (line_cnt);
}
</code>```

答:
While the question is about how often realloc should be called, looking at OP's code, I think it's better to start with how safely it should be done.

The C11 standard states (n1570 draft, § 7.22.3.5, The realloc function, emphasis mine):

Synopsis

#include <stdlib.h>

  void *realloc(void *ptr, size_t size);

Description

    The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object shall be the same as that of the old object prior to deallocation, up to the lesser of the new and old sizes. Any bytes in the new object beyond the size of the old object have indeterminate values.

    If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. (...). If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.

  Returns

    The realloc function returns a pointer to the new object (which may have the same value as a pointer to the old object), or a null pointer if the new object could not be allocated.

Now let's consider this snippet from the question, where sz is declared as int* sz;

```<code>realloc(sz, (sizeof(sz)*(memstart+line_cnt)));
</code>```

The return value is lost, so we can't know if the call succeeded and if it did, sz is invalidated. Moreover, sizeof(sz) is the size of the pointer, not of the pointed type (int).

A more safe (and correct) pattern would be:

```<code>size_t new_size = /* Whatever, let's say */ size + SOME_COSTANT + size / 2;
void *tmp = realloc(ptr, new_size * sizeof *ptr);
if ( tmp == NULL ) {
    /* Deal with the error, e.g. log a message with perror, return NULL
       (if this is in a function) or just give up, but remeber that
       realloc doesn't invalidate nor free 'ptr' on failure */
    exit(EXIT_FAILURE);
}
ptr = tmp; // <- on success, realloc invalidated ptr
size = new_size;
</code>```

Now, to answer the question, realloc should be called only when needed, because it involves potentially expansive system calls. So either allocate a big chunk ahead or choose a growing stratey like doubling (or 1.5 times) the size every time.

It's worth noting that if possible, the OS could perform the reallocation without copying any element of the original array.

Body:
I have a question about dynamic memory allocation.

Context: I'm writing a program that reads a text file of words and counts the frequency with which each word occurs (one word per line).

This particular function reads the file, counts the lines and characters, then dynamically allocates memory to the array of string pointers, an array storing the count of characters for each line and the strings themselves. (The other parts are less directly relevant to my question).

Question: How often should I reallocate memory if I run out of space? I set a constant ("memstart") for setting the initial memory allocation value. In the below code snippet I realloc for every line over the value of "memstart". Would the program process faster if a reallocated a larger block of memory instead of increasing the memory space by 1 "variable type" each time?

What would be best practice for something like this?

Code Snip:

int read_alloc(FILE* fin, FILE *tmp, char **wdp, int *sz){
    int line_cnt= 0, chr, let=1;
    do{
        chr=getc(fin);
        let++;
        //count characters

        if(chr!=EOF){
            chr=tolower(chr);
            fputc(chr, tmp);
        }
        //convert to lcase and write to temp file

        if ('\n' == chr || chr==EOF){
            sz[(line_cnt)]=((let)*sizeof(char));            //save size needed to store string in array
            *(wdp+(line_cnt))=malloc((let)*sizeof(char));   //allocate space for the string
            if ((line_cnt-1) >= memstart){
                realloc(wdp, (sizeof(wdp)*(memstart+line_cnt)));    //if more space needed increase size
                realloc(sz, (sizeof(sz)*(memstart+line_cnt)));
            }
            line_cnt++;
            let=1;
        }
    } while (EOF != chr);

    return (line_cnt);
}

Body:
While the question is about how often realloc should be called, looking at OP's code, I think it's better to start with how safely it should be done.

The C11 standard states (n1570 draft, § 7.22.3.5, The realloc function, emphasis mine):

Synopsis

#include <stdlib.h>

  void *realloc(void *ptr, size_t size);

Description

    The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object shall be the same as that of the old object prior to deallocation, up to the lesser of the new and old sizes. Any bytes in the new object beyond the size of the old object have indeterminate values.

    If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. (...). If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.

  Returns

    The realloc function returns a pointer to the new object (which may have the same value as a pointer to the old object), or a null pointer if the new object could not be allocated.

Now let's consider this snippet from the question, where sz is declared as int* sz;

realloc(sz, (sizeof(sz)*(memstart+line_cnt)));

The return value is lost, so we can't know if the call succeeded and if it did, sz is invalidated. Moreover, sizeof(sz) is the size of the pointer, not of the pointed type (int).

A more safe (and correct) pattern would be:

size_t new_size = /* Whatever, let's say */ size + SOME_COSTANT + size / 2;
void *tmp = realloc(ptr, new_size * sizeof *ptr);
if ( tmp == NULL ) {
    /* Deal with the error, e.g. log a message with perror, return NULL
       (if this is in a function) or just give up, but remeber that
       realloc doesn't invalidate nor free 'ptr' on failure */
    exit(EXIT_FAILURE);
}
ptr = tmp; // <- on success, realloc invalidated ptr
size = new_size;

Now, to answer the question, realloc should be called only when needed, because it involves potentially expansive system calls. So either allocate a big chunk ahead or choose a growing stratey like doubling (or 1.5 times) the size every time.

It's worth noting that if possible, the OS could perform the reallocation without copying any element of the original array.


问:
Search by Date range in Elastic search malformed query
I am trying to integrate search by date range with PHP and elastic search

```<code>$params1 = [
'index' => 'joborders',
'type' => 'joborder',
'from' =>0,
'size' => 50,

     'body' => [

     'query' => [
            'query_string' => [
                'query' => $wildCardString,
                'fields' => ['description'],

                ]
        ]
    ]
];

$filter_date=array();
$filter_date['range']['datecreatedsort']['gte']='2015-11-27';
$filter_date['range']['datecreatedsort']['lte']='2017-11-27';
$params1['body']['query']['filtered']['filter']=$filter_date;
$params1['body']['sort']['datecreatedsort']['order'] = 'desc';

   try {
     $results = $client->search($params1);
     //print_r($results);
   }
   catch (Exception $e) {
$last = $client->transport->getLastConnection()->getLastRequestInfo();
$last['results']['error'] = [];
print_r($last);
}
</code>```

When I am running above query I am getting following error

[query_string] malformed query, expected [END_OBJECT] but found
  [FIELD_NAME]","line":1,"col":78},"status":400}

datecreatedsort filed mapping is date type is date and value in
  elastic search db is "datecreatedsort":"2016-05-30T09:39:40.000Z"

please help where is the issue in elastic query.

答:
Hi Got the solution its working fine

```<code>$params1 = [
'index' => 'joborders',
'type' => 'joborder',
'body' => [
    'query' => [
        'bool' => [
            'filter' => [
                'range' => [ 'date_modified' => ['gt'=>$duration,'lt'=>$today,'boost'=> '2.0'] ]
            ],
            'must' => [
                'match' => [ 'description' => $wildCardString ]
            ]
        ]
    ]
 ]
];
</code>```

Thanks guys for help.

Body:
I am trying to integrate search by date range with PHP and elastic search

$params1 = [
'index' => 'joborders',
'type' => 'joborder',
'from' =>0,
'size' => 50,

     'body' => [

     'query' => [
            'query_string' => [
                'query' => $wildCardString,
                'fields' => ['description'],

                ]
        ]
    ]
];

$filter_date=array();
$filter_date['range']['datecreatedsort']['gte']='2015-11-27';
$filter_date['range']['datecreatedsort']['lte']='2017-11-27';
$params1['body']['query']['filtered']['filter']=$filter_date;
$params1['body']['sort']['datecreatedsort']['order'] = 'desc';

   try {
     $results = $client->search($params1);
     //print_r($results);
   }
   catch (Exception $e) {
$last = $client->transport->getLastConnection()->getLastRequestInfo();
$last['results']['error'] = [];
print_r($last);
}

When I am running above query I am getting following error

[query_string] malformed query, expected [END_OBJECT] but found
  [FIELD_NAME]","line":1,"col":78},"status":400}

datecreatedsort filed mapping is date type is date and value in
  elastic search db is "datecreatedsort":"2016-05-30T09:39:40.000Z"

please help where is the issue in elastic query.

Body:
Hi Got the solution its working fine

$params1 = [
'index' => 'joborders',
'type' => 'joborder',
'body' => [
    'query' => [
        'bool' => [
            'filter' => [
                'range' => [ 'date_modified' => ['gt'=>$duration,'lt'=>$today,'boost'=> '2.0'] ]
            ],
            'must' => [
                'match' => [ 'description' => $wildCardString ]
            ]
        ]
    ]
 ]
];

Thanks guys for help.


问:
BigDecimal format with exponential
I have a problem with formating BigDecimal in Java (Android Studio)!

I want to format BigDecimal to String when it is bigger than 16 characters, with 9 decimals plus exponential (0.000000000e+00).

I used String#format but the result is not correct, it is 1.000000000e+32 instead of 9.99999999e+31.

How can I get the number in the correct format? Here is the code.

```<code>String b = "9999999999999999";
String c = "9999999999999999";
BigDecimal resultMultyply = (new BigDecimal(b)).multiply(new BigDecimal(c));
String main_number = resultMultyply.toString();

if (main_number.length() > 16) {
    // main_number = 99999999999999980000000000000001
    main_number = String.format("%16.9e", new BigDecimal(main_number));
    // main_number = 1.000000000e+32
}
</code>```

main_number is correct before formatting.

答:
Use DecimalFormat with rounding mode DOWN

Your problem is that you don't have your hands on the rounding mode when creating your output value. The default rounding mode for BigDecimal is HALF_UP, which is not what you want: you want to see the first digits as is. So that means you discard the digits after your expected precision, which translates into rounding DOWN. Unfortunately, BigDecimal doesn't offer such fine grain by default. So you have to use DecimalFormat.

All in all, it works like this:

```<code>import java.math.*;
import java.text.*;
public class Main {
  public static void main(String[] args) {
    BigDecimal a = new BigDecimal("9999999999999999");
    BigDecimal mul = a.multiply(a);
    System.out.println(format(mul, 9));
  }

  private static String format(BigDecimal x, int scale) {
    NumberFormat formatter = new DecimalFormat("0.0E0");
    formatter.setRoundingMode(RoundingMode.DOWN);
    formatter.setMinimumFractionDigits(scale);
    return formatter.format(x);
  }

}
</code>```

Outputs:

```<code>9.999999999E31
</code>```

Title: BigDecimal format with exponential

Body:
I have a problem with formating BigDecimal in Java (Android Studio)!

I want to format BigDecimal to String when it is bigger than 16 characters, with 9 decimals plus exponential (0.000000000e+00).

I used String#format but the result is not correct, it is 1.000000000e+32 instead of 9.99999999e+31.

How can I get the number in the correct format? Here is the code.

String b = "9999999999999999";
String c = "9999999999999999";
BigDecimal resultMultyply = (new BigDecimal(b)).multiply(new BigDecimal(c));
String main_number = resultMultyply.toString();

if (main_number.length() > 16) {
    // main_number = 99999999999999980000000000000001
    main_number = String.format("%16.9e", new BigDecimal(main_number));
    // main_number = 1.000000000e+32
}

main_number is correct before formatting.

Body:
Use DecimalFormat with rounding mode DOWN

Your problem is that you don't have your hands on the rounding mode when creating your output value. The default rounding mode for BigDecimal is HALF_UP, which is not what you want: you want to see the first digits as is. So that means you discard the digits after your expected precision, which translates into rounding DOWN. Unfortunately, BigDecimal doesn't offer such fine grain by default. So you have to use DecimalFormat.

All in all, it works like this:

import java.math.*;
import java.text.*;
public class Main {
  public static void main(String[] args) {
    BigDecimal a = new BigDecimal("9999999999999999");
    BigDecimal mul = a.multiply(a);
    System.out.println(format(mul, 9));
  }

  private static String format(BigDecimal x, int scale) {
    NumberFormat formatter = new DecimalFormat("0.0E0");
    formatter.setRoundingMode(RoundingMode.DOWN);
    formatter.setMinimumFractionDigits(scale);
    return formatter.format(x);
  }

}

Outputs:

9.999999999E31


问:
Entity Framework: how to use two records in one column
I'm creating a simply database with Entity Framework using ASP.NET, i have class "Graphics" and class "InputOutput". I want to set in Initializer two records from InputOutput to Graphics one column.

Graphics.cs

```<code>public class Graphics
    {
        public int GraphicsID { get; set; }
        public int ProducerID { get; set; }
        public int InputOutputID { get; set; }

        public string Name { get; set; }
        public string TypeOfConnection { get; set; }
        public string ProducerOfChipset { get; set; }
        public string TypOfMemory { get; set; }
        public string CoreSpeed { get; set; }
        public string MemoryClock { get; set; }
        public string MultiCardsTech { get; set; }
        public string HDCP { get; set; }
        public string CUDA { get; set; }
        public string VRReady { get; set; }
        public string TypeOfCooling { get; set; }

        public string Size { get; set; }

        public ICollection<InputOutput> InputOutput { get; set; }
        public ICollection<Producer> Producer { get; set; }
        public ICollection<LaptopProduct> LaptopProduct { get; set; }

    }
</code>```

InputOutput.cs

```<code>public class InputOutput
    {
        public int InputOutputID { get; set; }
        public string Name { get; set; }

        public ICollection<Graphics> Graphics { get; set; }
    }
</code>```

And from Initializer:

```<code>var inputoutputs = new List<InputOutput>
            {
                new InputOutput { Name = "DVI"},
                new InputOutput { Name = "HDMI"},
                new InputOutput { Name = "VGA"}
            };

var graphics = new List<Graphics>
            {
                new Graphics { Name="GTX 1080", ProducerID=4, InputOutputID = "HERE ? What should i write to set 2 properties?" },
                new Graphics { Name="GTX 1070", ProducerID=4},
                new Graphics { Name="GTX 1080Ti", ProducerID=4},
            };
</code>```

I want to display GTX1080 with e.g. two ports HDMI and VGA but i can only set one property to InputOutputID.

答:
In your initializer you can reference your previous list inputoutputs.

```<code>var graphics = new List<Graphics>
            {
                new Graphics { Name="GTX 1080", ProducerID=4, InputOutputID = inputoutput[0].InputOutputId, InputOutput =
                   new List<InputOutput> {
                           inputoutputs[0], inputoutputs[1]
                   },
                new Graphics { Name="GTX 1070", ProducerID=4},
                new Graphics { Name="GTX 1080Ti", ProducerID=4},
            };
</code>```

However, since this is a many to many, I'm not sure how the InputOutputID column is going to be used.  You need the junction table to get the items you need.

Here's an example of many to many in EF.  http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx

Note, each table only have the collection to each other and none of the other table's ID attributes.

I also subscribe to making my many to many tables explicit in my ORM mappings.  AKA - I actually create the junction table in EF code.  Jimmy Bogard has a great example and reasons for this.

Body:
I'm creating a simply database with Entity Framework using ASP.NET, i have class "Graphics" and class "InputOutput". I want to set in Initializer two records from InputOutput to Graphics one column.

Graphics.cs

public class Graphics
    {
        public int GraphicsID { get; set; }
        public int ProducerID { get; set; }
        public int InputOutputID { get; set; }

        public string Name { get; set; }
        public string TypeOfConnection { get; set; }
        public string ProducerOfChipset { get; set; }
        public string TypOfMemory { get; set; }
        public string CoreSpeed { get; set; }
        public string MemoryClock { get; set; }
        public string MultiCardsTech { get; set; }
        public string HDCP { get; set; }
        public string CUDA { get; set; }
        public string VRReady { get; set; }
        public string TypeOfCooling { get; set; }

        public string Size { get; set; }

        public ICollection<InputOutput> InputOutput { get; set; }
        public ICollection<Producer> Producer { get; set; }
        public ICollection<LaptopProduct> LaptopProduct { get; set; }

    }

InputOutput.cs

public class InputOutput
    {
        public int InputOutputID { get; set; }
        public string Name { get; set; }

        public ICollection<Graphics> Graphics { get; set; }
    }

And from Initializer:

var inputoutputs = new List<InputOutput>
            {
                new InputOutput { Name = "DVI"},
                new InputOutput { Name = "HDMI"},
                new InputOutput { Name = "VGA"}
            };

var graphics = new List<Graphics>
            {
                new Graphics { Name="GTX 1080", ProducerID=4, InputOutputID = "HERE ? What should i write to set 2 properties?" },
                new Graphics { Name="GTX 1070", ProducerID=4},
                new Graphics { Name="GTX 1080Ti", ProducerID=4},
            };

I want to display GTX1080 with e.g. two ports HDMI and VGA but i can only set one property to InputOutputID.

Body:
In your initializer you can reference your previous list inputoutputs.

var graphics = new List<Graphics>
            {
                new Graphics { Name="GTX 1080", ProducerID=4, InputOutputID = inputoutput[0].InputOutputId, InputOutput =
                   new List<InputOutput> {
                           inputoutputs[0], inputoutputs[1]
                   },
                new Graphics { Name="GTX 1070", ProducerID=4},
                new Graphics { Name="GTX 1080Ti", ProducerID=4},
            };

However, since this is a many to many, I'm not sure how the InputOutputID column is going to be used.  You need the junction table to get the items you need.

Here's an example of many to many in EF.  http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx

Note, each table only have the collection to each other and none of the other table's ID attributes.

I also subscribe to making my many to many tables explicit in my ORM mappings.  AKA - I actually create the junction table in EF code.  Jimmy Bogard has a great example and reasons for this.


问:
unhex(hex()) function in SQL Injection
I'm learning about SQL Injection. And sometime I read in some document that we have to use unhex(hex()) function when exploit in URL address.

And my question is, why we have to use it?

答:
First off, it cannot help you with SQL injection. If SQL injection is impossible, then no hex/unhex/whatever function will make it possible.

It can only help to exploit an existing SQL injection, when a site is protected by a very silly protection method like a black list disallowing a single quote in the input. So these functions can help to avoid using a quote or any other "malicious word" that may alert the filter.

But honestly, I cannot imagine a developer in 2018 using a black list filterig against SQL injection instead of prepared statements for the data/a white list for the everything else

Title: unhex(hex()) function in SQL Injection


问:
How can I get the cordova InAppBrowser to provide a way for the user to close the browser when using an Android device?
I'm using the cordova InAppBrowser to display content from an external site in my app. When I open the browser on an iPhone, there are some buttons at the bottom of the InAppBrowser for closing it or navigating back and forth. The InAppBrowser on an Android device has no such buttons and has no obvious way for the user to close the browser.

I know how to programmatically close the InAppBrowser, but how can the user close it when using an Android device?

I know the user can hit the hardware back button to close the browser, but (1) that's not intuitive - the back button typically means "go back a page", and (2) I'd eventually like to change the behavior of the back button to go back a page within the site that is displaying inside the InAppBrowser, rather than close the browser.

答:
For those looking for a native "Done" button in the footer for Android (similar to iOS), I've implemented such a feature on this fork of cordova-plugin-inappbrowser.

Update: Jan 2018

My pull request has been merged into the official plugin repo,
so you can wait for the next release (which will be >=2.0.2) or install direct from Github, e.g.:

```<code>cordova plugin add https://github.com/apache/cordova-plugin-inappbrowser
</code>```

Original answer

The implementation is an extension of PR #246 which is currently (4 December 2017) awaiting approval to merge. Once that's done, I'll open a separate issue and PR to merge this back into the master cordova-plugin-inappbrowser.

Here's some screenshots with the relevant options:

location=yes,footer=yes

location=no,footer=yes

location=yes,footer=yes,closebuttoncaption=Done

location=no,footer=yes,closebuttoncaption=Done,closebuttoncolor=#0000ff

location=no,footer=yes,footercolor=#0000ff,closebuttoncaption=Done

location=no,footer=yes,footercolor=#00ff00,closebuttoncaption=Done,closebuttoncolor=#0000ff

location=no,footer=yes,footercolor=#CC000000,closebuttoncaption=Done,closebuttoncolor=#00FFFF

Body:
For those looking for a native "Done" button in the footer for Android (similar to iOS), I've implemented such a feature on this fork of cordova-plugin-inappbrowser.

Update: Jan 2018

My pull request has been merged into the official plugin repo,
so you can wait for the next release (which will be >=2.0.2) or install direct from Github, e.g.:

cordova plugin add https://github.com/apache/cordova-plugin-inappbrowser

Original answer

The implementation is an extension of PR #246 which is currently (4 December 2017) awaiting approval to merge. Once that's done, I'll open a separate issue and PR to merge this back into the master cordova-plugin-inappbrowser.

Here's some screenshots with the relevant options:

location=yes,footer=yes

location=no,footer=yes

location=yes,footer=yes,closebuttoncaption=Done

location=no,footer=yes,closebuttoncaption=Done,closebuttoncolor=#0000ff

location=no,footer=yes,footercolor=#0000ff,closebuttoncaption=Done

location=no,footer=yes,footercolor=#00ff00,closebuttoncaption=Done,closebuttoncolor=#0000ff

location=no,footer=yes,footercolor=#CC000000,closebuttoncaption=Done,closebuttoncolor=#00FFFF


问:
Hacking into the Drupal Login
I am very experienced with PHP etc but a Drupal newbie. I would like to know if there is a way I could put in some additional PHP code once a user has logged in to a Drupal site. The reason I need to do this - to update fields in a different database (not the MySQL Drupal DB). I would need to have access to the Drupal site login username and the session cookie generated by drupal. I would be most grateful for any help.</p>

答: You can access the global $user object in the hook_user to get the name and session info.</p>

Title: Hacking into the Drupal Login


问:
Debugging Sinon.js in some smart way
We're using Sinon.JS for some integration-ish testing and I'm having a problem I need to debug somehow. We're using the fakeServer.create() method like so:

```<code>server = Sinon.fakeServer.create()
server.autoRespond = true
server.respondWith "GET", ...
</code>```

Normally when working with xhr, you just open the network-tab in chrome dev tools and you can see all calls to the server, the order of them and the responses from the server. This is super helpful for debugging. Can I achieve something similar when working with Sinon?

答:
The documentation in this area is a little sparse, but one of the configuration options for Sinon's createFakeServer() is logger, here's an example of how you might use it:

```<code>var server = sinon.createFakeServer({ logger: console.log });
</code>```

This will produce:

```<code>Request:
  [FakeXMLHttpRequest] {
  async: true,
    errorFlag: false,
    eventListeners: {
    abort: [function () {}],
      error: [function () {}],
      load: [function () {}],
      loadend: [function () {}],
      loadstart: [function () {}],
      progress: [function () {}],
      timeout: [function () {}]
  },
  logError: function logError() {},
  method: "GET",
    onSend: function () {},
  onerror: function () {},
  onload: function () {},
  onreadystatechange: function () {},
  password: undefined,
    readyState: 1,
    requestBody: null,
    requestHeaders: {
    Accept: "application/json, text/javascript, */*; q=0.01",
    Content-Type: "text/plain;charset=utf-8",
    X-Requested-With: "XMLHttpRequest",
      twProjectsVer: "2.0"
  },
  response: (empty string),
  responseText: (empty string),
  responseType: (empty string),
  responseXML: null,
    sendFlag: true,
    status: 0,
    statusText: (empty string),
  timeout: 0,
    unsafeHeadersEnabled: function () {},
  upload: {
    eventListeners: {
      abort: [function () {}],
        error: [function () {}],
        load: [function () {}],
        loadend: [function () {}],
        loadstart: [function () {}],
        progress: [function () {}],
        timeout: [function () {}]
    }
  },
  url: "/entities.json?page=1&pageSize=50&offsetCount=0",
    username: undefined,
    withCredentials: false
}

Response:
  [404, {  }, (empty string)]
</code>```

Title: Debugging Sinon.js in some smart way

Body:
We're using Sinon.JS for some integration-ish testing and I'm having a problem I need to debug somehow. We're using the fakeServer.create() method like so:

server = Sinon.fakeServer.create()
server.autoRespond = true
server.respondWith "GET", ...

Normally when working with xhr, you just open the network-tab in chrome dev tools and you can see all calls to the server, the order of them and the responses from the server. This is super helpful for debugging. Can I achieve something similar when working with Sinon?

Body:
The documentation in this area is a little sparse, but one of the configuration options for Sinon's createFakeServer() is logger, here's an example of how you might use it:

var server = sinon.createFakeServer({ logger: console.log });

This will produce:

Request:
  [FakeXMLHttpRequest] {
  async: true,
    errorFlag: false,
    eventListeners: {
    abort: [function () {}],
      error: [function () {}],
      load: [function () {}],
      loadend: [function () {}],
      loadstart: [function () {}],
      progress: [function () {}],
      timeout: [function () {}]
  },
  logError: function logError() {},
  method: "GET",
    onSend: function () {},
  onerror: function () {},
  onload: function () {},
  onreadystatechange: function () {},
  password: undefined,
    readyState: 1,
    requestBody: null,
    requestHeaders: {
    Accept: "application/json, text/javascript, */*; q=0.01",
    Content-Type: "text/plain;charset=utf-8",
    X-Requested-With: "XMLHttpRequest",
      twProjectsVer: "2.0"
  },
  response: (empty string),
  responseText: (empty string),
  responseType: (empty string),
  responseXML: null,
    sendFlag: true,
    status: 0,
    statusText: (empty string),
  timeout: 0,
    unsafeHeadersEnabled: function () {},
  upload: {
    eventListeners: {
      abort: [function () {}],
        error: [function () {}],
        load: [function () {}],
        loadend: [function () {}],
        loadstart: [function () {}],
        progress: [function () {}],
        timeout: [function () {}]
    }
  },
  url: "/entities.json?page=1&pageSize=50&offsetCount=0",
    username: undefined,
    withCredentials: false
}

Response:
  [404, {  }, (empty string)]


问:
How to change Action bar for each Tab in Nativescript Angular
I hav TabBar app using Nativescript Angular. I want to change the Action Bar buttons based on the selected tab.
I just follow this tutorial https://www.youtube.com/watch?v=7go3L70QfIQ

But, don't know how to use TabView.selectedIndexChangedEvent in Angular.
If anyone has done this, please share the piece of code.

Thanks

答:
Use this example as a reference on how to use the selectedIndexChange event in Angular based application.

For example:

```<code><TabView selectedIndex="0"  (selectedIndexChange)="onIndexChanged($event)">
<!-- more code follows here -->
</code>```

And then in the component file use the onIndexChanged callback

```<code>public onIndexChanged(args) {
    let tabView = <TabView>args.object;
    console.log("Selected index changed! New inxed: " + tabView.selectedIndex);
}
</code>```

Body:
Use this example as a reference on how to use the selectedIndexChange event in Angular based application.

For example:

<TabView selectedIndex="0"  (selectedIndexChange)="onIndexChanged($event)">
<!-- more code follows here -->

And then in the component file use the onIndexChanged callback

public onIndexChanged(args) {
    let tabView = <TabView>args.object;
    console.log("Selected index changed! New inxed: " + tabView.selectedIndex);
}


问:
apply a permutation to a 1D tensor in Tensorflow
I would like to make the following node :

```<code>a=tf.variable([2,0,1,4,3])      (a permutation)
b=tf.variable([11,12,13,14,15])
</code>```

How to have

```<code>c="b[a]"=tf.variable([13,11,12,15,14])
</code>```

?

答:
I found an other way to solve my question, I think it is a good one : (tf.gather)

```<code>a = [2,0,1,4,3]
b = tf.constant([11,12,13,14,15])
c=tf.gather(b,a)
print(sess.run(c))
</code>```

it gives [12 13 11 14 15] so that is what I wanted

Body:
I would like to make the following node :

a=tf.variable([2,0,1,4,3])      (a permutation)
b=tf.variable([11,12,13,14,15])

How to have

c="b[a]"=tf.variable([13,11,12,15,14])

?

Body:
I found an other way to solve my question, I think it is a good one : (tf.gather)

a = [2,0,1,4,3]
b = tf.constant([11,12,13,14,15])
c=tf.gather(b,a)
print(sess.run(c))

it gives [12 13 11 14 15] so that is what I wanted


问:
How to check mongodb is running or not while starting the C++ application
I am beginner to c++. I have followed http://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/tutorial/ this tutorial. they told to connect to a running MongoDB instance, use the mongocxx::client class. I have done like this

```<code>mongocxx::client conn_;
conn_ =  mongocxx::client(mongocxx::uri{uri});

      if(!conn_){
        std::cout<<"db is not started";
      }else{
        std::cout<<"db is  started";
      }
</code>```

if the mongodb is not started, it has to print "db is not started" but the above code does not seems to be working.
Please suggest me how to check mongodb is running or not before starting the application

答:
In principle MongoDB is designed as a distributed system, which every component might fail. The best advice is to be prepared for each query you do against the database to fail.

If despite this, you still want to test it, the simplest way is to send a command to MongoDB. Use mongocxx::database::run_command to send an {"ismaster" : 1} command to the admin database.

Body:
I am beginner to c++. I have followed http://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/tutorial/ this tutorial. they told to connect to a running MongoDB instance, use the mongocxx::client class. I have done like this

mongocxx::client conn_;
conn_ =  mongocxx::client(mongocxx::uri{uri});

      if(!conn_){
        std::cout<<"db is not started";
      }else{
        std::cout<<"db is  started";
      }

if the mongodb is not started, it has to print "db is not started" but the above code does not seems to be working.
Please suggest me how to check mongodb is running or not before starting the application


问:
KeyListener for Escape in JPanel
I have a JPanel in a JFrame and want to make a KeyListener for the Escapebutton. I already used ActionListeners for Buttons and a MouseListener which all work. I don't know why the KeyListener doesn't work. There is nothing else in that panel so the Panel should be focused. I also tried several combinations of e.getKeyCode() or e.getKeyChar() and other keys than Escape.</p>

```<code>public GamePanel(GameState gameState, Window window) {
    game = gameState;
    myWindow = window;
    renderer = new Renderer();
    setFocusable(true);
    addMouseListener(this);
    addKeyListener(new KeyListener() {
        @Override
        public void keyPressed(KeyEvent e) {
            if( e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                System.out.println("escape");
            }

        }

        @Override
        public void keyReleased(KeyEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyTyped(KeyEvent e) {
            // TODO Auto-generated method stub

        }
    });
    add(renderer);
    setLayout(null);
    setBackground(Color.CYAN);
    setPreferredSize(new Dimension(8000, 600));

    timer = new Timer(20, this);
    timer.start();
}
</code>```

答:
You can register a listener for the Escape key for the whole frame.</p>

```<code>Action action = ...;
String name = "Escape"; // I think the exact name doesn't matter
JComponent pnl = frame.getRootPane();
KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
pnl.getActionMap().put(name, action);
pnl.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, name);
</code>```

Title: KeyListener for Escape in JPanel

Body:
I have a JPanel in a JFrame and want to make a KeyListener for the Escapebutton. I already used ActionListeners for Buttons and a MouseListener which all work. I don't know why the KeyListener doesn't work. There is nothing else in that panel so the Panel should be focused. I also tried several combinations of e.getKeyCode() or e.getKeyChar() and other keys than Escape.

public GamePanel(GameState gameState, Window window) {
    game = gameState;
    myWindow = window;
    renderer = new Renderer();
    setFocusable(true);
    addMouseListener(this);
    addKeyListener(new KeyListener() {
        @Override
        public void keyPressed(KeyEvent e) {
            if( e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                System.out.println("escape");
            }

        }

        @Override
        public void keyReleased(KeyEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyTyped(KeyEvent e) {
            // TODO Auto-generated method stub

        }
    });
    add(renderer);
    setLayout(null);
    setBackground(Color.CYAN);
    setPreferredSize(new Dimension(8000, 600));

    timer = new Timer(20, this);
    timer.start();
}

Body:
You can register a listener for the Escape key for the whole frame.

Action action = ...;
String name = "Escape"; // I think the exact name doesn't matter
JComponent pnl = frame.getRootPane();
KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
pnl.getActionMap().put(name, action);
pnl.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, name);


问:
Regex in a Tweet: match @reply WITHOUT matching @mention

I am working with Tweets.

I am looking for a regular expression that matches all the replies @reply that are present in the beginning of a Tweet WITHOUT matching the mentions @mention.

For example I have this Tweeet:

@AlexWassabi @laurDIY now i type my text and i mention @mention

I would like to match @AlexWassabi and @laurDIY WITHOUT matching @mention.

Please note that in this example there are 2 replies (e.g @AlexWassabi and @laurDIY) but in reality  we can have more @replies that are followed by each other, then we have text and then we have a mention.

Could please suggest a regular expression that does this job?

Thank you.

答:
^(@\w+\s)+ will match all the prefixed "@reply"(s) at beginning of string only.
regex101.com demo


问:
Best way of restarting a jetty instance
I'm using start.jar and stop.jar to stop and start my jetty instance.
I restart by calling stop.jar, then start.jar.
The problem is, if I don't sleep long enough between stop.jar and start.jar I start getting these random ClassNotFoundExceptions and the application doesn't work correctly.

Sleeping for a longer period of time between stop and start is my current option.

I also heard from someone that I should have something that manages my threads so that I end those before jetty finishes.
Is this correct? The question I have about this is that stop.jar returns immediately, so it doesn't seem to help me, unless there's something I'm missing.
Another option might be to poll the log file, but that's pretty ugly.

What's the best way of restarting jetty?

Gilbert: The Ant task is definitely not a bad way of doing it.  However, it sleeps for a set amount of time, which is exactly what I'm trying to avoid.

答:
This thread looks old but posting anyway, may help someone.  A cross-platform approach:

http://ptrthomas.wordpress.com/2009/01/24/how-to-start-and-stop-jetty-revisited/

OwnerDisplayName: Jeff Yang

LastEditorDisplayName: Jeff Yang

Title: Best way of restarting a jetty instance

OwnerDisplayName: Peter Thomas


问:
How to make a PHP XML/RPC call to UPC database
hay i am working on barcode reader project when i call upcdatabase from my php script it give me errors. i use the php example provided by www.upcdatabase.com

the code is

```<code><?php error_reporting(E_ALL);
ini_set('display_errors', true);

 require_once 'XML/RPC.php';

 $rpc_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; // Set your rpc_key here
 $upc='0639382000393';
 // Setup the URL of the XML-RPC service
 $client = new XML_RPC_Client('/xmlrpc', 'http://www.upcdatabase.com');
 $params = array( new XML_RPC_Value( array(
  'rpc_key' => new XML_RPC_Value($rpc_key, 'string'),
  'upc' => new XML_RPC_Value($upc, 'string'),
  ), 'struct'));
 $msg = new XML_RPC_Message('lookup', $params);
 $resp = $client->send($msg);
 if (!$resp)
            {
  echo 'Communication error: ' . $client->errstr;
  exit;
 }
 if(!$resp->faultCode())
 {
  $val = $resp->value();
  $data = XML_RPC_decode($val);
  echo "```" . print_r($data, true) . "```";
 }else{
  echo 'Fault Code: ' . $resp->faultCode() . "\n";
  echo 'Fault Reason: ' . $resp->faultString() . "\n";
 }
?>
</code>```

when i check the $upc='0639382000393'; into upc data base view this then it works fine but i run this script into the browser then it give the following error ```Array
(
    [status] => fail
    [message] => Invalid UPC length
)```

答:
Unfortunately, their API appears rather short on documentation.

There are three types of codes the site mentions on the Item Lookup page:

13 digits for an EAN/UCC-13

12 digits for a Type A UPC code, or

8 digits for a Type-E (zero-supressed) UPC code.

Right after the page mentions those three types, it also says,

Anything other than 8 or 12 digits is not a UPC code!

The 13-digit EAN/UCC-13 is a superset of UPC. It includes valid UPCs, but it has many other values that are not valid UPCs.

From the Wikipedia article on EAN-13:

If the first digit is zero, all digits in the first group of six are encoded using the patterns used for UPC, hence a UPC barcode is also an EAN-13 barcode with the first digit set to zero.

Having said that, when I removed the leading zero from $upc, it worked as expected. Apparently the Item Lookup page has logic to remove the leading zero, while the API does not.

```
Array
(
    [upc] => 639382000393
    [pendingUpdates] => 0
    [status] => success
    [ean] => 0639382000393
    [issuerCountryCode] => us
    [found] => 1
    [description] => The Teenager's Guide to the Real World by BYG Publishing
    [message] => Database entry found
    [size] => book
    [issuerCountry] => United States
    [noCacheAfterUTC] => 2011-01-22T14:46:15
    [lastModifiedUTC] => 2002-08-23T23:07:36
)
```

Alternatively, instead of setting the upc param, you can set the original 13-digit value to the ean param and it will also work.

Body:
hay i am working on barcode reader project when i call upcdatabase from my php script it give me errors. i use the php example provided by www.upcdatabase.com

the code is

<?php error_reporting(E_ALL);
ini_set('display_errors', true);

 require_once 'XML/RPC.php';

 $rpc_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; // Set your rpc_key here
 $upc='0639382000393';
 // Setup the URL of the XML-RPC service
 $client = new XML_RPC_Client('/xmlrpc', 'http://www.upcdatabase.com');
 $params = array( new XML_RPC_Value( array(
  'rpc_key' => new XML_RPC_Value($rpc_key, 'string'),
  'upc' => new XML_RPC_Value($upc, 'string'),
  ), 'struct'));
 $msg = new XML_RPC_Message('lookup', $params);
 $resp = $client->send($msg);
 if (!$resp)
            {
  echo 'Communication error: ' . $client->errstr;
  exit;
 }
 if(!$resp->faultCode())
 {
  $val = $resp->value();
  $data = XML_RPC_decode($val);
  echo "
" . print_r($data, true) . "
";
 }else{
  echo 'Fault Code: ' . $resp->faultCode() . "\n";
  echo 'Fault Reason: ' . $resp->faultString() . "\n";
 }
?>

when i check the $upc='0639382000393'; into upc data base view this then it works fine but i run this script into the browser then it give the following error
Array
(
    [status] => fail
    [message] => Invalid UPC length
)

Body:
Unfortunately, their API appears rather short on documentation.

There are three types of codes the site mentions on the Item Lookup page:

13 digits for an EAN/UCC-13

12 digits for a Type A UPC code, or

8 digits for a Type-E (zero-supressed) UPC code.

Right after the page mentions those three types, it also says,

Anything other than 8 or 12 digits is not a UPC code!

The 13-digit EAN/UCC-13 is a superset of UPC. It includes valid UPCs, but it has many other values that are not valid UPCs.

From the Wikipedia article on EAN-13:

If the first digit is zero, all digits in the first group of six are encoded using the patterns used for UPC, hence a UPC barcode is also an EAN-13 barcode with the first digit set to zero.

Having said that, when I removed the leading zero from $upc, it worked as expected. Apparently the Item Lookup page has logic to remove the leading zero, while the API does not.

Array
(
    [upc] => 639382000393
    [pendingUpdates] => 0
    [status] => success
    [ean] => 0639382000393
    [issuerCountryCode] => us
    [found] => 1
    [description] => The Teenager's Guide to the Real World by BYG Publishing
    [message] => Database entry found
    [size] => book
    [issuerCountry] => United States
    [noCacheAfterUTC] => 2011-01-22T14:46:15
    [lastModifiedUTC] => 2002-08-23T23:07:36
)

Alternatively, instead of setting the upc param, you can set the original 13-digit value to the ean param and it will also work.


问:
How can I create a launchd agent that will run only once?
Since there is no "Year" parameter in the launchd plist format, how is it possible to create an agent that will run only once and not once a year?

答:
Use the key LaunchOnlyOnce for this:

```<code><key>LaunchOnlyOnce</key>
<true/>
</code>```

This will launch the agent only once if the system is not rebooted.

Body:
Use the key LaunchOnlyOnce for this:

<key>LaunchOnlyOnce</key>
<true/>

This will launch the agent only once if the system is not rebooted.


问:
Clean-Css task gives error in gulpfile : cannot read property 'on'
I am totally new to gulp and I wanted to add a task to minify and eventually clean any duplicates or unused css. My gulpfile is below, and for the moment I'm still in the process of learning.

I know I will be using post-css and the modules that can go with it, later on. Right now I get an error: "Cannot read property 'on' of undefined at DestroyableTransform.Readable.pipe". It comes from the cleancss task, when I take it out, there's no errors. Any help and suggestions would be appreciated.

```<code>//JS
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var cleancss = require('clean-css');
var autoPrefixer = require('gulp-autoprefixer');

gulp.task('autoPrefixer', function() {
    return gulp.src('../css/*.css')
        .pipe(autoPrefixer ({
            browsers: ['last 2 versions'],
            }))
            .pipe(gulp.dest('../css'))
    });

gulp.task('cleancss', function() {
  return gulp.src('../css/*.css')
    .pipe(cleancss({compatibility: 'ie8'}))
    .pipe(gulp.dest('../css/min'));
});

gulp.task('sass', function(){
  return gulp.src('../scss/*.scss')
    .pipe(sass().on('error', function(err) {
      console.error('\x07'); // so it doesn't just fail (literally) silently!
      sass.logError.bind(this)(err);
    })) // Converts Sass to CSS with gulp-sass
    .pipe(gulp.dest('../css'))
    .pipe(autoPrefixer())
    .pipe(browserSync.reload({
        stream: true
    }))
});

gulp.task('watch', ['browserSync','sass','autoPrefixer','cleancss'], function() {
    gulp.watch('../scss/*.scss', ['sass']);
    gulp.watch('../*.php', browserSync.reload);
    gulp.watch('../js/*.js', browserSync.reload);
});

gulp.task('browserSync', function() {
    browserSync.init ({
        open: 'external',
        host: 'testsite.local',
        proxy: 'testsite.local',
        port: 3000
    })
        browserSync ({
        server: {
            baseDir: 'app'
        },
    })

});
</code>```

答: I actually managed to make it work by using "vynil-map" as discussed on here : https://github.com/jakubpawlowicz/clean-css/issues/342. Hope this link could help anybody else having the same problem.</p>

Body:
I am totally new to gulp and I wanted to add a task to minify and eventually clean any duplicates or unused css. My gulpfile is below, and for the moment I'm still in the process of learning.

I know I will be using post-css and the modules that can go with it, later on. Right now I get an error: "Cannot read property 'on' of undefined at DestroyableTransform.Readable.pipe". It comes from the cleancss task, when I take it out, there's no errors. Any help and suggestions would be appreciated.

//JS
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var cleancss = require('clean-css');
var autoPrefixer = require('gulp-autoprefixer');

gulp.task('autoPrefixer', function() {
    return gulp.src('../css/*.css')
        .pipe(autoPrefixer ({
            browsers: ['last 2 versions'],
            }))
            .pipe(gulp.dest('../css'))
    });

gulp.task('cleancss', function() {
  return gulp.src('../css/*.css')
    .pipe(cleancss({compatibility: 'ie8'}))
    .pipe(gulp.dest('../css/min'));
});

gulp.task('sass', function(){
  return gulp.src('../scss/*.scss')
    .pipe(sass().on('error', function(err) {
      console.error('\x07'); // so it doesn't just fail (literally) silently!
      sass.logError.bind(this)(err);
    })) // Converts Sass to CSS with gulp-sass
    .pipe(gulp.dest('../css'))
    .pipe(autoPrefixer())
    .pipe(browserSync.reload({
        stream: true
    }))
});

gulp.task('watch', ['browserSync','sass','autoPrefixer','cleancss'], function() {
    gulp.watch('../scss/*.scss', ['sass']);
    gulp.watch('../*.php', browserSync.reload);
    gulp.watch('../js/*.js', browserSync.reload);
});

gulp.task('browserSync', function() {
    browserSync.init ({
        open: 'external',
        host: 'testsite.local',
        proxy: 'testsite.local',
        port: 3000
    })
        browserSync ({
        server: {
            baseDir: 'app'
        },
    })

});


问:
jQuery: multiple 'tipsy' tool tips
When I bring back a list of results from my database, they are displayed like so:

Result 1

  Result 2

  Result 3

And so on... Now I've got the jQuery Tipsy plugin working so when you hover over the top of Result 1 it shows that persons users name. The thing is, if I hover over Result 2, that too should have the Tipsy tooltip appear, but it is just displaying the normal browsers tooltip.

I'm assuming it's because all the id's on the results a tag's are name the same: 'east'. I guess I need to make some sort of for each check in the jQuery yet I wouldn't have the foggiest on where to add this in the jQuery.

Has anyone got a solution to this?

答:
Your problem is having the same ID on all 3 a tags. Under no circumstance is it acceptable to have the same ID applied to more than one element on the same page. You'll need to fix that.

```<code><a href="result_one.html" id="result_one" class="tipsy">Result 1</a>
<a href="result_two.html" id="result_two" class="tipsy">Result 2</a>
<a href="result_three.html" id="result_three" class="tipsy">Result 3</a>
</code>```

You can apply the same class to all three a tags and then apply tipsy to the class.

```<code>$(document).ready(function() {
  $('.tipsy').tipsy({fade:true,gravity:'n'});
});
</code>```

Or you can do each ID separately.

```<code>$(document).ready(function() {
  $('#result_one').tipsy({fade:true,gravity:'n'});
  $('#result_two').tipsy({fade:true,gravity:'n'});
  $('#result_three').tipsy({fade:true,gravity:'n'});
});
</code>```

Title: jQuery: multiple 'tipsy' tool tips

Body:
Your problem is having the same ID on all 3 a tags. Under no circumstance is it acceptable to have the same ID applied to more than one element on the same page. You'll need to fix that.

<a href="result_one.html" id="result_one" class="tipsy">Result 1</a>
<a href="result_two.html" id="result_two" class="tipsy">Result 2</a>
<a href="result_three.html" id="result_three" class="tipsy">Result 3</a>

You can apply the same class to all three a tags and then apply tipsy to the class.

$(document).ready(function() {
  $('.tipsy').tipsy({fade:true,gravity:'n'});
});

Or you can do each ID separately.

$(document).ready(function() {
  $('#result_one').tipsy({fade:true,gravity:'n'});
  $('#result_two').tipsy({fade:true,gravity:'n'});
  $('#result_three').tipsy({fade:true,gravity:'n'});
});


问:
Cannot reference @types definitions in a global d.ts?
Got a global/ambient d.ts file in my project like so:

```<code>/// <reference types="moment" />

declare interface SomeSharedInternalType {
    date: moment.Moment;
}
</code>```

However, the compiler complains

Cannot find namespace 'moment'

Obviously, I cannot use import for this because these declarations have to stay ambient, so how do I reference these type definitions?

答:
```<code>import * as moment from 'moment'
</code>```

will only import type definitions so remains ambient - it will not compile any of the moment JS

EDIT Slightly misread the question here, so for clarity, this is true for ambiently pulling in defs into a TS project (ambient here meaning it will allow you to use types, without any of the referenced module being emmitted in the compiled JS) - however, it does not keep the .d.ts file ambient (ambient here meaning that the types declared within do not need to imported by modules that use them, essentially making them global types, the file itself being included in project via tsconfig.json configuration)

Body:
Got a global/ambient d.ts file in my project like so:

/// <reference types="moment" />

declare interface SomeSharedInternalType {
    date: moment.Moment;
}

However, the compiler complains

Cannot find namespace 'moment'

Obviously, I cannot use import for this because these declarations have to stay ambient, so how do I reference these type definitions?

Body:
import * as moment from 'moment'

will only import type definitions so remains ambient - it will not compile any of the moment JS

EDIT Slightly misread the question here, so for clarity, this is true for ambiently pulling in defs into a TS project (ambient here meaning it will allow you to use types, without any of the referenced module being emmitted in the compiled JS) - however, it does not keep the .d.ts file ambient (ambient here meaning that the types declared within do not need to imported by modules that use them, essentially making them global types, the file itself being included in project via tsconfig.json configuration)


问:
Is it possible to modify fields using a LINQ expression without using a SELECT?
I am using LINQ to populate a list of PhraseSource. Following this I am using a foreach to modify the list:

```<code>List<PhraseSource> phraseSources = App.DB.db1.Table<PhraseSource>().ToList();

List<PhraseSource> phraseSources2 = phraseSources
    .Where(p => categorySources.Any(c => c.Id == p.CategoryId)).ToList();

foreach (var item in phraseSources2)
{
    item.OneHash = Math.Abs(item.Id.GetHashCode() % 10);
    item.TwoHash = Math.Abs(item.Id.GetHashCode() % 100);
}
</code>```

My knowledge of LINQ is pretty limited and this was the code given to me.

Is there a way I could combine the foreach into the LINQ expression or must I use a foreach in this way to modify the data?  Note that I think I could do the with a SELECT but I am wondering if there is another way as PhraseSource has a lot of fields.

答:
Although LINQ does not let you modify items, you have several options at your disposal:

Since OneHash and TwoHash are computed based on other properties of item, you can replace stored properties with computed ones

If you do not need to modify items inside phraseSources (which you would need to do if you plan to save them) you could create copies with computed properties set

If OneHash and TwoHash are not stored in the PhraseSource table, you could remove them from PhraseSource object, and add them as properties of an anonymous "wrapper" object. This would let you compute properties in a LINQ query.

The first approach would look like this:

```<code>public class PhraseSource {
    ...
    public int OneHash => Id.GetHashCode() % 10;
    public int TwoHash => Id.GetHashCode() % 100;
    ...
}
</code>```

Note: in older C# versions that do not support lambda-bodied properties use the getter syntax:

```<code>public class PhraseSource {
    ...
    public int OneHash { get { return Id.GetHashCode() % 10; } }
    public int TwoHash { get { return Id.GetHashCode() % 100; } }
    ...
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using LINQ to populate a list of PhraseSource. Following this I am using a foreach to modify the list:

List<PhraseSource> phraseSources = App.DB.db1.Table<PhraseSource>().ToList();

List<PhraseSource> phraseSources2 = phraseSources
    .Where(p => categorySources.Any(c => c.Id == p.CategoryId)).ToList();

foreach (var item in phraseSources2)
{
    item.OneHash = Math.Abs(item.Id.GetHashCode() % 10);
    item.TwoHash = Math.Abs(item.Id.GetHashCode() % 100);
}

My knowledge of LINQ is pretty limited and this was the code given to me.

Is there a way I could combine the foreach into the LINQ expression or must I use a foreach in this way to modify the data?  Note that I think I could do the with a SELECT but I am wondering if there is another way as PhraseSource has a lot of fields.

Body:
Although LINQ does not let you modify items, you have several options at your disposal:

Since OneHash and TwoHash are computed based on other properties of item, you can replace stored properties with computed ones

If you do not need to modify items inside phraseSources (which you would need to do if you plan to save them) you could create copies with computed properties set

If OneHash and TwoHash are not stored in the PhraseSource table, you could remove them from PhraseSource object, and add them as properties of an anonymous "wrapper" object. This would let you compute properties in a LINQ query.

The first approach would look like this:

public class PhraseSource {
    ...
    public int OneHash => Id.GetHashCode() % 10;
    public int TwoHash => Id.GetHashCode() % 100;
    ...
}

Note: in older C# versions that do not support lambda-bodied properties use the getter syntax:

public class PhraseSource {
    ...
    public int OneHash { get { return Id.GetHashCode() % 10; } }
    public int TwoHash { get { return Id.GetHashCode() % 100; } }
    ...
}


问:
What is the work flow of this Spring Boot program
I am a beginner in spring boot application and I recently came across this project having following 3 packages

com.packagename.controller

com.packagname.domain

com.packagename.service

In domain package, there is a single class named Student
having the following code

```<code>private String name;

public Student() {
}

public Student(String name) {
        this.name = name;
}

public String getName() {
    return name;
}

public void setName(String name) {
        this.name = name;
}

@Override
public String toString() {
        return "Student [name=" + name + "]";
}
</code>```

Then in Service package,
  class StudentService

```<code>package com.javTpoint.service;

import org.springframework.stereotype.Service;

import com.javTpoint.domain.Student;

@Service
public class StudentService {

    public Student saveStudent(Student student) {
        student.setName(student.getName() + "123");
        return student;
    }
}
</code>```

And finally in Controller package,
Student class

```<code>package com.javTpoint.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.javTpoint.domain.Student;
import com.javTpoint.service.StudentService;

@RestController
public class StudentController {
@Autowired
private StudentService studentService;

    @RequestMapping(value = "/student", method = RequestMethod.POST)
    Student saveStuden(@RequestBody Student student) {
    System.out.println(student);
        return studentService.saveStudent(student);
    }
}
</code>```

The program asked to use this is Postman
I just want to understand the how the workflow is taking place like
why @RequestBody is used inside saveStuden() method in controller.

答:
When using Postman you likely invoke a URL such as http://<host>:<port>/student using the HTTP POST method to submit a payload (probably) expressed in JSON e.g.

```<code>{ "name": "aName" }
</code>```

The flow from Postman goes like this:

Postman POSTs the request body.

The application which exposes the http://<host>:<port>/student consumes the request, deserialises the request body into a Student object and delegates to an instance of StudentController. This: @RequestBody Student student instructs Spring to deserialise the given payload into an instance of Student.

The StudentController delegates to the instance of StudentService which it has been injected with. Note: the The @Autowired annotation instructs Spring's dependency injection mechanism to create an instance of StudentController with an instance of StudentService injected into it.

The StudentService appends "123" to the student name and returns the mutated Student instance.

The StudentController returns the mutated Student instance.

The framework (i.e. Spring Boot) serialises the returned Student and returns the serialised representation to Postman.

What you have described in your OP looks like a common division of responsibilities:

The framework (Spring Boot in this case) provides the servlet container pieces and maps HTTP invocations to public methods on contoller classes

The controller provides the HTTP endpoint integration and is typically a lightweight facade over a service

The service is responsible for 'doing something' with the given object

Update in response to this comment:

where should I learn what you know from? Any personal recommendations?

You could start with this Spring Boot example and walk through it step by step. Once you have it working (which typiclaly takes no more than 15 mins) then use ...

Logging

Debugging

Changing things (one thing at a time) and observing cause-and-effect

...  to  help you understand what Spring is doing 'under the covers'.

Body:
I am a beginner in spring boot application and I recently came across this project having following 3 packages

com.packagename.controller

com.packagname.domain

com.packagename.service

In domain package, there is a single class named Student
having the following code

private String name;

public Student() {
}

public Student(String name) {
        this.name = name;
}

public String getName() {
    return name;
}

public void setName(String name) {
        this.name = name;
}

@Override
public String toString() {
        return "Student [name=" + name + "]";
}

Then in Service package,
  class StudentService

package com.javTpoint.service;

import org.springframework.stereotype.Service;

import com.javTpoint.domain.Student;

@Service
public class StudentService {

    public Student saveStudent(Student student) {
        student.setName(student.getName() + "123");
        return student;
    }
}

And finally in Controller package,
Student class

package com.javTpoint.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.javTpoint.domain.Student;
import com.javTpoint.service.StudentService;

@RestController
public class StudentController {
@Autowired
private StudentService studentService;

    @RequestMapping(value = "/student", method = RequestMethod.POST)
    Student saveStuden(@RequestBody Student student) {
    System.out.println(student);
        return studentService.saveStudent(student);
    }
}

The program asked to use this is Postman
I just want to understand the how the workflow is taking place like
why @RequestBody is used inside saveStuden() method in controller.

Body:
When using Postman you likely invoke a URL such as http://<host>:<port>/student using the HTTP POST method to submit a payload (probably) expressed in JSON e.g.

{ "name": "aName" }

The flow from Postman goes like this:

Postman POSTs the request body.

The application which exposes the http://<host>:<port>/student consumes the request, deserialises the request body into a Student object and delegates to an instance of StudentController. This: @RequestBody Student student instructs Spring to deserialise the given payload into an instance of Student.

The StudentController delegates to the instance of StudentService which it has been injected with. Note: the The @Autowired annotation instructs Spring's dependency injection mechanism to create an instance of StudentController with an instance of StudentService injected into it.

The StudentService appends "123" to the student name and returns the mutated Student instance.

The StudentController returns the mutated Student instance.

The framework (i.e. Spring Boot) serialises the returned Student and returns the serialised representation to Postman.

What you have described in your OP looks like a common division of responsibilities:

The framework (Spring Boot in this case) provides the servlet container pieces and maps HTTP invocations to public methods on contoller classes

The controller provides the HTTP endpoint integration and is typically a lightweight facade over a service

The service is responsible for 'doing something' with the given object

Update in response to this comment:

where should I learn what you know from? Any personal recommendations?

You could start with this Spring Boot example and walk through it step by step. Once you have it working (which typiclaly takes no more than 15 mins) then use ...

Logging

Debugging

Changing things (one thing at a time) and observing cause-and-effect

...  to  help you understand what Spring is doing 'under the covers'.


问:
AH00072: make_sock: could not bind to address [::]:80 (13)Permission denied
After upgrading to macOS Sierra my apache doesn't start.

Where it goes the apache error_log:

```<code>AH00112: Warning: DocumentRoot [/usr/docs/dummy-host.example.com] does not exist

AH00112: Warning: DocumentRoot [/usr/docs/dummy-host2.example.com] does not exist

AH00557: httpd: apr_sockaddr_info_get() failed for username.local

AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName' directive globally to suppress this message (13)Permission denied:

AH00072: make_sock: could not bind to address [::]:80 (13)Permission denied:

AH00072: make_sock: could not bind to address 0.0.0.0:80 no listening sockets available, shutting down*
</code>```

I already follow these instructions without success: http://digitalshore.io/local-web-development-environment-apache-macos-sierra-10-12/

答:
AH00558: httpd: Could not reliably determine the server's fully qualified domain name.

You need to identify httpd.conf Apache configuration file by:

```<code>apachectl -t -D DUMP_INCLUDES
</code>```

then edit it and uncomment the line with ServerName (make sure it has the valid server name). E.g.

```<code>ServerName localhost
</code>```

AH00072: make_sock: could not bind to address [::]:80 (13) Permission denied

You need to launch Apache service as root user, otherwise the process doesn't have permission to bind to port 80 since all ports below 1024 needs administrative permissions.

So you need run it as:

```<code>sudo apachectl start
</code>```

Body:
After upgrading to macOS Sierra my apache doesn't start.

Where it goes the apache error_log:

AH00112: Warning: DocumentRoot [/usr/docs/dummy-host.example.com] does not exist

AH00112: Warning: DocumentRoot [/usr/docs/dummy-host2.example.com] does not exist

AH00557: httpd: apr_sockaddr_info_get() failed for username.local

AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName' directive globally to suppress this message (13)Permission denied:

AH00072: make_sock: could not bind to address [::]:80 (13)Permission denied:

AH00072: make_sock: could not bind to address 0.0.0.0:80 no listening sockets available, shutting down*

I already follow these instructions without success: http://digitalshore.io/local-web-development-environment-apache-macos-sierra-10-12/

Body:
AH00558: httpd: Could not reliably determine the server's fully qualified domain name.

You need to identify httpd.conf Apache configuration file by:

apachectl -t -D DUMP_INCLUDES

then edit it and uncomment the line with ServerName (make sure it has the valid server name). E.g.

ServerName localhost

AH00072: make_sock: could not bind to address [::]:80 (13) Permission denied

You need to launch Apache service as root user, otherwise the process doesn't have permission to bind to port 80 since all ports below 1024 needs administrative permissions.

So you need run it as:

sudo apachectl start


问:
Can "git push" hang on the same %?
I am starting to use Git.  I feel it is important to point out that this was not my choice.  I have found Git to be problematic to understand but largely stable, until last month.  A week into Dec 2010 I found that I could no longer push to our "central" repository.  The process would reach 70% on writing objects and then hang.  We have no Git "experts", but I asked some of the other people that have been using it and was given a number of suggested resolutions.  Issues with Logitech webcams, attempting to do the push from Safe Mode 9 (with networking obviously), using the command line in Git bash rather than Tortoise.  None worked.  What I ended up doing was uninstalling msysgit and reinstalling it.  That resolved the issue.  Or so I thought.  A couple of days ago the issue recurred.  I can no longer "push" to our repository.

I suppose I could just plan on reinstalling msysgit every month from now on, but that seems like to great a concession to me. :-)

Any idea what I can do to resolve this, or even troubleshoot it?

答:
There may be issues with where it is hosted. I've been using git (msysgit) since 2008 and never had such an issue. I would recommend hosting the server on a linux VM though. That's made things faster and gitolite is excellent for permissions.

Hope this helps.

Title: Can "git push" hang on the same %?


Title: Set month value for entire week as mid-week day month value

Body:
I have the following pandas.Dataframe:

Date-Time           Week Month
2017-07-29 16:05:00 30  Jul-17
2017-07-29 23:58:00 30  Jul-17
2017-07-30 04:46:00 31  Jul-17
2017-07-30 10:57:00 31  Jul-17
2017-07-31 09:36:00 31  Jul-17
2017-07-31 10:46:00 31  Jul-17
2017-08-01 09:06:00 31  Aug-17
2017-08-01 09:13:00 31  Aug-17
2017-08-02 16:02:00 31  Aug-17
2017-08-02 16:06:00 31  Aug-17
2017-08-02 16:55:00 31  Aug-17
2017-08-02 18:57:00 31  Aug-17
2017-08-02 21:56:00 31  Aug-17
2017-08-03 08:49:00 31  Aug-17
2017-08-03 14:16:00 31  Aug-17
2017-08-04 09:09:00 31  Aug-17
2017-08-04 10:08:00 31  Aug-17
2017-08-05 11:24:00 31  Aug-17
2017-08-05 12:42:00 31  Aug-17
2017-08-06 03:47:00 32  Aug-17
2017-08-06 03:55:00 32  Aug-17
2017-08-07 08:57:00 32  Aug-17
2017-08-07 11:35:00 32  Aug-17

Is there a way I can normalize the month value for each week to be the value of the month to which the mid-week day (Wednesday) belongs?

In the above dataframe, Wednesday of week 31 lies in August, so the month column for week 31 should be as follows:

Date-Time           Week Month
2017-07-29 16:05:00 30  Jul-17
2017-07-29 23:58:00 30  Jul-17
2017-07-30 04:46:00 31  Aug-17
2017-07-30 10:57:00 31  Aug-17
2017-07-31 09:36:00 31  Aug-17
2017-07-31 10:46:00 31  Aug-17
2017-08-01 09:06:00 31  Aug-17
2017-08-01 09:13:00 31  Aug-17
2017-08-02 16:02:00 31  Aug-17
2017-08-02 16:06:00 31  Aug-17
2017-08-02 16:55:00 31  Aug-17
2017-08-02 18:57:00 31  Aug-17
2017-08-02 21:56:00 31  Aug-17
2017-08-03 08:49:00 31  Aug-17
2017-08-03 14:16:00 31  Aug-17
2017-08-04 09:09:00 31  Aug-17
2017-08-04 10:08:00 31  Aug-17
2017-08-05 11:24:00 31  Aug-17
2017-08-05 12:42:00 31  Aug-17
2017-08-06 03:47:00 32  Aug-17
2017-08-06 03:55:00 32  Aug-17
2017-08-07 08:57:00 32  Aug-17
2017-08-07 11:35:00 32  Aug-17

Please note that, both the Week and Month column of the dataframe are derived from the Date-Time column of the same dataframe.

Body:
You can use a timedelta to move your Wednesday back to the beginning of the week and then use pandas.Dateoffset to clamp a date to a day of the week like:

Code:

df['DWY'] = df['Date-Time'] - pd.Timedelta(3, unit='d') - pd.DateOffset(weekday=2)

This is approximately fours time as fast as the string manipulations in your answer for long vectors.

Test Code:

import pandas as pd

data = u"""
date        month
2016-12-31  1
2017-01-01  1
2017-01-28  1
2017-01-29  1
2017-02-25  1
2017-02-26  1
2017-04-01  1
2017-04-02  1
2017-04-29  1
2017-04-30  1
2017-06-03  1
2017-06-04  1
2017-07-01  1
2017-07-02  1
2017-07-29  1
2017-07-30  1
2017-09-02  1
2017-09-03  1
2017-09-30  1
2017-10-01  1
2017-10-28  1
2017-10-29  1
2017-12-02  1
2017-12-03  1
2017-12-30  1
2017-12-31  1"""

df = pd.read_fwf(StringIO(data), header=1)
df['date'] = pd.to_datetime(df['date'])

df['weds-week'] = df['date'] - pd.Timedelta(3, unit='d') - pd.DateOffset(weekday=2)
df['month'] = df['weds-week'].dt.month
print(df)

Results:

         date  month  weds-week
0  2016-12-31     12 2016-12-28
1  2017-01-01      1 2017-01-04
2  2017-01-28      1 2017-01-25
3  2017-01-29      2 2017-02-01
4  2017-02-25      2 2017-02-22
5  2017-02-26      3 2017-03-01
6  2017-04-01      3 2017-03-29
7  2017-04-02      4 2017-04-05
8  2017-04-29      4 2017-04-26
9  2017-04-30      5 2017-05-03
10 2017-06-03      5 2017-05-31
11 2017-06-04      6 2017-06-07
12 2017-07-01      6 2017-06-28
13 2017-07-02      7 2017-07-05
14 2017-07-29      7 2017-07-26
15 2017-07-30      8 2017-08-02
16 2017-09-02      8 2017-08-30
17 2017-09-03      9 2017-09-06
18 2017-09-30      9 2017-09-27
19 2017-10-01     10 2017-10-04
20 2017-10-28     10 2017-10-25
21 2017-10-29     11 2017-11-01
22 2017-12-02     11 2017-11-29
23 2017-12-03     12 2017-12-06
24 2017-12-30     12 2017-12-27
25 2017-12-31      1 2018-01-03


问:
Join one table with only 1 first matching record
```<code>--------------------Table1-------------
Table1Id            item      SaleId       Dimensions
1                   test1      41           10*11*12
2                   test2      41           13*14*15

--------------------Table2-------------
Table2Id     item         Description
1           test1         Test element1 desc 1
2           test1         Test element1 desc 2
3           test2         Test element2 desc 1
4           Test2         Test element2 desc 2
</code>```

Currently I am using following query.

```<code>select Table1.Table1Id, Table1.item, Table1.Dimensions, Table2.Description
on Table1.item = Table2.item
where Table1.SaleId = 41
</code>```

But I want result like that (Need to join Table1.item with first record against item in Table2)

```<code>Result :
Table1Id            item            Dimensions       Description
1                   test1           10*11*12          Test element1 desc 1
2                   test2           13*14*15          Test element2 desc 1
</code>```

答:
The most typical way for handling this is to use the ANSI-standard row_number():

```<code>Select t1.Table1Id, t1.item, t1.Dimensions, t2.Description
from table1 t1 join
     (select t2.*, row_number() over (partition by t2.item order by t2.table2id desc) as seqnum
      from table2 t2
     ) t
     on t1.item = t2.item and t2.seqnum = 1
where t1.SaleId = 41;
</code>```

Body:
--------------------Table1-------------
Table1Id            item      SaleId       Dimensions
1                   test1      41           10*11*12
2                   test2      41           13*14*15

--------------------Table2-------------
Table2Id     item         Description
1           test1         Test element1 desc 1
2           test1         Test element1 desc 2
3           test2         Test element2 desc 1
4           Test2         Test element2 desc 2

Currently I am using following query.

select Table1.Table1Id, Table1.item, Table1.Dimensions, Table2.Description
on Table1.item = Table2.item
where Table1.SaleId = 41

But I want result like that (Need to join Table1.item with first record against item in Table2)

Result :
Table1Id            item            Dimensions       Description
1                   test1           10*11*12          Test element1 desc 1
2                   test2           13*14*15          Test element2 desc 1

Body:
The most typical way for handling this is to use the ANSI-standard row_number():

Select t1.Table1Id, t1.item, t1.Dimensions, t2.Description
from table1 t1 join
     (select t2.*, row_number() over (partition by t2.item order by t2.table2id desc) as seqnum
      from table2 t2
     ) t
     on t1.item = t2.item and t2.seqnum = 1
where t1.SaleId = 41;


问:
Azure Functions: CosmosDBTrigger connection string storage
I asked yesterday where to store the connection string for a CosmosDBTrigger. It worked great until I had to push it up to Azure. Now the function isn't working at all. It works locally just fine though. There is no difference between codebases so the only thing I can think of is the connection string isn't be pulled from local.settings.json when on Azure. I mean, it wouldn't surprise me if that was the case since the file has the word local in it.

I tried putting the contents in the host.json, but that didn't work either.

How do you specify the connection string when your Function is running on Azure?

答:
You need to put it in the Application Settings for the function app. These can be setup using the Azure Portal or deployed as part of the ARM template I believe.

Azure Application Settings


问:
Overflow Warning VBA
I am getting Overflow Warning while running the below fragment of code:

```<code>For Each Row In Rng.Rows

    For Each cell In Row.Cells

        cell.Activate

        ActiveCell.Select

        If IsNumeric(ActiveCell) Then

            ActiveCell.Value = CInt(ActiveCell.Value)

        End If

        Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
        Formula1:="=1"

        Selection.FormatConditions

        (Selection.FormatConditions.Count).SetFirstPriority

        With Selection.FormatConditions(1).Interior.ColorIndex = 20

        End With

        Selection.FormatConditions(1).StopIfTrue = False

    Next cell

Next Row
</code>```

cell and Row are both declared as Variant.

The code was written by someone else and the warning is not coming my system. The error is coming in few other systems.

Please let me know if there is a bug in the code or any other way to stop getting this message.

答:
Try with this. Avoid using Select statements. It can cause a lot of errors (which is what I suspect is causing yours). Also, you don't need two loops to achieve this

```<code>For Each cell In rng.cells
    If IsNumeric(cell) Then cell.Value = CLng(cell.Value)
    With cell
        .FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, Formula1:="=1"
        .FormatConditions(.FormatConditions.Count).SetFirstPriority
        .FormatConditions(1).Interior.ColorIndex = 20
        .FormatConditions(1).StopIfTrue = False
    End With
Next cell
</code>```

Title: Overflow Warning VBA

Body:
I am getting Overflow Warning while running the below fragment of code:

For Each Row In Rng.Rows

    For Each cell In Row.Cells

        cell.Activate

        ActiveCell.Select

        If IsNumeric(ActiveCell) Then

            ActiveCell.Value = CInt(ActiveCell.Value)

        End If

        Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
        Formula1:="=1"

        Selection.FormatConditions

        (Selection.FormatConditions.Count).SetFirstPriority

        With Selection.FormatConditions(1).Interior.ColorIndex = 20

        End With

        Selection.FormatConditions(1).StopIfTrue = False

    Next cell

Next Row

cell and Row are both declared as Variant.

The code was written by someone else and the warning is not coming my system. The error is coming in few other systems.

Please let me know if there is a bug in the code or any other way to stop getting this message.

Body:
Try with this. Avoid using Select statements. It can cause a lot of errors (which is what I suspect is causing yours). Also, you don't need two loops to achieve this

For Each cell In rng.cells
    If IsNumeric(cell) Then cell.Value = CLng(cell.Value)
    With cell
        .FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, Formula1:="=1"
        .FormatConditions(.FormatConditions.Count).SetFirstPriority
        .FormatConditions(1).Interior.ColorIndex = 20
        .FormatConditions(1).StopIfTrue = False
    End With
Next cell


问:
ng2-translate in unit test returns keys instead of translations
When attempting to test a service method that uses a translation (which works fine outside of the test) I am receiving the key I pass in back from TranslateService instead of the translation.

Service being tested (simplified for easiest error recreation):

```<code>// The proper imports are here.

@Injectable()
export class SiteHeaderService {
  private _titleText: BehaviorSubject<string> = new BehaviorSubject("");
  public readonly titleText: Observable<string> = this._titleText.asObservable();

  constructor(private translateService: TranslateService) {}

  public updateTitleTextValue(text: string) {
    this._titleText.next(text);
  }

  public setSettingsPageTitle() {
    const title = this.translateService.instant("settings-page.page-name") || "";
    this.updateTitleTextValue(title);
  }
}
</code>```

The test itself:

```<code>import { TestBed, inject } from "@angular/core/testing";

import { SiteHeaderService } from "../site-header.service";

import { Http } from "@angular/http";
import { TranslateLoader, TranslateModule, TranslateStaticLoader } from "ng2-translate";

describe("SiteHeaderService", () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ TranslateModule.forRoot({
        provide: TranslateLoader,
        useFactory: (http: Http) => new TranslateStaticLoader(http, 'base/i18n', '.json'),
        deps: [ Http ]
      }) ],
      providers: [ SiteHeaderService ]
    });
  });

  it("should update the _titleText subject with the given value", inject([SiteHeaderService], (service: SiteHeaderService) => {
    service.updateTitleTextValue("Firefly was canceled too soon!");
    service.titleText.subscribe( title => { expect(title).toEqual("Firefly was canceled too soon!"); } )
  }));  // Passes

  it("should update all subjects to their 'settings page' state", inject([SiteHeaderService], (service: SiteHeaderService) => {
    service.setSettingsPageTitle();
    service.titleText.subscribe( title => { expect(title).toEqual("Settings"); } )
  }));  // Fails: Expected 'settings-page.page-name' to equal 'Settings'.

});
</code>```

Hopefully I did't miss any brace or semi-colon in the shortened code above, assuming I did not if you run this test the first one will pass, and the second one will return the failure:

```<code>Expected 'settings-page.page-name' to equal 'Settings'.
</code>```

答:
You should set the language you are using for translations. I had similar issue.

```<code>translate.use('en');
</code>```

solved my issue.

Body:
When attempting to test a service method that uses a translation (which works fine outside of the test) I am receiving the key I pass in back from TranslateService instead of the translation.

Service being tested (simplified for easiest error recreation):

// The proper imports are here.

@Injectable()
export class SiteHeaderService {
  private _titleText: BehaviorSubject<string> = new BehaviorSubject("");
  public readonly titleText: Observable<string> = this._titleText.asObservable();

  constructor(private translateService: TranslateService) {}

  public updateTitleTextValue(text: string) {
    this._titleText.next(text);
  }

  public setSettingsPageTitle() {
    const title = this.translateService.instant("settings-page.page-name") || "";
    this.updateTitleTextValue(title);
  }
}

The test itself:

import { TestBed, inject } from "@angular/core/testing";

import { SiteHeaderService } from "../site-header.service";

import { Http } from "@angular/http";
import { TranslateLoader, TranslateModule, TranslateStaticLoader } from "ng2-translate";

describe("SiteHeaderService", () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ TranslateModule.forRoot({
        provide: TranslateLoader,
        useFactory: (http: Http) => new TranslateStaticLoader(http, 'base/i18n', '.json'),
        deps: [ Http ]
      }) ],
      providers: [ SiteHeaderService ]
    });
  });

  it("should update the _titleText subject with the given value", inject([SiteHeaderService], (service: SiteHeaderService) => {
    service.updateTitleTextValue("Firefly was canceled too soon!");
    service.titleText.subscribe( title => { expect(title).toEqual("Firefly was canceled too soon!"); } )
  }));  // Passes

  it("should update all subjects to their 'settings page' state", inject([SiteHeaderService], (service: SiteHeaderService) => {
    service.setSettingsPageTitle();
    service.titleText.subscribe( title => { expect(title).toEqual("Settings"); } )
  }));  // Fails: Expected 'settings-page.page-name' to equal 'Settings'.

});

Hopefully I did't miss any brace or semi-colon in the shortened code above, assuming I did not if you run this test the first one will pass, and the second one will return the failure:

Expected 'settings-page.page-name' to equal 'Settings'.

Body:
You should set the language you are using for translations. I had similar issue.

translate.use('en');

solved my issue.