答:
Variable Length Arrays (VLA) is not a standard feature of C++. Moreover there is no need to declare one more array that to output words separated by spaces.

Your program never outputs the second (or last) word in the string if there are no spaces after it.

And the program includes leading spaces in words because it does not skip spaces when there are more than one space between words.

The program can look the following way as it is shown in the demonstrative program.

```<code>#include <iostream>

int main()
{
    char s[] = "Computer Science";

    for ( const char *p = s; *p != '\0'; )
    {
        while ( *p == ' ' || *p == '\t' ) ++p;

        if ( *p )
        {
            size_t i = 0;

            while ( *p and not ( *p == ' ' || *p == '\t' ) )
            {
                ++i;
                ++p;
            }

            std::cout.write( p - i, i ) << std::endl;
        }
    }

    return 0;
}
</code>```

The program output is

```<code>Computer
Science
</code>```

For the condition

```<code>*p == ' ' || *p == '\t'
</code>```

you could use a lambda expression. For example

```<code>auto is_blank = []( char c ) { return c == ' ' || c == '\t'; }
</code>```

and then in loops you could write for example

```<code>while ( is_blank( *p ) ) ++p;
</code>```

and

```<code>while ( *p and not is_blank( *p ) )
</code>```

Or you could use standard C function isspace declared in header <cstring> to check the condition.

The task can be done using standard algorithms and iterators. For example

```<code>#include <iostream>
#include <sstream>
#include <string>
#include <iterator>

int main()
{
    char s[] = "Computer Science";

    std::istringstream is( s );

    std::copy( std::istream_iterator<std::string>( is ),
               std::istream_iterator<std::string>(),
               std::ostream_iterator<std::string>( std::cout, "\n") );

    return 0;
}
</code>```

The program output is the same as above that is

```<code>Computer
Science
</code>```

Title: Printing word by word from a sentence

Body:
I have a sentence "Computer Science" as my input and I want to print Computer and Science seperately. I wrote a program in c++ but it is printing only "Computer". Could anyone help me find out why it is not printing both the words seperately?

int main()
{
    char string[]="Computer Science";
    int l;
    l=strlen(string);
    char begin[l];
    int i=0,ind=0;

        while(string[i]!='\0')
        {
            begin[ind]=string[i];
            if(string[i]==' ')
                {
                    begin[ind]=NULL;
                    cout<<begin<<"\n";

                    ind=0;
                    //ind++;
                    i++;
                }
            else
            {

                ind++;
                i++;
            }
        }

    return 0;
}

Body:
Variable Length Arrays (VLA) is not a standard feature of C++. Moreover there is no need to declare one more array that to output words separated by spaces.

Your program never outputs the second (or last) word in the string if there are no spaces after it.

And the program includes leading spaces in words because it does not skip spaces when there are more than one space between words.

The program can look the following way as it is shown in the demonstrative program.

#include <iostream>

int main()
{
    char s[] = "Computer Science";

    for ( const char *p = s; *p != '\0'; )
    {
        while ( *p == ' ' || *p == '\t' ) ++p;

        if ( *p )
        {
            size_t i = 0;

            while ( *p and not ( *p == ' ' || *p == '\t' ) )
            {
                ++i;
                ++p;
            }

            std::cout.write( p - i, i ) << std::endl;
        }
    }

    return 0;
}

The program output is

Computer
Science

For the condition

*p == ' ' || *p == '\t'

you could use a lambda expression. For example

auto is_blank = []( char c ) { return c == ' ' || c == '\t'; }

and then in loops you could write for example

while ( is_blank( *p ) ) ++p;

and

while ( *p and not is_blank( *p ) )

Or you could use standard C function isspace declared in header <cstring> to check the condition.

The task can be done using standard algorithms and iterators. For example

#include <iostream>
#include <sstream>
#include <string>
#include <iterator>

int main()
{
    char s[] = "Computer Science";

    std::istringstream is( s );

    std::copy( std::istream_iterator<std::string>( is ),
               std::istream_iterator<std::string>(),
               std::ostream_iterator<std::string>( std::cout, "\n") );

    return 0;
}

The program output is the same as above that is

Computer
Science


来源: stackexchange

问:
Why OpenCV return strange value for pixel intensity?
I've c++ and OpenCV 3.1 and i separated the RGB three channels with these code :

```<code>Mat src = imread("original_image.jpg",CV_LOAD_IMAGE_COLOR);
Mat bgr[3] , bluemat ;
split(src,bgr);
bluemat = bgr[0];
std::cout << "bluemat.at<int>(0,1); : " << bluemat.at<int>(0,1) << '\n';
</code>```

The strange thing is it print out a big number : 1415208581 , why is that ?

Isn't it suppose to be in 0-255 range ? why it is not ?

答:
(expanding comment for search)

A feature of openCV is that the cv::Mat image type is a very simple object based on the original C version of the library.

The cv::Mat contains a field giving the pixel type but the data is stored simply as a block of memory bytes. You can use this block of memory to store and access pixels however you want. It makes it very flexible and easy to link with other libraries, but means you need to manually keep track of what the data is.

So data.at<int>(0,0) will extract the first pixel as if the data was ints (whatever int is on your platform), data.at<uchar> (0,0) will get the first pixel as a byte (which is generally what you want).

ContentLicense: CC BY-SA 3.0

Body:
I've c++ and OpenCV 3.1 and i separated the RGB three channels with these code :

Mat src = imread("original_image.jpg",CV_LOAD_IMAGE_COLOR);
Mat bgr[3] , bluemat ;
split(src,bgr);
bluemat = bgr[0];
std::cout << "bluemat.at<int>(0,1); : " << bluemat.at<int>(0,1) << '\n';

The strange thing is it print out a big number : 1415208581 , why is that ?

Isn't it suppose to be in 0-255 range ? why it is not ?


问:
Disable default domain https://[project-id].appspot.com of Node JS on Google App Engine
I have deployed my Node JS app onto Google Cloud App Engine, and I can successfully add my custom domain for my app.

Let say my custom domain is example.com.

Now I can browse my app via example.com & www.example.com, it works as expected. But I find that I can still browse my app through the default domain.
https://[project-id].appspot.com

I want to disable the default domain, is it possible to do that?

答:
You cannot disable that default domain.  You would have to write a redirect script.  You can test for "appspot" in the request's HTTP_HOST, and test for "AppEngine-Google" in the request's HTTP_USER_AGENT, to determine if it is an internal request.

Also, internal functions, like cron jobs and task queues, run on that domain, so be careful what you do.  Task queues will fail given a 301.


问:
Extract first row from each text file in directory subtree
I have set of 5000 CSV files in tree directory structure.
Every file was first row denoting its enconding, then typical CSV content follows.

```<code>UTF-8
Key1,"Value 1",
Key2,"Value 2"
etc, etc...
</code>```

How can I quickly collect first row from each file in order to oversee set of their encodings?

I'm trying this with help of this answer but I don't clearly understand all syntax nuances of batch file variables so I am getting stuff like Echo is on.

```<code>for /R D:\resources\ %%f in (*.csv) do (
    set /p line1=<%%f
    echo %line1% >> out.txt
)
</code>```

If parts are executed individually (for single file), they work.

I was also trying single-liner

```<code>for /R D:\resources\ %f in (*.csv) do set /p line1=<%f & echo %line1% >> out.txt
</code>```

but this one put value collected from first file into output from each file.

答:
The main problem here is the lack of delayed expansion, which is needed when you write and read a variable within the same block of code; without it, you are reading the variable value present when parsing the block, so before it is executed. Here is the fixed code:

@echo off
copy NUL out.txt
setlocal EnableDelayedExpansion
for /R "D:\resources" %%g in ("*.csv") do (
    set "line1="
    < "%%~g" set /P line1=""
    >> "out.txt" echo(!line1!
)
endlocal
```

<p>In addition, I quoted all file/directory paths in order to avoid trouble with white-spaces or special characters in them. I also reversed the redirection syntax, because <code>echo(!line1! >> "out.txt"</code> also outputs the <kbd>SPACE</kbd> in front of <code>>></code>. The <code>(</code> instead of a <kbd>SPACE</kbd> behind <code>echo</code> looks odd but prevents <code>ECHO is {on|off}.</code> being returned when the read line in <code>!line1!</code> is empty.</p>

<p>By the way, you do not need to prepare an empty output file <code>out.txt</code> initially, you can simply redirect the whole <code>for</code> loop into the output files once using <code>></code>, given that you put a surrounding pair of parentheses:</p>

<pre class="lang-cmd prettyprint-override"><code>@echo off
setlocal EnableDelayedExpansion
> "out.txt" (
    for /R "D:\resources" %%g in (*.csv) do (
        set "line1="
        < "%%~g" set /P line1=""
        echo(!line1!
    )
)
endlocal
</code>```

To do the same directly in command prompt as a single-liner, try this:

cmd /V /C (for /R "D:\resources" %g in ("*.csv") do @(set "line1=" ^& ^< "%~g" set /P line1="" ^& echo(!line1!)) ^> "out.txt"
```

Body:
I have set of 5000 CSV files in tree directory structure.
Every file was first row denoting its enconding, then typical CSV content follows.

UTF-8
Key1,"Value 1",
Key2,"Value 2"
etc, etc...

How can I quickly collect first row from each file in order to oversee set of their encodings?

I'm trying this with help of this answer but I don't clearly understand all syntax nuances of batch file variables so I am getting stuff like Echo is on.

for /R D:\resources\ %%f in (*.csv) do (
    set /p line1=<%%f
    echo %line1% >> out.txt
)

If parts are executed individually (for single file), they work.

I was also trying single-liner

for /R D:\resources\ %f in (*.csv) do set /p line1=<%f & echo %line1% >> out.txt

but this one put value collected from first file into output from each file.

Body:
The main problem here is the lack of delayed expansion, which is needed when you write and read a variable within the same block of code; without it, you are reading the variable value present when parsing the block, so before it is executed. Here is the fixed code:

@echo off
copy NUL out.txt
setlocal EnableDelayedExpansion
for /R "D:\resources" %%g in ("*.csv") do (
    set "line1="
    < "%%~g" set /P line1=""
    >> "out.txt" echo(!line1!
)
endlocal

In addition, I quoted all file/directory paths in order to avoid trouble with white-spaces or special characters in them. I also reversed the redirection syntax, because echo(!line1! >> "out.txt" also outputs the SPACE in front of >>. The ( instead of a SPACE behind echo looks odd but prevents ECHO is {on|off}. being returned when the read line in !line1! is empty.

By the way, you do not need to prepare an empty output file out.txt initially, you can simply redirect the whole for loop into the output files once using >, given that you put a surrounding pair of parentheses:

@echo off
setlocal EnableDelayedExpansion
> "out.txt" (
    for /R "D:\resources" %%g in (*.csv) do (
        set "line1="
        < "%%~g" set /P line1=""
        echo(!line1!
    )
)
endlocal

To do the same directly in command prompt as a single-liner, try this:

cmd /V /C (for /R "D:\resources" %g in ("*.csv") do @(set "line1=" ^& ^< "%~g" set /P line1="" ^& echo(!line1!)) ^> "out.txt"


问:
bash: oneliner to convert hex numbers in output to decimals
Does anyone know of a oneliner into which some output can be piped into in bash, to match and convert all occurrences of hexadecimal numbers and leave all other text untouched?

maybe match rather arbitrary output which could be a hexadecimal
shall somehow converted through a regexp, i.e.
/(0x)?[0-9a-fA-F]{5,}/

a leading 0x shall not be neccessary, but
also be handled properly

there can be false-positives, if not
specifying a minimum length of the numbers, but that should not be an
issue

the goal is to find solution which can be used with as much possible outputs having hex numbers in them

It should work on output like:

```<code>ssg sjas # cat /proc/net/stat/arp_cache | column -t
entries   allocs    destroys  hash_grows  lookups   hits      res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
0000000d  00000006  00000004  00000000    0000c3b9  0000c35e  00000000    00000000          00000000          0000965b          00000000        00000000             00000000
0000000d  0000000d  00000004  00000001    00000000  00000000  00000000    00000000          00000000          000007cd          00000000        00000000             00000000
0000000d  00000008  00000008  00000001    00000000  00000000  00000000    00000000          00000000          000006e0          00000000        00000000             00000000
0000000d  0000000a  00000008  00000000    00000000  00000000  00000002    00000000          00000000          00000704          00000000        00000000             00000000
</code>```

Most other questions on stackoverflow only tackle the issue of how to convert single numbers between number systems, only do the conversion for a specified column or completely kill the formatting being present in the input.

Desired output should look like: (column -t is there anyway, it really just need to replace the hex values it can find, and adding leading zeroes to a printf statement is also not a problem)

```<code>ssg sjas # cat /proc/net/stat/arp_cache | perl -pe 's/(?:0x)?[0-9a-f]{5,}/hex($&)/ge' | column -t
entries  allocs  destroys  hash_grows  lookups  hits   res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
13       6       4         0           50105    50014  0           0                 0                 38491             0               0                    0
13       13      4         1           0        0      0           0                 0                 1997              0               0                    0
13       8       8         1           0        0      0           0                 0                 1760              0               0                    0
13       10      8         0           0        0      2           0                 0                 1796              0               0                    0
</code>```

I could not find a short viable/reliable solution via sed/awk/perl in the last two hours, so I came here for help.

答:
with GNU awk:

```<code>awk 'BEGIN{IFS=OFS="\t"}NR==1{print $0}{for(i=1;i<=NF;i++) if(i!=NF){printf "%s%c",strtonum("0x"$i),OFS}else{printf "%d\n",strtonum("0x"$i)}}' filename
</code>```

Body:
Does anyone know of a oneliner into which some output can be piped into in bash, to match and convert all occurrences of hexadecimal numbers and leave all other text untouched?

maybe match rather arbitrary output which could be a hexadecimal
shall somehow converted through a regexp, i.e.
/(0x)?[0-9a-fA-F]{5,}/

a leading 0x shall not be neccessary, but
also be handled properly

there can be false-positives, if not
specifying a minimum length of the numbers, but that should not be an
issue

the goal is to find solution which can be used with as much possible outputs having hex numbers in them

It should work on output like:

ssg sjas # cat /proc/net/stat/arp_cache | column -t
entries   allocs    destroys  hash_grows  lookups   hits      res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
0000000d  00000006  00000004  00000000    0000c3b9  0000c35e  00000000    00000000          00000000          0000965b          00000000        00000000             00000000
0000000d  0000000d  00000004  00000001    00000000  00000000  00000000    00000000          00000000          000007cd          00000000        00000000             00000000
0000000d  00000008  00000008  00000001    00000000  00000000  00000000    00000000          00000000          000006e0          00000000        00000000             00000000
0000000d  0000000a  00000008  00000000    00000000  00000000  00000002    00000000          00000000          00000704          00000000        00000000             00000000

Most other questions on stackoverflow only tackle the issue of how to convert single numbers between number systems, only do the conversion for a specified column or completely kill the formatting being present in the input.

Desired output should look like: (column -t is there anyway, it really just need to replace the hex values it can find, and adding leading zeroes to a printf statement is also not a problem)

ssg sjas # cat /proc/net/stat/arp_cache | perl -pe 's/(?:0x)?[0-9a-f]{5,}/hex($&)/ge' | column -t
entries  allocs  destroys  hash_grows  lookups  hits   res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
13       6       4         0           50105    50014  0           0                 0                 38491             0               0                    0
13       13      4         1           0        0      0           0                 0                 1997              0               0                    0
13       8       8         1           0        0      0           0                 0                 1760              0               0                    0
13       10      8         0           0        0      2           0                 0                 1796              0               0                    0

I could not find a short viable/reliable solution via sed/awk/perl in the last two hours, so I came here for help.

Body:
with GNU awk:

awk 'BEGIN{IFS=OFS="\t"}NR==1{print $0}{for(i=1;i<=NF;i++) if(i!=NF){printf "%s%c",strtonum("0x"$i),OFS}else{printf "%d\n",strtonum("0x"$i)}}' filename


问:
Using Node.JS statements inside of PEG.js grammar
In my grammar rule i need to check whether directory exists.

However, seems i'm unable to use Node.JS-specific code in grammar JS.

Is it correct? Any workaround?

Thanks and sorry if a question was a silly one :)

Example grammar:

```<code>{
    var fs = require('fs');

    function isDirectoryExists(dir) {
        return fs.existsSync(path);
    }
}

Main = "stub"
</code>```

Output from the PEG.js online playground:

```<code>require is not defined
</code>```

答:
Node.JS-specific code perfectly works in Node environment on the host.

But not in my browser, there is no Node there.

So, PEG.JS online playground can execute only vanilla JavaScript code.

But this is a limitation of browser, not a PEG.js.

Body:
In my grammar rule i need to check whether directory exists.

However, seems i'm unable to use Node.JS-specific code in grammar JS.

Is it correct? Any workaround?

Thanks and sorry if a question was a silly one :)

Example grammar:

{
    var fs = require('fs');

    function isDirectoryExists(dir) {
        return fs.existsSync(path);
    }
}

Main = "stub"

Output from the PEG.js online playground:

require is not defined


问:
How to generate correlated random numbers?
I want to generate two random integers in python, which are correlated.
Let's say that integer n is a random integer between 0 and 10, and I want integer q to be in the same range but be not more that n. Any suggestions?

```<code>from __future__ import division

from random import randint

population = randint(100, 1000)
number_of_successes = randint(1, 100)
number_of_fails = population-number_of_successes
probability = number_of_successes/population
</code>```

答:
You can use the first variable as the second parameter</p>

```<code>from __future__ import division

from random import randint

population = randint(0 ,1000)
number_of_successes = randint(0 , population)
number_of_fails = population-number_of_successes
probability = number_of_successes/population
</code>```

Body:
I want to generate two random integers in python, which are correlated.
Let's say that integer n is a random integer between 0 and 10, and I want integer q to be in the same range but be not more that n. Any suggestions?

from __future__ import division

from random import randint

population = randint(100, 1000)
number_of_successes = randint(1, 100)
number_of_fails = population-number_of_successes
probability = number_of_successes/population

Body:
You can use the first variable as the second parameter

from __future__ import division

from random import randint

population = randint(0 ,1000)
number_of_successes = randint(0 , population)
number_of_fails = population-number_of_successes
probability = number_of_successes/population


问:
Table of Contents that Straddles Multiple Jupyter Notebooks
I have some huge Jupyter notebooks, each with lots of HTML links between sections, and some have gotten so big that they run really slowly now, but I'm reluctant to break them up because I find the links and cross-references very useful.

Is there any way to create a TOC (table of contents) that references multiple Jupyter notebooks?

That would allow me to keep smaller notebooks while retaining links between the sections.

答:
Just reference the notebook name (using a relative path if needed) with the bookmark in the linked notebook.

[My content's text](notebook2.ipynb#bookmark)


问:
How to dispatch a Redux action with a timeout?
I have an action that updates the notification state of my application. Usually, this notification will be an error or info of some sort. I need to then dispatch another action after 5 seconds that will return the notification state to the initial one, so no notification. The main reason behind this is to provide functionality where notifications disappear automatically after 5 seconds.

I had no luck with using setTimeout and returning another action and can't find how this is done online. So any advice is welcome.

答:
Redux itself is a pretty verbose library, and for such stuff you would have to use something like Redux-thunk, which will give a dispatch function, so you will be able to dispatch closing of the notification after several seconds.

I have created a library to address issues like verbosity and composability, and your example will look like the following:

```<code>import { createTile, createSyncTile } from 'redux-tiles';
import { sleep } from 'delounce';

const notifications = createSyncTile({
  type: ['ui', 'notifications'],
  fn: ({ params }) => params.data,
  // to have only one tile for all notifications
  nesting: ({ type }) => [type],
});

const notificationsManager = createTile({
  type: ['ui', 'notificationManager'],
  fn: ({ params, dispatch, actions }) => {
    dispatch(actions.ui.notifications({ type: params.type, data: params.data }));
    await sleep(params.timeout || 5000);
    dispatch(actions.ui.notifications({ type: params.type, data: null }));
    return { closed: true };
  },
  nesting: ({ type }) => [type],
});
</code>```

So we compose sync actions for showing notifications inside async action, which can request some info the background, or check later whether the notification was closed manually.

ContentLicense: CC BY-SA 4.0

Body:
Redux itself is a pretty verbose library, and for such stuff you would have to use something like Redux-thunk, which will give a dispatch function, so you will be able to dispatch closing of the notification after several seconds.

I have created a library to address issues like verbosity and composability, and your example will look like the following:

import { createTile, createSyncTile } from 'redux-tiles';
import { sleep } from 'delounce';

const notifications = createSyncTile({
  type: ['ui', 'notifications'],
  fn: ({ params }) => params.data,
  // to have only one tile for all notifications
  nesting: ({ type }) => [type],
});

const notificationsManager = createTile({
  type: ['ui', 'notificationManager'],
  fn: ({ params, dispatch, actions }) => {
    dispatch(actions.ui.notifications({ type: params.type, data: params.data }));
    await sleep(params.timeout || 5000);
    dispatch(actions.ui.notifications({ type: params.type, data: null }));
    return { closed: true };
  },
  nesting: ({ type }) => [type],
});

So we compose sync actions for showing notifications inside async action, which can request some info the background, or check later whether the notification was closed manually.


问:
Pandas : plot data frame object with marker?
This is my pandas DataFrame.

```<code>   value  action
0      1       0
1      2       1
2      3       1
3      4       1
4      3       0
5      2       1
6      5       0
</code>```

What I want to do is mark value as o if action=0, x if action=1.

So, the plot marker should be like this:
o x x x o x o

But have no idea how to do this...

Need your helps. Thanks.

答:
Consider the following approach:

```<code>plt.plot(df.index, df.value, '-X', markevery=df.index[df.action==1].tolist())
plt.plot(df.index, df.value, '-o', markevery=df.index[df.action==0].tolist())
</code>```

Result:

alternative solution:

```<code>plt.plot(df.index, df.value, '-')
plt.scatter(df.index[df.action==0], df.loc[df.action==0, 'value'],
            marker='o', s=100, c='green')
plt.scatter(df.index[df.action==1], df.loc[df.action==1, 'value'],
            marker='x', s=100, c='red')
</code>```

Result:

Body:
This is my pandas DataFrame.

   value  action
0      1       0
1      2       1
2      3       1
3      4       1
4      3       0
5      2       1
6      5       0

What I want to do is mark value as o if action=0, x if action=1.

So, the plot marker should be like this:
o x x x o x o

But have no idea how to do this...

Need your helps. Thanks.

Body:
Consider the following approach:

plt.plot(df.index, df.value, '-X', markevery=df.index[df.action==1].tolist())
plt.plot(df.index, df.value, '-o', markevery=df.index[df.action==0].tolist())

Result:

alternative solution:

plt.plot(df.index, df.value, '-')
plt.scatter(df.index[df.action==0], df.loc[df.action==0, 'value'],
            marker='o', s=100, c='green')
plt.scatter(df.index[df.action==1], df.loc[df.action==1, 'value'],
            marker='x', s=100, c='red')

Result:


问:
Count number of rows in sheet then subtract on a Google spreadsheet with Google Apps Script
I'm trying to set dynamic getRange function, so I use getRange(row, column, numRows, numColumns) function and my example looks like:

```<code>var range = sheet.getRange(7,11,sheet.getLastRow(),sheet.getLastColumn());
</code>```

And the result is ex. sheet.getRange(7,11,200,30);

But when I want to use this range, for example, to put some data to the sheet, function doesn't use starting point (startRow - 7, startColumn - 11). So I tried subtract it from getLastRow() and getLastColumn() and it works but gives me decimal number (example lastRow = 193.0) and the function crushed

```<code>function myFunction() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName('Arkusz1');
  var lastRow = sheet.getLastRow();
  var lastColumn = sheet.getLastColumn() - 2;
  var lastColumnParse = parseInt(lastColumn, 10);
  var range = sheet.getRange(1,1,lastRow, lastColumn);
  var formatting = range.getBackgrounds();
  var data = range.getValues();

  for(var y = 1; y < data.length; ++y){
    var message = '';

    for(var x = 0; x < data[y].length; x++){

      if(formatting[y][x] == '#ffff00'){
        var header = data[0][x];
        message += ' ' + header + ' - ' + data[y][x] + ' zł, ' + lastRow + ' ' + lastColumn;
      };

      data[y][lastColumn] = message
    }
  }

  range.setValues(data);
}
</code>```

And the error message is:

The message said that wide range is not correct. Inputted 7 but it should be 6.

In the console, we can see, that x = 7.0, not 6.

I cannot find the mistake. Please help me.

答: The problem is that in JavaScript/Google Apps Script the array index is 0 (zero) based, and row/columns indexes are 1 (one) based. In other words, the length for an array with seven elements is seven but the index of the last element is six.

Body:
I'm trying to set dynamic getRange function, so I use getRange(row, column, numRows, numColumns) function and my example looks like:

var range = sheet.getRange(7,11,sheet.getLastRow(),sheet.getLastColumn());

And the result is ex. sheet.getRange(7,11,200,30);

But when I want to use this range, for example, to put some data to the sheet, function doesn't use starting point (startRow - 7, startColumn - 11). So I tried subtract it from getLastRow() and getLastColumn() and it works but gives me decimal number (example lastRow = 193.0) and the function crushed

function myFunction() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName('Arkusz1');
  var lastRow = sheet.getLastRow();
  var lastColumn = sheet.getLastColumn() - 2;
  var lastColumnParse = parseInt(lastColumn, 10);
  var range = sheet.getRange(1,1,lastRow, lastColumn);
  var formatting = range.getBackgrounds();
  var data = range.getValues();

  for(var y = 1; y < data.length; ++y){
    var message = '';

    for(var x = 0; x < data[y].length; x++){

      if(formatting[y][x] == '#ffff00'){
        var header = data[0][x];
        message += ' ' + header + ' - ' + data[y][x] + ' zł, ' + lastRow + ' ' + lastColumn;
      };

      data[y][lastColumn] = message
    }
  }

  range.setValues(data);
}

And the error message is:

The message said that wide range is not correct. Inputted 7 but it should be 6.

In the console, we can see, that x = 7.0, not 6.

I cannot find the mistake. Please help me.


问:
Django autocomplete light
model.py:

```<code>class Reservation(models.Model):
    company = models.ForeignKey(GuestContact, on_delete=models.PROTECT)

class GuestContact(models.Model):
    company = models.CharField(max_lenght=30)
    last_name = models.CharField(max_lenght=30)
    first_name = models.CharField(max_lenght=30)
</code>```

form.py.

```<code>class ReservationForm(ModelForm):

    class Meta:
        model = Reservation
        fields = '__all__'
        widgets = {
            'company': autocomplete.ModelSelect2()
    }
</code>```

views.py

```<code>class GuestContactAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):

        qs = GuestContact.objects.all()

        if self.q:
            qs = qs.filter(name__istartswith=self.q)

        return qs
</code>```

How i can add to autocomplete queryset only not empty "company" field ?
Can you help me ?

答:
Try return qs.exclude(company='').exclude(company__isnull=True) instead of return qs.

What's more, you probably wanted qs = qs.filter(company__istartswith=self.q) instead of qs = qs.filter(name__istartswith=self.q) (based on forms.py)

so I think that your views.py code should be:

```<code>class GuestContactAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):

        qs = GuestContact.objects.all()

        if self.q:
            qs = qs.filter(company__istartswith=self.q)

        return qs.exclude(company='').exclude(company__isnull=True)
</code>```

Title: Django autocomplete light

Body:
model.py:

class Reservation(models.Model):
    company = models.ForeignKey(GuestContact, on_delete=models.PROTECT)

class GuestContact(models.Model):
    company = models.CharField(max_lenght=30)
    last_name = models.CharField(max_lenght=30)
    first_name = models.CharField(max_lenght=30)

form.py.

class ReservationForm(ModelForm):

    class Meta:
        model = Reservation
        fields = '__all__'
        widgets = {
            'company': autocomplete.ModelSelect2()
    }

views.py

class GuestContactAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):

        qs = GuestContact.objects.all()

        if self.q:
            qs = qs.filter(name__istartswith=self.q)

        return qs

How i can add to autocomplete queryset only not empty "company" field ?
Can you help me ?

Body:
Try return qs.exclude(company='').exclude(company__isnull=True) instead of return qs.

What's more, you probably wanted qs = qs.filter(company__istartswith=self.q) instead of qs = qs.filter(name__istartswith=self.q) (based on forms.py)

so I think that your views.py code should be:

class GuestContactAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):

        qs = GuestContact.objects.all()

        if self.q:
            qs = qs.filter(company__istartswith=self.q)

        return qs.exclude(company='').exclude(company__isnull=True)


问:
How do I add a column of incrementing values to cmdlet output?
Suppose I call Get-Service and want to assign a new column ID with the cmdlet output that prints incrementing integers so that:

```<code>ID  Status Name                            DisplayName
--  ------ ----                            -----------
 0 Running AdobeARMservice                 Adobe Acrobat Update Service
 1 Stopped AeLookupSvc                     Application Experience
 2 Stopped ALG                             Application Layer Gateway Service
</code>```

I'm trying to use Select-Object right now to add this column, but I don't quite understand how to iterate a variable in this sort of expression.  Here's what I've got:

```<code>Get-Service |
Select-Object @{ Name = "ID" ; Expression= {  } }, Status, Name, DisplayName |
Format-Table -Autosize
</code>```

Is there a way to iterate integers within Expression= {  }, or am I going about this problem the wrong way?

答:
I asked the same question a different way and got the following answer

```<code>$x = 10
Get-Service |
Select-Object @{ Name = "ID" ; Expression={ (([ref]$x).Value++) }}, Status, Name, DisplayName | Format-Table -Autosize
</code>```

It wasn't at all clear to me that the expression is being invoked within Select-Object's scope, not the pipe's.  The [ref] qualifier bumps the increment's result up to the pipe's scope achieving the same result as explicitly specifying the variable as global.

Body:
Suppose I call Get-Service and want to assign a new column ID with the cmdlet output that prints incrementing integers so that:

ID  Status Name                            DisplayName
--  ------ ----                            -----------
 0 Running AdobeARMservice                 Adobe Acrobat Update Service
 1 Stopped AeLookupSvc                     Application Experience
 2 Stopped ALG                             Application Layer Gateway Service

I'm trying to use Select-Object right now to add this column, but I don't quite understand how to iterate a variable in this sort of expression.  Here's what I've got:

Get-Service |
Select-Object @{ Name = "ID" ; Expression= {  } }, Status, Name, DisplayName |
Format-Table -Autosize

Is there a way to iterate integers within Expression= {  }, or am I going about this problem the wrong way?

Body:
I asked the same question a different way and got the following answer

$x = 10
Get-Service |
Select-Object @{ Name = "ID" ; Expression={ (([ref]$x).Value++) }}, Status, Name, DisplayName | Format-Table -Autosize

It wasn't at all clear to me that the expression is being invoked within Select-Object's scope, not the pipe's.  The [ref] qualifier bumps the increment's result up to the pipe's scope achieving the same result as explicitly specifying the variable as global.


问:
How many variables are too much for a class?
I want to see if anyone has a better design for a class (class as in OOP) I am writing. We have a script that puts shared folder stats in a CSV file. I am reading that in and putting it in a Share class.

My boss wants to know information like:

Total Number of Files

Total Size of Files

Number of Office Files

Size of Office Files

Number of Exe Files

Size of Exe Files

etc ....

I have a class with variables like $numOfficeFiles, $sizeOfficeFiles, etc. with a ton of get/set methods. Isn't there a better way to do this? What is the general rule if you have a class with a lot of variables/properties?

I think of this as a language agnostic question, but if it matters, I am using PHP.

答:
I think the answer is "there's no such thing as too many variables."

But then, if this data is going to be kept for a while, you might just want to put it in a database and make your functions calls to the database.

I assume you don't want to recalculate all these values every time you're asked for them.

OwnerDisplayName: Ben

LastEditorDisplayName: mmyers

ContentLicense: CC BY-SA 2.5


问:
Unit testing thread-based code? Forcing a race condition
In using my application, I've stumbled upon a race condition in some code that uses a NSOperationQueue to run tasks asynchronously following user-triggered events.  I know how to fix the race condition, since it's a stupid design error that I won't delve into, but I'd like to prove the bug with a test case (so that it doesn't come back during optimizing/refactoring further down the line).  This has me stumped.  How does one go about testing something that is multi-threaded, especially when the aim of the test is to generate a race condition?

Does anyone have any links to reference material I can refer to when it comes to dealing with threads and unit testing?  I'm particularly interested in race condition generation.

答:
You have to make sure that the sequence of events causing the race condition actually arises during testing. For that, you need to affect the thread interleaving inside the test case.

You can achieve that with additional (conditional) synchronization, or, (simpler and less reliable) additional timers. Put some sleep() calls into the critical sections to make sure they run long enough for the other thread to arrive in the undesirable state. When you have that working, replace the sleep calls with explicit synchronization (i.e. block one thread until the other one actually acknowledges to have arrived).

Then make this all conditional on a global flag that is set by the test case.


问:
Java Stream digits to number
I am struggling to get a functioning code for this.
I have a stream of digits between 0 and 9. I want to get a BigInteger out of those digits.
Example:

```<code>IntStream digits = IntStream.of(1, 2, 3) // should get me a Biginteger 123.
IntStream digits = IntStream.of(9, 5, 3) // should get me a Biginteger 953.
</code>```

Is there a way to concatenate all elements out of the stream?
Here is my basic idea:

```<code>digits.forEach(element -> result=result.concat(result, element.toString()));
</code>```

答:
Here is the solution by StreamEx

```<code>BigInteger res = new BigInteger(IntStreamEx.of(1, 2, 3).joining(""));
</code>```

Or maybe we should remove the prefix '0' if that could happen

```<code>BigInteger res = new BigInteger(IntStreamEx.of(0, 1, 2).dropWhile(i -> i == 0).joining(""));
</code>```

And maybe we should add the check for empty stream:

```<code>String str = IntStreamEx.of(0, 1, 2).dropWhile(i -> i == 0).joining("")
BigInteger res = str.length() == 0 ? BigInteger.ZERO : new BigInteger(str);
</code>```

Title: Java Stream digits to number

Body:
I am struggling to get a functioning code for this.
I have a stream of digits between 0 and 9. I want to get a BigInteger out of those digits.
Example:

IntStream digits = IntStream.of(1, 2, 3) // should get me a Biginteger 123.
IntStream digits = IntStream.of(9, 5, 3) // should get me a Biginteger 953.

Is there a way to concatenate all elements out of the stream?
Here is my basic idea:

digits.forEach(element -> result=result.concat(result, element.toString()));

Body:
Here is the solution by StreamEx

BigInteger res = new BigInteger(IntStreamEx.of(1, 2, 3).joining(""));

Or maybe we should remove the prefix '0' if that could happen

BigInteger res = new BigInteger(IntStreamEx.of(0, 1, 2).dropWhile(i -> i == 0).joining(""));

And maybe we should add the check for empty stream:

String str = IntStreamEx.of(0, 1, 2).dropWhile(i -> i == 0).joining("")
BigInteger res = str.length() == 0 ? BigInteger.ZERO : new BigInteger(str);


问:
Div has a margin even with margin:0 and padding:0;
I have four divs on my webpage; a header, menu, content and footer. In IE, everything displays correctly nested, but in Chrome there is a small gap between the footer and the menu and content divs. I have tried putting

```<code>margin:0;
padding:0;
</code>```

on everything but there is no change. Here are some images of my problem:

In Chrome (incorrect display):

In IE (correct display):

Why is this happening? Here is my HTML:

```<code><?php include "headermysql.php"?>
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<script type = "text/javascript">
function to_login_page()
{
window.location.assign("http://127.0.0.1/sxp/login.php");
}
function to_signup_page()
{
window.location.assign("http://127.0.0.1/sxp/signup.php");
}
</script>
<link rel = "stylesheet" type = "text/css" href = "textstyles.css">
</head>
<body>
<?php include "headerhtml.php";?>
<div class = "menu">
<p>menu</p>
</div>
<div class = "content">
<?php
//irrelevant PHP
?>
<a class = "main" href = "post.php">Post new topic</a>
</div>
<div class = "footer">
<p class = "footer">Copyright Stafford King 2013</p>
</div>
</body>
</html>
</code>```

And here is my CSS:

```<code>.error
{
font-weight:bold;
font-family:Courier New;
color:red;
text-align:left;
font-size:20px;
margin:0;
padding:0;
}
.main
{
font-family:Courier New;
font-size:15px;
text-align:left;
color:black;
margin:0;
padding:0;
}
a.main
{
font-family:Courier New;
font-size:15px;
text-align:left;
color:#000066;
margin:0;
padding:0;
}
a.searchresult
{
font-family:Courier New;
font-size:15px;
text-align:center;
color:#000066;
margin:0;
padding:0;
}
p.footer
{
text-align:center;
font-family:Courier New;
font-size:15px;
color:#000000;
}
div.header
{
height:150px;
background-color:#008AC8;
margin:0;
padding:0;
}
div.menu
{
float:left;
width:200px;
height:800px;
background-color:#64BCE2;
margin:0;
padding:0;
}
div.content
{
height:800px;
background-color:#F9F9D9;
margin:0;
padding:0;
}
div.footer
{
height:20px;
background-color:#008AC8;
margin:0;
padding:0;
}
h2.main
{
font-family:Cambria;
font-size:35px;
color:black;
text-align:center;
margin:0;
padding:0;
}
.searchresult
{
font-family:Courier New;
font-size:15px;
text-align:center;
color:black;
margin:0;
padding:0;
}
body{margin:0;}
</code>```

Sorry for the long post. All help is appreciated.

答:
The font always seem to cause this problem but I'm sure if you set this, it will take care of it </p>

```<code>line-height: 0px;
</code>```

Body:
I have four divs on my webpage; a header, menu, content and footer. In IE, everything displays correctly nested, but in Chrome there is a small gap between the footer and the menu and content divs. I have tried putting

margin:0;
padding:0;

on everything but there is no change. Here are some images of my problem:

In Chrome (incorrect display):

In IE (correct display):

Why is this happening? Here is my HTML:

<?php include "headermysql.php"?>
<!DOCTYPE html>

<title>Home</title>

<link rel = "stylesheet" type = "text/css" href = "textstyles.css">

<?php include "headerhtml.php";?>

menu

<?php
//irrelevant PHP
?>
Post new topic

Copyright Stafford King 2013

And here is my CSS:

.error
{
font-weight:bold;
font-family:Courier New;
color:red;
text-align:left;
font-size:20px;
margin:0;
padding:0;
}
.main
{
font-family:Courier New;
font-size:15px;
text-align:left;
color:black;
margin:0;
padding:0;
}
a.main
{
font-family:Courier New;
font-size:15px;
text-align:left;
color:#000066;
margin:0;
padding:0;
}
a.searchresult
{
font-family:Courier New;
font-size:15px;
text-align:center;
color:#000066;
margin:0;
padding:0;
}
p.footer
{
text-align:center;
font-family:Courier New;
font-size:15px;
color:#000000;
}
div.header
{
height:150px;
background-color:#008AC8;
margin:0;
padding:0;
}
div.menu
{
float:left;
width:200px;
height:800px;
background-color:#64BCE2;
margin:0;
padding:0;
}
div.content
{
height:800px;
background-color:#F9F9D9;
margin:0;
padding:0;
}
div.footer
{
height:20px;
background-color:#008AC8;
margin:0;
padding:0;
}
h2.main
{
font-family:Cambria;
font-size:35px;
color:black;
text-align:center;
margin:0;
padding:0;
}
.searchresult
{
font-family:Courier New;
font-size:15px;
text-align:center;
color:black;
margin:0;
padding:0;
}
body{margin:0;}

Sorry for the long post. All help is appreciated.

Body:
The font always seem to cause this problem but I'm sure if you set this, it will take care of it

line-height: 0px;


问:
regular expression to extract the user agent and browser from the text file

Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0

"Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B117 Safari/6531.22.7 (compatible; Googlebot-Mobile/2.1; +http://www.google.com/bot.html)"
http://www.google.com/m?q=kuhas&client=ms-opera-mini&channel=new    Opera/9.80 (Series 60; Opera Mini/6.5.27309/27.1382; U; en) Presto/2.8.119 Version/11.10

Body:
\d+\.\d+\.\d+\.\d+)[\s-]+(?\[.*\])[\s"]+(?\w+)\s+(?[^\s]+)\s+(?[^\s]+)[\s"]+(?\d+)\s+(?\d+)([ -]+(?[.*)]))?/m';
 $str = '115.241.154.148    -   -   [31/Mar/2012:18:09:53   +0530]  GET / HTTP/1.1  200 1131    -   Mozilla/4.0 (compatible; MSIE 6.0; Windows 98)
117.199.7.144   -   -   [31/Mar/2012:19:32:37   +0530]  GET / HTTP/1.1  304 -   -   Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0
66.249.69.138   -   -   [31/Mar/2012:19:35:31   +0530]  GET /robots.txt HTTP/1.1    404 613 -   Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
66.249.69.138   -   -   [31/Mar/2012:19:35:31   +0530]  GET /kuhsonline/main/head.php HTTP/1.1  200 1157    -   "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B117 Safari/6531.22.7 (compatible; Googlebot-Mobile/2.1; +http://www.google.com/bot.html)"
180.76.5.182    -   -   [31/Mar/2012:19:38:21   +0530]  GET / HTTP/1.1  200 1131    -   Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)';

preg_match_all($re, $str, $output, PREG_SET_ORDER, 0);

var_dump($output);
 ?>


问:
An untypical config with JSON using Spring Boot Rest API
I am sending the following JSON to the backend (with header content-type json):

```<code>{
    "userid": 1,
    "gamedata": {
        "completedMissions": 1,
        "points": 40
    }
}
</code>```

At backend, my controller is implemented in the following way:

```<code>@RestController
public class PlayerGameDataController {

    @RequestMapping(method = RequestMethod.POST, consumes="application/json", produces="application/json", value = "/player/syncgamedata")
    @ResponseBody public ResponseEntity<PlayerGameData> syncUser(@RequestBody HashMap map) {
        String data = map.get("gamedata").toString();
        ...
    }

}
</code>```

However the value of gamedata is being replaced by:

```<code>completedMissions=1
points=40
</code>```

I'd like to know why this is happening...

How can I solve this?

答:
The map.get("gamedata") seems to return another Map with has the String representation you are given.

```<code>{completedMissions=1,points=40}
</code>```

If you expect a Map, do not invoke toString() on the map value, cast* to a Map and go it further.

My problem is that Spring replaced : by = and removed ".

Yes, but it's the expected behavior. A Spring deserialiser can parse a JSON request like a Map<String, Map<String, ...>> and it is allowed to do so, cause you did not specify what you want by HashMap which simply is HashMap<Object, Object>.

There are two options here:

Trying to pass a Map<String, Map<String, Integer> which clearly tells Spring what the structure actually is.

Presenting it as a Map<String, JsonNode> since the JsonNode#toString returns an unformatted JSON representation.

*It's not OK you are using a raw type of the HashMap as a method parameter. Consider working with the generic superclass Map<String, Map<String, Integer> or providing your own class with a similar structure.

Body:
I am sending the following JSON to the backend (with header content-type json):

{
    "userid": 1,
    "gamedata": {
        "completedMissions": 1,
        "points": 40
    }
}

At backend, my controller is implemented in the following way:

@RestController
public class PlayerGameDataController {

    @RequestMapping(method = RequestMethod.POST, consumes="application/json", produces="application/json", value = "/player/syncgamedata")
    @ResponseBody public ResponseEntity<PlayerGameData> syncUser(@RequestBody HashMap map) {
        String data = map.get("gamedata").toString();
        ...
    }

}

However the value of gamedata is being replaced by:

completedMissions=1
points=40

I'd like to know why this is happening...

How can I solve this?

Body:
The map.get("gamedata") seems to return another Map with has the String representation you are given.

{completedMissions=1,points=40}

If you expect a Map, do not invoke toString() on the map value, cast* to a Map and go it further.

My problem is that Spring replaced : by = and removed ".

Yes, but it's the expected behavior. A Spring deserialiser can parse a JSON request like a Map<String, Map<String, ...>> and it is allowed to do so, cause you did not specify what you want by HashMap which simply is HashMap<Object, Object>.

There are two options here:

Trying to pass a Map<String, Map<String, Integer> which clearly tells Spring what the structure actually is.

Presenting it as a Map<String, JsonNode> since the JsonNode#toString returns an unformatted JSON representation.

*It's not OK you are using a raw type of the HashMap as a method parameter. Consider working with the generic superclass Map<String, Map<String, Integer> or providing your own class with a similar structure.


问:
How to connect points in python ax.scatter 3D plot
I have a 3D plot in python which I made using ax.scatter(x,y,z,c='r',s=100)
from the

```<code>import matplotlib.pyplot as plt

import pylab

from mpl_toolkits.mplot3d import Axes3D.
</code>```

I want to connect my points with a line. I know you can do it with marker='-o' but that works only in 2D for me and not 3D. Can anyone help ?
Thank you.

答:
Scatter does not allow for connecting points. The argument marker='-o' only works for plot, not for scatter. That is true for 2D and 3D. But of course you can use a scatter and a plot

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

ax = plt.gca(projection="3d")
x,y,z = [1,1.5,3],[1,2.4,3],[3.4,1.4,1]
ax.scatter(x,y,z, c='r',s=100)
ax.plot(x,y,z, color='r')

plt.show()
</code>```

Body:
I have a 3D plot in python which I made using ax.scatter(x,y,z,c='r',s=100)
from the

import matplotlib.pyplot as plt

import pylab

from mpl_toolkits.mplot3d import Axes3D.

I want to connect my points with a line. I know you can do it with marker='-o' but that works only in 2D for me and not 3D. Can anyone help ?
Thank you.

Body:
Scatter does not allow for connecting points. The argument marker='-o' only works for plot, not for scatter. That is true for 2D and 3D. But of course you can use a scatter and a plot

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

ax = plt.gca(projection="3d")
x,y,z = [1,1.5,3],[1,2.4,3],[3.4,1.4,1]
ax.scatter(x,y,z, c='r',s=100)
ax.plot(x,y,z, color='r')

plt.show()


问:
checking the input type in C
I want to check if my input is an integer (and not a char or string for example).
I stumbled across this code (that works):

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

int main (void)
{
    float a;
    int q;

    printf("\nInsert number\t");
    scanf("%f",&a);

    q=(int)a;
    ++q;

    if((q - a) != 1)
        printf("\nThe number is not an integer\n\n");
    else
        printf("\nThe number is an integer\n\n");

    return 0;
}
</code>```

Can someone please explain why it works?

答:
You take input a this is a float number. Then you are casting float to int by an integer q and increment 1 (q++). So, if you take input a = 3.4

q=(int)a;
    ++q;

then q will be 4. But it can not change the value of a. So a will be 3.4.
 After checking this condition (q - a) != 1  will true, otherwise false.

Finally if you take input a=3.0 then this code will not work.(as a=3.0 is a float number.)

Title: checking the input type in C

Body:
I want to check if my input is an integer (and not a char or string for example).
I stumbled across this code (that works):

#include <stdio.h>

int main (void)
{
    float a;
    int q;

    printf("\nInsert number\t");
    scanf("%f",&a);

    q=(int)a;
    ++q;

    if((q - a) != 1)
        printf("\nThe number is not an integer\n\n");
    else
        printf("\nThe number is an integer\n\n");

    return 0;
}

Can someone please explain why it works?


问:
sql case statement IN with group by
I have a 2 column table with the columns : "user_name" and "characteristic".   Each user_name may appear multiple times with a different characteristic.

The values in characteristic are:

Online

Instore

Account

Email

I want to write a sql statement that goes like this - but obviously this isn't working:

```<code>SELECT user_name,
       case
          when characteristic in ("online","instore") then 1
          else 0
       END as purchase_yn,
       case
          when characteristic in ("online","instore") and
               characteristic in ("email",'account')   then 1
          else 0
       END as   purchaser_with_account
 FROM my_table
 GROUP BY user_name;
</code>```

Essentially the first is a flag where I check for the presence of either value for that user_name.
The Second field  is that they  meet this criteria AND that they meet the criteria for having either 'email' or 'account'

答:
You just have to enclose the CASE expressions in COUNT aggregates:

```<code>SELECT user_name,
       COUNT(case when characteristic in ("online","instore") then 1 END) as purchase_yn,
       COUNT(case when characteristic in ("email",'account') then 1 END) as user_with_account
FROM my_table
GROUP BY user_name
</code>```

If purchase_yn > 0 then you first flag is set. If purchase_yn > 0 and user_with_account > 0 then you second flag is set as well.

Note: You have to remove ELSE 0 from the CASE expressions because COUNT takes into account all not null values.

Title: sql case statement IN with group by

Body:
I have a 2 column table with the columns : "user_name" and "characteristic".   Each user_name may appear multiple times with a different characteristic.

The values in characteristic are:

Online

Instore

Account

Email

I want to write a sql statement that goes like this - but obviously this isn't working:

SELECT user_name,
       case
          when characteristic in ("online","instore") then 1
          else 0
       END as purchase_yn,
       case
          when characteristic in ("online","instore") and
               characteristic in ("email",'account')   then 1
          else 0
       END as   purchaser_with_account
 FROM my_table
 GROUP BY user_name;

Essentially the first is a flag where I check for the presence of either value for that user_name.
The Second field  is that they  meet this criteria AND that they meet the criteria for having either 'email' or 'account'

Body:
You just have to enclose the CASE expressions in COUNT aggregates:

SELECT user_name,
       COUNT(case when characteristic in ("online","instore") then 1 END) as purchase_yn,
       COUNT(case when characteristic in ("email",'account') then 1 END) as user_with_account
FROM my_table
GROUP BY user_name

If purchase_yn > 0 then you first flag is set. If purchase_yn > 0 and user_with_account > 0 then you second flag is set as well.

Note: You have to remove ELSE 0 from the CASE expressions because COUNT takes into account all not null values.


问:
Laravel 5.4 - Mix - How to run browser live reload
I am using Laravel 5.4 in my project and trying to set up the frontend build system using Mix. Everything is working fine except I could not be able to get browser auto reload option. There is nothing about it on documentation.

Someone please help, how can I achieve that?

答:
If someone needs an alternative way to make it work, for instance if mix is not used on backend, here is how I've solved it:

edit server.php from project root directory and replace return false;:

```<code>if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
    return false;
}
</code>```

as follows:

```<code>if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {

    // set log file for debugging purposes if needed
    #ini_set('error_log', __DIR__ . '/storage/logs/laravel.log');

    header("HTTP/1.1 301 Moved Permanently");
    header("Location: http://localhost:8080" . $uri);

    exit();
}
</code>```

of course you need to start both artisan serve and npm run hot

Body:
If someone needs an alternative way to make it work, for instance if mix is not used on backend, here is how I've solved it:

edit server.php from project root directory and replace return false;:

if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
    return false;
}

as follows:

if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {

    // set log file for debugging purposes if needed
    #ini_set('error_log', __DIR__ . '/storage/logs/laravel.log');

    header("HTTP/1.1 301 Moved Permanently");
    header("Location: http://localhost:8080" . $uri);

    exit();
}

of course you need to start both artisan serve and npm run hot


问:
IE8 JavaScript in IE7
A website I'm working on has sidebar with expandable/collapsible entries. Some of the items on this sidebar have a bullet next to them that, when clicked on, reveals a second level of sidebar items. We are using an onclick event to call this function to do this. Here is the script:

```<code><script type="text/javascript">
function menuClick(menu)
{
    if(menu.nextSibling.nextSibling.nextSibling.style.display == "inline")
    {
        menu.nextSibling.nextSibling.nextSibling.style.display = "none";
    }
    else
    {
        menu.nextSibling.nextSibling.nextSibling.style.display = "inline";
    }
}
</script>
</code>```

This works in IE8, but doesn't work in IE7. In IE7, when these bullets are clicked, the menu will expand like normal, but doesn't show the next level of links. Also in IE7 these bullets are above their respective links on a separate line. If you'd like to take a look a the site it's www.triptac.org. If you have IE8 you can see how it doesn't work in compatability view. I'd greatly appreciate any help.

答:
display: inline really isn't what you want to show the hidden lists, display: block (the default for lists) is what you want. I suspect that will help with the show/hide but it is hard to say without an editable example.

You'll have to mess around with the padding and margins on the arrows to get them in the right place in IE7; set up an IE7-specific stylesheet and load it using an IE7 conditional comment, that will keep the IE7 nonsense from polluting everything else. Then start adjusting the margins and padding on the list, list items, and the arrows until IE7 behaves itself. I'd like to be able to offer better advice but getting IE7 to render things sensible is generally a simple process of fiddling with the margins and padding (and sometimes display) until it works (and then the drinking (or your equivalent) starts).

Matt Ball is right, jQuery would make a lot of this cleaner. OTOH, you'd still have to beat IE7 into submission so jQuery won't make all the pain go away.

Title: IE8 JavaScript in IE7

Body:
A website I'm working on has sidebar with expandable/collapsible entries. Some of the items on this sidebar have a bullet next to them that, when clicked on, reveals a second level of sidebar items. We are using an onclick event to call this function to do this. Here is the script:

This works in IE8, but doesn't work in IE7. In IE7, when these bullets are clicked, the menu will expand like normal, but doesn't show the next level of links. Also in IE7 these bullets are above their respective links on a separate line. If you'd like to take a look a the site it's www.triptac.org. If you have IE8 you can see how it doesn't work in compatability view. I'd greatly appreciate any help.


问:
How to click all buttons of a specific class with one button in javascript
The buttons that i want to click with one button.
The following button are created with every file upload so thats why it is buttons.

var td4=row.insertCell(-1);
td4.innerHTML=" delete";```
</div>
</div>
</p>

<p><strong>What i want:</strong>
I want to have a button created in js and then when i click that button it should click all buttons of the upper class.</p>

<p><strong>What i have tried:</strong></p>

<pre class="lang-js prettyprint-override"><code>// 1. Create the button
var button = document.createElement("button");
button.setAttribute("onclick", "divFunction()");

function divFunction(){
   var a = document.getElementsByClassName('delete-button');
   for(var i = 0; i <= a.length; i++)
       a[i].click();
}

// 2. Append somewhere
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
</code>```

答:
Here is a simple function that does the job:

```<code>const addAButtonThatClicksAllButtons = () => {

    const button = document.createElement('button');

    button.onclick = () =>
        Array.from(document.getElementsByClassName('delete-button'))
            .forEach(btn => btn.click());

    document.body.appendChild(button);

};
</code>```

It might be cleaner if you use jQuery:

```<code>const addAButtonThatClicksAllButtons = () => {

    const button = $('<button/>').click(
        () => $('delete-button').click()
    );

    $('body').append(button);

};
</code>```

Body:
The buttons that i want to click with one button.
The following button are created with every file upload so thats why it is buttons.

var td4=row.insertCell(-1);
td4.innerHTML=" delete";

What i want:
I want to have a button created in js and then when i click that button it should click all buttons of the upper class.

What i have tried:

// 1. Create the button
var button = document.createElement("button");
button.setAttribute("onclick", "divFunction()");

function divFunction(){
   var a = document.getElementsByClassName('delete-button');
   for(var i = 0; i <= a.length; i++)
       a[i].click();
}

// 2. Append somewhere
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);

Body:
Here is a simple function that does the job:

const addAButtonThatClicksAllButtons = () => {

    const button = document.createElement('button');

    button.onclick = () =>
        Array.from(document.getElementsByClassName('delete-button'))
            .forEach(btn => btn.click());

    document.body.appendChild(button);

};

It might be cleaner if you use jQuery:

const addAButtonThatClicksAllButtons = () => {

    const button = $('<button/>').click(
        () => $('delete-button').click()
    );

    $('body').append(button);

};


答:
I stumbled across this code (that works): ... why it works?

It does not work, in general.  Too many failing cases

Given input might be a single character Z, the follow code is undefined behavior (UB) as scanf() does not assign a.  Result: (int)a is UB.

```<code>scanf("%f",&a);
q=(int)a;
</code>```

Given input might be "12345678901234567890", something outside the range of an int, then converting with (int)a is also UB.

If a takes on the value of INT_MAX, ++q; is UB.

Values where the input can be exactly represented as an int, but not as a float fail OP's code.

Input that is rounded to a whole number like "0.99999999999999999999999999999" --> 1.0f fail OP's detection

Alternative.

scanf(), fgets() do not read C strings, int, float, etc.  Instead, better to think of them as reading text and converting them into C strings, int, float.

The f in scanf() implies formatted input and that is the unknown part here.  Better to avoid scanf().

Since code needs to detect various things about user input, use fgets() to read a line of text.  Then use strtol(), strtoll(), strtoul(), etc. to see if input fits into the target type.

```<code>// Check if input fits in a `long`
char buf[100];
if (fgets(buf, sizeof buf, stdin) == NULL) {
  puts("End-of-file or input error");
} else {
  char *endptr;
  errno = 0;
  long ivalue = strtol(buf, &endptr, 0);
  if (buf == endptr) puts("Fail: no conversion");
  else if (*endptr != '\n' && *endptr != '\0') puts("Fail: Extra junk");
  else if (errno) puts("Fail: Overlfow");
  else printf("Success: %ld\n", ivalue);
}
</code>```

Title: checking the input type in C

Body:
I stumbled across this code (that works): ... why it works?

It does not work, in general.  Too many failing cases

Given input might be a single character Z, the follow code is undefined behavior (UB) as scanf() does not assign a.  Result: (int)a is UB.

scanf("%f",&a);
q=(int)a;

Given input might be "12345678901234567890", something outside the range of an int, then converting with (int)a is also UB.

If a takes on the value of INT_MAX, ++q; is UB.

Values where the input can be exactly represented as an int, but not as a float fail OP's code.

Input that is rounded to a whole number like "0.99999999999999999999999999999" --> 1.0f fail OP's detection

Alternative.

scanf(), fgets() do not read C strings, int, float, etc.  Instead, better to think of them as reading text and converting them into C strings, int, float.

The f in scanf() implies formatted input and that is the unknown part here.  Better to avoid scanf().

Since code needs to detect various things about user input, use fgets() to read a line of text.  Then use strtol(), strtoll(), strtoul(), etc. to see if input fits into the target type.

// Check if input fits in a `long`
char buf[100];
if (fgets(buf, sizeof buf, stdin) == NULL) {
  puts("End-of-file or input error");
} else {
  char *endptr;
  errno = 0;
  long ivalue = strtol(buf, &endptr, 0);
  if (buf == endptr) puts("Fail: no conversion");
  else if (*endptr != '\n' && *endptr != '\0') puts("Fail: Extra junk");
  else if (errno) puts("Fail: Overlfow");
  else printf("Success: %ld\n", ivalue);
}


问:
Non-blocking file access with Twisted
I'm trying to figure out if there is a defacto pattern for file access using twisted. Lots of examples I've looked at (twisted.python.log, twisted.persisted.dirdbm, twisted.web.static) actually don't seem to worry about blocking for file access.

It seems like there should be some obvious interface, probably inheriting from abstract.FileDescriptor, that all file access should be going through it as a producer/consumer.

Have I missed something or is it just that the primary use for twisted in asynchronous programming is for networking and it hasn't really been worked out for other file descriptor operations, not worrying about the purity of non-blocking IO ?

答:
The fdesc module might be useful for asynchronously talking to a socket or pipe, but when given an fd that refers to an ordinary filesystem file, it does blocking io (and via a rather odd interface at that). For disk io, fdesc is effectively snake oil; don't use it.

As of May 2017, the only reasonable way to get async disk io in twisted is by wrapping synchronous io calls in a deferToThread.

Title: Non-blocking file access with Twisted


问:
"make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi)
I'm trying to install trac and mod_wsgi over SSL. I tried to manually install it, but that didn't work out so well so I started to follow this: trac-on-ubuntu

I skipped the svn part because I'd like to use git instead. After the first edit of httpd.conf:

```<code>WSGIScriptAlias /trac /var/trac/apache/trac.wsgi

<Directory /var/trac/apache>
    WSGIApplicationGroup %{GLOBAL}
    Order deny,allow
    Allow from all
</Directory>
</code>```

I restarted apache only to get this error:

```<code>* Restarting web server apache2

(98)Address already in use: make_sock: could not bind to address [::]:443

                                                                     [ OK ]
</code>```

Doing these showed nothing.

```<code> netstat -anp | grep 443
 fuser 443/tcp
</code>```

Doing this didn't yield anything except the grep command that I ran:

```<code>ps -aux | grep httpd
</code>```

Why is it saying that something else is using the port when there's nothing showing up?

EDIT: You guys are going to laugh at this. I had an extra Listen 443 in ports.conf that shouldn't have been there. Removing that solved this.

答:
In httpd.conf instead:

```<code>Listen *:443
</code>```

you need write Listen 127.0.0.1:443
It works for me.

Body:
I'm trying to install trac and mod_wsgi over SSL. I tried to manually install it, but that didn't work out so well so I started to follow this: trac-on-ubuntu

I skipped the svn part because I'd like to use git instead. After the first edit of httpd.conf:

WSGIScriptAlias /trac /var/trac/apache/trac.wsgi

<Directory /var/trac/apache>
    WSGIApplicationGroup %{GLOBAL}
    Order deny,allow
    Allow from all
</Directory>

I restarted apache only to get this error:

* Restarting web server apache2

(98)Address already in use: make_sock: could not bind to address [::]:443

                                                                     [ OK ]

Doing these showed nothing.

 netstat -anp | grep 443
 fuser 443/tcp

Doing this didn't yield anything except the grep command that I ran:

ps -aux | grep httpd

Why is it saying that something else is using the port when there's nothing showing up?

EDIT: You guys are going to laugh at this. I had an extra Listen 443 in ports.conf that shouldn't have been there. Removing that solved this.

Body:
In httpd.conf instead:

Listen *:443

you need write Listen 127.0.0.1:443
It works for me.


问:
Making string of --- with 0 on the end
I can not use this declaration, because selectedWords can be any string.

```<code>.DATA
guessWords BYTE SIZEOF selectedWords DUP ('-'), 0
</code>```

So I try to do this:

```<code>;Wordls what we select by rundom code
selectedWords BYTE ?
lengthSelectedWorld DWORD ?

;Letter what we guess, input from keyboard
guessLetter BYTE ?
guessWords BYTE ?
;Letter what are unknows, change with -
letterUnknown BYTE "-", 0
</code>```

And I have write this function

```<code>make_array1 PROC

    mov  edx,OFFSET selectedWords
    call StrLength
    mov  lengthSelectedWorld,eax
    mov  lengthSelectedWorld1 ,eax
    inc  lengthSelectedWorld

    loop_add_more:
        cmp lengthSelectedWorld, 1
        je done
        dec lengthSelectedWorld
        mov eax, '-'
        mov ecx, lengthSelectedWorld1
        mov edi, offset guessWords
        rep stosw

        mov edx, offset guessWords
        call WriteString
        call Crlf ;stampamo enter novi red

        jmp loop_add_more

    done:
        mov eax, '0'
        mov ecx, lengthSelectedWorld1
        mov edi, offset guessWords
        rep stosw

        mov edx, offset guessWords
        call WriteString
        call Crlf ;stampamo enter novi red

        ret

make_array1 ENDP
</code>```

But after this funcion I get guessWords what is string of ------- and dont have 0 on the and. So how to make string guessWords=-------0?

Its important for me to have 0 on the end of string because of some other comparation in code..

答:
selectedWords BYTE ? reserves just one byte for selectedWords. The same issue with guessWords BYTE ?. Don't play with dynamically allocated memory as newbie. Rather reserve space which is sufficient in any case: guessWords BYTE 50 DUP (?). The question mark means that MASM can decide to treat it as uninitialized memory (not stored in the .exe file, but allocated at program start).

STOSW stores a WORD (= two characters). However Irvine's StrLength returns the number of bytes of the string. Use STOSB instead. After STOSB, EDI points to the character after the last stored AL. You can store a null there. If you want to see it, temporarily change 0 to '0'.

```<code>INCLUDE Irvine32.inc

.DATA

;Wordls what we select by rundom code
selectedWords BYTE "WEIGHTLIFTING", 0
lengthSelectedWord DWORD ?

;Letter what we guess, input from keyboard
guessLetter BYTE ?
guessWords BYTE 50 DUP (?)

;Letter what are unknows, change with -
letterUnknown BYTE "-", 0

.CODE

make_array1 PROC

    mov  edx,OFFSET selectedWords
    call StrLength                      ; Irvine32: Length of a null-terminated string pointed to by EDX
    mov  lengthSelectedWord,eax

    loop_add_more:
        mov al, '-'                     ; Default charcter for guessWords
        mov ecx, lengthSelectedWord     ; REP counter
        mov edi, offset guessWords      ; Destination
        rep stosb                       ; Build guessWords
        mov BYTE PTR [edi], 0           ; Store the null termination

        mov edx, offset guessWords
        call WriteString                ; Irvine32: write a string pointed to by EDX
        call Crlf                       ; Irvine32: new line

        ret

make_array1 ENDP

main PROC

    call make_array1
    exit                                ; Irvine32: ExitProcess

main ENDP

END main
</code>```

Title: Making string of --- with 0 on the end

Body:
I can not use this declaration, because selectedWords can be any string.

.DATA
guessWords BYTE SIZEOF selectedWords DUP ('-'), 0

So I try to do this:

;Wordls what we select by rundom code
selectedWords BYTE ?
lengthSelectedWorld DWORD ?

;Letter what we guess, input from keyboard
guessLetter BYTE ?
guessWords BYTE ?
;Letter what are unknows, change with -
letterUnknown BYTE "-", 0

And I have write this function

make_array1 PROC

    mov  edx,OFFSET selectedWords
    call StrLength
    mov  lengthSelectedWorld,eax
    mov  lengthSelectedWorld1 ,eax
    inc  lengthSelectedWorld

    loop_add_more:
        cmp lengthSelectedWorld, 1
        je done
        dec lengthSelectedWorld
        mov eax, '-'
        mov ecx, lengthSelectedWorld1
        mov edi, offset guessWords
        rep stosw

        mov edx, offset guessWords
        call WriteString
        call Crlf ;stampamo enter novi red

        jmp loop_add_more

    done:
        mov eax, '0'
        mov ecx, lengthSelectedWorld1
        mov edi, offset guessWords
        rep stosw

        mov edx, offset guessWords
        call WriteString
        call Crlf ;stampamo enter novi red

        ret

make_array1 ENDP

But after this funcion I get guessWords what is string of ------- and dont have 0 on the and. So how to make string guessWords=-------0?

Its important for me to have 0 on the end of string because of some other comparation in code..

Body:
selectedWords BYTE ? reserves just one byte for selectedWords. The same issue with guessWords BYTE ?. Don't play with dynamically allocated memory as newbie. Rather reserve space which is sufficient in any case: guessWords BYTE 50 DUP (?). The question mark means that MASM can decide to treat it as uninitialized memory (not stored in the .exe file, but allocated at program start).

STOSW stores a WORD (= two characters). However Irvine's StrLength returns the number of bytes of the string. Use STOSB instead. After STOSB, EDI points to the character after the last stored AL. You can store a null there. If you want to see it, temporarily change 0 to '0'.

INCLUDE Irvine32.inc

.DATA

;Wordls what we select by rundom code
selectedWords BYTE "WEIGHTLIFTING", 0
lengthSelectedWord DWORD ?

;Letter what we guess, input from keyboard
guessLetter BYTE ?
guessWords BYTE 50 DUP (?)

;Letter what are unknows, change with -
letterUnknown BYTE "-", 0

.CODE

make_array1 PROC

    mov  edx,OFFSET selectedWords
    call StrLength                      ; Irvine32: Length of a null-terminated string pointed to by EDX
    mov  lengthSelectedWord,eax

    loop_add_more:
        mov al, '-'                     ; Default charcter for guessWords
        mov ecx, lengthSelectedWord     ; REP counter
        mov edi, offset guessWords      ; Destination
        rep stosb                       ; Build guessWords
        mov BYTE PTR [edi], 0           ; Store the null termination

        mov edx, offset guessWords
        call WriteString                ; Irvine32: write a string pointed to by EDX
        call Crlf                       ; Irvine32: new line

        ret

make_array1 ENDP

main PROC

    call make_array1
    exit                                ; Irvine32: ExitProcess

main ENDP

END main


问:
Firebase behavior changing Depending on what built the program
I'm attempting to implement Firebase in an existing .Net program using Firesharp. Firebase is being used to propagate information that is changed on one machine over to other machines that may have the same information loaded previously.

I'm attempting to have Firebase store the JSON representation of the objects as the value of a particular key.

When I build in VS 2013 and run the program locally then the values appear like so:

As you can see in the picture the JSON string that is the value is having all of its special characters escaped and the value of the key "-Kkvvz8vdPqvZWDmNgHf" is a single string. While I realize this probably isn't the intended structure, at this point this structure works best for our implementation due to the way that the subscriptions are working through Firesharp.

The above behavior is what I see when compiling through my dev environment on my local PC, Every night we use TeamCity to compile the program with the previous days changes and when that compiles the code I am receiving completely different behavior in Firebase:

The picture essentially shows that Firebase is taking the JSON representation of the object and breaking out its properties as individual nodes in the tree. Because of that the subscription that the program has to Node "288110_280" is receiving multiple updates, one for each property, instead of one update representing the change object that needs to be processed. We have verified that the configuration of TeamCity mimics our development environments and I've done a 1 to 1 check of the dll's that end up in the applications folder at the end of an install and the output of a build done on my dev environment and the dll's match exactly.

So my main questions are,

What dictates whether or not Firebase parses the JSON string that it is given?

If Firebase does parse the JSON into individual properties, is it possible to subscribe to the parent node in such a way that we would receive one update containing all of the properties together instead of the properties individually?

Is there a way to force Firebase to act as outlined in the first screenshot?

**Edit:

I believe the Teamcity inconsistency is a red herring. I was able to install the program as compiled by Teamcity on two separate machines. One yields the first result and one yields the second result. So this new information basically changes the question to how do I ensure consistent behavior across different machines?

答:
Ok, I've parsed through as about as much source code as I can stand without using a debugger.  Here's what I've found:

The example you have given above is escaping the string double quotes.  It doesn't look like it's escaping anything else.  This causes me to believe that when Firebase gets the string payload it attempts to parse as JSON and throws on the invalid \ escape token.  Then Firebase stores as a string. If the " isn't escaped, Firebase successfully parses as JSON object.

Tracing through Firesharp leads me to this String formating code that gives me pause. My first suspicions are that as string works on one system and not another.  However, without stepping through the debugger on two different machines to follow the formatting, I'll go down the _config.Serializer.Serialize path.

Turns out the _config.Serializer.Serialize method eventually uses a TextWriter to build the string.  TextWriter uses the System's CultureInfo (locale) to help determine how a string is built.

The thing that can change from machine to machine is the locale (CultureInfo).  I know that TeamCity spins up the build agents on the System account, which may or may not have the same locale.

I would probably test this theory using the following code:

```<code>  CultureInfo culture1 = CultureInfo.CurrentCulture;
  CultureInfo culture2 = Thread.CurrentThread.CurrentCulture;
  Console.WriteLine("The current culture is {0}", culture1.Name);
  Console.WriteLine("The two CultureInfo objects are equal: {0}",
                    culture1 == culture2);
</code>```

You can send Teamcity messages using the wire format. E.g.

```<code>Console.WriteLine("##teamcity[message 'The current culture is {0}' ]", culture2.Name);
</code>```

If the CultureInfo is implied, it takes the system culture.  I suspect that either they are different, or they are invariant.  Instead of using the invariant or implied culture, try setting an explicit culture to see if that fixes your problem.

Body:
Ok, I've parsed through as about as much source code as I can stand without using a debugger.  Here's what I've found:

The example you have given above is escaping the string double quotes.  It doesn't look like it's escaping anything else.  This causes me to believe that when Firebase gets the string payload it attempts to parse as JSON and throws on the invalid \ escape token.  Then Firebase stores as a string. If the " isn't escaped, Firebase successfully parses as JSON object.

Tracing through Firesharp leads me to this String formating code that gives me pause. My first suspicions are that as string works on one system and not another.  However, without stepping through the debugger on two different machines to follow the formatting, I'll go down the _config.Serializer.Serialize path.

Turns out the _config.Serializer.Serialize method eventually uses a TextWriter to build the string.  TextWriter uses the System's CultureInfo (locale) to help determine how a string is built.

The thing that can change from machine to machine is the locale (CultureInfo).  I know that TeamCity spins up the build agents on the System account, which may or may not have the same locale.

I would probably test this theory using the following code:

  CultureInfo culture1 = CultureInfo.CurrentCulture;
  CultureInfo culture2 = Thread.CurrentThread.CurrentCulture;
  Console.WriteLine("The current culture is {0}", culture1.Name);
  Console.WriteLine("The two CultureInfo objects are equal: {0}",
                    culture1 == culture2);

You can send Teamcity messages using the wire format. E.g.

Console.WriteLine("##teamcity[message 'The current culture is {0}' ]", culture2.Name);

If the CultureInfo is implied, it takes the system culture.  I suspect that either they are different, or they are invariant.  Instead of using the invariant or implied culture, try setting an explicit culture to see if that fixes your problem.


问:
Visual Studio Code - delete all blank lines - regex
I spent some time trying to figure out how to delete all blank lines in Visual Studio Code and I can't get it working. Anybody knows how to do it please?

If I search for ^$ while typing it in search field VSC does find the blank lines (completely blank lines, means no white spaces) but it doesn't remove them when I hit Replace All. It does nothing:

For blank lines with spaces ^\s+$ Search works, but it does not remove them. What it does is it replaces them with a blank line without spaces :))

It must be I am doing something wrong. I just can't figure out what is it. Anybody knows? Thanks.

答:
Code Maid Extension is all you need.
You can use shortcut Ctrl M + Space bar to Cleanup your file, It will remove empty lines and format your code. You also can configure about format and cleanup rule.
Hope this useful.</p>


问:
Visualizer for Cosmos DB Graph
Does anyone know of a tool to visualize a graph created in Cosmos DB Graph?

I'm looking for something like Gephi (https://gephi.org/), or the tool that OrientDB or Neo4j use.

I'm looking for something that will "connect" to the database. Gephi appears to require an export, and then it uses the exported file. The tools for OrientDB & Neo4j will connect to the server instance and provide graphical results of queries.

BTW, I'm working with the Azure Cosmos DB Emulator at the moment. So I need something that will work on a local development website (localhost).

答:
There is actually a pretty decent web app for graph visualizations available in the Azure Portal. Inside your Cosmos account just click the QuickStart button and then select the Guided Gremlin Tour:

Create the SalesGraph (you can point the app at any of your graph enabled collections later) and then download the package and run the solution file. You might have to modify the connection strings in appsettings depending on which graph you want to talk to.

Title: Visualizer for Cosmos DB Graph


问:
Python 3.5 base64 decoding seems to be incorrect?
In Python 3.5 the base64 module has a method, standard_b64decode() for decoding strings from base64, which returns a bytes object.

When I run base64.standard_b64decode("wc==") the output is b\xc1. When you base64 encode "\xc1", you get "wQ==". It looks like there is an error in the decoding function. Actually, I think "wc==" is an invalid base64 encoded string, by this reasoning:

wc== ends with ==, which means that it was produced from a single input byte.

The corresponding values of 'w' and 'c' in the regular base64 alphabet are, respectively, 48 and 28, meaning their 6-bit representations are, respectively, 110000 and 011100.

Concatenating these, the first 8 bits are 11000001, which is \xc1, but the remaining bits (1100) are non-zero, so couldn't have been produced by the padding process performed during base64 encoding, as that only appends bits with value 0, which means these extra 1 bits can't have been produced through valid base64 encoding -> the string is not a valid base64 encoded string.

I think this is true for any 4 character chunk of base64 encoding ending in == when any of the last 4 bits of the second character are 1.

I'm pretty convinced that this is right, but I'm rather less experienced than the Python developers.

Can anyone confirm the above, or explain why it's wrong, if indeed it is?

答:
The Base64 standard is defined by RFC 4648. Your question is answered by §3.5:

Canonical Encoding

The padding step in base 64 and base 32 encoding can, if improperly implemented, lead to non-significant alterations of the encoded data. For example, if the input is only one octet for a base 64 encoding, then all six bits of the first symbol are used, but only the first two bits of the next symbol are used.  These pad bits MUST be set to zero by conforming encoders, which is described in the descriptions on padding below.  If this property do not hold, there is no canonical representation of base-encoded data, and multiple base- encoded strings can be decoded to the same binary data.  If this property (and others discussed in this document) holds, a canonical encoding is guaranteed.

In some environments, the alteration is critical and therefore decoders MAY chose to reject an encoding if the pad bits have not been set to zero.

The meaning of MAY is defined by RFC 2119:

MAY   This word, or the adjective "OPTIONAL", mean that an item is truly optional.  One vendor may choose to include the item because a particular marketplace requires it or because the vendor feels that it enhances the product while another vendor may omit the same item.

So Python is not obliged by the standard to reject non-canonical encodings.


问:
Centering two divs in a wrapper
I am trying to center #left and #center inside #wrapper like this:

I am trying to get #center to be in the actual center of #wrapper both horizontally and vertically, and that #left will be in a slight margin to his left. How do I achieve that?

.c {
  border: 1px solid black;
  margin-left: auto;
  margin-right: auto;
  width: 60vw;
  height: 80vh;
  margin-top: 13vh;
}

#wrapper {
  height: 13vh;
  margin-top: 2vh;
  border: 1px solid blue;
}

#center {
  display: inline-block;
  width: 12vw;
  height: 10vh;
  border: 1px solid red;
}

#left {
  display: inline-block;
  width: 13vh;
  height: 13vh;
  border: 1px solid green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="c">
  <div>content content content</div>
  <div>content content content</div>

  <div id="wrapper">
    <div id="left">left</div>
    <div id="center">center</div>

  </div>
  <div>content content content</div>
  <div>content content content</div></code>```

Jsfiddle: https://jsfiddle.net/y6r585jk/2/

答:
A non-flexbox solution would be to give the center element position: relative, center it in the container using text-align: center, and give the left element position: absolute and a right setting of calc(50% + 7vw) (resulting in 1 vw distance to the center element - you can change that as you like):

.c {
  border: 1px solid black;
  margin-left: auto;
  margin-right: auto;
  width: 60vw;
  height: 80vh;
  margin-top: 13vh;
}

#wrapper {
  height: 13vh;
  margin-top: 2vh;
  border: 1px solid blue;
  text-align:center;
}

#center {
  display: inline-block;
  width: 12vw;
  height: 10vh;
  margin-top: 1vh;
  border: 1px solid red;
  position: relative;
}

#left {
  display: inline-block;
  position: absolute;
  right: calc(50% + 7vw);
  width: 13vh;
  height: 13vh;
  border: 1px solid green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="c">
  <div>content content content</div>
  <div>content content content</div>

  <div id="wrapper">
    <div id="left">left</div>
    <div id="center">center</div>
  </div>
  <div>content content content</div>
  <div>content content content</div></code>```

Title: Centering two divs in a wrapper

Body:
I am trying to center #left and #center inside #wrapper like this:

I am trying to get #center to be in the actual center of #wrapper both horizontally and vertically, and that #left will be in a slight margin to his left. How do I achieve that?

.c {
  border: 1px solid black;
  margin-left: auto;
  margin-right: auto;
  width: 60vw;
  height: 80vh;
  margin-top: 13vh;
}

#wrapper {
  height: 13vh;
  margin-top: 2vh;
  border: 1px solid blue;
}

#center {
  display: inline-block;
  width: 12vw;
  height: 10vh;
  border: 1px solid red;
}

#left {
  display: inline-block;
  width: 13vh;
  height: 13vh;
  border: 1px solid green;
}

content content content

content content content

left

center

content content content

content content content

Jsfiddle: https://jsfiddle.net/y6r585jk/2/

Body:
A non-flexbox solution would be to give the center element position: relative, center it in the container using text-align: center, and give the left element position: absolute and a right setting of calc(50% + 7vw) (resulting in 1 vw distance to the center element - you can change that as you like):

.c {
  border: 1px solid black;
  margin-left: auto;
  margin-right: auto;
  width: 60vw;
  height: 80vh;
  margin-top: 13vh;
}

#wrapper {
  height: 13vh;
  margin-top: 2vh;
  border: 1px solid blue;
  text-align:center;
}

#center {
  display: inline-block;
  width: 12vw;
  height: 10vh;
  margin-top: 1vh;
  border: 1px solid red;
  position: relative;
}

#left {
  display: inline-block;
  position: absolute;
  right: calc(50% + 7vw);
  width: 13vh;
  height: 13vh;
  border: 1px solid green;
}

<div class="c">
  <div>content content content</div>
  <div>content content content</div>

  <div id="wrapper">
    <div id="left">left</div>
    <div id="center">center</div>
  </div>
  <div>content content content</div>
  <div>content content content</div>


问:
JQuery ContextMenu simple example not working
I tried to implement this demo
https://swisnl.github.io/jQuery-contextMenu/demo.html

On a minimal ASP MVC page, but the context menu will not open on the right-click. I've trimmed unnecessary code down to a minimum

page
http://comicnet20170410070547.azurewebsites.net/Books/WesternIntelligence

答:
I can see that the problem start when you get the error

Failed to load resource: the server responded with a status of 404
  (Not Found)

For 2 files: jquery, bootstrap.

In you code you can see that:

```<code><script src="/bundles/jquery"></script>
<script src="/bundles/bootstrap"></script>
</code>```

Check your files:

http://comicnet20170410070547.azurewebsites.net/bundles/bootstrap
http://comicnet20170410070547.azurewebsites.net/bundles/jquery

Maybe just add the extension of each file.

Body:
I can see that the problem start when you get the error

Failed to load resource: the server responded with a status of 404
  (Not Found)

For 2 files: jquery, bootstrap.

In you code you can see that:

<script src="/bundles/jquery"></script>
<script src="/bundles/bootstrap"></script>

Check your files:

http://comicnet20170410070547.azurewebsites.net/bundles/bootstrap
http://comicnet20170410070547.azurewebsites.net/bundles/jquery

Maybe just add the extension of each file.


问:
Rails 3 Fixture Join Table Ids are Incorrect
I am trying to work with fixtures in rails.  The rake db:fixtures:load runs without error, and table populates my data, but my many to many join table contains incorrect ids:

Example:

```<code>**tags.yml**
one:
  id: 1
  tag: pie
  posts: two

two:
  id: 2
  tag: cake
  posts: one, two

**posts.yml**
one:
  id: 1
  subject: subject
  content: content
  slug: woot
  tags: cake

two:
  id: 2
  subject: subject2
  content: content2
  slug: this_is_good
  tags: pie, cake
</code>```

After running migrations and db:fixtures:load my tables get populated as:

tags:

id------tag

1 ...... pie

2 ...... cake

posts_tags:

rowid - post_id - tag_id

1 ...... 1 ...... 974324064

2 ...... 2 ...... 576189563

3 ...... 3 ...... 974324064

For some reason an auto-generated tag_id is getting created and being populated in my join table. Why?

Edit

The migrations are defined as:

```<code>  def self.up
    create_table :posts do |t|
      t.string :subject
      t.text :content

      t.timestamps
    end
  end
</code>```

and

```<code>  def self.up
    create_table :tags do |t|
      t.string :tag

      t.timestamps
    end

    create_table :posts_tags, :id => false do |t|
      t.integer :post_id
      t.integer :tag_id
    end
  end
</code>```

答:
I'm gonna assume your models are something like this.

```<code>class Tag Post < ActiveRecord::Base
  has_and_belongs_to_many :posts
end

class Post < ActiveRecord::Base
  has_and_belongs_to_many :tags
end
</code>```

That means the the posts_tags join table can only have post_id and tag_id in it as columns. It cannot have a rowid column. You'll need something like :id => false in the table definition of posts_tags.

Body:
I am trying to work with fixtures in rails.  The rake db:fixtures:load runs without error, and table populates my data, but my many to many join table contains incorrect ids:

Example:

**tags.yml**
one:
  id: 1
  tag: pie
  posts: two

two:
  id: 2
  tag: cake
  posts: one, two

**posts.yml**
one:
  id: 1
  subject: subject
  content: content
  slug: woot
  tags: cake

two:
  id: 2
  subject: subject2
  content: content2
  slug: this_is_good
  tags: pie, cake

After running migrations and db:fixtures:load my tables get populated as:

tags:

id------tag

1 ...... pie

2 ...... cake

posts_tags:

rowid - post_id - tag_id

1 ...... 1 ...... 974324064

2 ...... 2 ...... 576189563

3 ...... 3 ...... 974324064

For some reason an auto-generated tag_id is getting created and being populated in my join table. Why?

Edit

The migrations are defined as:

  def self.up
    create_table :posts do |t|
      t.string :subject
      t.text :content

      t.timestamps
    end
  end

and

  def self.up
    create_table :tags do |t|
      t.string :tag

      t.timestamps
    end

    create_table :posts_tags, :id => false do |t|
      t.integer :post_id
      t.integer :tag_id
    end
  end

Body:
I'm gonna assume your models are something like this.

class Tag Post < ActiveRecord::Base
  has_and_belongs_to_many :posts
end

class Post < ActiveRecord::Base
  has_and_belongs_to_many :tags
end

That means the the posts_tags join table can only have post_id and tag_id in it as columns. It cannot have a rowid column. You'll need something like :id => false in the table definition of posts_tags.


问:
How do I add multiple elements to an array?
I can easily add one element to an existing array:

```<code>arr = [1]
arr << 2
# => [1, 2]
</code>```

How would I add multiple elements to my array?

I'd like to do something like arr << [2, 3], but this adds an array to my array #=> [1, [2, 3]]

答:
One more, for building up an array with items n-times you can use the splat (AKA asterisk, *):

```<code>arr = [true] * 4           # => [true, true, true, true]
</code>```

You can also use the splat for repeating multiple elements:

```<code>arr = [123,'abc'] * 3      # => [123,'abc',123,'abc',123,'abc']
</code>```

Of course, you can use any array operators with that, such as +:

```<code>arr = [true] * 3 + [false] # => [true, true, true, false]
</code>```

I use that in conjunction with #sample to generate random weighted results:

```<code>arr.sample                 # => true 3 out of 4 times
</code>```

Body:
I can easily add one element to an existing array:

arr = [1]
arr << 2
# => [1, 2]

How would I add multiple elements to my array?

I'd like to do something like arr << [2, 3], but this adds an array to my array #=> [1, [2, 3]]

Body:
One more, for building up an array with items n-times you can use the splat (AKA asterisk, *):

arr = [true] * 4           # => [true, true, true, true]

You can also use the splat for repeating multiple elements:

arr = [123,'abc'] * 3      # => [123,'abc',123,'abc',123,'abc']

Of course, you can use any array operators with that, such as +:

arr = [true] * 3 + [false] # => [true, true, true, false]

I use that in conjunction with #sample to generate random weighted results:

arr.sample                 # => true 3 out of 4 times