问:
Pythonic way of setting a label in matplotlib
I am iterating over many lists of gpx data to create a plot of cumulative training for 2016. To do so, I set up a loop as follows, where paces is a list of lists of smoothed pacing data from each gpx file and total_distances the associated distances computed from the coordinate data.

```<code>for i in range(0, len(paces)):

    if i == 0:
        # need offset on paces from filtered data/NaN
        plt.plot(total_distances[i:i+1][0],
                 paces[i:i+1][0][10:len(paces[i:i+1][0])+1],
                 linewidth=.5, ls='-', color='#00FF00', label = 'all runs')
    else:
        plt.plot(total_distances[i:i+1][0],
                 paces[i:i+1][0][10:len(paces[i:i+1][0])+1],
                 linewidth=.5, ls='-', color='#00FF00')
</code>```

If I do not use the above conditional, the label gets printed as many times as there are lists.

Any suggestions for a my pythonic way of doing this?

答:
I don't know what pythonic means (everyone seems to understand it differently), but here is a solution which might be easier to implement.

The idea is based on the fact that matplotlib ignores labels which start with an underscore (_). So adding i underscores in the loop to the label, leaves only the first label without an underscore. This is then the label being shown.

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

x = range(39)
y = range(39)

for i in range(len(x)-1):
    plt.plot(x[i:i+2],y[i:i+2], lw=10, label="_"*i + "label")

plt.legend(borderpad=1.5)
plt.show()
</code>```

Body:
I am iterating over many lists of gpx data to create a plot of cumulative training for 2016. To do so, I set up a loop as follows, where paces is a list of lists of smoothed pacing data from each gpx file and total_distances the associated distances computed from the coordinate data.

for i in range(0, len(paces)):

    if i == 0:
        # need offset on paces from filtered data/NaN
        plt.plot(total_distances[i:i+1][0],
                 paces[i:i+1][0][10:len(paces[i:i+1][0])+1],
                 linewidth=.5, ls='-', color='#00FF00', label = 'all runs')
    else:
        plt.plot(total_distances[i:i+1][0],
                 paces[i:i+1][0][10:len(paces[i:i+1][0])+1],
                 linewidth=.5, ls='-', color='#00FF00')

If I do not use the above conditional, the label gets printed as many times as there are lists.

Any suggestions for a my pythonic way of doing this?

Body:
I don't know what pythonic means (everyone seems to understand it differently), but here is a solution which might be easier to implement.

The idea is based on the fact that matplotlib ignores labels which start with an underscore (_). So adding i underscores in the loop to the label, leaves only the first label without an underscore. This is then the label being shown.

import matplotlib.pyplot as plt

x = range(39)
y = range(39)

for i in range(len(x)-1):
    plt.plot(x[i:i+2],y[i:i+2], lw=10, label="_"*i + "label")

plt.legend(borderpad=1.5)
plt.show()


来源: stackexchange

问:
How to run django application on google app engine without using gunicorn
I have gone through all the documentation provided for the running Django Application on app engine.
I have a Django Application where I am using Vision and Storage clients and my app name is pvd.
I have been constantly getting below errors in error logs.

```<code>A  [2017-03-30 22:08:07 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:7)
A  [2017-03-30 22:08:07 +0000] [7] [INFO] Worker exiting (pid: 7)
A  [2017-03-30 22:08:07 +0000] [9] [INFO] Booting worker with pid: 9
A  [2017-03-30 22:12:35 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:9)
A  [2017-03-30 22:12:35 +0000] [9] [INFO] Worker exiting (pid: 9)
A  [2017-03-30 22:12:36 +0000] [11] [INFO] Booting worker with pid: 11
A  [2017-03-30 22:13:03 +0000] [1] [INFO] Handling signal: term
A  [2017-03-30 22:13:03 +0000] [7] [INFO] Worker exiting (pid: 7)
A  [2017-03-30 22:13:03 +0000] [1] [INFO] Shutting down: Master*
</code>```

Below is my app.yaml

```<code>runtime: python
env: flex
entrypoint: gunicorn -b :$PORT pythonvision.wsgi

runtime_config:
  python_version: 3
</code>```

Below is my requirement.txt

```<code>Django==1.10.6
google-cloud-storage==0.23.1
google-cloud-vision==0.23.1
gunicorn==19.7.0
</code>```

For deploying I am using:

```<code>gcloud app deploy
</code>```

What am I doing wrong?

答: Have you looked at this answer to someone else seeing gunicorn worker timeouts?</p>

ContentLicense: CC BY-SA 3.0

Body:
I have gone through all the documentation provided for the running Django Application on app engine.
I have a Django Application where I am using Vision and Storage clients and my app name is pvd.
I have been constantly getting below errors in error logs.

A  [2017-03-30 22:08:07 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:7)
A  [2017-03-30 22:08:07 +0000] [7] [INFO] Worker exiting (pid: 7)
A  [2017-03-30 22:08:07 +0000] [9] [INFO] Booting worker with pid: 9
A  [2017-03-30 22:12:35 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:9)
A  [2017-03-30 22:12:35 +0000] [9] [INFO] Worker exiting (pid: 9)
A  [2017-03-30 22:12:36 +0000] [11] [INFO] Booting worker with pid: 11
A  [2017-03-30 22:13:03 +0000] [1] [INFO] Handling signal: term
A  [2017-03-30 22:13:03 +0000] [7] [INFO] Worker exiting (pid: 7)
A  [2017-03-30 22:13:03 +0000] [1] [INFO] Shutting down: Master*

Below is my app.yaml

runtime: python
env: flex
entrypoint: gunicorn -b :$PORT pythonvision.wsgi

runtime_config:
  python_version: 3

Below is my requirement.txt

Django==1.10.6
google-cloud-storage==0.23.1
google-cloud-vision==0.23.1
gunicorn==19.7.0

For deploying I am using:

gcloud app deploy

What am I doing wrong?


问:
Gnuplot pm3d palette colors not mapping to the values specified?
I am trying to plot a solar spectrum.  I am having difficulty with Gnuplot mapping the colors that I specify to the correct values.  Here is my script.

```<code>set view map
set pm3d
set palette defined (380 "purple", 475 "blue", 510 "green", 570 "yellow", 590 "orange", 650 "red", 675 "dark-red", 700 "black")
splot [400:800][0:1] x
</code>```

As you can see at x=510, there plot is not green. Likewise it is not yellow at 570 as I specified.  How do I fix this so the colors on the plot match what I specified?

答:
I need to specify cbrange to match the plot ranges, e.g.

```<code>set view map
set pm3d
set palette defined (400 "purple", 475 "blue", 510 "green", 570 "yellow", 590 "orange", 650 "red", 675 "dark-red", 700 "black")
splot [400:700][0:1] x
set cbrange [400:700]
</code>```

so that the colors are scaled correctly.

Body:
I am trying to plot a solar spectrum.  I am having difficulty with Gnuplot mapping the colors that I specify to the correct values.  Here is my script.

set view map
set pm3d
set palette defined (380 "purple", 475 "blue", 510 "green", 570 "yellow", 590 "orange", 650 "red", 675 "dark-red", 700 "black")
splot [400:800][0:1] x

As you can see at x=510, there plot is not green. Likewise it is not yellow at 570 as I specified.  How do I fix this so the colors on the plot match what I specified?

Body:
I need to specify cbrange to match the plot ranges, e.g.

set view map
set pm3d
set palette defined (400 "purple", 475 "blue", 510 "green", 570 "yellow", 590 "orange", 650 "red", 675 "dark-red", 700 "black")
splot [400:700][0:1] x
set cbrange [400:700]

so that the colors are scaled correctly.


问:
Filtering in Scala
So suppose I have the following data (only the first few rows, this data covers an entire year) -

```<code>(2014-08-31T00:05:00.000+01:00, John)
(2014-08-31T00:11:00.000+01:00, Sarah)
(2014-08-31T00:12:00.000+01:00, George)
(2014-08-31T00:05:00.000+01:00, John)
(2014-09-01T00:05:00.000+01:00, Sarah)
(2014-09-01T00:05:00.000+01:00, George)
(2014-09-01T00:05:00.000+01:00, Jason)
</code>```

I would like to filter the data so that I only see what the names are for a specific date (say, 2014-09-05). I've tried doing this using the filter function in Scala but I keep receiving the following error -

```<code>error: value xxxx is not a member of (org.joda.time.DateTime, String)
</code>```

Is there another way of doing this?

答:
The filter method takes a function, called a predicate, that takes as parameter an element of your (I'm assuming) RDD, and returns a Boolean.

The returned RDD will keep only the rows for which the predicate evaluates to true.

In your case, it seems that what you want is something like

```<code>rdd.filter{
  case (date, _) => date.withTimeAtStartOfDay() == new DateTime("2017-03-31")
}
</code>```

Title: Filtering in Scala

Body:
So suppose I have the following data (only the first few rows, this data covers an entire year) -

(2014-08-31T00:05:00.000+01:00, John)
(2014-08-31T00:11:00.000+01:00, Sarah)
(2014-08-31T00:12:00.000+01:00, George)
(2014-08-31T00:05:00.000+01:00, John)
(2014-09-01T00:05:00.000+01:00, Sarah)
(2014-09-01T00:05:00.000+01:00, George)
(2014-09-01T00:05:00.000+01:00, Jason)

I would like to filter the data so that I only see what the names are for a specific date (say, 2014-09-05). I've tried doing this using the filter function in Scala but I keep receiving the following error -

error: value xxxx is not a member of (org.joda.time.DateTime, String)

Is there another way of doing this?

Body:
The filter method takes a function, called a predicate, that takes as parameter an element of your (I'm assuming) RDD, and returns a Boolean.

The returned RDD will keep only the rows for which the predicate evaluates to true.

In your case, it seems that what you want is something like

rdd.filter{
  case (date, _) => date.withTimeAtStartOfDay() == new DateTime("2017-03-31")
}


问:
Window Hangs And Freezes [SDL 2]
I have a text file full of information on where to place tiles in a game i'm making, the fastest way to access this information is with a for loop. But whenever i use the for loop to get through all the information it freezes the program for about 12 seconds, in those 12 i cant move the window, nothing on the renderer updates/is drawn, and then when i click on the window it breaks and says "window name (Not Responding)". I tried using a while loop but it still does the same thing.

How can i loop through bigger numbers (there are about 4,000 tiles in the level) without the program freezing/hanging on me? I'm just using SDL 2, no OpenGL involved.

```<code>    int tiles = 4000;
    int x[4000];
    int y[4000];
    tile obj[4000];

    for(int i = 0; i < tiles; i++)
    {

    x[i] = txt.x;
    y[i] = txt.y;

    obj[i].Load(x[i], y[i]);
    obj[i].Add();

    SDL_RenderClear(ren);
    LoadScreen();
    SDL_RenderPresent(ren);
    }
</code>```

Thanks.

答:
You need to create another thread.

It's good idea to wait for all data to load before starting game, so during load, you don't need to render anything. Even with this approach, it is better to use another thread and don't keep "UI Thread" busy. During load time your UI would be mostly disabled except a cancel button that will stop loading thread.

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

bool bReady;

void LoadTiles(void* pArg)
{
    // Load Data here
    *((int*)pArg) = 0;
    ///////////////////

    bReady = true;
}

void main()
{
    btnStart.SetEnabled(false);
    bReady = false;

    int iTarget;
    uintptr_t hLoadingThread = _beginthread(LoadTiles, 0, &iTarget);

    while (true) // usually you pick a message here
    {
        if (bReady)
            btnStart.SetEnabled(true);
    }
}
</code>```

This is just a very simple example, multi-threading needs a lot of work and study!

Title: Window Hangs And Freezes [SDL 2]

Body:
I have a text file full of information on where to place tiles in a game i'm making, the fastest way to access this information is with a for loop. But whenever i use the for loop to get through all the information it freezes the program for about 12 seconds, in those 12 i cant move the window, nothing on the renderer updates/is drawn, and then when i click on the window it breaks and says "window name (Not Responding)". I tried using a while loop but it still does the same thing.

How can i loop through bigger numbers (there are about 4,000 tiles in the level) without the program freezing/hanging on me? I'm just using SDL 2, no OpenGL involved.

    int tiles = 4000;
    int x[4000];
    int y[4000];
    tile obj[4000];

    for(int i = 0; i < tiles; i++)
    {

    x[i] = txt.x;
    y[i] = txt.y;

    obj[i].Load(x[i], y[i]);
    obj[i].Add();

    SDL_RenderClear(ren);
    LoadScreen();
    SDL_RenderPresent(ren);
    }

Thanks.

Body:
You need to create another thread.

It's good idea to wait for all data to load before starting game, so during load, you don't need to render anything. Even with this approach, it is better to use another thread and don't keep "UI Thread" busy. During load time your UI would be mostly disabled except a cancel button that will stop loading thread.

#include <process.h>

bool bReady;

void LoadTiles(void* pArg)
{
    // Load Data here
    *((int*)pArg) = 0;
    ///////////////////

    bReady = true;
}

void main()
{
    btnStart.SetEnabled(false);
    bReady = false;

    int iTarget;
    uintptr_t hLoadingThread = _beginthread(LoadTiles, 0, &iTarget);

    while (true) // usually you pick a message here
    {
        if (bReady)
            btnStart.SetEnabled(true);
    }
}

This is just a very simple example, multi-threading needs a lot of work and study!


问:
How to Add a String inside of another string without erasing the rest of it

I'm having bad times trying to add a string inside of another string in a especific position. Every time I use this code, the rest of the string become blank.

```<code>double temperature = 22.1;
unsigned char pacote[16] = "#0123456789ABCDEF";
unsigned char temp_local[3];
dtostrf(temperatura, 3, 1, temp_local);
sprintf(pacote+3,"%s", temp_local);
</code>```

or

```<code>sprintf(pacote+3,temp_local);
</code>```

got the same printf:

```<code>#0122.1
</code>```

istead of:

```<code>#0122.16789ABCDEF
</code>```

Why is it erasing all the rest of the string and not just replace the next 4 positions after [3] and leaving the rest alone.
I'm using arduino but I think that's generic C question.

Thank you very much!!!

答:
if you are using C++ then use string::substr as in

new_string = old_string.substr(0,3) + "some text" + old_string.substr(3);

In pure C you first need to ensure that the destination has enough space. sprintf returns the number of characters written. Use this to ensure that destination has sufficient space. Then concatenate the two substrings with the new string as desired.

Body:
I'm having bad times trying to add a string inside of another string in a especific position. Every time I use this code, the rest of the string become blank.

double temperature = 22.1;
unsigned char pacote[16] = "#0123456789ABCDEF";
unsigned char temp_local[3];
dtostrf(temperatura, 3, 1, temp_local);
sprintf(pacote+3,"%s", temp_local);

or

sprintf(pacote+3,temp_local);

got the same printf:

#0122.1

istead of:

#0122.16789ABCDEF

Why is it erasing all the rest of the string and not just replace the next 4 positions after [3] and leaving the rest alone.
I'm using arduino but I think that's generic C question.

Thank you very much!!!


问:
Finding multi-line string in PHP file
I am working on a program in which an addon needs to modify a system file.

I have a small method in which I am finding the beginning of the string in the file like this:

```<code>     /**
     * @param $fileName
     * @param $str
     *
     * @return int
     */
    private function getLineWithString($fileName, $str)
    {
        $lines = file($fileName);
        foreach ($lines as $lineNumber => $line) {
            if (strpos($line, $str) !== false) {
                return $line;
            }
        }
        return -1;
    }
</code>```

I am calling that from within the method where I need to pull that string out to replace it like this:

```<code>//  Set our file to use
$originalFile = 'file.php';

// Find The array['key'] string
$myString = "\$array['key']";

// Process - Find it
$lineNo = $this->getLineWithString($originalFile, $myString);
</code>```

Then echo $lineNo; returns $array['key'] = array(.

However, I need it to return the entire multi-line array/string up until the next ; (semicolon).

How would I go about this?

Thanks

* EDIT *

My PHP file contents are like this:

```<code><?php
    /**
     * Comment here
    */
     $first_array = array(
         'key1' => 'val1',
         'key2' => 'val2',
         'key3' => 'val3',
         'key4' => 'val4',
         'key5' => 'val5'
    );

    $second_array = array(
        'key1' => 'val1',
        'key2' => 'val2'
    );
    ...
</code>```

I have tried the suggestion from @Scuzzy

This is in my method now:

```<code>// Open Existing File And Get Contents
$myFile = file_get_contents('myFile.php');

$tokens = token_get_all($myFile);

foreach ( $tokens as $token ) {
    if (is_array($token)) {
        if( $token[0] === T_CONSTANT_ENCAPSED_STRING and strpos( $token[1], "\n" ) !== false )
        {
            var_dump( $token );
        }
    }
}
</code>```

However, this doesn't return anything.

I need to return something like:

```<code>$second_array = array(
    'key1' => 'val1',
    'key2' => 'val2'
);
</code>```

As a string I can manipulate and rewrite.

答:
I would be looking into http://php.net/manual/en/function.token-get-all.php and in particularly T_CONSTANT_ENCAPSED_STRING that have new line characters in them

token.php

```<code>$code = file_get_contents('token.code.php');

$tokens = token_get_all( $code );

foreach ( $tokens as $token ) {
  if (is_array($token)) {
    if( $token[0] === T_CONSTANT_ENCAPSED_STRING and strpos( $token[1], "\n" ) !== false )
    {
      var_dump( $token );
    }
  }
}
</code>```

token.code.php

```<code><?php
$bar = "single line";
$foo = "hello
multi
line
world";
$bar = 'single line';
$foo = 'hello
multi
line
world';
</code>```

will print the multi line but not the single lines:

```<code>array(3) {
  [0]=>
  int(318)
  [1]=>
  string(27) ""hello
multi
line
world""
  [2]=>
  int(4)
}
array(3) {
  [0]=>
  int(318)
  [1]=>
  string(27) "'hello
multi
line
world'"
  [2]=>
  int(9)
}
</code>```

Title: Finding multi-line string in PHP file

Body:
I am working on a program in which an addon needs to modify a system file.

I have a small method in which I am finding the beginning of the string in the file like this:

     /**
     * @param $fileName
     * @param $str
     *
     * @return int
     */
    private function getLineWithString($fileName, $str)
    {
        $lines = file($fileName);
        foreach ($lines as $lineNumber => $line) {
            if (strpos($line, $str) !== false) {
                return $line;
            }
        }
        return -1;
    }

I am calling that from within the method where I need to pull that string out to replace it like this:

//  Set our file to use
$originalFile = 'file.php';

// Find The array['key'] string
$myString = "\$array['key']";

// Process - Find it
$lineNo = $this->getLineWithString($originalFile, $myString);

Then echo $lineNo; returns $array['key'] = array(.

However, I need it to return the entire multi-line array/string up until the next ; (semicolon).

How would I go about this?

Thanks

* EDIT *

My PHP file contents are like this:

<?php
    /**
     * Comment here
    */
     $first_array = array(
         'key1' => 'val1',
         'key2' => 'val2',
         'key3' => 'val3',
         'key4' => 'val4',
         'key5' => 'val5'
    );

    $second_array = array(
        'key1' => 'val1',
        'key2' => 'val2'
    );
    ...

I have tried the suggestion from @Scuzzy

This is in my method now:

// Open Existing File And Get Contents
$myFile = file_get_contents('myFile.php');

$tokens = token_get_all($myFile);

foreach ( $tokens as $token ) {
    if (is_array($token)) {
        if( $token[0] === T_CONSTANT_ENCAPSED_STRING and strpos( $token[1], "\n" ) !== false )
        {
            var_dump( $token );
        }
    }
}

However, this doesn't return anything.

I need to return something like:

$second_array = array(
    'key1' => 'val1',
    'key2' => 'val2'
);

As a string I can manipulate and rewrite.

Body:
I would be looking into http://php.net/manual/en/function.token-get-all.php and in particularly T_CONSTANT_ENCAPSED_STRING that have new line characters in them

token.php

$code = file_get_contents('token.code.php');

$tokens = token_get_all( $code );

foreach ( $tokens as $token ) {
  if (is_array($token)) {
    if( $token[0] === T_CONSTANT_ENCAPSED_STRING and strpos( $token[1], "\n" ) !== false )
    {
      var_dump( $token );
    }
  }
}

token.code.php

<?php
$bar = "single line";
$foo = "hello
multi
line
world";
$bar = 'single line';
$foo = 'hello
multi
line
world';

will print the multi line but not the single lines:

array(3) {
  [0]=>
  int(318)
  [1]=>
  string(27) ""hello
multi
line
world""
  [2]=>
  int(4)
}
array(3) {
  [0]=>
  int(318)
  [1]=>
  string(27) "'hello
multi
line
world'"
  [2]=>
  int(9)
}


问:
ubuntu server pipeline stop process termination when the first exit
The situation is: I have an external application so I don't have the source code and i can't change it. While running, the application writes logs to the stderr. The task is to write a program that check the output of it and separate some part of the output to other file. My solution is to start the app like

```<code>./externalApp 2>&1 | myApp
</code>```

the myApp is a c++ app with the following source:

```<code>using namespace std;

int main ()
{
string str;
ofstream A;
A.open("A.log");

ofstream B;
B.open("B.log");

A << "test start" << endl;

int i = 0;

while (getline(cin,str))
{
    if(str.find("asdasd") != string::npos)
    {
        A << str << endl;
    }
    else
    {
        B << str << endl;
    }
    ++i;
}

A << "test end: " << i << " lines" << endl;
A.close();
B.close();

return 0;
}
</code>```

The externalApp can crash or be terminated. A that moment the myApp gets terminated too and it is don't write the last lines and don't close the files. The file can be 60Gb or larger so saving it and processing it after not a variant.

Correction: My problem is that when the externalApp crash it terminate myApp. That mean any code after while block will never run. So the question is: Is there a way to run myApp even after the externalApp closed?

How can I do this task correctly? I interesed in any other idea to do this task.

答: If you want your program to cleanly deal with the external program crashing you will probably need to handle SIGPIPE.  The default behaviour of this signal is to terminate the process. </p>

Body:
The situation is: I have an external application so I don't have the source code and i can't change it. While running, the application writes logs to the stderr. The task is to write a program that check the output of it and separate some part of the output to other file. My solution is to start the app like

./externalApp 2>&1 | myApp

the myApp is a c++ app with the following source:

using namespace std;

int main ()
{
string str;
ofstream A;
A.open("A.log");

ofstream B;
B.open("B.log");

A << "test start" << endl;

int i = 0;

while (getline(cin,str))
{
    if(str.find("asdasd") != string::npos)
    {
        A << str << endl;
    }
    else
    {
        B << str << endl;
    }
    ++i;
}

A << "test end: " << i << " lines" << endl;
A.close();
B.close();

return 0;
}

The externalApp can crash or be terminated. A that moment the myApp gets terminated too and it is don't write the last lines and don't close the files. The file can be 60Gb or larger so saving it and processing it after not a variant.

Correction: My problem is that when the externalApp crash it terminate myApp. That mean any code after while block will never run. So the question is: Is there a way to run myApp even after the externalApp closed?

How can I do this task correctly? I interesed in any other idea to do this task.


问:
Creating standalone (exe) viewer from code run on Ipython
I have this very basic piece of Python which I use to visualize some data and perform a few interactions with. I launch it from Spyder and it is basically just a function.
In broad terms:

open a file and create a DataFrame from it

plot some data and add a few sliders to interact with the data

I was wondering whether I could make this small code available to other people who do not have Python installed and probably not even the latest Qt5 libs I am using.

Os would be Linux but could also be Windows if it came easier.

Can you tell me how time consuming would it be to create a standalone file which could be double clicked and just show the plot with the interactive bits?

答:
Just followed the (2 line!) instructions on PyInstaller:

```<code>$ echo "print 'hello world...'" > helloworld.py
$ pip install pyinstaller
$ pyinstaller helloworld.py
$ dist/helloworld/helloworld
hello world...
</code>```

Looks pretty automated. It analyses your dependencies as far I can tell and brings everything you need together and then makes a launch script. It works on loads of platforms and even mentions Qt on the front page. I reckon its worth a go!

Body:
Just followed the (2 line!) instructions on PyInstaller:

$ echo "print 'hello world...'" > helloworld.py
$ pip install pyinstaller
$ pyinstaller helloworld.py
$ dist/helloworld/helloworld
hello world...

Looks pretty automated. It analyses your dependencies as far I can tell and brings everything you need together and then makes a launch script. It works on loads of platforms and even mentions Qt on the front page. I reckon its worth a go!


问:
C, HTTP 1.1 and Socket Send troubles
As an addition to my previous post on Creating a web server in pure C, I'm having some trouble with the Sending function. Here's two code snippets:

```<code>int Send(char *message)
{
        int length, bytes_sent;
        length = strlen(message);

        bytes_sent = send(connecting_socket, message, length, 0);

        return bytes_sent;
}
</code>```

This code sends void * to the current socket. Works like a charm!

Now here comes the SendHTML

```<code>void SendHTML(char *Status_code, char *Content_Type, char *HTML)
{
        char *head = "\r\nHTTP/1.1 ";
        char *content_head = "\r\nContent-Type: ";
        char *server_head = "\r\nServer: PT06";
        char *length_head = "\r\nContent-Length: ";
        char *date_head = "\r\nDate: ";
        char *newline = "\r\n";
        char Content_Length[100];
        int content_length = strlen(HTML);

        sprintf(Content_Length, "%i", content_length);

        char *message = malloc((
                strlen(head) +
                strlen(content_head) +
                strlen(server_head) +
                strlen(length_head) +
                strlen(date_head) +
                strlen(newline) +
                strlen(Status_code) +
                strlen(Content_Type) +
                strlen(Content_Length) +
                content_length +
                sizeof(char)) * 2);

        if ( message != NULL )
        {
                time_t rawtime;

                time ( &rawtime );

                strcpy(message, head);

                strcat(message, Status_code);

                strcat(message, content_head);
                strcat(message, Content_Type);
                strcat(message, server_head);
                strcat(message, length_head);
                strcat(message, Content_Length);
                strcat(message, date_head);
                strcat(message, (char*)ctime(&rawtime));
                strcat(message, newline);
                strcat(message, HTML);

                Send(message);

                free(message);
        }
}
</code>```

If I were to add

```<code>Send("Oh end of HTML Sending eh?");
</code>```

after Send(message) and before free(message), this isn't sent to the browser?

I figured this might be a HTTP 1.1 issue, does the RFC say that i can only do one Send? Does the browser Close the connection after it receives the first message?

How do I solve this so I could do the following:

```<code>SendHTML("200 OK", "text/plain", "HAaaaii!!");
Send("lolwut?");
</code>```

This should result in the Browser showing:

HAaaaii!!lolwut?

答:
In your head variable, there should be no leading "\r\n".  That's probably what's causing the problem.  Also, when you're malloc'ing your message, you're not reserving enough space for the date+time (26 bytes according to the documentation for ctime(3)), so you're almost certainly overwriting your buffer and causing heap corruption.

If you want to start sending data before you know what the Content-Length is, you can instead use the chunked transfer encoding.  The chunked transfer encoding says, "I'm going to keep giving you a bunch of data in chunks, and I can tell you how long each chunk is, but I don't know how many chunks there are until I'm done."  For example, Google uses the chunked transfer encoding.  Here's a trace of an HTTP request for the Google homepage, generated with cURL:

```<code>curl www.google.com --trace-ascii -
</code>```

(Header snipped -- but no Content-Length header)

The data stream consists of the chunk size (in hexadecimal) followed by a CRLF, then the data bytes.  In this case, there was only one chunk, but there could easily have been more.  After the last chunk, a chunk size of 0 is transmitted, indicating the last chunk.

OwnerDisplayName: Filip Ekberg

ContentLicense: CC BY-SA 2.5

Title: C, HTTP 1.1 and Socket Send troubles

Body:
As an addition to my previous post on Creating a web server in pure C, I'm having some trouble with the Sending function. Here's two code snippets:

int Send(char *message)
{
        int length, bytes_sent;
        length = strlen(message);

        bytes_sent = send(connecting_socket, message, length, 0);

        return bytes_sent;
}

This code sends void * to the current socket. Works like a charm!

Now here comes the SendHTML

void SendHTML(char *Status_code, char *Content_Type, char *HTML)
{
        char *head = "\r\nHTTP/1.1 ";
        char *content_head = "\r\nContent-Type: ";
        char *server_head = "\r\nServer: PT06";
        char *length_head = "\r\nContent-Length: ";
        char *date_head = "\r\nDate: ";
        char *newline = "\r\n";
        char Content_Length[100];
        int content_length = strlen(HTML);

        sprintf(Content_Length, "%i", content_length);

        char *message = malloc((
                strlen(head) +
                strlen(content_head) +
                strlen(server_head) +
                strlen(length_head) +
                strlen(date_head) +
                strlen(newline) +
                strlen(Status_code) +
                strlen(Content_Type) +
                strlen(Content_Length) +
                content_length +
                sizeof(char)) * 2);

        if ( message != NULL )
        {
                time_t rawtime;

                time ( &rawtime );

                strcpy(message, head);

                strcat(message, Status_code);

                strcat(message, content_head);
                strcat(message, Content_Type);
                strcat(message, server_head);
                strcat(message, length_head);
                strcat(message, Content_Length);
                strcat(message, date_head);
                strcat(message, (char*)ctime(&rawtime));
                strcat(message, newline);
                strcat(message, HTML);

                Send(message);

                free(message);
        }
}

If I were to add

Send("Oh end of HTML Sending eh?");

after Send(message) and before free(message), this isn't sent to the browser?

I figured this might be a HTTP 1.1 issue, does the RFC say that i can only do one Send? Does the browser Close the connection after it receives the first message?

How do I solve this so I could do the following:

SendHTML("200 OK", "text/plain", "HAaaaii!!");
Send("lolwut?");

This should result in the Browser showing:

HAaaaii!!lolwut?

Body:
In your head variable, there should be no leading "\r\n".  That's probably what's causing the problem.  Also, when you're malloc'ing your message, you're not reserving enough space for the date+time (26 bytes according to the documentation for ctime(3)), so you're almost certainly overwriting your buffer and causing heap corruption.

If you want to start sending data before you know what the Content-Length is, you can instead use the chunked transfer encoding.  The chunked transfer encoding says, "I'm going to keep giving you a bunch of data in chunks, and I can tell you how long each chunk is, but I don't know how many chunks there are until I'm done."  For example, Google uses the chunked transfer encoding.  Here's a trace of an HTTP request for the Google homepage, generated with cURL:

curl www.google.com --trace-ascii -

(Header snipped -- but no Content-Length header)

The data stream consists of the chunk size (in hexadecimal) followed by a CRLF, then the data bytes.  In this case, there was only one chunk, but there could easily have been more.  After the last chunk, a chunk size of 0 is transmitted, indicating the last chunk.

OwnerDisplayName: Adam Rosenfield

LastEditorDisplayName: Adam Rosenfield


问:
string.empty and string.isnullorempty
I have a function like this which checks whether the field is empty or what and if empty then get the setError icon aside the textbox.

```<code>      private bool ValidateHost()
      {
        ErrorProvider errorProvider = new ErrorProvider();
        bool isValid = true;

        //If the txtHost is empty, show a message to user
        if(txtHost.Text == string.Empty)
            {
            errorProvider.SetError(txtHost, "Please enter the host address");
            isValid = false;
            }
        else
            errorProvider.SetError(txtHost, string.Empty);
        return isValid;
      }
</code>```

but when I tried to use string,isnullorempty then I am not getting the seterror icon..
Can you guys plz tell me what is the proper way of using string.isnullorempty in this case..

答:
string.IsNullorEmpty() is a static method, invoked as follows:

```<code>if (string.IsNullOrEmpty(txtHost.Text))
{
    errorProvider.SetError(txtHost, "Please enter the host address");
    isValid = false;
}
</code>```

You can also consider the similar string.IsNullOrWhitespace if spaces, tabs, etc are also invalid.

Title: string.empty and string.isnullorempty

Body:
I have a function like this which checks whether the field is empty or what and if empty then get the setError icon aside the textbox.

      private bool ValidateHost()
      {
        ErrorProvider errorProvider = new ErrorProvider();
        bool isValid = true;

        //If the txtHost is empty, show a message to user
        if(txtHost.Text == string.Empty)
            {
            errorProvider.SetError(txtHost, "Please enter the host address");
            isValid = false;
            }
        else
            errorProvider.SetError(txtHost, string.Empty);
        return isValid;
      }

but when I tried to use string,isnullorempty then I am not getting the seterror icon..
Can you guys plz tell me what is the proper way of using string.isnullorempty in this case..

Body:
string.IsNullorEmpty() is a static method, invoked as follows:

if (string.IsNullOrEmpty(txtHost.Text))
{
    errorProvider.SetError(txtHost, "Please enter the host address");
    isValid = false;
}

You can also consider the similar string.IsNullOrWhitespace if spaces, tabs, etc are also invalid.


问:
Perform a google.cloud.happybase Bigtable RowKeyRegexFilter Scan

UPDATE: This only happens with Google Cloud Bigtable Emulator, not with actual development or production BigTable instances (Google Cloud SDK 149.0.0)

I'm trying to do row filtering by Key regex filter, everything is working like a charm (filter by prefix, filter by key start and stop range, by key, by keys) but I can't get it working passing in the RowKeyRegexFilteras filter, it just returns all the keys as an empty keys scan:

```<code># all the boilerplate to create a happybase connection skipped
t = connection.table("sometable")
t.put(
    b'row1',
    {
       b"family1:col2": b".1",
       b"family2:col2": b".12",
    }
)
t.put(
    b'row2',
    {
       b"family1:col2": b".2",
       b"family2:col2": b".22",
    }
)
t.put(
    b'row3',
    {
       b"family1:col2": b".3",
       b"family2:col2": b".32",
    }
)
rows = t.scan(
    filter=RowKeyRegexFilter(b'.+3')
)
print(len([i for i in rows])
</code>```

That gives always 3, no matter if you put (nomatchforsure)+ as regex, I could not find any documentation with a working example, and the most amazing thing is that google.cloud.happybase.table.Table.rows performs a filter by row key always with RowKeyRegexFilter, but passing regex into rows method instead of real rows keys don't give regex filtering either, you can see it

here: https://github.com/GoogleCloudPlatform/google-cloud-python-happybase/blob/master/src/google/cloud/happybase/table.py#L197

and here: https://github.com/GoogleCloudPlatform/google-cloud-python-happybase/blob/master/src/google/cloud/happybase/table.py#L971

Any help on this would be very appreciated

答:
UPDATE: It's actually annotated in the docs as noticed by @gary-elliott: https://cloud.google.com/bigtable/docs/emulator#filters
  Regular expressions must contain only valid UTF-8 characters, unlike the actual Cloud Bigtable service which can process regular expressions as arbitrary bytes. Although something simple like (notmatchforsure)+is not working either although it seems containing valid UTF8 characters, on my testings I would say it is not limited, but generally speaking not working. Anyway is correctly warned in docs.

The actual problem is a bug on the emulator, I updated the answer to avoid misleading feedback, the solution was to create a development instance for testing the code, so for now if you want to do some development with Regex filters in BigTable you gotta create (and pay for...) an at least development instance ($0.65/hour, $0.17/GB at the moment of the response). Hope this helps as if someone is expecting to play with emulator he can get some hours stuck as I was.

Body:
UPDATE: This only happens with Google Cloud Bigtable Emulator, not with actual development or production BigTable instances (Google Cloud SDK 149.0.0)

I'm trying to do row filtering by Key regex filter, everything is working like a charm (filter by prefix, filter by key start and stop range, by key, by keys) but I can't get it working passing in the RowKeyRegexFilteras filter, it just returns all the keys as an empty keys scan:

# all the boilerplate to create a happybase connection skipped
t = connection.table("sometable")
t.put(
    b'row1',
    {
       b"family1:col2": b".1",
       b"family2:col2": b".12",
    }
)
t.put(
    b'row2',
    {
       b"family1:col2": b".2",
       b"family2:col2": b".22",
    }
)
t.put(
    b'row3',
    {
       b"family1:col2": b".3",
       b"family2:col2": b".32",
    }
)
rows = t.scan(
    filter=RowKeyRegexFilter(b'.+3')
)
print(len([i for i in rows])

That gives always 3, no matter if you put (nomatchforsure)+ as regex, I could not find any documentation with a working example, and the most amazing thing is that google.cloud.happybase.table.Table.rows performs a filter by row key always with RowKeyRegexFilter, but passing regex into rows method instead of real rows keys don't give regex filtering either, you can see it

here: https://github.com/GoogleCloudPlatform/google-cloud-python-happybase/blob/master/src/google/cloud/happybase/table.py#L197

and here: https://github.com/GoogleCloudPlatform/google-cloud-python-happybase/blob/master/src/google/cloud/happybase/table.py#L971

Any help on this would be very appreciated


问:
NOT EXIST clause
I am trying to find Products that have never been ordered. My 2 tables look like this.

```<code>CREATE TABLE Orders
(OrderNum    NUMBER(10)      NOT NULL,
 OrderDate   DATE            NOT NULL,
 Cust        NUMBER(10),
 Rep         NUMBER(10),
 Mfr         CHAR(3)         NOT NULL,
 Product     CHAR(5)         NOT NULL,
 Qty         NUMBER(5)       NOT NULL,
 Amount      NUMBER(9,2)     NOT NULL,
 CONSTRAINT OrdersPK
      PRIMARY KEY (OrderNum));

CREATE TABLE Products
(Mfr         CHAR(3)         NOT NULL,
 Product     CHAR(5)         NOT NULL,
 Description VARCHAR2(20)    NOT NULL,
 Price       NUMBER(9,2)     NOT NULL,
 QtyOnHand   NUMBER(5),
 CONSTRAINT ProductsPK
      PRIMARY KEY (Mfr, Product));
</code>```

The code I currently have looks like this.

```<code>SELECT Mfr, Product
FROM Products
WHERE NOT EXISTS (SELECT Products.Mfr
                  FROM Orders, Products
                  WHERE Orders.Mfr = Products.Mfr);
</code>```

Although I am not getting any errors there are also no results showing up.

**EDIT: There are 26 Products and 19 of them have been ordered. I am expecting to get 7 Results but I am getting 0.

答:
You can use NOT EXISTS, but you need to compare both keys:

```<code>SELECT p.Mfr, p.Product
FROM Products p
WHERE NOT EXISTS (SELECT 1
                  FROM Orders o
                  WHERE o.Mfr = p.Mfr AND
                        o.Product = p.Product
                 );
</code>```

This is a case where it makes lots of sense to have an auto generated primary key that can be used for foreign key relationships.

Title: NOT EXIST clause

Body:
I am trying to find Products that have never been ordered. My 2 tables look like this.

CREATE TABLE Orders
(OrderNum    NUMBER(10)      NOT NULL,
 OrderDate   DATE            NOT NULL,
 Cust        NUMBER(10),
 Rep         NUMBER(10),
 Mfr         CHAR(3)         NOT NULL,
 Product     CHAR(5)         NOT NULL,
 Qty         NUMBER(5)       NOT NULL,
 Amount      NUMBER(9,2)     NOT NULL,
 CONSTRAINT OrdersPK
      PRIMARY KEY (OrderNum));

CREATE TABLE Products
(Mfr         CHAR(3)         NOT NULL,
 Product     CHAR(5)         NOT NULL,
 Description VARCHAR2(20)    NOT NULL,
 Price       NUMBER(9,2)     NOT NULL,
 QtyOnHand   NUMBER(5),
 CONSTRAINT ProductsPK
      PRIMARY KEY (Mfr, Product));

The code I currently have looks like this.

SELECT Mfr, Product
FROM Products
WHERE NOT EXISTS (SELECT Products.Mfr
                  FROM Orders, Products
                  WHERE Orders.Mfr = Products.Mfr);

Although I am not getting any errors there are also no results showing up.

**EDIT: There are 26 Products and 19 of them have been ordered. I am expecting to get 7 Results but I am getting 0.

Body:
You can use NOT EXISTS, but you need to compare both keys:

SELECT p.Mfr, p.Product
FROM Products p
WHERE NOT EXISTS (SELECT 1
                  FROM Orders o
                  WHERE o.Mfr = p.Mfr AND
                        o.Product = p.Product
                 );

This is a case where it makes lots of sense to have an auto generated primary key that can be used for foreign key relationships.


问:
Efficient alternative for calculating sum of number of prime divisors (not distinct) of numbers till num
A number is said to have n prime divisors if it can factored into n prime numbers (not necessarily distinct).

E.g.:

```<code>12 = 2*2*3 ---> 12 has 3 prime divisors
</code>```

Given numbers a and b we have to find the number of such prime divisors of a!/b!(a>=b). Hence I decided to do the following way:

```<code>long long pre[5000001];

long long solve(int num)
{
    if(!num)
        return 0;
    if(pre[num] || num==1)
        return pre[num];
    int num1=num;
    if(num1%2==0)
    {
        int cnt=0;
        while(num1%2==0)
        {
            num1/=2;
            cnt++;
        }
        pre[num] = solve(num-1) + (solve(num1)-solve(num1-1)) + cnt;
        return pre[num];
    }

    for(int i=3;i<=(int)(sqrt(num1))+1;++i)
    {
        if(num1%i==0)
        {
            int cnt=0;
            while(num1%i==0)
            {
                cnt++;
                num1/=i;
            }
            pre[num] = solve(num-1) + (solve(num1)-solve(num1-1)) + cnt;
            return pre[num];
        }
    }
    if(num>1)
    {
        pre[num]=1 + solve(num-1);
        return pre[num];
    }
}

int main()
{
    int t;
    cin>>t;
    pre[1]=0;
    while(t--)
    {
        int a,b;
        cin>>a>>b;
        long long ans = solve(a)-solve(b);
        cout<<ans<<endl;
    }
    return 0;
}
</code>```

My approach was to basically to calculate the number of prime divisors and store them because the limit for a and b was <=5000000. pre[num] gives the sum of number of prime divisors of all numbers <=num. But it results in run-time error for larger inputs such as a=5000000 b=4999995. Is there any better way to do this or the present approach can be tweaked for a better solution?

答:
You reach your limit of recursion.

To fix your problem, your may build your array from 0 to a first:

```<code>int main()
{
    int max_a = 0;
    int t;
    cin >> t;
    pre[1] = 0;
    while(t--)
    {
        int a, b;
        cin >> a >> b;

        for (int i = max_a; i < a; ++i) {
            solve(i); // memoization until `a` max recursion is limited to 1 :)
        }
        max_a = std::max(max_a, a);
        long long ans = solve(a) - solve(b);
        std::cout << ans << std::endl;
    }
}
</code>```

Body:
A number is said to have n prime divisors if it can factored into n prime numbers (not necessarily distinct).

E.g.:

12 = 2*2*3 ---> 12 has 3 prime divisors

Given numbers a and b we have to find the number of such prime divisors of a!/b!(a>=b). Hence I decided to do the following way:

long long pre[5000001];

long long solve(int num)
{
    if(!num)
        return 0;
    if(pre[num] || num==1)
        return pre[num];
    int num1=num;
    if(num1%2==0)
    {
        int cnt=0;
        while(num1%2==0)
        {
            num1/=2;
            cnt++;
        }
        pre[num] = solve(num-1) + (solve(num1)-solve(num1-1)) + cnt;
        return pre[num];
    }

    for(int i=3;i<=(int)(sqrt(num1))+1;++i)
    {
        if(num1%i==0)
        {
            int cnt=0;
            while(num1%i==0)
            {
                cnt++;
                num1/=i;
            }
            pre[num] = solve(num-1) + (solve(num1)-solve(num1-1)) + cnt;
            return pre[num];
        }
    }
    if(num>1)
    {
        pre[num]=1 + solve(num-1);
        return pre[num];
    }
}

int main()
{
    int t;
    cin>>t;
    pre[1]=0;
    while(t--)
    {
        int a,b;
        cin>>a>>b;
        long long ans = solve(a)-solve(b);
        cout<<ans<<endl;
    }
    return 0;
}

My approach was to basically to calculate the number of prime divisors and store them because the limit for a and b was <=5000000. pre[num] gives the sum of number of prime divisors of all numbers <=num. But it results in run-time error for larger inputs such as a=5000000 b=4999995. Is there any better way to do this or the present approach can be tweaked for a better solution?

Body:
You reach your limit of recursion.

To fix your problem, your may build your array from 0 to a first:

int main()
{
    int max_a = 0;
    int t;
    cin >> t;
    pre[1] = 0;
    while(t--)
    {
        int a, b;
        cin >> a >> b;

        for (int i = max_a; i < a; ++i) {
            solve(i); // memoization until `a` max recursion is limited to 1 :)
        }
        max_a = std::max(max_a, a);
        long long ans = solve(a) - solve(b);
        std::cout << ans << std::endl;
    }
}


问:
Sizing elements to percentage of screen width/height
Is there a simple (non-LayoutBuilder) way to size an element relative to screen size (width/height)? For example: how do I set the width of a CardView to be 65% of the screen width.

It can't be done inside the build method (obviously) so it would have to be deferred until post build. Is there a preferred place to put logic like this?

答:
You could build a Column/Row with Flexible or Expanded children that have flex values that add up to the percentages you want.

You may also find the AspectRatio widget useful.

ContentLicense: CC BY-SA 4.0


问:
ionic POST request error, net::ERR_CONNECTION_REFUSED
i have an ionic app and i'm trying to test it on my android device. the app works when testing it on the browser using 'ionic serve' but when i run 'ionic run android' the post request does not seem to hit the server. I'm getting an error

```<code>'POST http://localhost:3000/login net::ERR_CONNECTION_REFUSED'
</code>```

for the server i'm using nodejs and have access-control..

```<code>app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header(
    'Access-Control-Allow-Headers',
    'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'
  );
  if ('OPTIONS' === req.method) {
    res.status(200).end();
  } else {
    next();
  }
});
</code>```

i've also installed cordova whitelist plugin and the meta content-security-policy like so..

```<code><meta http-equiv="Content-Security-Policy" content="default-src *; style-src *    'unsafe-inline'; script-src * 'unsafe-inline'; media-src *; img-src * data:;"/>
</code>```

but i'm still getting the same error.
i've also tried using my ip instead of localhost and got this error.

```<code>OPTIONS http://192.168.1.66:3000/login net::ERR_CONNECTION_TIMED_OUT
</code>```

i've followed this thread..
net::ERR_CONNECTION_REFUSED ionic
suggesting that i enable CORS by installing the microsoft.aspnet.webapi.cors.. i followed this link https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors and now i'm totally lost. please help, i've been on this for 3 days now.
i appreciate all your help. thank you.

答:
You are getting a CONNECTION_REFUSED when you try to connect to localhost from the device, which makes sense - as the server process is not running on the device - it is running on your machine.

The second example is more correct, in that from the device, you are trying to connect to your machine - but we see a different error: CONNECTION TIMEOUT

This one is actually due to your local firewall; you will by default allow connections to that port from within your local host - but we need to do some magic to allow packets from the world to talk to that service.

Are you running the server process on *nix? Or Windows?

For *nix

```<code># Using firewalld (advanced wrapper around iptables)
firewall-cmd --zone=public --add-port=tcp/3000 --permanent
firewall-cmd --reload

# Using bare iptables
iptables -I INPUT -p tcp --dport 3000 -j ACCEPT
</code>```

For Windows

Open the Firewall configuration, and under Inbound Rules find the listing for the server process that you are running.

Double click the entry to open the properties window - in here click Allow the Connection, and Apply.

From the device

Try to again connect to the server process on your computer.

Body:
i have an ionic app and i'm trying to test it on my android device. the app works when testing it on the browser using 'ionic serve' but when i run 'ionic run android' the post request does not seem to hit the server. I'm getting an error

'POST http://localhost:3000/login net::ERR_CONNECTION_REFUSED'

for the server i'm using nodejs and have access-control..

app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header(
    'Access-Control-Allow-Headers',
    'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'
  );
  if ('OPTIONS' === req.method) {
    res.status(200).end();
  } else {
    next();
  }
});

i've also installed cordova whitelist plugin and the meta content-security-policy like so..

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src *    'unsafe-inline'; script-src * 'unsafe-inline'; media-src *; img-src * data:;"/>

but i'm still getting the same error.
i've also tried using my ip instead of localhost and got this error.

OPTIONS http://192.168.1.66:3000/login net::ERR_CONNECTION_TIMED_OUT

i've followed this thread..
net::ERR_CONNECTION_REFUSED ionic
suggesting that i enable CORS by installing the microsoft.aspnet.webapi.cors.. i followed this link https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors and now i'm totally lost. please help, i've been on this for 3 days now.
i appreciate all your help. thank you.

Body:
You are getting a CONNECTION_REFUSED when you try to connect to localhost from the device, which makes sense - as the server process is not running on the device - it is running on your machine.

The second example is more correct, in that from the device, you are trying to connect to your machine - but we see a different error: CONNECTION TIMEOUT

This one is actually due to your local firewall; you will by default allow connections to that port from within your local host - but we need to do some magic to allow packets from the world to talk to that service.

Are you running the server process on *nix? Or Windows?

For *nix

# Using firewalld (advanced wrapper around iptables)
firewall-cmd --zone=public --add-port=tcp/3000 --permanent
firewall-cmd --reload

# Using bare iptables
iptables -I INPUT -p tcp --dport 3000 -j ACCEPT

For Windows

Open the Firewall configuration, and under Inbound Rules find the listing for the server process that you are running.

Double click the entry to open the properties window - in here click Allow the Connection, and Apply.

From the device

Try to again connect to the server process on your computer.


问:
DRBD - automatic recover after disconnect
I have High availability cluster that configured with DRBD resource.

```<code> Master/Slave Set: RVClone01 [RV_data01]
     Masters: [ rvpcmk01-cr ]
     Slaves: [ rvpcmk02-cr ]
</code>```

I perform a test that disconnect one of the network adapter that connect between the DRBD network interfaces (for example shutdown the network adapter).
Now the cluster display statuses that everything o.k BUT the status of the DRBD when running "drbd-overview" shows in primary server:

```<code>[root@rvpcmk01 ~]# drbd-overview
 0:drbd0/0  WFConnection Primary/Unknown UpToDate/DUnknown /opt ext4 30G 13G 16G 45%
</code>```

and in the secondary server:

```<code>[root@rvpcmk02 ~]# drbd-overview
 0:drbd0/0  StandAlone Secondary/Unknown UpToDate/DUnknown
</code>```

Now I have few questions:
1. Why cluster doesn't know about the problem with the DRBD?
2. Why when I put the network adapter that was down to UP again and connect back the connection between the DRBD the DRBD didn't handle this failure and sync back the DRBD when connection is o.k?
3. I saw an article that talk about "Solve a DRBD split-brain" - https://www.hastexo.com/resources/hints-and-kinks/solve-drbd-split-brain-4-steps/
in this article it's explain how to get over a problem of disconnection and resync the DRBD.
BUT how I should know that this kind of problem exist?

I hope I explain my case clearly and provide enough information about what I have and what I need...

答:
1) You aren't using fencing/STONITH devices in Pacemaker or DRBD, which is why nothing happens when you unplug your network interface that DRBD is using. This isn't a scenario that Pacemaker will react to without defining fencing policies within DRBD, and STONITH devices within Pacemaker.

2) You likely are only using one ring for the Corosync communications (the same as the DRBD device), which will cause the Secondary to promote to Primary (introducing a split-brain in DRBD), until the cluster communications are reconnected and realize they have two masters, demoting one to Secondary. Again, fencing/STONITH would prevent/handle this.

3) You can set up the split-brain notification handler in your DRBD configuration.

Once you have STONITH/fencing devices setup in Pacemaker, you would add the following definitions to your DRBD configuration to "fix" all the issues you mentioned in your question:

```<code>resource <resource>
  handlers {
    split-brain "/usr/lib/drbd/notify-split-brain.sh root";
    fence-peer "/usr/lib/drbd/crm-fence-peer.sh";
    after-resync-target "/usr/lib/drbd/crm-unfence-peer.sh";
    ...
  }
  disk {
    fencing resource-and-stonith;
    ...
  }
  ...
}
</code>```

Setting up fencing/STONITH in Pacemaker is a little too dependent on your hardware/software for me to give you pointers on setting that up for your cluster. This should get you pointed in the right direction:
  http://clusterlabs.org/doc/crm_fencing.html

Hope that helps!

Body:
I have High availability cluster that configured with DRBD resource.

 Master/Slave Set: RVClone01 [RV_data01]
     Masters: [ rvpcmk01-cr ]
     Slaves: [ rvpcmk02-cr ]

I perform a test that disconnect one of the network adapter that connect between the DRBD network interfaces (for example shutdown the network adapter).
Now the cluster display statuses that everything o.k BUT the status of the DRBD when running "drbd-overview" shows in primary server:

[root@rvpcmk01 ~]# drbd-overview
 0:drbd0/0  WFConnection Primary/Unknown UpToDate/DUnknown /opt ext4 30G 13G 16G 45%

and in the secondary server:

[root@rvpcmk02 ~]# drbd-overview
 0:drbd0/0  StandAlone Secondary/Unknown UpToDate/DUnknown

Now I have few questions:
1. Why cluster doesn't know about the problem with the DRBD?
2. Why when I put the network adapter that was down to UP again and connect back the connection between the DRBD the DRBD didn't handle this failure and sync back the DRBD when connection is o.k?
3. I saw an article that talk about "Solve a DRBD split-brain" - https://www.hastexo.com/resources/hints-and-kinks/solve-drbd-split-brain-4-steps/
in this article it's explain how to get over a problem of disconnection and resync the DRBD.
BUT how I should know that this kind of problem exist?

I hope I explain my case clearly and provide enough information about what I have and what I need...

Body:
1) You aren't using fencing/STONITH devices in Pacemaker or DRBD, which is why nothing happens when you unplug your network interface that DRBD is using. This isn't a scenario that Pacemaker will react to without defining fencing policies within DRBD, and STONITH devices within Pacemaker.

2) You likely are only using one ring for the Corosync communications (the same as the DRBD device), which will cause the Secondary to promote to Primary (introducing a split-brain in DRBD), until the cluster communications are reconnected and realize they have two masters, demoting one to Secondary. Again, fencing/STONITH would prevent/handle this.

3) You can set up the split-brain notification handler in your DRBD configuration.

Once you have STONITH/fencing devices setup in Pacemaker, you would add the following definitions to your DRBD configuration to "fix" all the issues you mentioned in your question:

resource <resource>
  handlers {
    split-brain "/usr/lib/drbd/notify-split-brain.sh root";
    fence-peer "/usr/lib/drbd/crm-fence-peer.sh";
    after-resync-target "/usr/lib/drbd/crm-unfence-peer.sh";
    ...
  }
  disk {
    fencing resource-and-stonith;
    ...
  }
  ...
}

Setting up fencing/STONITH in Pacemaker is a little too dependent on your hardware/software for me to give you pointers on setting that up for your cluster. This should get you pointed in the right direction:
  http://clusterlabs.org/doc/crm_fencing.html

Hope that helps!


问:
how to hide the content of the div in css
I have this html code

```<code><div id="mybox"> aaaaaaa </div>
</code>```

and this is my css

```<code>#mybox{
   background-color:green;
}

#mybox:hover{
   background-color:red;
}
</code>```

the question is how to hide the content of the div (aaaaaaa) when the mouse hover event by using css only and without changing the structure of the code
I think I should put some code under #mybox:hover but I don't know the code.

Body:
I have this html code

 aaaaaaa

and this is my css

#mybox{
   background-color:green;
}

#mybox:hover{
   background-color:red;
}

the question is how to hide the content of the div (aaaaaaa) when the mouse hover event by using css only and without changing the structure of the code
I think I should put some code under #mybox:hover but I don't know the code.

Body:
.button {
        width: 40px;
        height: 40px;
        font-size: 0;
        background: url("data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%221284%20207%2024%2024%22%3E%3Cg%20fill%3D%22none%22%3E%3Cpath%20d%3D%22M1298.5%20222.9C1297.5%20223.6%201296.3%20224%201295%20224%201291.7%20224%201289%20221.3%201289%20218%201289%20214.7%201291.7%20212%201295%20212%201298.3%20212%201301%20214.7%201301%20218%201301%20219.3%201300.6%20220.5%201299.9%20221.5L1302.7%20224.2C1303%20224.6%201303.1%20225.3%201302.7%20225.7%201302.3%20226%201301.6%20226%201301.2%20225.7L1298.5%20222.9ZM1295%20222C1297.2%20222%201299%20220.2%201299%20218%201299%20215.8%201297.2%20214%201295%20214%201292.8%20214%201291%20215.8%201291%20218%201291%20220.2%201292.8%20222%201295%20222Z%22%20fill%3D%22%239299A6%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E") #f0f2f5 no-repeat 50%;
    }

<button class="button">Поиск</button>


问:
How to remove and replace select options using jquery?
Need a little help here. I have a dynamic form that enables user to select his/her correct addresses. What I did is I have 2 select boxes. One is States and second is city. After the user choose his/her states the dropdown city options will be change dynamically according to the selected states. My problem is, I am appending it. That's why I have a problem changing the correct city. Because it will display the previous selected option value. It keeps on appending and appending. Any idea how can I work on this? Here's my code.

```<code>$('#state').on('change',function(){
    var state_code = $('#state').val();
    var city_url = '<?php echo site_url("locations/displayCity/' + state_code + '"); ?>';
    $.ajax({
        type: 'POST',
        url: city_url,
        data: '',
        dataType: 'json',
        async: false,
        success: function(i){
            var select = $('#city');
            for (var j = 0; j < i.length; j++){
                console.log(i[j].name + "--" + i[j].id);
                $("#city").append("<option value='" +i[j].name+ "'>" +i[j].name+ "</option>");
            }
        }
    });
});
</code>```

Here's the select for city:

```<code><select id="city" name="city">
    <option value="">---Select City---</option>
</select>
</code>```

答:
Simply because I ran into this situation - I thought I'd mention that if you are using bootstrap-select to prettify your select boxes (or even another similar javascript visual substitution for your conventional html select) you may need to refresh it once you've repopulated the options. In the case of select-bootstrap it's a matter of $(element).selectpicker('refresh') - in example:

```<code>function changeSelectOptions( id, max ) {
    var selectbox = $(id);
    selectbox.empty();
    var list = '';
    for (var j = 1; j < max; j++){
        list += "<option value='" +j+ "'>" +j+ "</option>";
    }
    selectbox.html(list);
    $(id).selectpicker('refresh');
}
</code>```

Body:
Need a little help here. I have a dynamic form that enables user to select his/her correct addresses. What I did is I have 2 select boxes. One is States and second is city. After the user choose his/her states the dropdown city options will be change dynamically according to the selected states. My problem is, I am appending it. That's why I have a problem changing the correct city. Because it will display the previous selected option value. It keeps on appending and appending. Any idea how can I work on this? Here's my code.

$('#state').on('change',function(){
    var state_code = $('#state').val();
    var city_url = '<?php echo site_url("locations/displayCity/' + state_code + '"); ?>';
    $.ajax({
        type: 'POST',
        url: city_url,
        data: '',
        dataType: 'json',
        async: false,
        success: function(i){
            var select = $('#city');
            for (var j = 0; j < i.length; j++){
                console.log(i[j].name + "--" + i[j].id);
                $("#city").append("<option value='" +i[j].name+ "'>" +i[j].name+ "</option>");
            }
        }
    });
});

Here's the select for city:

<select id="city" name="city">
    <option value="">---Select City---</option>
</select>

Body:
Simply because I ran into this situation - I thought I'd mention that if you are using bootstrap-select to prettify your select boxes (or even another similar javascript visual substitution for your conventional html select) you may need to refresh it once you've repopulated the options. In the case of select-bootstrap it's a matter of $(element).selectpicker('refresh') - in example:

function changeSelectOptions( id, max ) {
    var selectbox = $(id);
    selectbox.empty();
    var list = '';
    for (var j = 1; j < max; j++){
        list += "<option value='" +j+ "'>" +j+ "</option>";
    }
    selectbox.html(list);
    $(id).selectpicker('refresh');
}


问:
How to disable TinyMCE confirm dialog
Does anyone know how to disable TinyMCE alerts, and confirms. The confirm in talking about says:

This page is asking you to confirm
  that you want to leave - data you have
  entered may not be saved Leave Page -
  Stay on Page

I've written my own stuff that detects if the page data has been change so I don;t want TinyMCE to worry. I found the function in the TinyMCE source so I'm about to overwrite it but I want to know if anyone knows a better way to accomplish this.
Thanks.

答:
If the problem you're having is just that the content isn't actually dirty, maybe because you replaced it programmatically, you can explicitly mark the editor as not dirty like this:</p>

```<code>tinyMCE.activeEditor.isNotDirty = true
</code>```

Title: How to disable TinyMCE confirm dialog

Body:
If the problem you're having is just that the content isn't actually dirty, maybe because you replaced it programmatically, you can explicitly mark the editor as not dirty like this:

tinyMCE.activeEditor.isNotDirty = true


问:
How to import code formatting settings from tslint.json in webstorm?
Is it possible to import formatting settings (Settings => Editor => Code Style => Typescript) from my tslint.json file in webstorm? I use rules directory "node_modules/codelyzer" in my tslint.json file

答:
Since 2017 WebStorm version, it's possible to Apply code style.

Just open tslint.json and WebStorm will ask if it can import it.

Read it about it in WebStorm 2017.1 EAP, 171.2455: improved integration with TSLint


问:
Add string elements to Dynamic Array
Parsing a file and need to add students to a struct vector using an array for student names specific to that course line.

In my course.h file:

```<code>struct Course {
    std::string name;
    int enrollment;
    int maxEnrollment;

    std::string* students; ///< array of student names

    Course(std::string courseName, int maxEnrollmentPermitted);

    bool enroll(std::string studentName);

    void print(std::ostream& output);
};
</code>```

In my course.cpp file:

```<code>bool Course::enroll(std::string studentName) {
    this->students = new std::string[studentName];
    if (this->enrollment < this->maxEnrollment) {
        this->enrollment++;
        return true;
    }
    else {
        return false;
</code>```

In my source file:

```<code>void processEnrollmentRequests(istream& enrollmentRequestsFile, vector<Course>& courses) {
    // Read the requests, one at a time, serving each one
    string courseName;
    enrollmentRequestsFile >> courseName;

    while (enrollmentRequestsFile) {
        enrollmentRequestsFile >> ws;
        string studentName;
        getline(enrollmentRequestsFile, studentName);

        int pos = search(courses, courseName);
        if (pos >= 0) {
            // Found a matching course
            bool enrolled = courses[pos].enroll(studentName);
            if (enrolled) {
                cout << studentName << " has enrolled in " << courseName << endl;
            }
            else {
                // course is full
                cout << studentName << " cannot enroll in " << courseName << endl;
            }
        }
        else {
            // course does not exist
            cout << studentName << " cannot enroll in " << courseName << endl;
        }
        enrollmentRequestsFile >> courseName;
    }
}
        }
    }
</code>```

I cant seem to add the gathered studentName to the array using this->students = new std::string[studentName]. Getting an error that says must have integral or enumeration type.

答:
For the sake of completeness, the allocation of students is not the only problem.  Given that the code you posted also uses std::vector<Course>, and Course does not follow the rule of 3, using it in a std::vector is highly likely to cause memory corruption, leaks, etc.

Given that you state that students must remain a pointer, the complete fix is to write Course in this manner:

```<code>#include <string>
#include <algorithm>

struct Course {
    std::string name;
    int enrollment;
    int maxEnrollment;
    std::string* students; ///< array of student names
    Course(std::string courseName, int maxEnrollmentPermitted);
    bool enroll(std::string studentName);
    void print(std::ostream& output);
    Course(const Course& rhs);
    Course& operator =(const Course& rhs);
    ~Course();
};

Course::Course(const Course& rhs) : name(rhs.name),
                                    enrollment(rhs.enrollment),
                                    maxEnrollment(rhs.maxEnrollment),
                                    students(new std::string[rhs.maxEnrollment])
{
   for (int i = 0; i < maxEnrollment; ++i)
      students[i] = rhs.students[i];
}

Course& Course::operator= (const Course& rhs)
{
   Course temp(rhs);
   std::swap(temp.students, students);
   std::swap(temp.maxEnrollment, maxEnrollment);
   std::swap(temp.enrollment, enrollment);
   std::swap(temp.name, name);
   return *this;
}

Course::~Course() { delete [] students; }

Course::Course(std::string courseName, int maxEnrollmentPermitted) :
               name(courseName),
               enrollment(0),
               maxEnrollment(maxEnrollmentPermitted),
               students(new std::string[maxEnrollmentPermitted])
{}
</code>```

Why all of this code?  Well, in the code you posted in your question, you are using a std::vector<Course>.  The Course class as written could not be safely used in a vector, due to Course having incorrect copy semantics.  Thus your error you're getting may have a lot to do with code you stated wasn't yours (the vector<Course>).

The adjustments to Course above now makes Course safe to be used in a vector since the copy semantics (copy constructor, assignment operator, and destructor) have now been implemented to handle the dynamically allocated students member.

Note that absolutely none of this code would be necessary if students were simply a std::vector<std::string> instead of std::string *.

For more reading:

What is the rule of 3?

What is the copy / swap idiom?

Title: Add string elements to Dynamic Array

Body:
Parsing a file and need to add students to a struct vector using an array for student names specific to that course line.

In my course.h file:

struct Course {
    std::string name;
    int enrollment;
    int maxEnrollment;

    std::string* students; ///< array of student names

    Course(std::string courseName, int maxEnrollmentPermitted);

    bool enroll(std::string studentName);

    void print(std::ostream& output);
};

In my course.cpp file:

bool Course::enroll(std::string studentName) {
    this->students = new std::string[studentName];
    if (this->enrollment < this->maxEnrollment) {
        this->enrollment++;
        return true;
    }
    else {
        return false;

In my source file:

void processEnrollmentRequests(istream& enrollmentRequestsFile, vector<Course>& courses) {
    // Read the requests, one at a time, serving each one
    string courseName;
    enrollmentRequestsFile >> courseName;

    while (enrollmentRequestsFile) {
        enrollmentRequestsFile >> ws;
        string studentName;
        getline(enrollmentRequestsFile, studentName);

        int pos = search(courses, courseName);
        if (pos >= 0) {
            // Found a matching course
            bool enrolled = courses[pos].enroll(studentName);
            if (enrolled) {
                cout << studentName << " has enrolled in " << courseName << endl;
            }
            else {
                // course is full
                cout << studentName << " cannot enroll in " << courseName << endl;
            }
        }
        else {
            // course does not exist
            cout << studentName << " cannot enroll in " << courseName << endl;
        }
        enrollmentRequestsFile >> courseName;
    }
}
        }
    }

I cant seem to add the gathered studentName to the array using this->students = new std::string[studentName]. Getting an error that says must have integral or enumeration type.

Body:
For the sake of completeness, the allocation of students is not the only problem.  Given that the code you posted also uses std::vector<Course>, and Course does not follow the rule of 3, using it in a std::vector is highly likely to cause memory corruption, leaks, etc.

Given that you state that students must remain a pointer, the complete fix is to write Course in this manner:

#include <string>
#include <algorithm>

struct Course {
    std::string name;
    int enrollment;
    int maxEnrollment;
    std::string* students; ///< array of student names
    Course(std::string courseName, int maxEnrollmentPermitted);
    bool enroll(std::string studentName);
    void print(std::ostream& output);
    Course(const Course& rhs);
    Course& operator =(const Course& rhs);
    ~Course();
};

Course::Course(const Course& rhs) : name(rhs.name),
                                    enrollment(rhs.enrollment),
                                    maxEnrollment(rhs.maxEnrollment),
                                    students(new std::string[rhs.maxEnrollment])
{
   for (int i = 0; i < maxEnrollment; ++i)
      students[i] = rhs.students[i];
}

Course& Course::operator= (const Course& rhs)
{
   Course temp(rhs);
   std::swap(temp.students, students);
   std::swap(temp.maxEnrollment, maxEnrollment);
   std::swap(temp.enrollment, enrollment);
   std::swap(temp.name, name);
   return *this;
}

Course::~Course() { delete [] students; }

Course::Course(std::string courseName, int maxEnrollmentPermitted) :
               name(courseName),
               enrollment(0),
               maxEnrollment(maxEnrollmentPermitted),
               students(new std::string[maxEnrollmentPermitted])
{}

Why all of this code?  Well, in the code you posted in your question, you are using a std::vector<Course>.  The Course class as written could not be safely used in a vector, due to Course having incorrect copy semantics.  Thus your error you're getting may have a lot to do with code you stated wasn't yours (the vector<Course>).

The adjustments to Course above now makes Course safe to be used in a vector since the copy semantics (copy constructor, assignment operator, and destructor) have now been implemented to handle the dynamically allocated students member.

Note that absolutely none of this code would be necessary if students were simply a std::vector<std::string> instead of std::string *.

For more reading:

What is the rule of 3?

What is the copy / swap idiom?


问:
string operator and valgrind
I having some problem with correctly write method:
Edited i wrote new probably good

```<code>void operator += ( const string& s )
{
    size_t newLen = len + s.len;
    char    *tmpStr = new char [newLen+1];
    size_t i = 0;
    for(i;i<len;i++)
        {tmpStr[i] = p[i];}
    for(size_t j=0;j<s.len;j++)
    {
    tmpStr[i] = s[j];
    i++;
    }
    delete []p;
    p = tmpStr;
    len = newLen;
    p[len] = '\0';
}
</code>```

Valgrind return me, i got some error and 1 memory leak

```<code>HEAP SUMMARY:
==10152==     in use at exit: 72,704 bytes in 1 blocks
==10152==   total heap usage: 5 allocs, 4 frees, 73,747 bytes
allocated

==10152== LEAK SUMMARY:
==10152==    definitely lost: 0 bytes in 0 blocks
==10152==    indirectly lost: 0 bytes in 0 blocks
==10152==      possibly lost: 0 bytes in 0 blocks
==10152==    still reachable: 72,704 bytes in 1 blocks
==10152==         suppressed: 0 bytes in 0 blocks
==10152== Reachable blocks (those to which a pointer was found) are
not shown.
==10152== To see them, rerun with: --leak-check=full --show-leak-
kinds=all

==10152== For counts of detected and suppressed errors, rerun with: -v
==10152== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
</code>```

I tried it for:

```<code>string s2 = "hello";
string s3 = "abc";
s3 += s2;
</code>```

And my next question is how write, any idea what i have to do?

```<code>void operator += ( char c );
</code>```

Here you are my constructor:

```<code>string( )
  : len{0},
    p{ nullptr }
{ }

string( const char* s )
  : len{ strlen(s) },
    p{ new char[ len ] }
{
  for( size_t i = 0; i < len; ++ i )
     p[i] = s[i];
}

string( const string& s )
  : len{ s. len },
    p{ new char[ len ] }
{
  for( size_t i = 0; i < len; ++ i )
     p[i] = s.p[i];
}
</code>```

Its correct: Leak memory still reachable: 72,704 bytes in 1 blocks

答:
The two errors pointed out make me think that strcpy is going over the allocated memory for the buffer of your internal string type. (since it's going after 5 bytes for "hello" and 3 bytes for "abc").

strcpy is an unsafe operation, it keeps going until it finds a \0 terminator. Now it seems that your internal buffer for your string type is not considering this, suppose something like

```<code>char data[] = {'h', 'e', 'l', 'l', 'o'};
</code>```

This won't work for strcpy since there is no \0. Show us how you construct a string instance.

Now that you've edited the question the problem is clear, your constructor doesn't reserve the space nor it is placing the NUL terminator at the end of the char[] so standard stdlib functions are not working properly, try something like:

```<code>string( const char* s )
  : len{ strlen(s) },
    p{ new char[ len+1 ] }
{
  for( size_t i = 0; i < len; ++ i )
     p[i] = s[i];
  p[len] = '\0';
}
</code>```

The difference here is that you are allocating len+1 character for your buffer and placing \0 in the last element of the array.

This terminator will work for stdlib functions so that they'll know where to stop. Now strcpy will properly work when finding the terminator.

Title: string operator and valgrind

Body:
I having some problem with correctly write method:
Edited i wrote new probably good

void operator += ( const string& s )
{
    size_t newLen = len + s.len;
    char    *tmpStr = new char [newLen+1];
    size_t i = 0;
    for(i;i<len;i++)
        {tmpStr[i] = p[i];}
    for(size_t j=0;j<s.len;j++)
    {
    tmpStr[i] = s[j];
    i++;
    }
    delete []p;
    p = tmpStr;
    len = newLen;
    p[len] = '\0';
}

Valgrind return me, i got some error and 1 memory leak

HEAP SUMMARY:
==10152==     in use at exit: 72,704 bytes in 1 blocks
==10152==   total heap usage: 5 allocs, 4 frees, 73,747 bytes
allocated

==10152== LEAK SUMMARY:
==10152==    definitely lost: 0 bytes in 0 blocks
==10152==    indirectly lost: 0 bytes in 0 blocks
==10152==      possibly lost: 0 bytes in 0 blocks
==10152==    still reachable: 72,704 bytes in 1 blocks
==10152==         suppressed: 0 bytes in 0 blocks
==10152== Reachable blocks (those to which a pointer was found) are
not shown.
==10152== To see them, rerun with: --leak-check=full --show-leak-
kinds=all

==10152== For counts of detected and suppressed errors, rerun with: -v
==10152== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

I tried it for:

string s2 = "hello";
string s3 = "abc";
s3 += s2;

And my next question is how write, any idea what i have to do?

void operator += ( char c );

Here you are my constructor:

string( )
  : len{0},
    p{ nullptr }
{ }

string( const char* s )
  : len{ strlen(s) },
    p{ new char[ len ] }
{
  for( size_t i = 0; i < len; ++ i )
     p[i] = s[i];
}

string( const string& s )
  : len{ s. len },
    p{ new char[ len ] }
{
  for( size_t i = 0; i < len; ++ i )
     p[i] = s.p[i];
}

Its correct: Leak memory still reachable: 72,704 bytes in 1 blocks

Body:
The two errors pointed out make me think that strcpy is going over the allocated memory for the buffer of your internal string type. (since it's going after 5 bytes for "hello" and 3 bytes for "abc").

strcpy is an unsafe operation, it keeps going until it finds a \0 terminator. Now it seems that your internal buffer for your string type is not considering this, suppose something like

char data[] = {'h', 'e', 'l', 'l', 'o'};

This won't work for strcpy since there is no \0. Show us how you construct a string instance.

Now that you've edited the question the problem is clear, your constructor doesn't reserve the space nor it is placing the NUL terminator at the end of the char[] so standard stdlib functions are not working properly, try something like:

string( const char* s )
  : len{ strlen(s) },
    p{ new char[ len+1 ] }
{
  for( size_t i = 0; i < len; ++ i )
     p[i] = s[i];
  p[len] = '\0';
}

The difference here is that you are allocating len+1 character for your buffer and placing \0 in the last element of the array.

This terminator will work for stdlib functions so that they'll know where to stop. Now strcpy will properly work when finding the terminator.


问:
Detect HTML5 Geolocation Support Using PHP
I need to detect HTML5 Geolocation support using PHP so that I can load a backup JavaScript that supports Geolocation using IP Address.

How to do this with or without PHP.

答:
You can check Geolocation support using javascript:

```<code>function supports_geolocation() {
     return !!navigator.geolocation;
}
</code>```

I've taken the function from the nice Dive into HTML 5.

Body:
You can check Geolocation support using javascript:

function supports_geolocation() {
     return !!navigator.geolocation;
}

I've taken the function from the nice Dive into HTML 5.


问:
Traversing through nested objects and arrays in php
I am accessing this data via soap and wsdl, finally have the connection returning data. However, I am getting stuck trying to properly access the values in the fv array.  What is the proper way to loop through and access them?</p>

```<code>   stdClass Object
 (
       [DataFormItem] => stdClass Object
    (
        [Values] => stdClass Object
            (
                [fv] => Array
                    (
                        [0] => stdClass Object
                            (
                                [Value] => xxxx
                                [ID] => FIRSTNAME
                            )

                        [1] => stdClass Object
                            (
                                [Value] => xxxx
                                [ID] => LASTNAME
                            )

                        [2] => stdClass Object
                            (
                                [Value] => xxxx
                                [ID] => BIRTHDATE
                            )

                        [3] => stdClass Object
                            (
                                [Value] => xxxx
                                [ID] => DEGREEYEAR
                            )

                        [4] => stdClass Object
                            (
                                [Value] => xxxx
                                [ID] => ADDRESSBLOCK
                            )

                        [5] => stdClass Object
                            (
                                [Value] => xxxx
                                [ID] => CITY
                            )

                   )

            )

    )
</code>```

答:
Try this:</p>

```<code>foreach ($your_object->DataFormItem->Values->fv as $fv_element) {
    echo $fv_element->Value." ".$fv_element->ID."<br>";
}
</code>```

Body:
I am accessing this data via soap and wsdl, finally have the connection returning data. However, I am getting stuck trying to properly access the values in the fv array.  What is the proper way to loop through and access them?

   stdClass Object
 (
       [DataFormItem] => stdClass Object
    (
        [Values] => stdClass Object
            (
                [fv] => Array
                    (
                        [0] => stdClass Object
                            (
                                [Value] => xxxx
                                [ID] => FIRSTNAME
                            )

                        [1] => stdClass Object
                            (
                                [Value] => xxxx
                                [ID] => LASTNAME
                            )

                        [2] => stdClass Object
                            (
                                [Value] => xxxx
                                [ID] => BIRTHDATE
                            )

                        [3] => stdClass Object
                            (
                                [Value] => xxxx
                                [ID] => DEGREEYEAR
                            )

                        [4] => stdClass Object
                            (
                                [Value] => xxxx
                                [ID] => ADDRESSBLOCK
                            )

                        [5] => stdClass Object
                            (
                                [Value] => xxxx
                                [ID] => CITY
                            )

                   )

            )

    )

Body:
Try this:

foreach ($your_object->DataFormItem->Values->fv as $fv_element) {
    echo $fv_element->Value." ".$fv_element->ID."<br>";
}


问:
ajax progress loading does not work properly
I am now in javascript, I am trying to display a indictor icon when ajax  starts and hide it when it finishes, below is my code:

```<code>CSS:
 div.ajax-progress {
      //some setting and url
}
<body>
   <div class="ajax-progress"></div>
</body>
Javascript:

$('#fileToUpload').on('change', function(e) {

            var file = e.target.files[0];
            var formData = new FormData($('form')[0]);
            imageId = cornerstoneWADOImageLoader.fileManager.add(file);

            $.ajax({
            url: 'loadfile.php',
            type: 'POST',
            data: formData,
            async: false,
            dataType: 'json',
            timeout : 60000,
            beforeSend :function(){
                $(".ajax-progress").show();
            }，
            success: function (html) {}
           $(".ajax-progress").hide();
             //doing something}
        });
    });
</code>```

but nothing happens, any idea? appreciated.

答:
I don't know if that's the same to what you have in your code but you commented out the success closing bracket }

you can also use console.log() or alert() to see what's going on in your code.

Body:
I am now in javascript, I am trying to display a indictor icon when ajax  starts and hide it when it finishes, below is my code:

CSS:
 div.ajax-progress {
      //some setting and url
}

Javascript:

$('#fileToUpload').on('change', function(e) {

            var file = e.target.files[0];
            var formData = new FormData($('form')[0]);
            imageId = cornerstoneWADOImageLoader.fileManager.add(file);

            $.ajax({
            url: 'loadfile.php',
            type: 'POST',
            data: formData,
            async: false,
            dataType: 'json',
            timeout : 60000,
            beforeSend :function(){
                $(".ajax-progress").show();
            }，
            success: function (html) {}
           $(".ajax-progress").hide();
             //doing something}
        });
    });

but nothing happens, any idea? appreciated.


问:
Scraping a webpage that has JavaScript with BeautifulSoup
guys! I am applying to you once again. I am ok with scraping simple websites with tags but recently I've encountered a quite complex website which has JavaScript. As a result I would like to obtain all the estimates at the bottom of the page in a format of table (csv). Like 'User', 'Revenue estimate', 'EPS estimate'.

I hoped to figure it by myself but kinda failed.

Here is my code:

```<code>from urllib import urlopen
from bs4 import BeautifulSoup
html = urlopen("https://www.estimize.com/jpm/fq3-2016?sort=rank&direction=asc&estimates_per_page=142&show_confirm=false")
soup = BeautifulSoup(html.read(), "html.parser")
print(soup.findAll('script')[11].string.encode('utf8'))
</code>```

The output has a strange format and I don't know how to extract the data in an adequate form.
 I'll appreciate any help!

答:
Looks like the data you're trying to extract is in a data model, which means it's in JSON.  If you do a small amount of parsing with the following:

```<code>import json
import re

data_string = soup.findAll('script')[11].string.encode('utf8')
data_string = data_string.split("DataModel.parse(")[1]
data_string = data_string.split(");")[0]

// parse out erroneous html
while re.search('\<[^\>]*\>', datastring):
    data_string = ''.join(datastring.split(re.search('\<[^\>]*\>', datastring).group(0)))

// parse out other function parameters, leaving you with the json
data_you_want = json.loads(data_string.split(re.search('\}[^",\}\]]+,', data_string).group(0))[0]+'}')

print(data_you_want["estimate"])
>>> {'shares': {'shares_hash': {'twitter': None, 'stocktwits': None, 'linkedin': None}}, 'lastRevised': None, 'id': None, 'revenue_points': None, 'sector': 'financials', 'persisted': False, 'points': None, 'instrumentSlug': 'jpm', 'wallstreetRevenue': 23972, 'revenue': 23972, 'createdAt': None, 'username': None, 'isBlind': False, 'releaseSlug': 'fq3-2016', 'statement': '', 'errorRanges': {'revenue': {'low': 21247.3532016398, 'high': 26820.423240734}, 'eps': {'low': 1.02460526459765, 'high': 1.81359679579922}}, 'eps_points': None, 'rank': None, 'instrumentId': 981, 'eps': 1.4, 'season': '2016-fall', 'releaseId': 52773}
</code>```

The DataModel.parse is a javascript method which means it ends with a parenthesis and a colon.  the parameter for the function is the JSON object you want.  By loading it into json.loads you're able to access it much like a dictionary.

From there you remap the data into the form you want it to be in for the csv.

Body:
guys! I am applying to you once again. I am ok with scraping simple websites with tags but recently I've encountered a quite complex website which has JavaScript. As a result I would like to obtain all the estimates at the bottom of the page in a format of table (csv). Like 'User', 'Revenue estimate', 'EPS estimate'.

I hoped to figure it by myself but kinda failed.

Here is my code:

from urllib import urlopen
from bs4 import BeautifulSoup
html = urlopen("https://www.estimize.com/jpm/fq3-2016?sort=rank&direction=asc&estimates_per_page=142&show_confirm=false")
soup = BeautifulSoup(html.read(), "html.parser")
print(soup.findAll('script')[11].string.encode('utf8'))

The output has a strange format and I don't know how to extract the data in an adequate form.
 I'll appreciate any help!

Body:
Looks like the data you're trying to extract is in a data model, which means it's in JSON.  If you do a small amount of parsing with the following:

import json
import re

data_string = soup.findAll('script')[11].string.encode('utf8')
data_string = data_string.split("DataModel.parse(")[1]
data_string = data_string.split(");")[0]

// parse out erroneous html
while re.search('\<[^\>]*\>', datastring):
    data_string = ''.join(datastring.split(re.search('\<[^\>]*\>', datastring).group(0)))

// parse out other function parameters, leaving you with the json
data_you_want = json.loads(data_string.split(re.search('\}[^",\}\]]+,', data_string).group(0))[0]+'}')

print(data_you_want["estimate"])
>>> {'shares': {'shares_hash': {'twitter': None, 'stocktwits': None, 'linkedin': None}}, 'lastRevised': None, 'id': None, 'revenue_points': None, 'sector': 'financials', 'persisted': False, 'points': None, 'instrumentSlug': 'jpm', 'wallstreetRevenue': 23972, 'revenue': 23972, 'createdAt': None, 'username': None, 'isBlind': False, 'releaseSlug': 'fq3-2016', 'statement': '', 'errorRanges': {'revenue': {'low': 21247.3532016398, 'high': 26820.423240734}, 'eps': {'low': 1.02460526459765, 'high': 1.81359679579922}}, 'eps_points': None, 'rank': None, 'instrumentId': 981, 'eps': 1.4, 'season': '2016-fall', 'releaseId': 52773}

The DataModel.parse is a javascript method which means it ends with a parenthesis and a colon.  the parameter for the function is the JSON object you want.  By loading it into json.loads you're able to access it much like a dictionary.

From there you remap the data into the form you want it to be in for the csv.


问:
DrRacket Scheme current-pseudo-random-generator contract violation
For the following line:

```<code>(random 9 current-pseudo-random-generator)
</code>```

I'm getting the following error:

```<code>. . random: contract violation
  expected: (or/c (integer-in 1 4294967087) pseudo-random-generator?)
  given: #<procedure:current-pseudo-random-generator>
>
</code>```

What's wrong?

答:
current-pseudo-random-generator is a parameter, so you must use it like

```<code>(random 9 (current-pseudo-random-generator))
</code>```

By default, random will use that automatically so you could simplify your example to (random 9).

Body:
For the following line:

(random 9 current-pseudo-random-generator)

I'm getting the following error:

. . random: contract violation
  expected: (or/c (integer-in 1 4294967087) pseudo-random-generator?)
  given: #<procedure:current-pseudo-random-generator>
>

What's wrong?

Body:
current-pseudo-random-generator is a parameter, so you must use it like

(random 9 (current-pseudo-random-generator))

By default, random will use that automatically so you could simplify your example to (random 9).