问:
"Spell check" and return the corrected term in Python
I recently extracted text data from a directory of pdf files. When reading pdfs, sometimes the text returned is a little messy.

For example, I can be looking at a string that says:

"T he administrati on is doing bad things, and not fulfilling what it
  prom ised"

I want the result to be:

"The administration is doing bad things, and not fulfilling what it
  promised"

I tested code (using pyenchant and wx) I found on stackoverflow here and it did not return what I wanted. My modifications were as follows:

```<code>a = "T he administrati on is doing bad things, and not fulfilling what it prom ised"
chkr = enchant.checker.SpellChecker("en_US")
chkr.set_text(a)
for err in chkr:
    sug = err.suggest()[0]
    err.replace(sug)

c = chkr.get_text()#returns corrected text
print(c)
</code>```

This code returns:

"T he administrate on is doing bad things, and not fulfilling what it
  prom side"

I'm using Python 3.5.x on a Windows 7 Enterprise, 64-bit. I would appreciate any suggestions!

答:
It looks like the enchant library you're using just isn't that good. It doesn't look for spelling mistakes across words, but instead just looks at words individually. I guess this makes sense since the function itself is called 'SpellChecker'.

The only thing I can think of is to look for better autocorrect libraries.
Maybe this one might help?
https://github.com/phatpiglet/autocorrect

No guarantees though.

Body:
I recently extracted text data from a directory of pdf files. When reading pdfs, sometimes the text returned is a little messy.

For example, I can be looking at a string that says:

"T he administrati on is doing bad things, and not fulfilling what it
  prom ised"

I want the result to be:

"The administration is doing bad things, and not fulfilling what it
  promised"

I tested code (using pyenchant and wx) I found on stackoverflow here and it did not return what I wanted. My modifications were as follows:

a = "T he administrati on is doing bad things, and not fulfilling what it prom ised"
chkr = enchant.checker.SpellChecker("en_US")
chkr.set_text(a)
for err in chkr:
    sug = err.suggest()[0]
    err.replace(sug)

c = chkr.get_text()#returns corrected text
print(c)

This code returns:

"T he administrate on is doing bad things, and not fulfilling what it
  prom side"

I'm using Python 3.5.x on a Windows 7 Enterprise, 64-bit. I would appreciate any suggestions!


来源: stackexchange

问:
With text analysis inner_join removes more than a thousand words in R
I'm analysing a column with words in my most_used_words dataframe. With 2180 words.

```<code>most_used_words

        word times_used
       <chr>      <int>
 1    people         70
 2      news         69
 3      fake         68
 4   country         54
 5     media         44
 6       u.s         42
 7  election         40
 8      jobs         37
 9       bad         36
10 democrats         35
# ... with 2,170 more rows
</code>```

When I inner_join with the AFINN lexicon only 364 of the 2180 words are scored. Is this because the words in the in the AFINN lexicon don't appear in my dataframe? I'm affraid if that's the case this may introduce bias in my analysis. Should I use a different lexicon? Is there something else that's happening?

```<code>library(tidytext)
library(tidyverse)

afinn <- get_sentiments("afinn")

most_used_words %>%
  inner_join(afinn)

          word times_used score
         <chr>      <int> <int>
     1    fake         68    -3
     2     bad         36    -3
     3     win         24     4
     4 failing         21    -2
     5    hard         20    -1
     6  united         19     1
     7 illegal         17    -3
     8    cuts         15    -1
     9   badly         13    -3
    10 strange         13    -1
    # ... with 354 more rows
</code>```

答:
```<code>"Is this because the words in the in the AFINN lexicon don't appear in my dataframe?"
</code>```

Yes.

An inner join will only return matching rows (words) from each data.frame.
You can try a different lexicon, sure, but that might not help you with nouns. A noun identifies a person, animal, place, thing, or idea. In your example above, "u.s.", "people", "country", "news", "democrats" are all nouns that don't exist in afinn. None of these have any sentiment without context. Welcome to the world of text analysis.

However, based on the output displayed from you analysis, I think you can conclude the sentiment of your column of words is overwhelmingly "negative". The word "fake" appears nearly twice as much as the next most used word, which is "bad".

If you had complete sentences, you can gain context by using the the sentimentr r package. Check it out:

```<code>install.packages("sentimentr")
library(sentimentr)
?sentiment
</code>```

It will take more work than what you've done here, and will produce richer results. But in the end, they will likely be the same. Good luck.

ContentLicense: CC BY-SA 3.0

Body:
I'm analysing a column with words in my most_used_words dataframe. With 2180 words.

most_used_words

        word times_used
       <chr>      <int>
 1    people         70
 2      news         69
 3      fake         68
 4   country         54
 5     media         44
 6       u.s         42
 7  election         40
 8      jobs         37
 9       bad         36
10 democrats         35
# ... with 2,170 more rows

When I inner_join with the AFINN lexicon only 364 of the 2180 words are scored. Is this because the words in the in the AFINN lexicon don't appear in my dataframe? I'm affraid if that's the case this may introduce bias in my analysis. Should I use a different lexicon? Is there something else that's happening?

library(tidytext)
library(tidyverse)

afinn <- get_sentiments("afinn")

most_used_words %>%
  inner_join(afinn)

          word times_used score
         <chr>      <int> <int>
     1    fake         68    -3
     2     bad         36    -3
     3     win         24     4
     4 failing         21    -2
     5    hard         20    -1
     6  united         19     1
     7 illegal         17    -3
     8    cuts         15    -1
     9   badly         13    -3
    10 strange         13    -1
    # ... with 354 more rows

Body:
"Is this because the words in the in the AFINN lexicon don't appear in my dataframe?"

Yes.

An inner join will only return matching rows (words) from each data.frame.
You can try a different lexicon, sure, but that might not help you with nouns. A noun identifies a person, animal, place, thing, or idea. In your example above, "u.s.", "people", "country", "news", "democrats" are all nouns that don't exist in afinn. None of these have any sentiment without context. Welcome to the world of text analysis.

However, based on the output displayed from you analysis, I think you can conclude the sentiment of your column of words is overwhelmingly "negative". The word "fake" appears nearly twice as much as the next most used word, which is "bad".

If you had complete sentences, you can gain context by using the the sentimentr r package. Check it out:

install.packages("sentimentr")
library(sentimentr)
?sentiment

It will take more work than what you've done here, and will produce richer results. But in the end, they will likely be the same. Good luck.


问:
How to split String on two different chars
I already splitted the String value2 on the char "-" and saved its values in a new array as you can see. Now I wanna seperate the String again on the "," and save it again in a new array but it doesn't work. It always just seperates the second name with the number. And overrites the first. So I got in the first Array on [0]: Peter,2 and in [1]: Leo,1
and in the second array just on [0] Leo and on [1] 1.

I know my for loop is wrong and I don't know how to fix it.

```<code>    final int value = 2;
    final String value2 = "Peter,2-Leo,1";

    String[] splittedStringOne = new String[value];
    String[] splittedStringTwo = new String[splittedStringOne.length*2];

    splittedStringOne = value2.split("-");

    for(int i=0;i<splittedStringOne.length;i++) {
        splittedStringTwo=splittedStringOne[i].split(",");
</code>```

答:
Assuming that your splittedStringOne contains the right values at index [0] and [1], in your for loop, you will just overwrite the content of splittedStringTwo.
Since String.split(',') returns an array, you should also make splittedStringTwo two dimensional :

```<code>    String[][] splittedStringTwo = new String[splitedStringOne.length][2];
</code>```

This should work for the for loop:

```<code>    for(int i=0;i<splittedStringOne.length;i++) {
    splittedStringTwo[i]  = splittedStringOne[i].split(",");
    }
</code>```

note that I added [i] to splittedStringTwo

Body:
I already splitted the String value2 on the char "-" and saved its values in a new array as you can see. Now I wanna seperate the String again on the "," and save it again in a new array but it doesn't work. It always just seperates the second name with the number. And overrites the first. So I got in the first Array on [0]: Peter,2 and in [1]: Leo,1
and in the second array just on [0] Leo and on [1] 1.

I know my for loop is wrong and I don't know how to fix it.

    final int value = 2;
    final String value2 = "Peter,2-Leo,1";

    String[] splittedStringOne = new String[value];
    String[] splittedStringTwo = new String[splittedStringOne.length*2];

    splittedStringOne = value2.split("-");

    for(int i=0;i<splittedStringOne.length;i++) {
        splittedStringTwo=splittedStringOne[i].split(",");

Body:
Assuming that your splittedStringOne contains the right values at index [0] and [1], in your for loop, you will just overwrite the content of splittedStringTwo.
Since String.split(',') returns an array, you should also make splittedStringTwo two dimensional :

    String[][] splittedStringTwo = new String[splitedStringOne.length][2];

This should work for the for loop:

    for(int i=0;i<splittedStringOne.length;i++) {
    splittedStringTwo[i]  = splittedStringOne[i].split(",");
    }

note that I added [i] to splittedStringTwo


问:
use pygame to create animation of an enlarged radius of circle failed

i want to use python to create an animation of an enlarged raidus of a circle.
i use two ways to accomplish this, one way is success, the another is failed.
i want to know why, is there anyone can help.

version 1:

```<code>import pygame
global DISPLAYSURF, FPSCLOCK
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWNWIDTH, WINDOWNHEIGHT))
radius = 1
while True:

    for event in pygame.event.get():
        if event.type == QUIT:
             pygame.quit()
            sys.exit()
    radius = radius + 1
    pygame.draw.circle(DISPLAYSURF, RED, (100, 100), radius)
    pygame.display.update()
    FPSCLOCK.tick(1)
</code>```

version2:

```<code>import pygame
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWNWIDTH, WINDOWNHEIGHT))

for radius in range(0, 100, 2):
    pygame.draw.circle(DISPLAYSURF, RED, (100, 100), radius)
    pygame.display.update()
    FPSCLOCK.tick(1)
while True:
   just_wait = True
</code>```

the version is what i want , the version2 can not work

i run the code on macOs 10.13.1 High Sierra with python3 , why!!!

答:
I think you put code with wrong indentions and it should be

```<code>for radius in range(0, 100, 2):
    pygame.draw.circle(DISPLAYSURF, RED, (100, 100), radius)
    pygame.display.update()
    FPSCLOCK.tick(1)
    while True:
       just_wait = True
</code>```

And it means you run while True loop inside for loop.

But while True loop is endless loop - you never leave it.

So it never go back to draw new circle and update screen.

You can put print() in code and you will see it.

First version is preferred version because it not only draw animation but it checks events so you can leave program in any time.

On some systems if you will not use pygame.event.get(): to get events from system then system will think that program hung up and system can kill program.

Body:
i want to use python to create an animation of an enlarged raidus of a circle.
i use two ways to accomplish this, one way is success, the another is failed.
i want to know why, is there anyone can help.

version 1:

import pygame
global DISPLAYSURF, FPSCLOCK
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWNWIDTH, WINDOWNHEIGHT))
radius = 1
while True:

    for event in pygame.event.get():
        if event.type == QUIT:
             pygame.quit()
            sys.exit()
    radius = radius + 1
    pygame.draw.circle(DISPLAYSURF, RED, (100, 100), radius)
    pygame.display.update()
    FPSCLOCK.tick(1)

version2:

import pygame
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWNWIDTH, WINDOWNHEIGHT))

for radius in range(0, 100, 2):
    pygame.draw.circle(DISPLAYSURF, RED, (100, 100), radius)
    pygame.display.update()
    FPSCLOCK.tick(1)
while True:
   just_wait = True

the version is what i want , the version2 can not work

i run the code on macOs 10.13.1 High Sierra with python3 , why!!!

Body:
I think you put code with wrong indentions and it should be

for radius in range(0, 100, 2):
    pygame.draw.circle(DISPLAYSURF, RED, (100, 100), radius)
    pygame.display.update()
    FPSCLOCK.tick(1)
    while True:
       just_wait = True

And it means you run while True loop inside for loop.

But while True loop is endless loop - you never leave it.

So it never go back to draw new circle and update screen.

You can put print() in code and you will see it.

First version is preferred version because it not only draw animation but it checks events so you can leave program in any time.

On some systems if you will not use pygame.event.get(): to get events from system then system will think that program hung up and system can kill program.


问:
copy a sub part of a string
I'm trying to copy a part of a string in a other string.
I know the 2 identifiers starting and ending the sub-string.

I'm trying to copy the IP from this string:

```<code>0x200085f6 <memp_memory+4502> "GET / HTTP/1.1\r\nHost: 192.168.1.200\r\nConnection
</code>```

The beginning of the string will be "Host: " or 192
The ending will be "\r\nC" or the 2nd occurrence of "\r\n"
So the desired output is:

```<code>192.168.1.200
</code>```

I tried using strcpy and memcpy but the IP has to be variable so I don't know how long it will be or what it will be, the minimum will be 11 and the maximum 15 chars.

I hope you can help me further.

答:
One solution is to extract all the characters which are number or . from the

```<code>"GET / HTTP/1.1\r\nHost: 192.168.1.200\r\nConnection" till `\r` is encounter.
</code>```

Start extraction after Host:
Remember to terminate the string with '\0'.

Simplified version of the program:

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

int main() {

  char ip[64];
  char *p = NULL;
  char *str = "GET / HTTP/1.1\r\nHost: 192.168.1.200\r\nConnection";
  char c;
  int i = 0;
  int len;

  len = strlen("Host ");
  p = strstr(str,"Host: ");

  if(p)
  {
      while(1)
      {
        c = *(p+i+len);

        if(c != '\r' && c!= '\0')
        {
            if( c == ' '){
            i++;
            continue;
            }

            ip[i++] = c;
        }
        else
        {
            ip[i] = '\0';
            break;
        }

     } // while

  }

   printf("Ip=%s", ip);
   return 0;
}
</code>```

OUTPUT:

```<code>Ip=192.168.1.200
</code>```

Title: copy a sub part of a string

Body:
I'm trying to copy a part of a string in a other string.
I know the 2 identifiers starting and ending the sub-string.

I'm trying to copy the IP from this string:

0x200085f6 <memp_memory+4502> "GET / HTTP/1.1\r\nHost: 192.168.1.200\r\nConnection

The beginning of the string will be "Host: " or 192
The ending will be "\r\nC" or the 2nd occurrence of "\r\n"
So the desired output is:

192.168.1.200

I tried using strcpy and memcpy but the IP has to be variable so I don't know how long it will be or what it will be, the minimum will be 11 and the maximum 15 chars.

I hope you can help me further.

Body:
One solution is to extract all the characters which are number or . from the

"GET / HTTP/1.1\r\nHost: 192.168.1.200\r\nConnection" till `\r` is encounter.

Start extraction after Host:
Remember to terminate the string with '\0'.

Simplified version of the program:

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

int main() {

  char ip[64];
  char *p = NULL;
  char *str = "GET / HTTP/1.1\r\nHost: 192.168.1.200\r\nConnection";
  char c;
  int i = 0;
  int len;

  len = strlen("Host ");
  p = strstr(str,"Host: ");

  if(p)
  {
      while(1)
      {
        c = *(p+i+len);

        if(c != '\r' && c!= '\0')
        {
            if( c == ' '){
            i++;
            continue;
            }

            ip[i++] = c;
        }
        else
        {
            ip[i] = '\0';
            break;
        }

     } // while

  }

   printf("Ip=%s", ip);
   return 0;
}

OUTPUT:

Ip=192.168.1.200


问:
Is there a way to get CommandText after replacing parameter values, programmatically?
Is there a way to get CommandText after replacing paramater values programmatically in .NET?

Assume we have a command:

```<code>let cmd = conn.CreateCommand()
cmd.CommandText <- "select * from smsqueue where smsqueueid=:pid"
cmd.CommandType <- CommandType.Text
cmd.Parameters.Add("pid", 0)
</code>```

I want to get the prepared command text; which would be like this:

```<code>select * from smsqueue where smsqueueid=0
</code>```

There are profilers to get this information, but I want to do this explicitly in code (e.g., F# or C#).

答:
Not possible, because that command is not being built. The program sends the exact command text you provided, including the parameter names, to the database engine, along with the parameter values separately. It never physically replaces them to come up with a new string.

If you really need something like that, you'll have to write your own string replacement function, but it would be misleading since that's not what really happens.

Body:
Is there a way to get CommandText after replacing paramater values programmatically in .NET?

Assume we have a command:

let cmd = conn.CreateCommand()
cmd.CommandText <- "select * from smsqueue where smsqueueid=:pid"
cmd.CommandType <- CommandType.Text
cmd.Parameters.Add("pid", 0)

I want to get the prepared command text; which would be like this:

select * from smsqueue where smsqueueid=0

There are profilers to get this information, but I want to do this explicitly in code (e.g., F# or C#).

ContentLicense: CC BY-SA 2.5


问:
You must feed a value for placeholder tensor 'Placeholder' with dtype float(Tensorflow)
```<code>import tensorflow as tf
import os
import sklearn.preprocessing
import pandas as pd
import numpy as np

print(os.getcwd())
os.chdir("C:/Users/jbnu/Documents/양지성/Scholar/정규학기/3-2/데이터마이닝실습/프로젝트/현행/bank-additional/bank-additional")
</code>```

Importing and managing datasets

```<code>bank = pd.read_csv("bank4.csv", index_col=False)

tf.reset_default_graph()
keep_prob = tf.placeholder(tf.float32)
learning_rate = 0.003

x_data = bank.ix[:,0:9]; print(x_data)
y_data = bank.ix[:, [-1]]; print(y_data)
x_data = sklearn.preprocessing.scale(x_data).astype(np.float32); print(x_data)
y_data = y_data.astype(np.float32)
</code>```

Setting placeholder and weights with 3 layers.

```<code>X = tf.placeholder(tf.float32, [None, 9]); print(X)
Y = tf.placeholder(tf.float32, [None, 1])

# Layer 1
W1 = tf.get_variable("weight1", shape=[9,15], dtype = tf.float32,
                     initializer=tf.contrib.layers.xavier_initializer())
b1 = tf.get_variable("bias1", shape=[15], dtype = tf.float32,
                     initializer=tf.contrib.layers.xavier_initializer())
layer1 = tf.nn.relu(tf.matmul(X, W1) + b1)
layer1 = tf.nn.dropout(layer1, keep_prob=keep_prob)

# Layer 2
W2 = tf.get_variable("weight2", shape=[15,15], dtype = tf.float32,
                     initializer=tf.contrib.layers.xavier_initializer())
b2 = tf.get_variable("bias2", shape=[15], dtype = tf.float32,
                     initializer=tf.contrib.layers.xavier_initializer())
layer2 = tf.nn.relu(tf.matmul(layer1, W2) + b2)
layer2 = tf.nn.dropout(layer2, keep_prob=keep_prob)

# Layer 3
W3 = tf.get_variable("weight3", shape=[15,15], dtype = tf.float32,
                     initializer=tf.contrib.layers.xavier_initializer())
b3 = tf.get_variable("bias3", shape=[15], dtype = tf.float32,
                     initializer=tf.contrib.layers.xavier_initializer())
layer3 = tf.nn.relu(tf.matmul(layer2, W3) + b3)
layer3 = tf.nn.dropout(layer3, keep_prob=keep_prob)

# Output Layer
W4 = tf.get_variable("weight4", shape=[15,1], dtype = tf.float32,
                     initializer=tf.contrib.layers.xavier_initializer())
b4 = tf.get_variable("bias4", shape=[1], dtype = tf.float32,
                     initializer=tf.contrib.layers.xavier_initializer())
hypothesis = tf.sigmoid(tf.matmul(layer3, W4) + b4)
hypothesis = tf.nn.dropout(hypothesis, keep_prob=keep_prob)
</code>```

Defining cost function and optimizer.

```<code>cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) * tf.log(1 - hypothesis))

train = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)
accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))
</code>```

Training and accuracy test

```<code># Launch graph
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for step in range(10001):
        sess.run(train, feed_dict={X: x_data, Y: y_data})
        if step % 1000 == 0:
            print("step: ", step, sess.run(cost, feed_dict={X: x_data, Y: y_data}), sep="\n")

    # Accuracy report
    h, c, a = sess.run([hypothesis, predicted, accuracy],
                       feed_dict={X: x_data, Y: y_data})
    print("\nHypothesis: ", h, "\nCorrect: ", c, "\nAccuracy: ", a)
</code>```

I have no idea why my NN is not working.

I constantly get a message "You must feed a value for placeholder tensor 'Placeholder' with dtype float" though all of them are float32.

Also, my dropout rate encounters feed_dict error. Please run the code and tell me what's wrong.

答:
It's complaining about dropout keep_prob placeholder:

```<code>keep_prob = tf.placeholder(tf.float32)
</code>```

You should either provide it in feed_dict along with X and Y or make it a tf.placeholder_with_default, if you don't want to pass it all the time.

Body:
import tensorflow as tf
import os
import sklearn.preprocessing
import pandas as pd
import numpy as np

print(os.getcwd())
os.chdir("C:/Users/jbnu/Documents/양지성/Scholar/정규학기/3-2/데이터마이닝실습/프로젝트/현행/bank-additional/bank-additional")

Importing and managing datasets

bank = pd.read_csv("bank4.csv", index_col=False)

tf.reset_default_graph()
keep_prob = tf.placeholder(tf.float32)
learning_rate = 0.003

x_data = bank.ix[:,0:9]; print(x_data)
y_data = bank.ix[:, [-1]]; print(y_data)
x_data = sklearn.preprocessing.scale(x_data).astype(np.float32); print(x_data)
y_data = y_data.astype(np.float32)

Setting placeholder and weights with 3 layers.

X = tf.placeholder(tf.float32, [None, 9]); print(X)
Y = tf.placeholder(tf.float32, [None, 1])

# Layer 1
W1 = tf.get_variable("weight1", shape=[9,15], dtype = tf.float32,
                     initializer=tf.contrib.layers.xavier_initializer())
b1 = tf.get_variable("bias1", shape=[15], dtype = tf.float32,
                     initializer=tf.contrib.layers.xavier_initializer())
layer1 = tf.nn.relu(tf.matmul(X, W1) + b1)
layer1 = tf.nn.dropout(layer1, keep_prob=keep_prob)

# Layer 2
W2 = tf.get_variable("weight2", shape=[15,15], dtype = tf.float32,
                     initializer=tf.contrib.layers.xavier_initializer())
b2 = tf.get_variable("bias2", shape=[15], dtype = tf.float32,
                     initializer=tf.contrib.layers.xavier_initializer())
layer2 = tf.nn.relu(tf.matmul(layer1, W2) + b2)
layer2 = tf.nn.dropout(layer2, keep_prob=keep_prob)

# Layer 3
W3 = tf.get_variable("weight3", shape=[15,15], dtype = tf.float32,
                     initializer=tf.contrib.layers.xavier_initializer())
b3 = tf.get_variable("bias3", shape=[15], dtype = tf.float32,
                     initializer=tf.contrib.layers.xavier_initializer())
layer3 = tf.nn.relu(tf.matmul(layer2, W3) + b3)
layer3 = tf.nn.dropout(layer3, keep_prob=keep_prob)

# Output Layer
W4 = tf.get_variable("weight4", shape=[15,1], dtype = tf.float32,
                     initializer=tf.contrib.layers.xavier_initializer())
b4 = tf.get_variable("bias4", shape=[1], dtype = tf.float32,
                     initializer=tf.contrib.layers.xavier_initializer())
hypothesis = tf.sigmoid(tf.matmul(layer3, W4) + b4)
hypothesis = tf.nn.dropout(hypothesis, keep_prob=keep_prob)

Defining cost function and optimizer.

cost = -tf.reduce_mean(Y * tf.log(hypothesis) + (1 - Y) * tf.log(1 - hypothesis))

train = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)
accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))

Training and accuracy test

# Launch graph
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for step in range(10001):
        sess.run(train, feed_dict={X: x_data, Y: y_data})
        if step % 1000 == 0:
            print("step: ", step, sess.run(cost, feed_dict={X: x_data, Y: y_data}), sep="\n")

    # Accuracy report
    h, c, a = sess.run([hypothesis, predicted, accuracy],
                       feed_dict={X: x_data, Y: y_data})
    print("\nHypothesis: ", h, "\nCorrect: ", c, "\nAccuracy: ", a)

I have no idea why my NN is not working.

I constantly get a message "You must feed a value for placeholder tensor 'Placeholder' with dtype float" though all of them are float32.

Also, my dropout rate encounters feed_dict error. Please run the code and tell me what's wrong.

Body:
It's complaining about dropout keep_prob placeholder:

keep_prob = tf.placeholder(tf.float32)

You should either provide it in feed_dict along with X and Y or make it a tf.placeholder_with_default, if you don't want to pass it all the time.


问:
How to present viewController before presenting tabBarItem?
I have TabBarViewController and with tap on several of tabBarItems I must to check, if authorize user. If user is not authorised (it's a simple function returns true/false), I must present him viewController with authorisation, but if he is authorised, viewController will not must present.
Questions:
1) If I do it in class UITabBarController of my TabBarController in func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {}, then first was loaded view of tabBarItem, and then I get my authorisation vc. How could I do it and where?
screen of my code

2) How can I present from my authorisation vc (it has not tabbar) my view of tabBarItem? If I do it simply with self.present(animated: true, completion: nil), then with presenting I lose bottom tabBar.
what I need screen and what I have screen

答:
you can use </p>

```<code>func setViewControllers(_ viewControllers: [UIViewController]?,
           animated: Bool)
</code>```

<p>inside function check if user has been authorized then put your view controllers if not put array of viewController with authorisation </p>

Body:
you can use

func setViewControllers(_ viewControllers: [UIViewController]?,
           animated: Bool)

inside function check if user has been authorized then put your view controllers if not put array of viewController with authorisation


问:
Calling GMainLoop.quit() for mainloop running in child process, from parent process
I need to run a gstreamer pipeline to perform video streaming. The GStreamer pipeline requires a GObject.MainLoop object which has a run() method that does not terminate until quit() is called.
For this I create a process (P2) from my main application process (P1), which runs the GObject.MainLoop instance in its main thread. The problem is that loop goes on indefinitly within the process P2 and I'm unable to exit/quit it from the main application process (P1).

Following is the section of code that might help understanding the scenario.

```<code>'''
start() spawns a new process P2 that runs Mainloop within its main thread.
stop() is called from P1, but does not quit the Mainloop. This is probably because
processes do not have shared memory
'''
from multiprocessing import Process
import gi

from gi.repository import GObject

class Main:
    def __init__(self):
        self.process = None
        self.loop = GObject.MainLoop()

    def worker(self):
        self.loop.run()

    def start(self):
        self.process=Process(target=self.worker, args=())
        self.process.start()

    def stop(self):
        self.loop.quit()
</code>```

Next, I tried using a multiprocessing Queue for sharing the 'loop' variable between the processes, but am still unable to quit the mainloop.

```<code>'''
start() spawns a new process and puts the loop object in a multiprocessing Queue
stop() calls get() from the loop and calls the quit() method, though it still does not quit the mainloop.
'''
from multiprocessing import Process, Queue
import gi

from gi.repository import GObject

class Main:
    def __init__(self):
        self.p=None
        self.loop = GObject.MainLoop()
        self.queue = Queue()

    def worker(self):
        self.queue.put(self.loop)
        self.loop.run()

    def start(self):
        self.p=Process(target=self.worker, args=())
        self.p.start()

    def stop(self):
        # receive loop instance shared by Child Process
        loop=self.queue.get()
        loop.quit()
</code>```

How do I call the quit method for the MainLoop object which is only accessible within the child Process P2?

答:
I extended multiprocessing.Process module in my class Main and overridden its run() method to actually run the GObject.Mainloop instance inside another thread (T1) instead of its main thread. And then implemented a wait-notify mechanism which will make the main thread of Process (P2) to go under wait-notify loop and used multiprocessing.Queue to forward messages to the main thread of P2 and P2 will be notified at the same time. For eg, stop() method, which will send the quit message to P2 for which a handler is defined in the overridden run() method.
This module can be extended to parse any number of messages to the Child Process provided their handlers are to be defined also.

Following is the code snippet which I used.

```<code>from multiprocessing import Process, Condition, Queue
from threading import Thread
import gi

from gi.repository import GObject

loop=GObject.MainLoop()

def worker():
    loop.run()

class Main(Process):

    def __init__(self, target=None, args=()):
        self.target=target
        self.args=tuple(args)
        print self.args
        self.message_queue = Queue()
        self.cond = Condition()
        self.thread = None
        self.loop = GObject.MainLoop()
        Process.__init__(self)

    def run(self):
        if self.target:
            self.thread = Thread(target=self.target, args=())
            print "running target method"
            self.thread.start()

        while True:
            with self.cond:
                self.cond.wait()
            msg = self.message_queue.get()
            if msg == 'quit':
                print loop.is_running()
                loop.quit()
                print loop.is_running()
                break
            else:
                print 'message received', msg

    def send_message(self, msg):
        self.message_queue.put(msg)
        with self.cond:
            self.cond.notify_all()

    def stop(self):
        self.send_message("quit")
        self.join()

    def func1(self):
        self.send_message("msg 1") # handler is defined in the overridden run method

    # few others functions which will send unique messages to the process, and their handlers
    # are defined in the overridden run method above
</code>```

This method is working fine for my scenerio but suggestions are welcomed if there is a better way to do the same.

Body:
I need to run a gstreamer pipeline to perform video streaming. The GStreamer pipeline requires a GObject.MainLoop object which has a run() method that does not terminate until quit() is called.
For this I create a process (P2) from my main application process (P1), which runs the GObject.MainLoop instance in its main thread. The problem is that loop goes on indefinitly within the process P2 and I'm unable to exit/quit it from the main application process (P1).

Following is the section of code that might help understanding the scenario.

'''
start() spawns a new process P2 that runs Mainloop within its main thread.
stop() is called from P1, but does not quit the Mainloop. This is probably because
processes do not have shared memory
'''
from multiprocessing import Process
import gi

from gi.repository import GObject

class Main:
    def __init__(self):
        self.process = None
        self.loop = GObject.MainLoop()

    def worker(self):
        self.loop.run()

    def start(self):
        self.process=Process(target=self.worker, args=())
        self.process.start()

    def stop(self):
        self.loop.quit()

Next, I tried using a multiprocessing Queue for sharing the 'loop' variable between the processes, but am still unable to quit the mainloop.

'''
start() spawns a new process and puts the loop object in a multiprocessing Queue
stop() calls get() from the loop and calls the quit() method, though it still does not quit the mainloop.
'''
from multiprocessing import Process, Queue
import gi

from gi.repository import GObject

class Main:
    def __init__(self):
        self.p=None
        self.loop = GObject.MainLoop()
        self.queue = Queue()

    def worker(self):
        self.queue.put(self.loop)
        self.loop.run()

    def start(self):
        self.p=Process(target=self.worker, args=())
        self.p.start()

    def stop(self):
        # receive loop instance shared by Child Process
        loop=self.queue.get()
        loop.quit()

How do I call the quit method for the MainLoop object which is only accessible within the child Process P2?

Body:
I extended multiprocessing.Process module in my class Main and overridden its run() method to actually run the GObject.Mainloop instance inside another thread (T1) instead of its main thread. And then implemented a wait-notify mechanism which will make the main thread of Process (P2) to go under wait-notify loop and used multiprocessing.Queue to forward messages to the main thread of P2 and P2 will be notified at the same time. For eg, stop() method, which will send the quit message to P2 for which a handler is defined in the overridden run() method.
This module can be extended to parse any number of messages to the Child Process provided their handlers are to be defined also.

Following is the code snippet which I used.

from multiprocessing import Process, Condition, Queue
from threading import Thread
import gi

from gi.repository import GObject

loop=GObject.MainLoop()

def worker():
    loop.run()

class Main(Process):

    def __init__(self, target=None, args=()):
        self.target=target
        self.args=tuple(args)
        print self.args
        self.message_queue = Queue()
        self.cond = Condition()
        self.thread = None
        self.loop = GObject.MainLoop()
        Process.__init__(self)

    def run(self):
        if self.target:
            self.thread = Thread(target=self.target, args=())
            print "running target method"
            self.thread.start()

        while True:
            with self.cond:
                self.cond.wait()
            msg = self.message_queue.get()
            if msg == 'quit':
                print loop.is_running()
                loop.quit()
                print loop.is_running()
                break
            else:
                print 'message received', msg

    def send_message(self, msg):
        self.message_queue.put(msg)
        with self.cond:
            self.cond.notify_all()

    def stop(self):
        self.send_message("quit")
        self.join()

    def func1(self):
        self.send_message("msg 1") # handler is defined in the overridden run method

    # few others functions which will send unique messages to the process, and their handlers
    # are defined in the overridden run method above

This method is working fine for my scenerio but suggestions are welcomed if there is a better way to do the same.


问:
Backup Visual Studio Projects
I want to format my computer and make a clean install of Windows 10 (Fall Creators Update), and I want make backup of my all visual studio projects (UWP apps).

In addition to copying project folders do I have to copy something else?

答:
you only need to copy the projects folder.

ideally you should be using a version control (like git) and not ask questions like this!

Title: Backup Visual Studio Projects


问:
How to add a Qt SDK in Qt Creator (Mac OS X)
I need to compile my Qt project using a static version of the Qt SDK.

So I have compiled from source a new SDK using these steps:

```configure (+some options)
make
sudo make -j1 install```

I think all these steps were successful and I can see the SDK in /usr/local/Trolltech. Then, as indicated on the reference, I have added these lines two my .profile file:

```PATH=/usr/local/Trolltech/Qt-4.7.1/bin:$PATH
export PATH```

However, when I start Qt Creator, it is not using this new SDK but still using the one that was installed initially. How can I change that and make it use my new SDK?

答:
In QtCreator's preferences, there's "Qt4" item (on the left) where you can specify path to your Qt manually.

Regarding PATH variable changes, they'll only be taken into account if you start QtCreator from Terminal.

Body:
I need to compile my Qt project using a static version of the Qt SDK.

So I have compiled from source a new SDK using these steps:

configure (+some options)
make
sudo make -j1 install

I think all these steps were successful and I can see the SDK in /usr/local/Trolltech. Then, as indicated on the reference, I have added these lines two my .profile file:

PATH=/usr/local/Trolltech/Qt-4.7.1/bin:$PATH
export PATH

However, when I start Qt Creator, it is not using this new SDK but still using the one that was installed initially. How can I change that and make it use my new SDK?


问:
Symfony unique cache bug
When I change the controller i do not see any changes. Only after two minutes automatically changes show on the website.
I work using netbeans, run as remote web site(FTP).
If I change the controller using directly FileZilla is the same.
I use dev environment of course.

Now please don't tell me delete

var/cache folder

or use php app/console

cache:clear --env=prod --no-debug

This help once and provoke error from the image. And then i have to wait 2 minutes. After 2 minutes that error automatically disappear. My changes are visible but if i change the controller again, i have the same problem. Now again delete var/cache..wait two minutes, changes are visible. I can't work like that.
Twig is ok, this reffering only php.

IMAGE

enter image description here

IMAGE

My web/app_dev.php

```<code>$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();

$kernel = new AppKernel('dev', true);
//$kernel->loadClassCache();
Request::setTrustedHosts(array('^(.+\.)?finearts.klitom1.sldc.pl$'));
$request = Request::createFromGlobals();

$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
</code>```

Any ideas?

答:
The most probable reason: You have a race condition rebuilding the cache on your server due to concurrent requests. Your hosting/server has limited cpu (php-fpm process) assigned to your site and a script timeout quite low that does not give enough time to rebuild completely the cache in one request.

If you want to keep doing live coding you should follow the following steps:

Update .htaccess to setup your site in maintenance mode so you do not get external traffic and only you access to the site

Upload your code

Run app/console cache:clear --no-warmup --env prod

Run app/console cache:warmup --env prod #this makes symfony rebuild the cache via CLI instead of php-fpm

Disable maintenance mode

This is alot of work and it will slow down as you already mentioned but it will make it faster to get symfony up and running again.

My recommended steps:

Never do live coding on a production server. Setup your machine for web development with: https://symfony.com/doc/current/setup/homestead.html or http://phansible.com/ or Docker

Setup a one step deployment process. Example: https://deployer.org/ or https://github.com/capistrano/capistrano if you want more complex setups I can give you more, those are the most basic ones.

Use a repository to store your code bitbucket, github, gitlab, phabricator ...

Title: Symfony unique cache bug

Body:
When I change the controller i do not see any changes. Only after two minutes automatically changes show on the website.
I work using netbeans, run as remote web site(FTP).
If I change the controller using directly FileZilla is the same.
I use dev environment of course.

Now please don't tell me delete

var/cache folder

or use php app/console

cache:clear --env=prod --no-debug

This help once and provoke error from the image. And then i have to wait 2 minutes. After 2 minutes that error automatically disappear. My changes are visible but if i change the controller again, i have the same problem. Now again delete var/cache..wait two minutes, changes are visible. I can't work like that.
Twig is ok, this reffering only php.

IMAGE

enter image description here

IMAGE

My web/app_dev.php

$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();

$kernel = new AppKernel('dev', true);
//$kernel->loadClassCache();
Request::setTrustedHosts(array('^(.+\.)?finearts.klitom1.sldc.pl$'));
$request = Request::createFromGlobals();

$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Any ideas?


问:
Deleting stop-words and punctuation signs
I parse information from a news website. Each news is a dictionary that is stored inside translated_news variable. Each news has its title, url and country.
Then I try to iterate over each news title and delete stop-words and punctuation signs. I've written this code:

```<code>for new in translated_news:
    tk = tokenize(new['title'])
    # delete punctuation signs & stop-words
    for t in tk:
        if (t in punkts) or (t+'\n' in stops):
            tk.remove(t)
tokens.append(tk)
</code>```

Tokenize is a function that returns a list of tokens. Here's an example of the output:

```<code>['medium', ':', 'russian', 'athlete', 'will', 'be', 'admit', 'to', 'the', '2018', 'olympics', 'in', 'neutral', 'status']
</code>```

Here's the same output, but with deleted stop-words and punctuation:

```<code>['medium', 'russian', 'athlete', 'be', 'admit', 'the', 'olympics', 'neutral', 'status']
</code>```

The problem is: even though the words 'the' and 'be' are included in my stop-words list, they were not deleted from the news title. However, on other titles it sometimes works correctly:

['wada', 'acknowledge', 'the', 'reliable', 'information', 'provide', 'to', 'rodchenkov']
['wada', 'acknowledge', 'reliable', 'information', 'provide', 'rodchenkov']

Here 'the' was deleted from the title.
I don't understand what is wrong with the code and why sometimes the output is perfect and sometimes not.

答:
You have to iterate on tokenize(new['title']) and use De Morgan's laws to simplify the if statement:

```<code>import string

stops = ['will', 'be', 'to', 'the', 'in']

tk = ['medium', ':', 'russian', 'athlete', 'will', 'be', 'admit', 'to', 'the',
      '2018', 'olympics', 'in', 'neutral', 'status']

# delete punctuation signs & stop-words
tk = []
for t in tokenize(new['title']):
    # if not ((t in string.punctuation) or (t in stops)):
    if (t not in string.punctuation) and (t not in stops): # De Morgan's laws
        tk.append(t)
print(tk)
</code>```

will print:

```<code>['medium', 'russian', 'athlete', 'admit', '2018', 'olympics', 'neutral', 'status']
</code>```

You can get rid of new lines in stops words:

```<code>stops = ['will\n', 'be\n', 'to\n', 'the\n', 'in\n']
stops = [item.strip() for item in stops]
print(stops)
</code>```

will print:

```<code>['will', 'be', 'to', 'the', 'in']
</code>```

The solution suggested from incanus86 does work:

```<code>tk = [x for x in tokenize(new['title']) if x not in stops and x not in string.punctuation]
</code>```

but you won't be asking in SO if you knew about list comprehensions.

I don't understand what is wrong with the code and why sometimes the output is perfect and sometimes not.

While iterating on tk items you do miss 'be' and 'the' because you are removing tk items as seen in code:

```<code>import string

stops = ['will', 'be', 'to', 'the', 'in']

tk = [
    'medium',  # 0
    ':',  # 1
    'russian',  # 2
    'athlete',  # 3
    'will',  # 4
    'be',  # 5
    'admit',  # 6
    'to',  # 7
    'the',  # 8
    '2018',  # 9
    'olympics',  # 10
    'in',  # 11
    'neutral',  # 12
    'status'  # 13
]

# delete punctuation signs & stop-words
for t in tk:
    print(len(tk), t, tk.index(t))
    if (t in string.punctuation) or (t in stops):
        tk.remove(t)

print(tk)
</code>```

will print:

```<code>(14, 'medium', 0)
(14, ':', 1)
(13, 'athlete', 2)
(13, 'will', 3)
(12, 'admit', 4)
(12, 'to', 5)
(11, '2018', 6)
(11, 'olympics', 7)
(11, 'in', 8)
(10, 'status', 9)
['medium', 'russian', 'athlete', 'be', 'admit', 'the', '2018', 'olympics', 'neutral', 'status']
</code>```

You do miss "russian", "be", "the" and "neutral".

Index of "athlete" is 2 and index of  "will" is 3 because you removed ":" from tk.

Index of "admit" is 4 and index if "to" is 5 because you removed "will" from tk.

Index of "2018" is 6, index of "olympics" is 7, index of "in" is 8 and index of "status" is 9.

You MUST not change list while iterating on it!

Body:
I parse information from a news website. Each news is a dictionary that is stored inside translated_news variable. Each news has its title, url and country.
Then I try to iterate over each news title and delete stop-words and punctuation signs. I've written this code:

for new in translated_news:
    tk = tokenize(new['title'])
    # delete punctuation signs & stop-words
    for t in tk:
        if (t in punkts) or (t+'\n' in stops):
            tk.remove(t)
tokens.append(tk)

Tokenize is a function that returns a list of tokens. Here's an example of the output:

['medium', ':', 'russian', 'athlete', 'will', 'be', 'admit', 'to', 'the', '2018', 'olympics', 'in', 'neutral', 'status']

Here's the same output, but with deleted stop-words and punctuation:

['medium', 'russian', 'athlete', 'be', 'admit', 'the', 'olympics', 'neutral', 'status']

The problem is: even though the words 'the' and 'be' are included in my stop-words list, they were not deleted from the news title. However, on other titles it sometimes works correctly:

['wada', 'acknowledge', 'the', 'reliable', 'information', 'provide', 'to', 'rodchenkov']
['wada', 'acknowledge', 'reliable', 'information', 'provide', 'rodchenkov']

Here 'the' was deleted from the title.
I don't understand what is wrong with the code and why sometimes the output is perfect and sometimes not.

Body:
You have to iterate on tokenize(new['title']) and use De Morgan's laws to simplify the if statement:

import string

stops = ['will', 'be', 'to', 'the', 'in']

tk = ['medium', ':', 'russian', 'athlete', 'will', 'be', 'admit', 'to', 'the',
      '2018', 'olympics', 'in', 'neutral', 'status']

# delete punctuation signs & stop-words
tk = []
for t in tokenize(new['title']):
    # if not ((t in string.punctuation) or (t in stops)):
    if (t not in string.punctuation) and (t not in stops): # De Morgan's laws
        tk.append(t)
print(tk)

will print:

['medium', 'russian', 'athlete', 'admit', '2018', 'olympics', 'neutral', 'status']

You can get rid of new lines in stops words:

stops = ['will\n', 'be\n', 'to\n', 'the\n', 'in\n']
stops = [item.strip() for item in stops]
print(stops)

will print:

['will', 'be', 'to', 'the', 'in']

The solution suggested from incanus86 does work:

tk = [x for x in tokenize(new['title']) if x not in stops and x not in string.punctuation]

but you won't be asking in SO if you knew about list comprehensions.

I don't understand what is wrong with the code and why sometimes the output is perfect and sometimes not.

While iterating on tk items you do miss 'be' and 'the' because you are removing tk items as seen in code:

import string

stops = ['will', 'be', 'to', 'the', 'in']

tk = [
    'medium',  # 0
    ':',  # 1
    'russian',  # 2
    'athlete',  # 3
    'will',  # 4
    'be',  # 5
    'admit',  # 6
    'to',  # 7
    'the',  # 8
    '2018',  # 9
    'olympics',  # 10
    'in',  # 11
    'neutral',  # 12
    'status'  # 13
]

# delete punctuation signs & stop-words
for t in tk:
    print(len(tk), t, tk.index(t))
    if (t in string.punctuation) or (t in stops):
        tk.remove(t)

print(tk)

will print:

(14, 'medium', 0)
(14, ':', 1)
(13, 'athlete', 2)
(13, 'will', 3)
(12, 'admit', 4)
(12, 'to', 5)
(11, '2018', 6)
(11, 'olympics', 7)
(11, 'in', 8)
(10, 'status', 9)
['medium', 'russian', 'athlete', 'be', 'admit', 'the', '2018', 'olympics', 'neutral', 'status']

You do miss "russian", "be", "the" and "neutral".

Index of "athlete" is 2 and index of  "will" is 3 because you removed ":" from tk.

Index of "admit" is 4 and index if "to" is 5 because you removed "will" from tk.

Index of "2018" is 6, index of "olympics" is 7, index of "in" is 8 and index of "status" is 9.

You MUST not change list while iterating on it!


问:
Socket recv() function get null message
I have a problem about the recv() function.

When I sent the first message(ex: hi) to server first, the server would send back the same message to client.

And I sent again(ex: hi2), I would get a null message.

But I kept sending message,maybe I sent two times again. I got the second message I sent.

I want the result is client send to server and client receive the right message immediately.

How can I solve this problem?

my client:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc , char *argv[])
{
    int sockFD = 0;
    sockFD = socket(AF_INET , SOCK_STREAM , 0);

    if (sockFD == -1){
        printf("Fail to create a socket.");
    }

    struct sockaddr_in info;
    bzero(&info,sizeof(info));
    info.sin_family = PF_INET;
    info.sin_addr.s_addr = inet_addr("127.0.0.1");
    info.sin_port = htons(8080);

    if(connect(sockFD,(struct sockaddr *)&info,sizeof(info)) == -1){
        perror("connect()");
    }

    char receiveMessage[100] = {};
    memset(receiveMessage, 0, sizeof(receiveMessage));

    char* input;
    while(scanf("%s", input) == 1){
        if(strcmp("exit", input) == 0){
            break;
        }

        if(send(sockFD, input, sizeof(input), 0) < 0){
            perror("send()");
        }

        if(recv(sockFD, receiveMessage, sizeof(receiveMessage), 0) < 0){
            perror("recv()");
        }

        printf("Server: %s\n",receiveMessage);
    }
    printf("close Socket\n");
    close(sockFD);
    return 0;
}
</code>```

my server:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main()
{
    int sockFD = 0, clientSockFD= 0;
    char inputBuffer[256] = {};
    //char outputBuffer[256] = {};
    fd_set masterFD;
    fd_set readFD;
    int fdMax;

    // create socket
    sockFD = socket(AF_INET, SOCK_STREAM, 0);
    if(sockFD == -1){
        perror("socket()");
        exit(0);
    }

    struct sockaddr_in serverInfo, clientInfo;
    int addrLen = sizeof(clientInfo);
    bzero(&serverInfo, sizeof(serverInfo));

    serverInfo.sin_family = PF_INET;
    serverInfo.sin_addr.s_addr = INADDR_ANY;
    serverInfo.sin_port = htons(8080);

    // bind port
    if(bind(sockFD, (struct sockaddr *)&serverInfo, sizeof(serverInfo))){
        perror("bind()");
    }
    // listen
    if(listen(sockFD, 10)){
        perror("listen()");
    }

    FD_SET(sockFD, &masterFD);
    fdMax = sockFD;

    while(1){
        readFD = masterFD;

        if(select(fdMax + 1, &readFD, NULL, NULL, NULL) == -1){
            perror("select()");
            exit(0);
        }

        for(int i = 0; i <= fdMax; i++){
            if(FD_ISSET(i, &readFD)){
                if(i == sockFD){
                    if((clientSockFD = accept(sockFD, (struct sockaddr *)&clientInfo, &addrLen)) < 0){
                        perror("accept()");
                    }

                    FD_SET(clientSockFD, &masterFD);
                    if(clientSockFD > fdMax){
                        fdMax = clientSockFD;
                    }

                    printf("selectserver: new connection\n");
                }
                else{
                    int recvStatus = recv(i, inputBuffer, sizeof(inputBuffer), 0);
                    if(recvStatus <= 0){
                        if(recvStatus < 0){perror("recv()");}
                        else if(recvStatus = 0){printf("colse connected");}

                        close(i);
                        FD_CLR(i, &masterFD);
                    }
                    else{
                        printf("client: %s\n", inputBuffer);
                        send(i, inputBuffer, sizeof(inputBuffer), 0);
                    }
                }
            }
        }
    }

    return 0;
}
</code>```

答:
Change

```<code> send(i, inputBuffer, sizeof(inputBuffer), 0);
</code>```

Into:

```<code> send(i, inputBuffer,recvStatus , 0);
</code>```

The cause: you were sending a complete buffer, containing only a few intended characters, but padded (upto size=256) with NULs, (or whatever garbage is the buffer from previous calls))

recv() and read() return the number of characters received. (or 0 on EOF,or -1 on errors (some of which could be handled, for instance: EAGAIN, EINTR))

Title: Socket recv() function get null message

Body:
I have a problem about the recv() function.

When I sent the first message(ex: hi) to server first, the server would send back the same message to client.

And I sent again(ex: hi2), I would get a null message.

But I kept sending message,maybe I sent two times again. I got the second message I sent.

I want the result is client send to server and client receive the right message immediately.

How can I solve this problem?

my client:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc , char *argv[])
{
    int sockFD = 0;
    sockFD = socket(AF_INET , SOCK_STREAM , 0);

    if (sockFD == -1){
        printf("Fail to create a socket.");
    }

    struct sockaddr_in info;
    bzero(&info,sizeof(info));
    info.sin_family = PF_INET;
    info.sin_addr.s_addr = inet_addr("127.0.0.1");
    info.sin_port = htons(8080);

    if(connect(sockFD,(struct sockaddr *)&info,sizeof(info)) == -1){
        perror("connect()");
    }

    char receiveMessage[100] = {};
    memset(receiveMessage, 0, sizeof(receiveMessage));

    char* input;
    while(scanf("%s", input) == 1){
        if(strcmp("exit", input) == 0){
            break;
        }

        if(send(sockFD, input, sizeof(input), 0) < 0){
            perror("send()");
        }

        if(recv(sockFD, receiveMessage, sizeof(receiveMessage), 0) < 0){
            perror("recv()");
        }

        printf("Server: %s\n",receiveMessage);
    }
    printf("close Socket\n");
    close(sockFD);
    return 0;
}

my server:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main()
{
    int sockFD = 0, clientSockFD= 0;
    char inputBuffer[256] = {};
    //char outputBuffer[256] = {};
    fd_set masterFD;
    fd_set readFD;
    int fdMax;

    // create socket
    sockFD = socket(AF_INET, SOCK_STREAM, 0);
    if(sockFD == -1){
        perror("socket()");
        exit(0);
    }

    struct sockaddr_in serverInfo, clientInfo;
    int addrLen = sizeof(clientInfo);
    bzero(&serverInfo, sizeof(serverInfo));

    serverInfo.sin_family = PF_INET;
    serverInfo.sin_addr.s_addr = INADDR_ANY;
    serverInfo.sin_port = htons(8080);

    // bind port
    if(bind(sockFD, (struct sockaddr *)&serverInfo, sizeof(serverInfo))){
        perror("bind()");
    }
    // listen
    if(listen(sockFD, 10)){
        perror("listen()");
    }

    FD_SET(sockFD, &masterFD);
    fdMax = sockFD;

    while(1){
        readFD = masterFD;

        if(select(fdMax + 1, &readFD, NULL, NULL, NULL) == -1){
            perror("select()");
            exit(0);
        }

        for(int i = 0; i <= fdMax; i++){
            if(FD_ISSET(i, &readFD)){
                if(i == sockFD){
                    if((clientSockFD = accept(sockFD, (struct sockaddr *)&clientInfo, &addrLen)) < 0){
                        perror("accept()");
                    }

                    FD_SET(clientSockFD, &masterFD);
                    if(clientSockFD > fdMax){
                        fdMax = clientSockFD;
                    }

                    printf("selectserver: new connection\n");
                }
                else{
                    int recvStatus = recv(i, inputBuffer, sizeof(inputBuffer), 0);
                    if(recvStatus <= 0){
                        if(recvStatus < 0){perror("recv()");}
                        else if(recvStatus = 0){printf("colse connected");}

                        close(i);
                        FD_CLR(i, &masterFD);
                    }
                    else{
                        printf("client: %s\n", inputBuffer);
                        send(i, inputBuffer, sizeof(inputBuffer), 0);
                    }
                }
            }
        }
    }

    return 0;
}

Body:
Change

 send(i, inputBuffer, sizeof(inputBuffer), 0);

Into:

 send(i, inputBuffer,recvStatus , 0);

The cause: you were sending a complete buffer, containing only a few intended characters, but padded (upto size=256) with NULs, (or whatever garbage is the buffer from previous calls))

recv() and read() return the number of characters received. (or 0 on EOF,or -1 on errors (some of which could be handled, for instance: EAGAIN, EINTR))


问:
Exporting list to .csv [Scala]
I am new to Scala and programming in general.
How would I go to write a list into a .csv file using Scala?

So I have a list of objects...

```<code>List[test] = List(test(Group1,lol,1,2,3),test(Group2,lel,4,5,6)....)
</code>```

how would I export it to a .csv with 4 columns, and each line having the attributes of an object?

Any help is appreciated.

答:
Case classes are instances of Product that offers a nice way to iterate through all of the fields as .productIterator.

The idea is that you convert all fields to strings, then escape backslashes and double-quotes if there are any, then join them all together, double-quoted and separated by commas, and then glue everything with a new-line:

```<code>list
 .map {
    _.productIterator
     .map(_.toString)
     .map(_.replaceAll("\\", "\\\\"))
     .map(_.replaceAll("\"", "\\\""))
     .mkString("\"", "\",\"", "\"")
 }.mkString("\n")
</code>```

Title: Exporting list to .csv [Scala]

Body:
I am new to Scala and programming in general.
How would I go to write a list into a .csv file using Scala?

So I have a list of objects...

List[test] = List(test(Group1,lol,1,2,3),test(Group2,lel,4,5,6)....)

how would I export it to a .csv with 4 columns, and each line having the attributes of an object?

Any help is appreciated.

Body:
Case classes are instances of Product that offers a nice way to iterate through all of the fields as .productIterator.

The idea is that you convert all fields to strings, then escape backslashes and double-quotes if there are any, then join them all together, double-quoted and separated by commas, and then glue everything with a new-line:

list
 .map {
    _.productIterator
     .map(_.toString)
     .map(_.replaceAll("\\", "\\\\"))
     .map(_.replaceAll("\"", "\\\""))
     .mkString("\"", "\",\"", "\"")
 }.mkString("\n")


问:
insert records in cycle MS SQL

And SQL again.
My situation.
I need make insert into the table. I have the condition.
Some inserts can be doing if the equal their rates in the week and in the month.
For example: for category 2 rate = 1 time in month. So I need insert only one time in April. But in my case, it inserts 1 record I expected and inserts 5 additional times yet.

```<code> SET @Rate_Init = 1
 DECLARE @Min_Amount INT = (SELECT T.AccountMin FROM Transactions T
 FULL JOIN Marathon.dbo.Categories C ON C.CategoryName =
 T.OperationName WHERE C.CategoryID = @External_Loop_Counter)
 DECLARE @Max_Amount INT = (SELECT T.AccountMax FROM Transactions T
 FULL JOIN Marathon.dbo.Categories C ON C.CategoryName =
 T.OperationName WHERE C.CategoryID = @External_Loop_Counter)
 DECLARE @Check_Period NVARCHAR(10) = (SELECT Period  FROM (SELECT *
 FROM Transactions T FULL JOIN Marathon.dbo.Categories C ON
 C.CategoryName = T.OperationName) X WHERE CategoryID =
 @External_Loop_Counter)
 DECLARE @Frequency INT = (SELECT Rate  FROM (SELECT * FROM
 Transactions T FULL JOIN Marathon.dbo.Categories C ON C.CategoryName
 = T.OperationName) X WHERE CategoryID = @External_Loop_Counter)
 WHILE @Total_Dates >= @Internal_Loop_Counter
                    BEGIN

                    IF(@Frequency <= @Rate_Init)
                        BEGIN
                        INSERT INTO Transactions (TransactionDate, TransactionAmount, CategoryID)
                        VALUES((DATEADD(DAY, @Internal_Loop_Counter, @Start_DT)), (@Max_Amount - CAST(((@Max_Amount - @Min_Amount)) AS FLOAT)*RAND()),
                        (SELECT CategoryID FROM (SELECT * FROM Transactions T FULL JOIN Marathon.dbo.Categories C ON C.CategoryName = T.OperationName) X WHERE CategoryID = @External_Loop_Counter))
                        END

                        SET @Rate_Init = @Rate_Init + 1
                    SET @Jump_Ratio = (
                    CASE
                    WHEN @Check_Period = 'Week' THEN (@Internal_Loop_Counter + CAST(CAST(@Week_T AS FLOAT)*RAND() AS INT))
                    WHEN @Check_Period = 'Month' THEN (@Internal_Loop_Counter + CAST(CAST(@Month_T AS FLOAT)*RAND() AS INT))
                    WHEN @Check_Period = 'Year' THEN (@Internal_Loop_Counter + CAST(CAST(@Year_T AS FLOAT)*RAND() AS INT))
                    END
                    )

                    SET @Internal_Loop_Counter = @Jump_Ratio + 1
                    END
</code>```

Expect
140     2012-03-28 00:00:00 628 2

141     2012-04-26 00:00:00 334 2

142     2012-05-03 00:00:00 418 2

Actual result I had got

140     2012-03-28 00:00:00 628 2

141     2012-04-03 00:00:00 592 2

142     2012-04-04 00:00:00 353 2

143     2012-04-10 00:00:00 403 2

144     2012-04-16 00:00:00 635 2

145     2012-04-22 00:00:00 673 2

146     2012-04-26 00:00:00 334 2

147     2012-05-03 00:00:00 418 2

Use 2017 MS SQL

答:
I had solved my problem. I had used 2 inner loops in external loop. And, of course, didn't forget to change steps of the loops
PS Here is no difference what exactly use - full or inner join

Title: insert records in cycle MS SQL

Body:
And SQL again.
My situation.
I need make insert into the table. I have the condition.
Some inserts can be doing if the equal their rates in the week and in the month.
For example: for category 2 rate = 1 time in month. So I need insert only one time in April. But in my case, it inserts 1 record I expected and inserts 5 additional times yet.

 SET @Rate_Init = 1
 DECLARE @Min_Amount INT = (SELECT T.AccountMin FROM Transactions T
 FULL JOIN Marathon.dbo.Categories C ON C.CategoryName =
 T.OperationName WHERE C.CategoryID = @External_Loop_Counter)
 DECLARE @Max_Amount INT = (SELECT T.AccountMax FROM Transactions T
 FULL JOIN Marathon.dbo.Categories C ON C.CategoryName =
 T.OperationName WHERE C.CategoryID = @External_Loop_Counter)
 DECLARE @Check_Period NVARCHAR(10) = (SELECT Period  FROM (SELECT *
 FROM Transactions T FULL JOIN Marathon.dbo.Categories C ON
 C.CategoryName = T.OperationName) X WHERE CategoryID =
 @External_Loop_Counter)
 DECLARE @Frequency INT = (SELECT Rate  FROM (SELECT * FROM
 Transactions T FULL JOIN Marathon.dbo.Categories C ON C.CategoryName
 = T.OperationName) X WHERE CategoryID = @External_Loop_Counter)
 WHILE @Total_Dates >= @Internal_Loop_Counter
                    BEGIN

                    IF(@Frequency <= @Rate_Init)
                        BEGIN
                        INSERT INTO Transactions (TransactionDate, TransactionAmount, CategoryID)
                        VALUES((DATEADD(DAY, @Internal_Loop_Counter, @Start_DT)), (@Max_Amount - CAST(((@Max_Amount - @Min_Amount)) AS FLOAT)*RAND()),
                        (SELECT CategoryID FROM (SELECT * FROM Transactions T FULL JOIN Marathon.dbo.Categories C ON C.CategoryName = T.OperationName) X WHERE CategoryID = @External_Loop_Counter))
                        END

                        SET @Rate_Init = @Rate_Init + 1
                    SET @Jump_Ratio = (
                    CASE
                    WHEN @Check_Period = 'Week' THEN (@Internal_Loop_Counter + CAST(CAST(@Week_T AS FLOAT)*RAND() AS INT))
                    WHEN @Check_Period = 'Month' THEN (@Internal_Loop_Counter + CAST(CAST(@Month_T AS FLOAT)*RAND() AS INT))
                    WHEN @Check_Period = 'Year' THEN (@Internal_Loop_Counter + CAST(CAST(@Year_T AS FLOAT)*RAND() AS INT))
                    END
                    )

                    SET @Internal_Loop_Counter = @Jump_Ratio + 1
                    END

Expect
140     2012-03-28 00:00:00 628 2

141     2012-04-26 00:00:00 334 2

142     2012-05-03 00:00:00 418 2

Actual result I had got

140     2012-03-28 00:00:00 628 2

141     2012-04-03 00:00:00 592 2

142     2012-04-04 00:00:00 353 2

143     2012-04-10 00:00:00 403 2

144     2012-04-16 00:00:00 635 2

145     2012-04-22 00:00:00 673 2

146     2012-04-26 00:00:00 334 2

147     2012-05-03 00:00:00 418 2

Use 2017 MS SQL


问:
Browserless JavaScript
I talked to the Team Lead at Snap-On Tools once, and she told they used an "implementation of JavaScript" for their server-side coding. It's been a while, but I was thinking, WTF is she talking about? Are there interpreters for JavaScript besides those implemented in browsers?

How can you create a program or code, especially server-side, using JavaScript that doesn't execute in the context of a browser? What the hell is server-side about JavaScript if it's not generating content after the browser has loaded it? Can "server-side" JavaScript generate content before the HTTP response is deliver—and if so, how does that work/is set up?

I have many issues with JavaScript, but first-class functions are so sexy. And JavaScript Object Notation is so pure; I couldn't imagine an easier way to define data structures. Plus, you can hack out some code pretty quickly with dynamic typing if you're not writing something that's mission critical.

As a side question, given the last paragraph, have any suggestions about a good language to learn (comments will suffice)?

答: SpiderMonkey and Rhino seem to be pretty much related. SpiderMonkey seems to be a C-library for executing JS, while Rhino is a Java-ditto.</p>

OwnerDisplayName: Chris

Title: Browserless JavaScript

LastEditorDisplayName: Chris

OwnerDisplayName: wolfie


问:
Form input to select multiple files to save as array
Newbie question - Not sure if this is a html or php question.  I would like to create a form that would allow multiple files to be selected to be later posted as an array.  Is this possible with a different type of type="file" to allow more than one file?</p>

答:
If you are looking for a multiple file uploader, then try this.</p>

```<code><?php
if(isset($_POST['btn_upload'])){
    $limit=count($_FILES['uploads']['name']);
    $success=$fail=0;
    for($i=0;$i<$limit;$i++){
        if(move_uploaded_file($_FILES['uploads']['tmp_name'][$i],
                              "uploads/".$_FILES['uploads']['name'][$i])){
            $success++;
        }
        else{
            $fail++;
        }
    }
    if($success>0){
        echo "Successfully uploaded ".$success." files";
    }
    if($fail>0){
        echo "uploading of ".$fail." files failed";
    }
}
?>
<html>
<head>
<title></title>
</head>
<body>
    <frameset style="width:30%">
        <legend>Multiple Upload</legend>
        <form name="multipleUpload" id="" action="" method="POST"
              enctype='multipart/form-data'>
            <input type='file' id='uploadFile' name='uploads[]' multiple=""/>
            <input type='submit' value='upload' name='btn_upload'/>
        </form>
    </frameset>
</body>
</html>
</code>```

Body:
If you are looking for a multiple file uploader, then try this.

<?php
if(isset($_POST['btn_upload'])){
    $limit=count($_FILES['uploads']['name']);
    $success=$fail=0;
    for($i=0;$i<$limit;$i++){
        if(move_uploaded_file($_FILES['uploads']['tmp_name'][$i],
                              "uploads/".$_FILES['uploads']['name'][$i])){
            $success++;
        }
        else{
            $fail++;
        }
    }
    if($success>0){
        echo "Successfully uploaded ".$success." files";
    }
    if($fail>0){
        echo "uploading of ".$fail." files failed";
    }
}
?>
<html>
<head>
<title></title>
</head>
<body>
    <frameset style="width:30%">
        <legend>Multiple Upload</legend>
        <form name="multipleUpload" id="" action="" method="POST"
              enctype='multipart/form-data'>
            <input type='file' id='uploadFile' name='uploads[]' multiple=""/>
            <input type='submit' value='upload' name='btn_upload'/>
        </form>
    </frameset>
</body>
</html>


问:
2 pipe, one fork, bc and execlp (C)
I'm trying to get something like this to work in c using piping and fork :
echo "an operation like 10+10" | bc

To be precise, I tried to create 2 pipes, one where the server will write the operation and bc will read and another where the result of the operation (by bc) will go and the server will read it and printf it. For this, I'm changing the output and input of the parent and child process.

Here is my code:

int main(){

```<code>int t1, t2;
char resultat[5];
int pipe1[2];
int pipe2[2];

pipe(pipe1);
pipe(pipe2);

int resultat_fork = fork();

if(resultat_fork == -1){
    exit(EXIT_FAILURE);
}

if(resultat_fork!=0){
    printf("I am the parent\n");

    close(pipe1[0]);
    close(pipe2[1]);
    //We only want to write into pipe1 and read from pipe2, we can close the two other

    write(pipe1[1], "20*5\n", 20);
    //write on pipe1 the expression

    read(pipe2[0], resultat, sizeof(resultat));
    //read from pipe2 the answer (written by bc)

    printf("resultat : %s\n",resultat);

    close(pipe1[1]);
    close(pipe2[0]);

}else{
    printf("I am the children\n");

    close(pipe1[1]);
    close(pipe2[0]);
    //We only want to write into pipe2 and read from pipe1, we can close the two other

    dup2(pipe1[0], 0);
    //redirection standard input to pipe1[0]

    dup2(pipe2[1], 1);
    //redirection standard output to pipe2[1]

    execlp("bc", "bc", NULL);
    //execute bc, which normaly will read the operation from pipe1 and write the answer into pipe2, but I think it's here the problem come out

    close(pipe1[0]);
    close(pipe2[1]);
}

return 0;
</code>```

}

I'm getting the correct answer but with the error :
"(standard_in) 2: illegal character : ^@"
"(standard_in) 2: illegal character : :"
plus I have to CTRL C to quit.
I guess it comes from BC but why...

What am I doing wrong? Thank you!
I've already seen few exemple but only threw one pipe.

答:
This works.  Note how it specifies the size of the data to be written, and how it checks the writes and reads, and also how it closes file descriptors.  (Remember: sizeof("string literal") counts the null byte, unlike strlen().  It's also a compile time constant.  However, more general purpose code would use strlen() on the current expression string.)

Rule of Thumb: If you use dup2() to duplicate a pipe file descriptor to standard input or standard output, close both ends of the pipe.

That also applies if you use dup(), or fcntl() with F_DUPFD or F_DUPFD_CLOEXEC instead.

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

int main(void)
{
    char resultat[5];
    int pipe1[2];
    int pipe2[2];

    pipe(pipe1);
    pipe(pipe2);

    int resultat_fork = fork();

    if (resultat_fork == -1)
    {
        exit(EXIT_FAILURE);
    }

    if (resultat_fork != 0)
    {
        printf("I am the parent\n");

        close(pipe1[0]);
        close(pipe2[1]);

        if (write(pipe1[1], "20*5\n", sizeof("20*5\n") - 1) != sizeof("20*5\n") - 1)
            fprintf(stderr, "write to child failed\n");

        int nbytes = read(pipe2[0], resultat, sizeof(resultat));
        if (nbytes <= 0)
            fprintf(stderr, "read from child failed\n");
        else
            printf("resultat: [%.*s]\n", nbytes, resultat);

        close(pipe1[1]);
        close(pipe2[0]);
    }
    else
    {
        printf("I am the child\n");

        close(pipe1[1]);
        close(pipe2[0]);
        dup2(pipe1[0], 0);
        dup2(pipe2[1], 1);
        close(pipe1[0]);    /* More closes! */
        close(pipe2[1]);    /* More closes! */

        execlp("bc", "bc", NULL);
        fprintf(stderr, "Failed to execute bc\n");
        exit(EXIT_FAILURE);
    }

    return 0;
}
</code>```

There is still room for improving the error handling; the code ploughs on after reporting some of the errors, which is probably not the best behaviour.

Output:

```<code>I am the parent
I am the child
resultat: [100
]
</code>```

(Note: if you pipe the output of the program somewhere, you don't see the I am the child message.  For the reasons why, see printf() anomaly after fork().)

Title: 2 pipe, one fork, bc and execlp (C)

Body:
I'm trying to get something like this to work in c using piping and fork :
echo "an operation like 10+10" | bc

To be precise, I tried to create 2 pipes, one where the server will write the operation and bc will read and another where the result of the operation (by bc) will go and the server will read it and printf it. For this, I'm changing the output and input of the parent and child process.

Here is my code:

int main(){

int t1, t2;
char resultat[5];
int pipe1[2];
int pipe2[2];

pipe(pipe1);
pipe(pipe2);

int resultat_fork = fork();

if(resultat_fork == -1){
    exit(EXIT_FAILURE);
}

if(resultat_fork!=0){
    printf("I am the parent\n");

    close(pipe1[0]);
    close(pipe2[1]);
    //We only want to write into pipe1 and read from pipe2, we can close the two other

    write(pipe1[1], "20*5\n", 20);
    //write on pipe1 the expression

    read(pipe2[0], resultat, sizeof(resultat));
    //read from pipe2 the answer (written by bc)

    printf("resultat : %s\n",resultat);

    close(pipe1[1]);
    close(pipe2[0]);

}else{
    printf("I am the children\n");

    close(pipe1[1]);
    close(pipe2[0]);
    //We only want to write into pipe2 and read from pipe1, we can close the two other

    dup2(pipe1[0], 0);
    //redirection standard input to pipe1[0]

    dup2(pipe2[1], 1);
    //redirection standard output to pipe2[1]

    execlp("bc", "bc", NULL);
    //execute bc, which normaly will read the operation from pipe1 and write the answer into pipe2, but I think it's here the problem come out

    close(pipe1[0]);
    close(pipe2[1]);
}

return 0;

}

I'm getting the correct answer but with the error :
"(standard_in) 2: illegal character : ^@"
"(standard_in) 2: illegal character : :"
plus I have to CTRL C to quit.
I guess it comes from BC but why...

What am I doing wrong? Thank you!
I've already seen few exemple but only threw one pipe.

Body:
This works.  Note how it specifies the size of the data to be written, and how it checks the writes and reads, and also how it closes file descriptors.  (Remember: sizeof("string literal") counts the null byte, unlike strlen().  It's also a compile time constant.  However, more general purpose code would use strlen() on the current expression string.)

Rule of Thumb: If you use dup2() to duplicate a pipe file descriptor to standard input or standard output, close both ends of the pipe.

That also applies if you use dup(), or fcntl() with F_DUPFD or F_DUPFD_CLOEXEC instead.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
    char resultat[5];
    int pipe1[2];
    int pipe2[2];

    pipe(pipe1);
    pipe(pipe2);

    int resultat_fork = fork();

    if (resultat_fork == -1)
    {
        exit(EXIT_FAILURE);
    }

    if (resultat_fork != 0)
    {
        printf("I am the parent\n");

        close(pipe1[0]);
        close(pipe2[1]);

        if (write(pipe1[1], "20*5\n", sizeof("20*5\n") - 1) != sizeof("20*5\n") - 1)
            fprintf(stderr, "write to child failed\n");

        int nbytes = read(pipe2[0], resultat, sizeof(resultat));
        if (nbytes <= 0)
            fprintf(stderr, "read from child failed\n");
        else
            printf("resultat: [%.*s]\n", nbytes, resultat);

        close(pipe1[1]);
        close(pipe2[0]);
    }
    else
    {
        printf("I am the child\n");

        close(pipe1[1]);
        close(pipe2[0]);
        dup2(pipe1[0], 0);
        dup2(pipe2[1], 1);
        close(pipe1[0]);    /* More closes! */
        close(pipe2[1]);    /* More closes! */

        execlp("bc", "bc", NULL);
        fprintf(stderr, "Failed to execute bc\n");
        exit(EXIT_FAILURE);
    }

    return 0;
}

There is still room for improving the error handling; the code ploughs on after reporting some of the errors, which is probably not the best behaviour.

Output:

I am the parent
I am the child
resultat: [100
]

(Note: if you pipe the output of the program somewhere, you don't see the I am the child message.  For the reasons why, see printf() anomaly after fork().)


问:
how to hide a form in angular
I have been trying to hide my form and making it appear only when user click on the button. but for some reason, the function I have created never work is there something wrong with my code? and I saw quite a few example that uses angular.module and I tried it but I always get an error message.

transfer.component.html

```<code><form [formGroup]="AddRiciverForm" id="AddRiciverForm" (ngSubmit)="addRiciverFunc()" *ngIf="show">
  <div class="container">
    <div class="row">
      <div class="col-sm-6 col-sm-offset-3">
        <p><input type="email" id="emailTo" formControlName="emailTo"  placeholder="Reciver Email" [(ngModel)]="this.AddRiciverForm.value.emailTo" required></p>
      </div>
    </div>
     <div class="row">
      <div class="col-sm-6 col-sm-offset-3">
        <p><button class="btn btn-primary" type="submit" [disabled]="!transferForm.form.valid">Add</button> </p>
      </div>
    </div>
   </div>
  </form>
<button ng-click="AddEmailFunc()">add user</button>
</code>```

transfer.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { Http } from '@angular/http';
import { PostsService } from '../posts.service';

@Component({
  selector: 'app-transfer',
  templateUrl: './transfer.component.html',
  styleUrls: ['./transfer.component.css']
})
export class TransferComponent implements OnInit {

  constructor(private fb: FormBuilder, private http: Http, private router: Router, private auth: AuthService,private postsService: PostsService) { }
  transfer = {};
  addRiciver = {};
  recivers: any;
  AddRiciverForm: FormGroup;
  transferForm: FormGroup;
  public userEmail: string;
  show=false;
  ngOnInit() {
    this.transferForm = this.fb.group({
      emailTo: '',
      amount: ''
    });
    this.AddRiciverForm = this.fb.group({
      emailTo: ''
    });
    this.auth.currentEmail.subscribe(email => this.userEmail = email);

    this.postsService.getAllReciver().subscribe(reciver => {
      this.recivers = reciver;
    });
  }
  transFunds(){

  }
  addRiciverFunc(){
        this.addRiciver={
          emailFrom: this.userEmail,
          emailTo: this.AddRiciverForm.value.emailTo
        }
        this.http.post('/transfer', this.addRiciver)
        .subscribe(res => {
            let id = res['_id'];

          }, (err) => {
            console.log(err);
          }
        );

  }

  AddEmailFunc(){
  if(!this.show){
    this.show = true;
  }

  }
}
</code>```

答:
You must try adding [hidden]="AddEmailFunc()" on your form.

please see my sample code

```<code>import { Component } from '@angular/core';

@Component({
    selector: 'Sandbox',
    template: `<form [hidden]="isDisplayed">
    <label>Sample: </label>
    <input type="text">
    </form>

    <button (click)="showMe()">Click</button>`
})

export class SandboxComponent{
    isDisplayed = true;

    showMe()
    {
        if(this.isDisplayed)
        {
            this.isDisplayed = false;
        }else{
            this.isDisplayed = true;
        }
    }
}
</code>```

Hope it helps. :) cheers!

Title: how to hide a form in angular

Body:
I have been trying to hide my form and making it appear only when user click on the button. but for some reason, the function I have created never work is there something wrong with my code? and I saw quite a few example that uses angular.module and I tried it but I always get an error message.

transfer.component.html

<form [formGroup]="AddRiciverForm" id="AddRiciverForm" (ngSubmit)="addRiciverFunc()" *ngIf="show">

<input type="email" id="emailTo" formControlName="emailTo"  placeholder="Reciver Email" [(ngModel)]="this.AddRiciverForm.value.emailTo" required>

<button class="btn btn-primary" type="submit" [disabled]="!transferForm.form.valid">Add</button>

  </form>
<button ng-click="AddEmailFunc()">add user</button>

transfer.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { Http } from '@angular/http';
import { PostsService } from '../posts.service';

@Component({
  selector: 'app-transfer',
  templateUrl: './transfer.component.html',
  styleUrls: ['./transfer.component.css']
})
export class TransferComponent implements OnInit {

  constructor(private fb: FormBuilder, private http: Http, private router: Router, private auth: AuthService,private postsService: PostsService) { }
  transfer = {};
  addRiciver = {};
  recivers: any;
  AddRiciverForm: FormGroup;
  transferForm: FormGroup;
  public userEmail: string;
  show=false;
  ngOnInit() {
    this.transferForm = this.fb.group({
      emailTo: '',
      amount: ''
    });
    this.AddRiciverForm = this.fb.group({
      emailTo: ''
    });
    this.auth.currentEmail.subscribe(email => this.userEmail = email);

    this.postsService.getAllReciver().subscribe(reciver => {
      this.recivers = reciver;
    });
  }
  transFunds(){

  }
  addRiciverFunc(){
        this.addRiciver={
          emailFrom: this.userEmail,
          emailTo: this.AddRiciverForm.value.emailTo
        }
        this.http.post('/transfer', this.addRiciver)
        .subscribe(res => {
            let id = res['_id'];

          }, (err) => {
            console.log(err);
          }
        );

  }

  AddEmailFunc(){
  if(!this.show){
    this.show = true;
  }

  }
}

Body:
You must try adding [hidden]="AddEmailFunc()" on your form.

please see my sample code

import { Component } from '@angular/core';

@Component({
    selector: 'Sandbox',
    template: `<form [hidden]="isDisplayed">
    <label>Sample: </label>
    <input type="text">
    </form>

    <button (click)="showMe()">Click</button>`
})

export class SandboxComponent{
    isDisplayed = true;

    showMe()
    {
        if(this.isDisplayed)
        {
            this.isDisplayed = false;
        }else{
            this.isDisplayed = true;
        }
    }
}

Hope it helps. :) cheers!


问:
A configurable (high/low level) programming language?
Is there a programming language that can be both high and low level? I'll elaborate...

Say, for example, you want to write an enterprise system which needs good abstractions and static typing (among other things), so you pick Java. But then, you need a portion of this system to be very low latency, so you pick C++ and do your garbage collection. Then, you want some kind of automated build script, so you quickly write something up in python.

Is there a language that could do all of these tasks, and be configurable such that one can use a GC or not if specified, the script be interpreted or not if specified, and the language can have static typing if specified? - Say, a unified syntax with optional static typing, customizable GC, and compilers..a sort of customizable Frankenstein language?

Disclaimer, I have not taken any programming language/compiler course, so this may be a noob-ish question!

答:
Real world challenges are better dealt with multiple programming languages and programming language implementations.

Since you mentioned Python, important parts of the library are implemented in C (or in Cython) for performance reasons.

The programming languages involved on a modern Web site are at least HTML, CSS, and JavaScript, plus a templating language, plush the language used for the backend, plus the language used for services, plus SQL or the likes for querying databases.

The history of programming has recurring attempts at a single programming language for everything (ADA comes to mind), and each of them resulted in either inconsistent languages or complicated code. All of them were short-sighted.

ContentLicense: CC BY-SA 4.0


问:
How to find Time taken for doing a mathematical operation?
I am trying to do an program where i need to find the time take for doing a mathematical function. Suppose i am doing a calculation a/b, then how can i find the time taken to finish that calculation in millisecond??
Please help me</p>

答:
Have a look at ctime library. </p>

```<code>#include<ctime>
#include<time.h>
clock_t t1=clock();
//Your calculation here
clock_t t2=clock();
cout<<"Time taken" << doubel(t2-t1) << "clock cycles";
</code>```

Body:
Have a look at ctime library.

#include<ctime>
#include<time.h>
clock_t t1=clock();
//Your calculation here
clock_t t2=clock();
cout<<"Time taken" << doubel(t2-t1) << "clock cycles";


问:
python 2.7.14 & 3.6 good practice for package imports
I'm having some trouble with latest python version (2 & 3) to find a good common way for imports.

About the packages I pushed on PyPI, that's ok yet as I create a subfolder for the package, then use package.module in __init__.py for imports.
I would do the same in module files.

Other than that, I have some packages that I share between projects (stored on my svn server) which I import as svn external in projects.

The hierarchy is usually designed this way:

```<code>package:
 |- __init__.py
 |- module1.py
 |- module2.py
 |- ...
</code>```

When I import it into projects, folders looks like this:

```<code>project:
 |- package:
     |- what's above
 |- app.py
</code>```

I usually develop the package itself as a project, meaning package is root.
When I import it into projects, they become packages, thus not at root anymore.

When using package.module or .module in standalone package project, of course, this does not work.
When using same as package in other projects, this tends to work almost fine, but I experience some issues with Python 3.6, telling that some names aren't defined (when launched directly from the command line; but working under pycharm).
Last but not least, when using py2exe to make executables (from Python 2.7), I get some undefined names (classes, etc) exceptions even if imports seems to be ok as no such exception is raised; please note I was able to see that related .pyc files are there in library.zip.

I did not go through these issues some months ago, neither python 2 nor python 3 with older versions.

I open this question as I searched on StackOverflow, python documentation (2 & 3) and a lot through the web these last days without finding something that is really relevant to the overall issue.

My question is, does anyone have any clue on a good practice for imports that would be compatible between python 2 & 3, and which would work also when package is __main__? And the bonus, still ok when packed with py2exe?

At some point, i tried some try/except ImportError blocks for these imports, but it messes things up a bit & seems to be unreliable.

Thanks a lot for your help!

答:
Given some clues about __package__ from:

Relative imports for the billionth time

I found some more consistent solution to check before import.

```<code>if __package__ is None or __package__ == '':
    from module1 import *
    from module2 import *
else:
    from .module1 import *
    from .module2 import *
</code>```

In case you run directly from the file itself (let's say module1), __package__ is None. I still had to add check for __package__ == '' as if module1 imports module2, package is not None in module2.

In this case, I prefer using relative imports even if not really recommended, as when used as a package, the package itself can have any name without changing anything.

About __init__.py file, I just use relative imports as it will be used only when importing as a package from the main app with:

```<code>import package
from package import xxx
</code>```

This seems to solve things well about imports for both python 2.7.14 & 3.6, yet still causes issues with py2exe (2.7) and doesn't generate the whole poject.

Body:
I'm having some trouble with latest python version (2 & 3) to find a good common way for imports.

About the packages I pushed on PyPI, that's ok yet as I create a subfolder for the package, then use package.module in __init__.py for imports.
I would do the same in module files.

Other than that, I have some packages that I share between projects (stored on my svn server) which I import as svn external in projects.

The hierarchy is usually designed this way:

package:
 |- __init__.py
 |- module1.py
 |- module2.py
 |- ...

When I import it into projects, folders looks like this:

project:
 |- package:
     |- what's above
 |- app.py

I usually develop the package itself as a project, meaning package is root.
When I import it into projects, they become packages, thus not at root anymore.

When using package.module or .module in standalone package project, of course, this does not work.
When using same as package in other projects, this tends to work almost fine, but I experience some issues with Python 3.6, telling that some names aren't defined (when launched directly from the command line; but working under pycharm).
Last but not least, when using py2exe to make executables (from Python 2.7), I get some undefined names (classes, etc) exceptions even if imports seems to be ok as no such exception is raised; please note I was able to see that related .pyc files are there in library.zip.

I did not go through these issues some months ago, neither python 2 nor python 3 with older versions.

I open this question as I searched on StackOverflow, python documentation (2 & 3) and a lot through the web these last days without finding something that is really relevant to the overall issue.

My question is, does anyone have any clue on a good practice for imports that would be compatible between python 2 & 3, and which would work also when package is __main__? And the bonus, still ok when packed with py2exe?

At some point, i tried some try/except ImportError blocks for these imports, but it messes things up a bit & seems to be unreliable.

Thanks a lot for your help!

Body:
Given some clues about __package__ from:

Relative imports for the billionth time

I found some more consistent solution to check before import.

if __package__ is None or __package__ == '':
    from module1 import *
    from module2 import *
else:
    from .module1 import *
    from .module2 import *

In case you run directly from the file itself (let's say module1), __package__ is None. I still had to add check for __package__ == '' as if module1 imports module2, package is not None in module2.

In this case, I prefer using relative imports even if not really recommended, as when used as a package, the package itself can have any name without changing anything.

About __init__.py file, I just use relative imports as it will be used only when importing as a package from the main app with:

import package
from package import xxx

This seems to solve things well about imports for both python 2.7.14 & 3.6, yet still causes issues with py2exe (2.7) and doesn't generate the whole poject.


问:
Git treating directory like a file
I have an odd question, It seems as if Git is treating a directory as a file... Right after doing git add .:

Then, after my push, I get:

"mov" is actually a directory but it seems like it is being treated as a file when doing the git push, this even happens if I am inside the directory when doing the push. I have attenpted to add the file by going into the mov directory and running: git remote -v, however it didn't change anything.

Am I overlooking something? This has never happened to me before :(

答: The mov folder appears to have its own git repo and is therefor a submodule. Look for a .git folder inside of the mov folder. You can delete this directory to make mov part of the parent git repo.

Title: Git treating directory like a file


问:
re-fork only one branch on github
I forked a repo, added new branches and have currently some open pull requests.

Now I have done something wrong inside a branch and want to re-fork it from the original.

How can I do this?
I can not remove the whole fork because of the open pull requests.

I am a newbie and until now, I did everything on the github web page.
Now I have downloded the 'Github Desktop' software, but it seems that this tool is not helpful for that.

答:
No need to 're-fork' (that's even not possible to fork only one branch).

The thing you have to do, if you already have not done it, is to add the upstream repository as a remote.

Then fetch from this remote. You will have the commits you lost. Then fix your branch (using a 'git reset --hard'. Beware of lost data! ) and push it to your forked repository (that should be your 'origin' remote).

Title: re-fork only one branch on github


问:
Splunk regular expression to find data
I am trying to find x-sw-client-id value i.e. self-service-automation from below log.  key is always same but value will be different based on the client.  could you suggest me a regex or query to find the number of clients hitting my service?</p>

```<code>POST : http://selfservice.host.io/service
36677 > host: billing-host.io
36677 > user-agent: unirest-java/1.2.11 32322 > x-key: self-service
36677 > x-app-name: Self_Service_Consumer
36677 > x-sw-client-id: self-service-automation
36677 > x-forwarded-for: 111.111.110.134, 120.24.519.232, 110.423.232.432
36677 > x-forwarded-host: api-qa-self-service.host.io
36677 > x-forwarded-port: 443
</code>```

答:
Try this. Your new field name will be "ClientID"

... | rex x\-sw\-client\-id\:\s(?<ClientID>\S+)

Title: Splunk regular expression to find data

Body:
I am trying to find x-sw-client-id value i.e. self-service-automation from below log.  key is always same but value will be different based on the client.  could you suggest me a regex or query to find the number of clients hitting my service?

POST : http://selfservice.host.io/service
36677 > host: billing-host.io
36677 > user-agent: unirest-java/1.2.11 32322 > x-key: self-service
36677 > x-app-name: Self_Service_Consumer
36677 > x-sw-client-id: self-service-automation
36677 > x-forwarded-for: 111.111.110.134, 120.24.519.232, 110.423.232.432
36677 > x-forwarded-host: api-qa-self-service.host.io
36677 > x-forwarded-port: 443


问:
Cannot resolve symbol 'Theme.AppCompat.Light.DarkActionBar' in styles.xml
Theme.AppCompat.Light.DarkActionBar is not compiling in styles.xml. I have added compile 'com.android.support:appcompat-v7:25.1.0' in app module's
build.gradle.

I have searched for solution in google. A lot of them are about changing the classpath in Project's build.gradle.Still its showing the same error.

```<code>build.gradle

dependencies {
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
    compile 'com.android.support:support-annotations:25.1.0'
    compile 'com.android.support:cardview-v7:25.1.0'
    compile 'com.android.support:recyclerview-v7:25.1.0'
    //    compile 'ch.acra:acra:4.5.0'

    testCompile 'junit:junit:4.12'
}

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 25
        versionCode = 146
        versionName = "0.6.65"
    }
</code>```

答:
I have noticed that all themes available with the prefix @android:style/ can be used. So, I have solved this issue by replacing

Theme.AppCompat.Light.DarkActionBar

with

@android:style/Theme.DeviceDefault.Light.DarkActionBar

Body:
Theme.AppCompat.Light.DarkActionBar is not compiling in styles.xml. I have added compile 'com.android.support:appcompat-v7:25.1.0' in app module's
build.gradle.

I have searched for solution in google. A lot of them are about changing the classpath in Project's build.gradle.Still its showing the same error.

build.gradle

dependencies {
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
    compile 'com.android.support:support-annotations:25.1.0'
    compile 'com.android.support:cardview-v7:25.1.0'
    compile 'com.android.support:recyclerview-v7:25.1.0'
    //    compile 'ch.acra:acra:4.5.0'

    testCompile 'junit:junit:4.12'
}

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 25
        versionCode = 146
        versionName = "0.6.65"
    }