问:
How to configure a Play application to use Let's Encrypt certificate and to convert let's encrypt certificate so that play can understand it?
I have been using play framework as my server and react webpage as a client. I have already created and set up certificate for react webpage using letsencrypt. But, now i have to configure this certificate work also for play application. How can i configure application.conf to use it?</p>

答:
I myself found answer answer to my Question.

First create certificate for nginx from https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04#step-5-enabling-the-changes-in-nginx

After creating certificate, follow following step:

1) First stop your play server

2) Do sudo su

3) Do ssh and go to the location where your sslcertificate is which will be like: /etc/letsencrypt/live/example.com

4)Type following command

```<code>openssl pkcs12 -export -in fullchain.pem -inkey privkey.pem -out cert_and_key.p12 -CAfile chain.pem -caname root -passout pass:your_password
</code>```

5)Type following command

```<code>keytool -importkeystore -srcstorepass your_password -destkeystore keyStore.jks -srckeystore cert_and_key.p12 -srcstoretype PKCS12 -storepass your_password
</code>```

6) After .jks is created put following code in your application.conf file:

```<code>play.crypto.secret="changethissosomethingsecret"
play.server.https.keyStore.path = "Path to your .jks file"
play.server.https.keyStore.type = "JKS"
play.server.https.keyStore.password = "yourKeyStorePassword"
</code>```

5) Now change your play run command to following

```<code>nohup /home/ubuntu/webserver/manpowercompany-1.0-SNAPSHOT/bin/manpowercompany -J-Xms128M -J-Xmx1024M -Dplay.crypto.secret=anyKey -Dhttps.port=9002 &
</code>```

Note: Change the directory according to your file locations

6) Start the server with the file containing above run command. You might need to do sudo.

7) You are good to go. Now your server is served as https at port 9002

Above procedure are the step i did according to my project. So, do reference this and make changes according to your project.
Thank you!!!

Body:
I myself found answer answer to my Question.

First create certificate for nginx from https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04#step-5-enabling-the-changes-in-nginx

After creating certificate, follow following step:

1) First stop your play server

2) Do sudo su

3) Do ssh and go to the location where your sslcertificate is which will be like: /etc/letsencrypt/live/example.com

4)Type following command

openssl pkcs12 -export -in fullchain.pem -inkey privkey.pem -out cert_and_key.p12 -CAfile chain.pem -caname root -passout pass:your_password

5)Type following command

keytool -importkeystore -srcstorepass your_password -destkeystore keyStore.jks -srckeystore cert_and_key.p12 -srcstoretype PKCS12 -storepass your_password

6) After .jks is created put following code in your application.conf file:

play.crypto.secret="changethissosomethingsecret"
play.server.https.keyStore.path = "Path to your .jks file"
play.server.https.keyStore.type = "JKS"
play.server.https.keyStore.password = "yourKeyStorePassword"

5) Now change your play run command to following

nohup /home/ubuntu/webserver/manpowercompany-1.0-SNAPSHOT/bin/manpowercompany -J-Xms128M -J-Xmx1024M -Dplay.crypto.secret=anyKey -Dhttps.port=9002 &

Note: Change the directory according to your file locations

6) Start the server with the file containing above run command. You might need to do sudo.

7) You are good to go. Now your server is served as https at port 9002

Above procedure are the step i did according to my project. So, do reference this and make changes according to your project.
Thank you!!!


来源: stackexchange

问:
Dice Simulation java
I'm writing a dice simulation program, however I'm having problems with the results because it just prints:

```<code>You rolled a ...1 and 1

You rolled double ones 0 out of 10000 rolls.
You rolled double twos 0 out of 10000 rolls.
You rolled double threes 0 out of 10000 rolls.
You rolled double fours 0 out of 10000 rolls.
You rolled double fives 0 out of 10000 rolls.
You rolled double sixes 0 out of 10000 rolls.
</code>```

it always prints this and I don't understand why, since it should print different numbers each time.

```<code>    public class Dice
{
    private int die1;
    private int die2;

    public Dice()
    {
        die1 = 1;
        die2 = 1;
    }

    public void rollDice()
    {
        Random myRan = new Random();

        die1 = myRan.nextInt(6) + 1;
        die2 = myRan.nextInt(6) + 1;
    }

   public int getDie1()
   {
   return die1;
   }

   public int getDie2()
   {
    return die2;
   }

    public String toString()
    {
         return "You rolled a ..." + die1 + " and " + die2 + "\n";   }
}
</code>```

and...

```<code> import java.util.Random;
public class DiceSimulation
{
    static final int NUMBER = 10000;
    static Random generator = new Random();

    static int die1Value;
    static int die2Value;
    static int count = 0;
    static int ones = 0;
    static int twos = 0;
    static int threes = 0;
    static int fours = 0;
    static int fives = 0;
    static int sixes = 0;
    static int c=1;

public static void main(String[] args)
{

    rollDiceAndTabulateWhile();
    rollDiceAndTabulteDoWhile();
    rollDiceAndTabulteFor();
    summarizeResults();
}

public static void rollDiceAndTabulateWhile()
{

        Dice d = new Dice();
        while(c<= NUMBER)
        {
        d.rollDice();
        die1Value = d.getDie1();
        die2Value = d.getDie2();
        if(die1Value == die2Value)
        count++;
        else if(die1Value == 1 && die2Value == 1)
        ones++;
        else if(die1Value == 2 && die2Value == 2)
        twos++;
        else if(die1Value == 3 && die2Value == 3)
        threes++;
        else if(die1Value == 4 && die2Value == 4)
        fours++;
        else if(die1Value == 5 && die2Value == 5)
        fives++;
        else if(die1Value == 6 && die2Value == 6)
        sixes++;

        c++;
        }
}

public static void rollDiceAndTabulteDoWhile()
{

     DiceSimulation dw = new DiceSimulation();

        Dice d = new Dice();
        do
        {
        d.rollDice();
        dw.die1Value = d.getDie1();
        dw.die2Value = d.getDie2();
        if(die1Value == die2Value)
        count++;
        else if(dw.die1Value == 1 && dw.die2Value == 1)
        ones++;
        else if(dw.die1Value == 2 && dw.die2Value == 2)
        twos++;
        else if(dw.die1Value == 3 && dw.die2Value == 3)
        threes++;
        else if(dw.die1Value == 4 && dw.die2Value == 4)
        fours++;
        else if(dw.die1Value == 5 && dw.die2Value == 5)
        fives++;
        else if(dw.die1Value == 6 && dw.die2Value == 6)
        sixes++;
        c++;
        } while(c <= NUMBER);
}

public static void rollDiceAndTabulteFor()
  {
    DiceSimulation dw = new DiceSimulation();
    Dice d = new Dice();

    for(c=1;c<=NUMBER;c++)
    {
    d.rollDice();
    dw.die1Value = d.getDie1();
    dw.die2Value = d.getDie2();
    if(die1Value == die2Value)
    count++;
    else if(dw.die1Value == 1 && dw.die2Value == 1)
    ones++;
    else if(dw.die1Value == 2 && dw.die2Value == 2)
    twos++;
    else if(dw.die1Value == 3 && dw.die2Value == 3)
    threes++;
    else if(dw.die1Value == 4 && dw.die2Value == 4)
    fours++;
    else if(dw.die1Value == 5 && dw.die2Value == 5)
    fives++;
    else if(dw.die1Value == 6 && dw.die2Value == 6)
    sixes++;
  }
  }
public static void summarizeResults()
{
    Dice d = new Dice();
    System.out.println(d.toString());
    System.out.println("You rolled double ones " + ones
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double twos " + twos
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double threes " + threes
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double fours " + fours
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double fives " + fives
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double sixes " + sixes
            + " out of " + NUMBER + " rolls.");
}
</code>```

}

答:
You are creating Random object when you call the rollDice() each and everytime. It is not good, make it instance variable.

It is not the problem in your code. The problem is your if and else if conditions, Because if one condition is true not reach to other else if and else, that is the flow of the if, else if and else. Since, you need to execute all the incrementation you need to change them to separate if conditions.

Change else if to if:

```<code>    if(die1Value == die2Value)
      count++;
    if(die1Value == 1 && die2Value == 1)
      ones++;
    if(die1Value == 2 && die2Value == 2)
      twos++;
    if(die1Value == 3 && die2Value == 3)
      threes++;
    if(die1Value == 4 && die2Value == 4)
      fours++;
    if(die1Value == 5 && die2Value == 5)
      fives++;
    if(die1Value == 6 && die2Value == 6)
      sixes++;
</code>```

Also make sure to indent your code.

Output:

```<code>You rolled double ones 286 out of 10000 rolls.
You rolled double twos 280 out of 10000 rolls.
You rolled double threes 265 out of 10000 rolls.
You rolled double fours 262 out of 10000 rolls.
You rolled double fives 278 out of 10000 rolls.
You rolled double sixes 303 out of 10000 rolls.
</code>```

UPDATE:

To get

```<code>You rolled a ...4 and 3
</code>```

Change:

```<code>  //add static keyword
  private static int die1 = 1;
  private static int die2 = 1;

  public Dice()
  {
     //remove die1 = 1; die2 = 1;
  }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Dice Simulation java

Body:
I'm writing a dice simulation program, however I'm having problems with the results because it just prints:

You rolled a ...1 and 1

You rolled double ones 0 out of 10000 rolls.
You rolled double twos 0 out of 10000 rolls.
You rolled double threes 0 out of 10000 rolls.
You rolled double fours 0 out of 10000 rolls.
You rolled double fives 0 out of 10000 rolls.
You rolled double sixes 0 out of 10000 rolls.

it always prints this and I don't understand why, since it should print different numbers each time.

    public class Dice
{
    private int die1;
    private int die2;

    public Dice()
    {
        die1 = 1;
        die2 = 1;
    }

    public void rollDice()
    {
        Random myRan = new Random();

        die1 = myRan.nextInt(6) + 1;
        die2 = myRan.nextInt(6) + 1;
    }

   public int getDie1()
   {
   return die1;
   }

   public int getDie2()
   {
    return die2;
   }

    public String toString()
    {
         return "You rolled a ..." + die1 + " and " + die2 + "\n";   }
}

and...

 import java.util.Random;
public class DiceSimulation
{
    static final int NUMBER = 10000;
    static Random generator = new Random();

    static int die1Value;
    static int die2Value;
    static int count = 0;
    static int ones = 0;
    static int twos = 0;
    static int threes = 0;
    static int fours = 0;
    static int fives = 0;
    static int sixes = 0;
    static int c=1;

public static void main(String[] args)
{

    rollDiceAndTabulateWhile();
    rollDiceAndTabulteDoWhile();
    rollDiceAndTabulteFor();
    summarizeResults();
}

public static void rollDiceAndTabulateWhile()
{

        Dice d = new Dice();
        while(c<= NUMBER)
        {
        d.rollDice();
        die1Value = d.getDie1();
        die2Value = d.getDie2();
        if(die1Value == die2Value)
        count++;
        else if(die1Value == 1 && die2Value == 1)
        ones++;
        else if(die1Value == 2 && die2Value == 2)
        twos++;
        else if(die1Value == 3 && die2Value == 3)
        threes++;
        else if(die1Value == 4 && die2Value == 4)
        fours++;
        else if(die1Value == 5 && die2Value == 5)
        fives++;
        else if(die1Value == 6 && die2Value == 6)
        sixes++;

        c++;
        }
}

public static void rollDiceAndTabulteDoWhile()
{

     DiceSimulation dw = new DiceSimulation();

        Dice d = new Dice();
        do
        {
        d.rollDice();
        dw.die1Value = d.getDie1();
        dw.die2Value = d.getDie2();
        if(die1Value == die2Value)
        count++;
        else if(dw.die1Value == 1 && dw.die2Value == 1)
        ones++;
        else if(dw.die1Value == 2 && dw.die2Value == 2)
        twos++;
        else if(dw.die1Value == 3 && dw.die2Value == 3)
        threes++;
        else if(dw.die1Value == 4 && dw.die2Value == 4)
        fours++;
        else if(dw.die1Value == 5 && dw.die2Value == 5)
        fives++;
        else if(dw.die1Value == 6 && dw.die2Value == 6)
        sixes++;
        c++;
        } while(c <= NUMBER);
}

public static void rollDiceAndTabulteFor()
  {
    DiceSimulation dw = new DiceSimulation();
    Dice d = new Dice();

    for(c=1;c<=NUMBER;c++)
    {
    d.rollDice();
    dw.die1Value = d.getDie1();
    dw.die2Value = d.getDie2();
    if(die1Value == die2Value)
    count++;
    else if(dw.die1Value == 1 && dw.die2Value == 1)
    ones++;
    else if(dw.die1Value == 2 && dw.die2Value == 2)
    twos++;
    else if(dw.die1Value == 3 && dw.die2Value == 3)
    threes++;
    else if(dw.die1Value == 4 && dw.die2Value == 4)
    fours++;
    else if(dw.die1Value == 5 && dw.die2Value == 5)
    fives++;
    else if(dw.die1Value == 6 && dw.die2Value == 6)
    sixes++;
  }
  }
public static void summarizeResults()
{
    Dice d = new Dice();
    System.out.println(d.toString());
    System.out.println("You rolled double ones " + ones
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double twos " + twos
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double threes " + threes
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double fours " + fours
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double fives " + fives
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double sixes " + sixes
            + " out of " + NUMBER + " rolls.");
}

}

Body:
You are creating Random object when you call the rollDice() each and everytime. It is not good, make it instance variable.

It is not the problem in your code. The problem is your if and else if conditions, Because if one condition is true not reach to other else if and else, that is the flow of the if, else if and else. Since, you need to execute all the incrementation you need to change them to separate if conditions.

Change else if to if:

    if(die1Value == die2Value)
      count++;
    if(die1Value == 1 && die2Value == 1)
      ones++;
    if(die1Value == 2 && die2Value == 2)
      twos++;
    if(die1Value == 3 && die2Value == 3)
      threes++;
    if(die1Value == 4 && die2Value == 4)
      fours++;
    if(die1Value == 5 && die2Value == 5)
      fives++;
    if(die1Value == 6 && die2Value == 6)
      sixes++;

Also make sure to indent your code.

Output:

You rolled double ones 286 out of 10000 rolls.
You rolled double twos 280 out of 10000 rolls.
You rolled double threes 265 out of 10000 rolls.
You rolled double fours 262 out of 10000 rolls.
You rolled double fives 278 out of 10000 rolls.
You rolled double sixes 303 out of 10000 rolls.

UPDATE:

To get

You rolled a ...4 and 3

Change:

  //add static keyword
  private static int die1 = 1;
  private static int die2 = 1;

  public Dice()
  {
     //remove die1 = 1; die2 = 1;
  }


问:
docker: how to get veth bridge interface pair easily?
i have 2 containers by docker, and bridge like this:

```<code># docker ps
CONTAINER ID        IMAGE                                         COMMAND                CREATED             STATUS              PORTS                      NAMES
ef99087167cb        images.docker.sae.sina.com.cn/ubuntu:latest   /bin/bash -c /home/c   2 days ago          Up 21 minutes       0.0.0.0:49240->22223/tcp   night_leve3
c8a7b18ec20d        images.docker.sae.sina.com.cn/ubuntu:latest   /bin/bash -c /home/c   2 days ago          Up 54 minutes       0.0.0.0:49239->22223/tcp   night_leve2

#brctl show cbr0
bridge name bridge id       STP enabled interfaces
docker0     8000.72b675c52895   no      vethRQOy1I
                                        vethjKYWka
</code>```

How can i get which container match veth* ?

ef99 => vethRQOy1I or ef99 => vethjKYWka

//----------------------------------------------------------

I know it works by ethtool, but is there any better way?

答:
Try this script:

```<code>get_network_mode() {
    docker inspect --format='{{.HostConfig.NetworkMode}}' "$1"
}

created_by_kubelet() {
    [[ $(docker inspect --format='{{.Name}}' "$1") =~ ^/k8s_ ]]
}

for container_id in $(docker ps -q); do
    network_mode=$(get_network_mode "${container_id}")
    # skip the containers whose network_mode is 'host' or 'none',
    # but do NOT skip the container created by kubelet.
    if [[ "${network_mode}" == "host" || \
          $(! created_by_kubelet "${container_id}") && "${network_mode}" == "none" ]]; then
        echo "${container_id} => ${network_mode}"
        continue
    fi

    # if one container's network_mode is 'other container',
    # then get its root parent container's network_mode.
    while grep container <<< "${network_mode}" -q; do
        network_mode=$(get_network_mode "${network_mode/container:/}")
        # skip the containers whose network_mode is 'host' or 'none',
        # but do NOT skip the container created by kubelet.
        if [[ "${network_mode}" == "host" || \
              $(! created_by_kubelet "${container_id}") && "${network_mode}" == "none" ]]; then
            echo "${container_id} => ${network_mode}"
            continue 2
        fi
    done

    # get current container's 'container_id'.
    pid=$(docker inspect --format='{{.State.Pid}}' "${container_id}")

    # get the 'id' of veth device in the container.
    veth_id=$(nsenter -t "${pid}" -n ip link show eth0 |grep -oP '(?<=eth0@if)\d+(?=:)')

    # get the 'name' of veth device in the 'docker0' bridge (or other name),
    # which is the peer of veth device in the container.
    veth_name=$(ip link show |sed -nr "s/^${veth_id}: *([^ ]*)@if.*/\1/p")

    echo "${container_id} => ${veth_name}"
done
</code>```

Explains:

avoid to execute commands in container.

avoid to create temporary folders and files.

MOST importantly, avoid to get incorrect answers for containers whose NetworkMode is host, none, or container:<name|id> (share network stack with another container's. For example: user's containers in one pod in kubernetes share the network stack with the pause pod container's network stack)

ContentLicense: CC BY-SA 4.0

Body:
i have 2 containers by docker, and bridge like this:

# docker ps
CONTAINER ID        IMAGE                                         COMMAND                CREATED             STATUS              PORTS                      NAMES
ef99087167cb        images.docker.sae.sina.com.cn/ubuntu:latest   /bin/bash -c /home/c   2 days ago          Up 21 minutes       0.0.0.0:49240->22223/tcp   night_leve3
c8a7b18ec20d        images.docker.sae.sina.com.cn/ubuntu:latest   /bin/bash -c /home/c   2 days ago          Up 54 minutes       0.0.0.0:49239->22223/tcp   night_leve2

#brctl show cbr0
bridge name bridge id       STP enabled interfaces
docker0     8000.72b675c52895   no      vethRQOy1I
                                        vethjKYWka

How can i get which container match veth* ?

ef99 => vethRQOy1I or ef99 => vethjKYWka

//----------------------------------------------------------

I know it works by ethtool, but is there any better way?

Body:
Try this script:

get_network_mode() {
    docker inspect --format='{{.HostConfig.NetworkMode}}' "$1"
}

created_by_kubelet() {
    [[ $(docker inspect --format='{{.Name}}' "$1") =~ ^/k8s_ ]]
}

for container_id in $(docker ps -q); do
    network_mode=$(get_network_mode "${container_id}")
    # skip the containers whose network_mode is 'host' or 'none',
    # but do NOT skip the container created by kubelet.
    if [[ "${network_mode}" == "host" || \
          $(! created_by_kubelet "${container_id}") && "${network_mode}" == "none" ]]; then
        echo "${container_id} => ${network_mode}"
        continue
    fi

    # if one container's network_mode is 'other container',
    # then get its root parent container's network_mode.
    while grep container <<< "${network_mode}" -q; do
        network_mode=$(get_network_mode "${network_mode/container:/}")
        # skip the containers whose network_mode is 'host' or 'none',
        # but do NOT skip the container created by kubelet.
        if [[ "${network_mode}" == "host" || \
              $(! created_by_kubelet "${container_id}") && "${network_mode}" == "none" ]]; then
            echo "${container_id} => ${network_mode}"
            continue 2
        fi
    done

    # get current container's 'container_id'.
    pid=$(docker inspect --format='{{.State.Pid}}' "${container_id}")

    # get the 'id' of veth device in the container.
    veth_id=$(nsenter -t "${pid}" -n ip link show eth0 |grep -oP '(?<=eth0@if)\d+(?=:)')

    # get the 'name' of veth device in the 'docker0' bridge (or other name),
    # which is the peer of veth device in the container.
    veth_name=$(ip link show |sed -nr "s/^${veth_id}: *([^ ]*)@if.*/\1/p")

    echo "${container_id} => ${veth_name}"
done

Explains:

avoid to execute commands in container.

avoid to create temporary folders and files.

MOST importantly, avoid to get incorrect answers for containers whose NetworkMode is host, none, or container:<name|id> (share network stack with another container's. For example: user's containers in one pod in kubernetes share the network stack with the pause pod container's network stack)


问:
PHP function to make text from an RSS feed render properly?
I'm pulling some text from an RSS feed and need to wrap it in a PHP function to get it to render right.  The text has been augmented and looks like this:

Reply to this update by 4PM & you're entered to win a pair of tickets to the SOLD OUT 'Twas the Night Before Christmas Tour' featuring Relient K (Acoustic) with Sherwood and Deas Vail show on Friday at 7PM (All Ages). We'll be making our list, checking it twice, etc. at 4PM down in the comments- remember to stop by and see if you've won. Happy Holidays :)

12-17-2010 Relient K Acoustic | Lincoln Hall
www.lincolnhallchicago.com
Lincoln Hall in Chicago, Illinois - Live Music Nightly

I don't know what to call the formatting of this text, but whatever it is, I don't want it to display this way, I want it to display as properly readable, rendered HTML.

Can someone point me to the right resources? I don't even know what to google.  Thanks.

答: It looks like it's either been "magic quoted" or someone has run it through urlencode...It's hard to say just looking at the output, because that's all valid HTML (and Javascript. If you don't have those scripts on the page, it shouldn't matter, but their lack will break any Javascript you DO have on the page, so be aware)...How are you looking at it? Are you using a browser, and it looks like the above text?</p>

ContentLicense: CC BY-SA 2.5


问:
Rails when to avoid database

how big a data is too big to go into a database?

If optimised, database access can be faster than simple file system access.

But assuming the server is running on either:

a conventional budget home server

AWS

Is there any reason to use database for storing things larger than some articles?

The power of X-sendfile made me decide to move some data to the filesystem, but to what extent should I do this?

答:
The only data I wouldn't store on a database are files.

Files whose content I do not need to search.

Like images, videos etc.

Any other data, regardless of the size will go into a database.

If I have a JSON file it will go into a NoSQL database that can search and index JSON file.

If I have a Gigabytes of data on anything, anything at all it will go into a database.

Databases have much better mechanisms than anything anyone can rig for files in a filesystem.

You question lacks context for me to give a better answer.

Title: Rails when to avoid database


问:
Execute a python file c#
I have a python converter that works calling it with some parameters from cmd. I want to create an exe that automatically calls it with the needed parameters, which are the model I want to convert and the name of the model that it will be created.
The code is:</p>

```<code>blender -b -P dae-obj.py -- file.dae file.obj
</code>```

答:
I believe you want the subprocess module - https://docs.python.org/3/library/subprocess.html

One way to do what I think you're trying to do would be:

```<code>import subprocess

out = subprocess.getoutput('blender -b -P dae-obj.py -- file.dae file.obj')
</code>```

Though I expect you don't care about the output.  You could also try getstatusoutput or call

Title: Execute a python file c#

Body:
I have a python converter that works calling it with some parameters from cmd. I want to create an exe that automatically calls it with the needed parameters, which are the model I want to convert and the name of the model that it will be created.
The code is:

blender -b -P dae-obj.py -- file.dae file.obj

Body:
I believe you want the subprocess module - https://docs.python.org/3/library/subprocess.html

One way to do what I think you're trying to do would be:

import subprocess

out = subprocess.getoutput('blender -b -P dae-obj.py -- file.dae file.obj')

Though I expect you don't care about the output.  You could also try getstatusoutput or call


问:
C/C++ Windows or Linux map random memory blocks into consecutive order
My requirement is to emulate an old motorola memory controller.

Basically the controller maps 8 x 8Kbyte memory blocks into a 64Kbyte address space for subsequent access by a CPU.  The controller has access to upto 1024 such 8K blocks.

At the moment I have accomplished this by using a large flat array like so:

```<code>unsigned char Memory[1024][8192];
int MappedMemoryBank[8];
short int Address;
</code>```

Then to access any particular memory address I use something like this

```<code>unsigned char aByte = Memory[MappedMemoryBank[Address>>13]][Address&0x1FFF];
</code>```

This works fine but as memory references comprise 99% of processing time it is very inefficient.

Is there a memory mapping mechanism where I can allocate a number (1024) of memory blocks and then map them (in any order) into a consecutive memory space?

This would reduce my memory references to:

```<code>unsigned char *Memory;
Memory = pointed to first byte of (re-)mapped memory

unsigned char aByte = Memory[Address];
</code>```

Which would be an order of magnitude faster (I hope)

A solution for either Windows and/or Linux is OK.

答:
How often do you change the mapping vs. how often you access the memory?

Assuming accessing it is a lot more common than rearranging it, I'd probably keep two copies of the data: a "mapped" array, and a "physical array".

Your use "ping-pongs" between the two. That is, when you create a mapping, you copy the data in the correct order from the physical to the mapped array. When you need to rearrange it, copy back to the physical array, and then (again, in the correct order) to the mapped array.

This is likely to slow re-mapping by a factor of 10 (or something on that order) but speed up accesses by at least a factor of 10 as well. Since the re-mapping apparently took less than 1% of the time previously, that should be a fairly substantial win.

Body:
My requirement is to emulate an old motorola memory controller.

Basically the controller maps 8 x 8Kbyte memory blocks into a 64Kbyte address space for subsequent access by a CPU.  The controller has access to upto 1024 such 8K blocks.

At the moment I have accomplished this by using a large flat array like so:

unsigned char Memory[1024][8192];
int MappedMemoryBank[8];
short int Address;

Then to access any particular memory address I use something like this

unsigned char aByte = Memory[MappedMemoryBank[Address>>13]][Address&0x1FFF];

This works fine but as memory references comprise 99% of processing time it is very inefficient.

Is there a memory mapping mechanism where I can allocate a number (1024) of memory blocks and then map them (in any order) into a consecutive memory space?

This would reduce my memory references to:

unsigned char *Memory;
Memory = pointed to first byte of (re-)mapped memory

unsigned char aByte = Memory[Address];

Which would be an order of magnitude faster (I hope)

A solution for either Windows and/or Linux is OK.


问:
Import Array from file in Javascript
I have an array of strings in their own file that I'm looking to use as a variable in my client side Javascript. I've been trying various $.getJSON and function loadJSON(callback){} solutions but everything is giving me the error GET http://localhost:3001/strings.json 404 (Not Found)

(I've also tried it with the file called strings.js and get the same results)

both the strings.json file and my client side JavaScript file are in the /public/js/ directory, so I'm fairly certain it isn't a path issue.

script.js

```<code>$.getJSON("strings.json", function(json){
    console.log(json);
});
</code>```

strings.json

```<code>["string 1","string 2","string 3", "string 4", "etc"]
</code>```

Edit: Added the small amount of actually relevant code. I'm aware strings.json is not actually json, but it seemed like the most logical file type. Please let me know if there's something better.

答:
The error is saying it as is, your file couldn't be found.

The path you provided for your $.getJSON is incorrect, unless you place strings.json in the same directory of your webpage.

Try placing an absolute path in the function, IE:

```<code>$.getJSON("/public/js/strings.json", function(json){
    console.log(json);
});
</code>```

EDIT: If it is in the same directory already, try lead the path with a "./" to indicate the path is in the same directory:

```<code>$.getJSON("./strings.json", function(json){
    console.log(json);
});
</code>```

EDIT: Lastly, if you still can't navigate properly, you can also try to submit a path as a parameter to $.getJSON coming from your server script. If you use ASP C#, for example you can use:

```<code>currPath = Page.ResolveUrl("~/public/js/strings.json");
</code>```

Then pass currPath as a parameter for pathVal below:

```<code>    function getThis(pathVal){
        $.getJSON(pathVal, function(json){
             console.log(json);
         });
      }
</code>```

Or something equivalent in php. Note that it might make your code messy though, but it works.

Title: Import Array from file in Javascript

Body:
I have an array of strings in their own file that I'm looking to use as a variable in my client side Javascript. I've been trying various $.getJSON and function loadJSON(callback){} solutions but everything is giving me the error GET http://localhost:3001/strings.json 404 (Not Found)

(I've also tried it with the file called strings.js and get the same results)

both the strings.json file and my client side JavaScript file are in the /public/js/ directory, so I'm fairly certain it isn't a path issue.

script.js

$.getJSON("strings.json", function(json){
    console.log(json);
});

strings.json

["string 1","string 2","string 3", "string 4", "etc"]

Edit: Added the small amount of actually relevant code. I'm aware strings.json is not actually json, but it seemed like the most logical file type. Please let me know if there's something better.

Body:
The error is saying it as is, your file couldn't be found.

The path you provided for your $.getJSON is incorrect, unless you place strings.json in the same directory of your webpage.

Try placing an absolute path in the function, IE:

$.getJSON("/public/js/strings.json", function(json){
    console.log(json);
});

EDIT: If it is in the same directory already, try lead the path with a "./" to indicate the path is in the same directory:

$.getJSON("./strings.json", function(json){
    console.log(json);
});

EDIT: Lastly, if you still can't navigate properly, you can also try to submit a path as a parameter to $.getJSON coming from your server script. If you use ASP C#, for example you can use:

currPath = Page.ResolveUrl("~/public/js/strings.json");

Then pass currPath as a parameter for pathVal below:

    function getThis(pathVal){
        $.getJSON(pathVal, function(json){
             console.log(json);
         });
      }

Or something equivalent in php. Note that it might make your code messy though, but it works.


问:
How I can send custom parameters through java?
Suppose I want to send following parameters :

```<code>key1: value1,
key2: value2
</code>```

But currently I can't decide what will be there at place of key1,key2
That may be any string. key1 may be city,key2 may be code. Or key 1 may be companyName and key 2 is domain. So how can I set any custom unknown parametrs in method of java? Consider that I know total number of parameters and data type of their values, but can't determine their exact keys now. How to implement it in java?

答:
You can send an array of objects in your method:

```<code>Object[] myObjects = new Object[2];
myObjects[0] = "This is a string";
myObjects[1] = 5;

myMethod(myObjects);

public void myMethod(Object[] myObjects){
    // DoSomethingOverHere
}
</code>```

If you only have Strings you can do the same but specify an array of Strings instead of objects. If you use objects, make sure to check the instance of the objects before using it.

Body:
Suppose I want to send following parameters :

key1: value1,
key2: value2

But currently I can't decide what will be there at place of key1,key2
That may be any string. key1 may be city,key2 may be code. Or key 1 may be companyName and key 2 is domain. So how can I set any custom unknown parametrs in method of java? Consider that I know total number of parameters and data type of their values, but can't determine their exact keys now. How to implement it in java?

Body:
You can send an array of objects in your method:

Object[] myObjects = new Object[2];
myObjects[0] = "This is a string";
myObjects[1] = 5;

myMethod(myObjects);

public void myMethod(Object[] myObjects){
    // DoSomethingOverHere
}

If you only have Strings you can do the same but specify an array of Strings instead of objects. If you use objects, make sure to check the instance of the objects before using it.


问:
Android API 23: intent-filter not working
My app is registering an extension "myapp" so we can import file from email or inside the My Files app. It has been working before, but now it has stopped working. The app in the Play Store cannot see the files with those extension any more. The problem seems to start with Android Marshmallow, Android 6, API 23. The Play Store app works on Android 4.1.

Here is our code to register for intent-filter. What could possibly go wrong?
Something is wrong with Stackoverflow, I cannot post my code, so I took a picture of it

答:
Starting from API-23,To enable your app to handle links, use intent filters in your app manifest to declare the URI patterns that your app handles.

The following example shows an intent filter that can handle links to http://www.example.com and https://www.example.com:

```<code><intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="http" android:host="www.example.com" />
        <data android:scheme="https" android:host="www.example.com" />
    </intent-filter>
</code>```

When the android:autoVerify attribute is present, installing your app causes the system to attempt to verify all hosts associated with the web URIs in all of your app's intent filters. The system treats your app as the default handler for the specified URI pattern only if it successfully verifies all app link patterns declared in your manifest.

Body:
Starting from API-23,To enable your app to handle links, use intent filters in your app manifest to declare the URI patterns that your app handles.

The following example shows an intent filter that can handle links to http://www.example.com and https://www.example.com:

<intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="http" android:host="www.example.com" />
        <data android:scheme="https" android:host="www.example.com" />
    </intent-filter>

When the android:autoVerify attribute is present, installing your app causes the system to attempt to verify all hosts associated with the web URIs in all of your app's intent filters. The system treats your app as the default handler for the specified URI pattern only if it successfully verifies all app link patterns declared in your manifest.


问:
c# .NET multipart/form-data Upload A File
I want to create an application to automaticly upload a file to googles SearchbyImage-tool
https://www.google.de/searchbyimage/upload

Google is using a multipart/form-data for submitting the file, something like that:

```<code>Content-Type: multipart/form-data; boundary=---------------------------265001916915724
Content-Length: 9989
-----------------------------265001916915724
Content-Disposition: form-data; name="image_url"

-----------------------------265001916915724
Content-Disposition: form-data; name="encoded_image"; filename=""
Content-Type: application/octet-stream

-----------------------------265001916915724
Content-Disposition: form-data; name="image_content"

[encoded data, 9080 characters]
-----------------------------265001916915724
Content-Disposition: form-data; name="filename"

filename.bmp
-----------------------------265001916915724
Content-Disposition: form-data; name="num"

10
-----------------------------265001916915724
Content-Disposition: form-data; name="hl"

de
-----------------------------265001916915724
Content-Disposition: form-data; name="bih"

976
-----------------------------265001916915724
Content-Disposition: form-data; name="biw"

1920
-----------------------------265001916915724--
</code>```

I have absolutely no idea on how to do that in C#... Any suggestions?

答:
using c# you can use HttpClient to do the Post Multi-part Form Data.

below is the code snippet that i tried and worked for me..

give it a try!!

```<code>using (var client = new HttpClient())
{
  //client.DefaultRequestHeaders.Add("User-Agent", "CBS Brightcove API Service");
  string authorization = GenerateBase64();
  client.DefaultRequestHeaders.Add("Authorization", authorization);

  using (var content = new MultipartFormDataContent())
  {

    string fileName = Path.GetFileName(textBox1.Text);

    //Content-Disposition: form-data; name="json"
    var stringContent = new StringContent(InstancePropertyObject);
    stringContent.Headers.Remove("Content-Type");
    stringContent.Headers.Add("Content-Type", "application/json");
    stringContent.Headers.Add("Content-Disposition", "form-data; name=\"instance\"");
    content.Add(stringContent, "instance");

    var fileContent = new ByteArrayContent(filecontent);
    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
      FileName = fileName
    };
    content.Add(fileContent);

    var result = client.PostAsync(targetURL, content).Result;
    Console.Read();
  }
}
</code>```

Body:
I want to create an application to automaticly upload a file to googles SearchbyImage-tool
https://www.google.de/searchbyimage/upload

Google is using a multipart/form-data for submitting the file, something like that:

Content-Type: multipart/form-data; boundary=---------------------------265001916915724
Content-Length: 9989
-----------------------------265001916915724
Content-Disposition: form-data; name="image_url"

-----------------------------265001916915724
Content-Disposition: form-data; name="encoded_image"; filename=""
Content-Type: application/octet-stream

-----------------------------265001916915724
Content-Disposition: form-data; name="image_content"

[encoded data, 9080 characters]
-----------------------------265001916915724
Content-Disposition: form-data; name="filename"

filename.bmp
-----------------------------265001916915724
Content-Disposition: form-data; name="num"

10
-----------------------------265001916915724
Content-Disposition: form-data; name="hl"

de
-----------------------------265001916915724
Content-Disposition: form-data; name="bih"

976
-----------------------------265001916915724
Content-Disposition: form-data; name="biw"

1920
-----------------------------265001916915724--

I have absolutely no idea on how to do that in C#... Any suggestions?

Body:
using c# you can use HttpClient to do the Post Multi-part Form Data.

below is the code snippet that i tried and worked for me..

give it a try!!

using (var client = new HttpClient())
{
  //client.DefaultRequestHeaders.Add("User-Agent", "CBS Brightcove API Service");
  string authorization = GenerateBase64();
  client.DefaultRequestHeaders.Add("Authorization", authorization);

  using (var content = new MultipartFormDataContent())
  {

    string fileName = Path.GetFileName(textBox1.Text);

    //Content-Disposition: form-data; name="json"
    var stringContent = new StringContent(InstancePropertyObject);
    stringContent.Headers.Remove("Content-Type");
    stringContent.Headers.Add("Content-Type", "application/json");
    stringContent.Headers.Add("Content-Disposition", "form-data; name=\"instance\"");
    content.Add(stringContent, "instance");

    var fileContent = new ByteArrayContent(filecontent);
    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
      FileName = fileName
    };
    content.Add(fileContent);

    var result = client.PostAsync(targetURL, content).Result;
    Console.Read();
  }
}


问:
Sending customised email to multiple recipients via macro
I am trying to send an email that is customized to the recipient to over hundred recipients.

I am able to send out my email to one person now but I have no idea how to loop it for multiple recipients and to change the content inside.

I have something like this and it works but I have no idea how to proceed

```<code>With OutlookMailItem
.To = Range("O2").Value
.Subject = "Promotion campaign"
.Body = "Dear Sir/Madam," & vbNewLine & vbNewLine & _
        "You are eligible for & Range("A2").Value & _
       "Please follow the instruction below to redeem your gift"
</code>```

答:
Nice place to looking for a solution in this kind of issues is:
https://www.rondebruin.nl/win/s1/outlook/amail8.htm

Below you'll find code which is what you want to achieve, i think.

Assumptions:

List of e-mails addresses starts from A1

List of, for example names, starts from B1. If you want to make some more changes just modify .Body

List of subjects starts from C1

For now i use .Display method which just showing all emails, but if you change it to .Send it will automatically send these mails without showing them

```<code>Sub Send_Row_Or_Rows_Attachment_1()
'Working in 2000-2016
'For Tips see: <a href="http://www.rondebruin.nl/win/winmail/Outlook/tips.htm" rel="nofollow noreferrer">http://www.rondebruin.nl/win/winmail/Outlook/tips.htm</a>
    Dim OutApp As Object
    Dim OutMail As Object
    Set OutApp = CreateObject("Outlook.Application")
    Dim intHowManyRows As Integer</p>

With Application
    .ScreenUpdating = False
End With

intHowManyRows = Application.Range("A1").CurrentRegion.Rows.Count

For r = 1 To intHowManyRows
    'Save, Mail, Close and Delete the file
    Set OutMail = OutApp.CreateItem(0)

    With OutMail
        .To = Cells(r, 1).Value
        .Subject = Cells(r, 3).Value
        '.Attachments.Add FullName  -> If you want to add attachments
        .Body = "Hi there" & vbNewLine & vbNewLine & "How are you " & Cells(r, 2)
        .Display  'Or use Send
    End With

Next r

Set OutMail = Nothing
Set OutApp = Nothing
Application.ScreenUpdating = True
End Sub
</code>```

Body:
I am trying to send an email that is customized to the recipient to over hundred recipients.

I am able to send out my email to one person now but I have no idea how to loop it for multiple recipients and to change the content inside.

I have something like this and it works but I have no idea how to proceed

With OutlookMailItem
.To = Range("O2").Value
.Subject = "Promotion campaign"
.Body = "Dear Sir/Madam," & vbNewLine & vbNewLine & _
        "You are eligible for & Range("A2").Value & _
       "Please follow the instruction below to redeem your gift"

Body:
Nice place to looking for a solution in this kind of issues is:
https://www.rondebruin.nl/win/s1/outlook/amail8.htm

Below you'll find code which is what you want to achieve, i think.

Assumptions:

List of e-mails addresses starts from A1

List of, for example names, starts from B1. If you want to make some more changes just modify .Body

List of subjects starts from C1

For now i use .Display method which just showing all emails, but if you change it to .Send it will automatically send these mails without showing them

Sub Send_Row_Or_Rows_Attachment_1()
'Working in 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
    Dim OutApp As Object
    Dim OutMail As Object
    Set OutApp = CreateObject("Outlook.Application")
    Dim intHowManyRows As Integer

With Application
    .ScreenUpdating = False
End With

intHowManyRows = Application.Range("A1").CurrentRegion.Rows.Count

For r = 1 To intHowManyRows
    'Save, Mail, Close and Delete the file
    Set OutMail = OutApp.CreateItem(0)

    With OutMail
        .To = Cells(r, 1).Value
        .Subject = Cells(r, 3).Value
        '.Attachments.Add FullName  -> If you want to add attachments
        .Body = "Hi there" & vbNewLine & vbNewLine & "How are you " & Cells(r, 2)
        .Display  'Or use Send
    End With

Next r

Set OutMail = Nothing
Set OutApp = Nothing
Application.ScreenUpdating = True
End Sub


问:
Uncheck item from checkboxList which gets selected with querystring onLoad
I have checkboxList which has autopostback true. I have made it in such way in which, on SelectedIndexChanged it gets redirected to same page with querystrting. Querystring value gets generated with selected items. Something like this
www.abcd.com/product?price=2000|3000|5000

So when page gets load the Checkboxlist items gets selected where its value is 2000,3000,5000 etc. But here I have drawback is that when I uncheck any item then agin first it executes pageLoad event code & there it finds value which is uncheck & gets selected again. In short unchecked items gets selected again.

PageLoadevent(Checkbox Items gets selected with querystring values)

```<code>string PageUrl = Request.Url.AbsolutePath;
if (PageUrl.Contains("price")) {
    string price = Request.QueryString("price");
    string[] priceList = price.Split('|');
    foreach (string p in priceList) {
        if (priceRange.Items.FindByValue(p + "|") != null) {
            priceRange.Items.FindByValue(p + "|").Selected = true;
        }
    }
}
</code>```

SelectedIndexChanged(URL created with querystring & redirected)

```<code>string pageURL = Request.Url.AbsoluteUri;
string strPrice = Request.QueryString("price").ToString;
if (totalcount > 1) {
    foreach (ListItem chk in brandsList.Items) {
        if (chk.Selected == true) {
            selectedBrands += (chk.Value);
        }
    }
    selectedBrands = selectedBrands.Remove(selectedBrands.Length - 1);

    Response.Redirect((Request.Url.AbsolutePath + "?") + "&brand=" + selectedBrands + "&price=" + strPrice);
}
</code>```

答:
```<code>if (!IsPostBack)
{
    string price = Request.QueryString["price"];
    string[] priceList = price.Split('|');

    foreach (string p in priceList)
    {
        if (chkList.Items.FindByText(p) != null)
        {
            chkList.Items.FindByText(p).Selected = true;
        }
    }
}
</code>```

Enclose logic of checkbox selection into IsPostBack condition in page load event. As above. When your page get postback your selection remain as it.

Body:
I have checkboxList which has autopostback true. I have made it in such way in which, on SelectedIndexChanged it gets redirected to same page with querystrting. Querystring value gets generated with selected items. Something like this
www.abcd.com/product?price=2000|3000|5000

So when page gets load the Checkboxlist items gets selected where its value is 2000,3000,5000 etc. But here I have drawback is that when I uncheck any item then agin first it executes pageLoad event code & there it finds value which is uncheck & gets selected again. In short unchecked items gets selected again.

PageLoadevent(Checkbox Items gets selected with querystring values)

string PageUrl = Request.Url.AbsolutePath;
if (PageUrl.Contains("price")) {
    string price = Request.QueryString("price");
    string[] priceList = price.Split('|');
    foreach (string p in priceList) {
        if (priceRange.Items.FindByValue(p + "|") != null) {
            priceRange.Items.FindByValue(p + "|").Selected = true;
        }
    }
}

SelectedIndexChanged(URL created with querystring & redirected)

string pageURL = Request.Url.AbsoluteUri;
string strPrice = Request.QueryString("price").ToString;
if (totalcount > 1) {
    foreach (ListItem chk in brandsList.Items) {
        if (chk.Selected == true) {
            selectedBrands += (chk.Value);
        }
    }
    selectedBrands = selectedBrands.Remove(selectedBrands.Length - 1);

    Response.Redirect((Request.Url.AbsolutePath + "?") + "&brand=" + selectedBrands + "&price=" + strPrice);
}

Body:
if (!IsPostBack)
{
    string price = Request.QueryString["price"];
    string[] priceList = price.Split('|');

    foreach (string p in priceList)
    {
        if (chkList.Items.FindByText(p) != null)
        {
            chkList.Items.FindByText(p).Selected = true;
        }
    }
}

Enclose logic of checkbox selection into IsPostBack condition in page load event. As above. When your page get postback your selection remain as it.


问:
Jackson fails to deserialize Kotlin data classes
I'm using Jackson to deserialize Kotlin data classes. I'm using the jackson-kotlin-module but Jackson is giving me the following error:

Can not construct instance of MyClass: no suitable constructor found, can not deserialize from Object value

I've tried adding proguard rules to keep my classes, and it's constructor without any success.

If I add a rule to keep all kotlin classes the error goes away.

Any ideas?

答:
After a lot of trial and error, I discovered that Proguard was stripping kotlin.Metadata annotations from my data classes.

Adding the following rule fixes the issue:

```<code>-keep class kotlin.Metadata { *; }
</code>```

I also found adding a rule to keep synthetic methods on my data classes was needed too:

```<code>-keepclassmembers public class com.mypackage.** {
    public synthetic <methods>;
}
</code>```

Body:
After a lot of trial and error, I discovered that Proguard was stripping kotlin.Metadata annotations from my data classes.

Adding the following rule fixes the issue:

-keep class kotlin.Metadata { *; }

I also found adding a rule to keep synthetic methods on my data classes was needed too:

-keepclassmembers public class com.mypackage.** {
    public synthetic <methods>;
}


问:
Adjust button text size with button height
I have a button that I set a particular height for and have the button text fill the entire button. I achieved this before by setting textSize to a specific dimension to fill the button.

But the problem is whenever the user changes the system font of his/her device, it affects the button text and the text overflows and gets cut in the button. How can I make the button text size match the height of the button?

Edit

The button's height is set to match_parent for it's parent widget

```<code>        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay">
            <RelativeLayout
                android:layout_marginEnd="16dp"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginRight="16dp">
                <Button
                    android:id="@+id/text_toolbar"
                    style="?android:attr/borderlessButtonStyle"
                    android:layout_centerInParent="true"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:textSize="36sp"
                    android:textColor="@color/white"
                    android:text="@string/k_i_n_e_c_t"/>
            </RelativeLayout>
        </android.support.v7.widget.Toolbar>
</code>```

答:
I guess you must have used dp as the unit for your textsize. It is preferable to use sp for text dimensions.

Why should we use sp for font sizes in Android?

Body:
I have a button that I set a particular height for and have the button text fill the entire button. I achieved this before by setting textSize to a specific dimension to fill the button.

But the problem is whenever the user changes the system font of his/her device, it affects the button text and the text overflows and gets cut in the button. How can I make the button text size match the height of the button?

Edit

The button's height is set to match_parent for it's parent widget

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay">
            <RelativeLayout
                android:layout_marginEnd="16dp"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginRight="16dp">
                <Button
                    android:id="@+id/text_toolbar"
                    style="?android:attr/borderlessButtonStyle"
                    android:layout_centerInParent="true"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:textSize="36sp"
                    android:textColor="@color/white"
                    android:text="@string/k_i_n_e_c_t"/>
            </RelativeLayout>
        </android.support.v7.widget.Toolbar>


问:
How to write react / angular micro application that share the route based on redux?
Writing micro-services on back-end is not that much confusing, specially if we are building api endpoints. We can write separate project for users management, separate project for reporting, ..., and combine all their endpoint with AWS gateway api, or for smaller one acomplish this with nginx reverse proxy to provide a integrated api service.

The way I am suggesting the team for writing back-end is something like that:

localhost:8001/list <- reverse proxy to -> apiproxy.com/users/list

localhost:8003/transaction <- reverse proxy to -> apiproxy.com/transactions/create

So it seems simple, we write our projects by category in separate repos, and each team/person can work individualy on it. But here goes my question:

" How can we implement a solution, that a server rendered React app ( Or, angular, Vue ) can render, and developed with separate repositories, but in build time, they merge into each other, and their routing works well."

So, in this senario, each repository must be able to bootstrap independetly. The aim is not create a new framework.

Does anyone has any kind of suggestion?

答:
Canopy Tax, a tech startup based in Utah that builds solutions for tax professionals, faced a similar situation about 2 years ago. They wanted to be able to implement some sort of microservice architecture in the front end, and guess what, they succeeded. The solution is not perfect yet, there's a lot of trade offs, but the objective is met and they are using this in production with their customers. I have seen it in action at some meet ups they have hosted.

Canopy Tax open sourced their framework last year, it is called Sofe. Here it is the link to the github project. Their solution, is used in production and is here to stay for a long time. They recently raised another 20 million in VC this year.

This sofe framework is what they call a Meta-framework. It is basically a main router that decides where to dispatch your routes. Then it dispatches to an angular, ember, react, angular2 app. And it gets even better, in the same page you can have pieces built in react, pieces in angular, etc. You get the idea. This allowed them to scale faster, get more talent as well as they are no longer limited to just one framework. And they can deploy anytime and their teams (squads) don't depend on each other as those pieces of the app are independent applications, like microservices in the front end.

It is still fairly new but definitively worth a look. I recently talked with them at a meet up and some other companies are using this as well in production. They also have an inspector tool an other tools that show you what framework that piece of the web app you select belongs to (e.g. react, angular, etc). Here it is the live demo of sofe in action.

Click on framework inspector there, then turn it on. It will show you.

There's trade offs on this approach, one is that this is not supported yet for mobile. It works great for their product but they are working on solutions for that as well.

Disclaimer: I do not work at Canopy Tax, I have never worked there and I do not have any relation with the company. I just like Sofe and what they are doing with the project.


问:
Nginx + PHP-FPM 502 Bad Gateway
I am getting a 502 Bad Gateway from Nginx on a line of PHP code that is working fine in other places of my program ($this->provider = new OAuthProvider();), and that have worked fine before. This is the message I get in the Nginx error log for each 502:

recv() failed (104: Connection reset by peer) while reading response header from upstream

In the PHP-FPM log there is a warning for each 502:

[WARNING] [pool www] child 17427 exited on signal 11 SIGSEGV after 142070.657176 seconds from start

After trying a number of changes to the nginx.conf I am stuck and would very much appreciate any pointers of what to do next.

I'm running Nginx 0.7.67 and PHP 5.3.2 on Ubuntu 10.04.

答: ZendOptimizer + APC + php-fpm 5.2.14 gives constantly reproducible SIGSEGV even on phpinfo();.</p>

Title: Nginx + PHP-FPM 502 Bad Gateway


问:
Accessing CollectionViewCell
I have added a button on the collectionviewcell, and once user clicks on that button, it calls the following method, but uviCollectionViewCell is returning nil.

```<code>- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(collectionView == productCollectionView)
    {
        __weak ProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

        cell.addBtnOutlet.tag = indexPath.row;
        [cell.addBtnOutlet addTarget:self
                        action:@selector(collectionViewCellAddButtonPressed:)
              forControlEvents:UIControlEventTouchUpInside];
    }
  return cell;
}

- (IBAction)collectionViewCellAddButtonPressed:(UIButton *)button{
     NSLog(@"Add Button Clicked" );
     // the following is nil
     UICollectionViewCell *uviCollectionCell =  [self.productCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathWithIndex:0]];
 }
</code>```

答:
All you need is,

If you need a cell with index path being equal to button tag then as Karthik said,

```<code>UICollectionViewCell *uviCollectionCell = [self.collectionView.dataSource collectionView:self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:button.tag inSection:0]];
</code>```

if you need always a cell at index path 0,0 then use

```<code>UICollectionViewCell *uviCollectionCell = [self.collectionView.dataSource collectionView:self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
</code>```

Hope it helps.

Title: Accessing CollectionViewCell

Body:
I have added a button on the collectionviewcell, and once user clicks on that button, it calls the following method, but uviCollectionViewCell is returning nil.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(collectionView == productCollectionView)
    {
        __weak ProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

        cell.addBtnOutlet.tag = indexPath.row;
        [cell.addBtnOutlet addTarget:self
                        action:@selector(collectionViewCellAddButtonPressed:)
              forControlEvents:UIControlEventTouchUpInside];
    }
  return cell;
}

- (IBAction)collectionViewCellAddButtonPressed:(UIButton *)button{
     NSLog(@"Add Button Clicked" );
     // the following is nil
     UICollectionViewCell *uviCollectionCell =  [self.productCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathWithIndex:0]];
 }

Body:
All you need is,

If you need a cell with index path being equal to button tag then as Karthik said,

UICollectionViewCell *uviCollectionCell = [self.collectionView.dataSource collectionView:self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:button.tag inSection:0]];

if you need always a cell at index path 0,0 then use

UICollectionViewCell *uviCollectionCell = [self.collectionView.dataSource collectionView:self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];

Hope it helps.


问:
htaccess file issue for multiple application in codeigniter
I am running 3 application in one codeigniter. When i run 1st app i type //localhost/foldername it runs well, when i run 2nd app it takes  localhost/foldername/admin.php and when i run 3rd app it takes localhost/foldername/project.php i want to remove .php
i have tried with this.

```<code>RewriteEngine On
RewriteCond %{REQUEST_URI} ^/system.*
RewriteRule ^(.*)$ index.php?/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?/$1 [L]

 My Application Structure is like :
    -abc
    --application-htaccess
    --application2-htaccess
    --application3-htaccess
    --assets
    --systems
    --uploads
    --htaccess
    --index.php
    --application2.php
    --application3.php
</code>```

URL:localhost/abc/application1/------------error----Directory access is forbidden

答:
Add this .htaccess in all apps. It's work for me

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
</code>```

Body:
I am running 3 application in one codeigniter. When i run 1st app i type //localhost/foldername it runs well, when i run 2nd app it takes  localhost/foldername/admin.php and when i run 3rd app it takes localhost/foldername/project.php i want to remove .php
i have tried with this.

RewriteEngine On
RewriteCond %{REQUEST_URI} ^/system.*
RewriteRule ^(.*)$ index.php?/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?/$1 [L]

 My Application Structure is like :
    -abc
    --application-htaccess
    --application2-htaccess
    --application3-htaccess
    --assets
    --systems
    --uploads
    --htaccess
    --index.php
    --application2.php
    --application3.php

URL:localhost/abc/application1/------------error----Directory access is forbidden

Body:
Add this .htaccess in all apps. It's work for me

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>


问:
Image annotation: Is it better to create one file per image or one big file for the whole dataset?
I'm developing an application that extracts some information for every image in a dataset of images, and store these data for future use. The problem I have is how to properly store these data. Is it better to create a single annotation file (I use JSON files) for each image in the dataset or to create a big unique file that contains all the extracted data?

The kind of information I'm extracting is similar from image to image but not equal. The dataset of images can be huge, >1milion images.

If relevant, I'm using Python on Linux or MacOS.

答:
I would use a single document (file or in a NoSQL database) per dataset.

If you have > 1 million images, single file per image will mean  > 1 million files/documents.

Not something that will be easy to manage or manipulate.

A single file/document is much easier to manage and search.

I'd also consider using a NoSQL database to store the JSON documents.

EDIT:

After considering the comments, I'd have to say that you might need to cut off a JSON file at a certain amount of data, resulting in a few files per dataset.

As for files getting corrupted that's a risk you run on any storage, even database files, that's why we have backups and replicas.

You can always run a NoSQL database locally, but again, this will need some computing resources.


问:
Get the daily maximum gives strange results
I have a data set of temperature recorded every 15 minutes. The file looks like that (~50000 rows)

```<code>02/01/2016;05:15:00;10.800
02/01/2016;05:30:00;10.300
02/01/2016;05:45:00;9.200
02/01/2016;06:00:00;9.200
02/01/2016;06:15:00;8.900
02/01/2016;06:30:00;8.900
02/01/2016;06:45:00;9.400
02/01/2016;07:00:00;9.000
02/01/2016;07:15:00;9.200
02/01/2016;07:30:00;11.100
02/01/2016;07:45:00;13.000
02/01/2016;08:00:00;14.400
02/01/2016;08:15:00;15.600
</code>```

My goal is to calculate daily min/max, so here my code to do it

```<code># load dataframe
with open(intraday_file_path, "r") as fl:
    df_intraday = pd.read_csv(fl,
                              **load_args
                              )

df_daily = df_intraday.groupby(df_intraday[0])
df_daily = df_daily.aggregate({0:np.max})

df_daily.index.names = [0]
df_daily.reset_index(level=[0], inplace=True)

df_daily.sort_values(by=[0], inplace=True)
df_daily.drop_duplicates(subset=0,
                         keep="first",
                         inplace=True)

daily_name = "daily_%s" %(intraday_file_name,)
daily_path = os.getcwd() + "\\" + daily_name

df_daily = df_daily[0, 1]

with open(daily_path, "w") as fl:
    df_daily.to_csv(fl,
                    **save_args
                    )
</code>```

But the output is strange as soon as I have a temperature below 10°C. For example for 02/01/2016 the code output is 9.4°C?!

Any ideas?

Body:
I have a data set of temperature recorded every 15 minutes. The file looks like that (~50000 rows)

02/01/2016;05:15:00;10.800
02/01/2016;05:30:00;10.300
02/01/2016;05:45:00;9.200
02/01/2016;06:00:00;9.200
02/01/2016;06:15:00;8.900
02/01/2016;06:30:00;8.900
02/01/2016;06:45:00;9.400
02/01/2016;07:00:00;9.000
02/01/2016;07:15:00;9.200
02/01/2016;07:30:00;11.100
02/01/2016;07:45:00;13.000
02/01/2016;08:00:00;14.400
02/01/2016;08:15:00;15.600

My goal is to calculate daily min/max, so here my code to do it

# load dataframe
with open(intraday_file_path, "r") as fl:
    df_intraday = pd.read_csv(fl,
                              **load_args
                              )

df_daily = df_intraday.groupby(df_intraday[0])
df_daily = df_daily.aggregate({0:np.max})

df_daily.index.names = [0]
df_daily.reset_index(level=[0], inplace=True)

df_daily.sort_values(by=[0], inplace=True)
df_daily.drop_duplicates(subset=0,
                         keep="first",
                         inplace=True)

daily_name = "daily_%s" %(intraday_file_name,)
daily_path = os.getcwd() + "\\" + daily_name

df_daily = df_daily[0, 1]

with open(daily_path, "w") as fl:
    df_daily.to_csv(fl,
                    **save_args
                    )

But the output is strange as soon as I have a temperature below 10°C. For example for 02/01/2016 the code output is 9.4°C?!

Any ideas?

Body:
There is problem your data are not numeric in last column.

Solution is use to_numeric for convert bad data to NaNs:

Also for better working with DataFrame is possible add parameter names to read_csv for column names.

import pandas as pd
from pandas.compat import StringIO
temp=u"""02/01/2016;05:15:00;10.800
02/01/2016;05:30:00;10.300
02/01/2016;05:45:00;9.200
02/01/2016;06:00:00;9.200
02/01/2016;06:15:00;8.900
02/01/2016;06:30:00;8.900
02/01/2016;06:45:00;9.400
03/01/2016;07:00:00;9.000
03/01/2016;07:15:00;9.200
03/01/2016;07:30:00;11.100
04/01/2016;07:45:00;13.000
04/01/2016;08:00:00;14.400
04/01/2016;08:15:00;a"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df_intraday = pd.read_csv(StringIO(temp),
                          sep=";",
                          names=['date','time','val'],
                          parse_dates=[0])
print (df_intraday)
         date      time     val
0  2016-02-01  05:15:00  10.800
1  2016-02-01  05:30:00  10.300
2  2016-02-01  05:45:00   9.200
3  2016-02-01  06:00:00   9.200
4  2016-02-01  06:15:00   8.900
5  2016-02-01  06:30:00   8.900
6  2016-02-01  06:45:00   9.400
7  2016-03-01  07:00:00   9.000
8  2016-03-01  07:15:00   9.200
9  2016-03-01  07:30:00  11.100
10 2016-04-01  07:45:00  13.000
11 2016-04-01  08:00:00  14.400
12 2016-04-01  08:15:00       a

df_daily = df_intraday.groupby('date', as_index=False)['val'].max()
print (df_daily)
        date    val
0 2016-02-01  9.400
1 2016-03-01  9.200
2 2016-04-01      a

#check dtypes -  object is obviusly string
print (df_intraday['val'].dtypes)
object

df_intraday['val'] = pd.to_numeric(df_intraday['val'], errors='coerce')
print (df_intraday)
         date      time   val
0  2016-02-01  05:15:00  10.8
1  2016-02-01  05:30:00  10.3
2  2016-02-01  05:45:00   9.2
3  2016-02-01  06:00:00   9.2
4  2016-02-01  06:15:00   8.9
5  2016-02-01  06:30:00   8.9
6  2016-02-01  06:45:00   9.4
7  2016-03-01  07:00:00   9.0
8  2016-03-01  07:15:00   9.2
9  2016-03-01  07:30:00  11.1
10 2016-04-01  07:45:00  13.0
11 2016-04-01  08:00:00  14.4
12 2016-04-01  08:15:00   NaN

print (df_intraday['val'].dtypes)
float64

#simplier way for aggregating max
df_daily = df_intraday.groupby('date', as_index=False)['val'].max()
print (df_daily)
        date   val
0 2016-02-01  10.8
1 2016-03-01  11.1
2 2016-04-01  14.4


问:
throughput control via Sleep
I have this code, the point is that I want to receive no more than 600Kbits/s using a UDP socket, I implemented an algorithm using duration during which we receive and the sleep command....

```<code>#if defined (WIN32)
#include <winsock2.h>

typedef int socklen_t;
#elif defined (linux)
#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <unistd.h>

#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define closesocket(s) close(s)
typedef int SOCKET;
typedef struct sockaddr_in SOCKADDR_IN;
typedef struct sockaddr SOCKADDR;
#endif

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

 #define RCVBUFSIZE 4
#define PORT 4444
 #define ECHOMAX 255

int main(void)
 {
#if defined (WIN32)
    WSADATA WSAData;
    int erreur = WSAStartup(MAKEWORD(2,2), &WSAData);
#else
    int erreur = 0;
#endif

int recvMsgSize;
char echoBuffer[RCVBUFSIZE];
//unsigned int echoStringLen;
//int bytesRcvd, totalBytesRcvd; //bytes received in a single recv()

SOCKET sock;
SOCKADDR_IN sin;
SOCKADDR_IN SenderAddr;
int SenderAddrSize = sizeof(SenderAddr);

if(!erreur)
{

    sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    sin.sin_addr.s_addr = inet_addr("127.0.0.1");
    sin.sin_family = AF_INET;
    sin.sin_port = htons(4444);
   memset(&sin.sin_zero, '\0', sizeof(sin.sin_zero));

     bind(sock, (SOCKADDR*)&sin, sizeof(sin));

//totalBytesRcvd = 0;

printf("Received: ");

int speed_limit= 614400; //600Kbits/s
int one_second=1000;
int elapsed; //elapsed time
int transmit=0; // how much i receive during 'elapsed'
int expected_receive; //what I'm excpected to receive
int transmit_delta; //diference
int time_sleep; //how much to sleep
clock_t start_time= clock();

 for(;;)
{

    if((recvMsgSize=recvfrom(sock, echoBuffer,1024, 0, (SOCKADDR *)&SenderAddr, &SenderAddrSize)) > 0)
    {
            transmit+=recvMsgSize;
            clock_t tempo= clock();

            elapsed=(tempo-start_time)/CLOCKS_PER_SEC;
        // Check moment speed every five second, you can choose any value
            if(elapsed>5)
            {
                start_time= tempo;
                expected_receive=speed_limit*elapsed/8;
                transmit_delta=expected_receive-transmit;

                if(transmit_delta>0)
                {
                    time_sleep=8*transmit_delta*one_second/speed_limit;
                    Sleep(time_sleep);
                }
                transmit=0;
            }
            echoBuffer[recvMsgSize]='\0';
            printf(echoBuffer);

    }

}
    printf("\n");
    getchar() ;

closesocket(sock);

    #if defined (WIN32)
        WSACleanup();
    #endif
}

return EXIT_SUCCESS;
}
</code>```

the problem is that it receive the message but it blocks the receiving process from time to time...which I guess will cause loss of data especially when I'm using UDP...

any alternative solution is welcolme...

thanks in advance..

答:
If the data is arriving over UDP, there is no way to reduce the throughput at the receiving end.  You'd have to tell the sending computer to send less data.  The receiver's only choice is the receive the UDP packets, or let them get dropped, and do something with them, or not.

If you use TCP, then the TCP protocol includes a built-in way to do what you want (called "source quench") ... the TCP protocol layer of the receiver will send a message to the sender telling the sender to slow down if the receiver is having problems keeping up.  (and you can influence whether "the receiver is having problems keeping up" by reading the data slower than usual, if you want).

Title: throughput control via Sleep

Body:
I have this code, the point is that I want to receive no more than 600Kbits/s using a UDP socket, I implemented an algorithm using duration during which we receive and the sleep command....

#if defined (WIN32)
#include <winsock2.h>

typedef int socklen_t;
#elif defined (linux)
#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <unistd.h>

#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define closesocket(s) close(s)
typedef int SOCKET;
typedef struct sockaddr_in SOCKADDR_IN;
typedef struct sockaddr SOCKADDR;
#endif

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

 #define RCVBUFSIZE 4
#define PORT 4444
 #define ECHOMAX 255

int main(void)
 {
#if defined (WIN32)
    WSADATA WSAData;
    int erreur = WSAStartup(MAKEWORD(2,2), &WSAData);
#else
    int erreur = 0;
#endif

int recvMsgSize;
char echoBuffer[RCVBUFSIZE];
//unsigned int echoStringLen;
//int bytesRcvd, totalBytesRcvd; //bytes received in a single recv()

SOCKET sock;
SOCKADDR_IN sin;
SOCKADDR_IN SenderAddr;
int SenderAddrSize = sizeof(SenderAddr);

if(!erreur)
{

    sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    sin.sin_addr.s_addr = inet_addr("127.0.0.1");
    sin.sin_family = AF_INET;
    sin.sin_port = htons(4444);
   memset(&sin.sin_zero, '\0', sizeof(sin.sin_zero));

     bind(sock, (SOCKADDR*)&sin, sizeof(sin));

//totalBytesRcvd = 0;

printf("Received: ");

int speed_limit= 614400; //600Kbits/s
int one_second=1000;
int elapsed; //elapsed time
int transmit=0; // how much i receive during 'elapsed'
int expected_receive; //what I'm excpected to receive
int transmit_delta; //diference
int time_sleep; //how much to sleep
clock_t start_time= clock();

 for(;;)
{

    if((recvMsgSize=recvfrom(sock, echoBuffer,1024, 0, (SOCKADDR *)&SenderAddr, &SenderAddrSize)) > 0)
    {
            transmit+=recvMsgSize;
            clock_t tempo= clock();

            elapsed=(tempo-start_time)/CLOCKS_PER_SEC;
        // Check moment speed every five second, you can choose any value
            if(elapsed>5)
            {
                start_time= tempo;
                expected_receive=speed_limit*elapsed/8;
                transmit_delta=expected_receive-transmit;

                if(transmit_delta>0)
                {
                    time_sleep=8*transmit_delta*one_second/speed_limit;
                    Sleep(time_sleep);
                }
                transmit=0;
            }
            echoBuffer[recvMsgSize]='\0';
            printf(echoBuffer);

    }

}
    printf("\n");
    getchar() ;

closesocket(sock);

    #if defined (WIN32)
        WSACleanup();
    #endif
}

return EXIT_SUCCESS;
}

the problem is that it receive the message but it blocks the receiving process from time to time...which I guess will cause loss of data especially when I'm using UDP...

any alternative solution is welcolme...

thanks in advance..


问:
Stored procedure to update different columns
I have an API that i'm trying to read that gives me just the updated field. I'm trying to take that and update my tables using a stored procedure. So far the only way I have been able to figure out how to do this is with dynamic SQL but i would prefer to not do that if there is a way not to.

If it was just a couple columns, I'd just write a proc for each but we are talking about 100 fields and any of them could be updated together. One ticket might just need a timestamp updated at this time, but the next ticket might be a timestamp and who modified it while the next one might just be a note.

Everything I've read and have been taught have told me that dynamic SQL is bad and while I'll write it if I have too, I'd prefer to have a proc.

答:
YOU CAN PERHAPS DO SOMETHING LIKE THIS:::</p>

```<code>IF EXISTS (SELECT * FROM NEWTABLE NOT IN (SELECT * FROM OLDTABLE))
BEGIN
UPDATE OLDTABLE
   SET OLDTABLE.OLDRECORDS = NEWTABLE.NEWRECORDS
   WHERE OLDTABLE.PRIMARYKEY= NEWTABLE.PRIMARYKEY
END
</code>```

Body:
YOU CAN PERHAPS DO SOMETHING LIKE THIS:::

IF EXISTS (SELECT * FROM NEWTABLE NOT IN (SELECT * FROM OLDTABLE))
BEGIN
UPDATE OLDTABLE
   SET OLDTABLE.OLDRECORDS = NEWTABLE.NEWRECORDS
   WHERE OLDTABLE.PRIMARYKEY= NEWTABLE.PRIMARYKEY
END


问:
Database does not accept decimal values in live
I am using the following bit of code to insert some data into a database:

```<code>internal int InsertSample(Sample sample)
{
    using (var db = new OleDbConnection(connectionString))
    {
        var query = Constants.InsertNewSample;
        return db.Execute(query, sample);
    }
}
</code>```

And it works fine when I run it locally through Visual Studio.

However, when I publish the site and try inserting, I get an error:

Data type mismatch in criteria expression.

Stack trace

```<code>[OleDbException (0x80040e07): Data type mismatch in criteria expression.]
   System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) +1138392
   System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) +247
   System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) +208
   System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) +58
   System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) +162
   System.Data.OleDb.OleDbCommand.ExecuteNonQuery() +107
   Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn, CommandDefinition& command, Action`2 paramReader) +93
   Dapper.SqlMapper.ExecuteImpl(IDbConnection cnn, CommandDefinition& command) +758
   MVCQCPage.Helpers.Access.InsertSample(Sample sample) +208
</code>```

But this only happens if the value of Sample.MassOff is in decimal format (e.g. 1.6).

If this value is passed as an integer (e.g. 5), it works without any issue when debugging and after publishing.

How is this possible????

The data type in the database is numeric, and the data type of Sample.MassOff is string.

Let me know if I can provide any more details.

答:
Culture of the system must be an issue here. Make sure Culture of your development system and deployment system is same.

If you cannot control/change Culture of deployment system, you can set Culture of your application as below:

Web Application (Your case)

Set globalization attribute in web.config

```<code><configuration>
    <system.web>
        <globalization culture="en-US" uiCulture="en-US" />/*Whatever your default culture you want to use irrespective of system*/
    </system.web>
</configuration>
</code>```

Windows Application (May be helpful for others)

If you are using DotNet Framework 4.5, following will do:

```<code>CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture("en-US");//Whatever your default culture you want to use irrespective of system
Thread.CurrentThread.CurrentCulture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = cultureInfo;
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
</code>```

If you are using DotNet Framework 4 or earlier, following is the trick:

```<code>CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture("en-US");//Whatever your default culture you want to use irrespective of system
Thread.CurrentThread.CurrentCulture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = cultureInfo;

Type type = typeof(CultureInfo);
type.InvokeMember("s_userDefaultCulture",
                    BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static,
                    null,
                    cultureInfo,
                    new object[] { cultureInfo });

type.InvokeMember("s_userDefaultUICulture",
                    BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static,
                    null,
                    cultureInfo,
                    new object[] { cultureInfo });
</code>```

Call above code at the start of your application.

Body:
I am using the following bit of code to insert some data into a database:

internal int InsertSample(Sample sample)
{
    using (var db = new OleDbConnection(connectionString))
    {
        var query = Constants.InsertNewSample;
        return db.Execute(query, sample);
    }
}

And it works fine when I run it locally through Visual Studio.

However, when I publish the site and try inserting, I get an error:

Data type mismatch in criteria expression.

Stack trace

[OleDbException (0x80040e07): Data type mismatch in criteria expression.]
   System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) +1138392
   System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) +247
   System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) +208
   System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) +58
   System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) +162
   System.Data.OleDb.OleDbCommand.ExecuteNonQuery() +107
   Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn, CommandDefinition& command, Action`2 paramReader) +93
   Dapper.SqlMapper.ExecuteImpl(IDbConnection cnn, CommandDefinition& command) +758
   MVCQCPage.Helpers.Access.InsertSample(Sample sample) +208

But this only happens if the value of Sample.MassOff is in decimal format (e.g. 1.6).

If this value is passed as an integer (e.g. 5), it works without any issue when debugging and after publishing.

How is this possible????

The data type in the database is numeric, and the data type of Sample.MassOff is string.

Let me know if I can provide any more details.

Body:
Culture of the system must be an issue here. Make sure Culture of your development system and deployment system is same.

If you cannot control/change Culture of deployment system, you can set Culture of your application as below:

Web Application (Your case)

Set globalization attribute in web.config

<configuration>
    <system.web>
        <globalization culture="en-US" uiCulture="en-US" />/*Whatever your default culture you want to use irrespective of system*/
    </system.web>
</configuration>

Windows Application (May be helpful for others)

If you are using DotNet Framework 4.5, following will do:

CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture("en-US");//Whatever your default culture you want to use irrespective of system
Thread.CurrentThread.CurrentCulture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = cultureInfo;
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

If you are using DotNet Framework 4 or earlier, following is the trick:

CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture("en-US");//Whatever your default culture you want to use irrespective of system
Thread.CurrentThread.CurrentCulture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = cultureInfo;

Type type = typeof(CultureInfo);
type.InvokeMember("s_userDefaultCulture",
                    BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static,
                    null,
                    cultureInfo,
                    new object[] { cultureInfo });

type.InvokeMember("s_userDefaultUICulture",
                    BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static,
                    null,
                    cultureInfo,
                    new object[] { cultureInfo });

Call above code at the start of your application.


问:
How to create a code that tells two integers are co-prime?
Write a method that, when passed two positive integers m and n, returns true if m and n are co-prime. Two integers are co-prime when they don't have any positive integer common divisor expect 1.

You can assume that m≤n.

```<code>public static boolean coPrime( int m, int n) {
      if ( m%n == 0){
           return true;
      }
      return false;
</code>```

}

Here is what I have so far.
How do you realise that they are co-prime?

答:
You know two numbers are co prime if their GCD is 1.

Euclid's algorithm is pretty simple and straight forward for finding the GCD between two integers:

```<code>private int gcd(int p, int q) {
    if (q == 0) {
        return p;
    }
    return gcd(q, p % q);
}
</code>```

So all you need to do is call this method with your two integers, something like the following:

```<code>private boolean coprime(int p, int q) {
    return (gcd(p, q) == 1);
}
</code>```

Body:
Write a method that, when passed two positive integers m and n, returns true if m and n are co-prime. Two integers are co-prime when they don't have any positive integer common divisor expect 1.

You can assume that m≤n.

public static boolean coPrime( int m, int n) {
      if ( m%n == 0){
           return true;
      }
      return false;

}

Here is what I have so far.
How do you realise that they are co-prime?

Body:
You know two numbers are co prime if their GCD is 1.

Euclid's algorithm is pretty simple and straight forward for finding the GCD between two integers:

private int gcd(int p, int q) {
    if (q == 0) {
        return p;
    }
    return gcd(q, p % q);
}

So all you need to do is call this method with your two integers, something like the following:

private boolean coprime(int p, int q) {
    return (gcd(p, q) == 1);
}


问:
VSTS/TFS Git Branching Strategy and Continuous Integration
Our company had been using a git branching strategy that kept a long-running sprint work branch around that looked something like this:

```<code>master
  \
   Sprint
     \
      Feature1
      Feature2
</code>```

With the current sprint, we switched to having a new branch with a new name for each sprint:

```<code>master
  \
   Sprint123
     \
      Feature1
      Feature2
</code>```

With this change some pain points arise:

Policy has to be set up each time a new Sprint### branch is created (which includes continuous integration and pull request settings).

Build definitions have triggers which still work fine via wildcard ("Sprint*"), but the repository source setting for the build doesn't support wildcards.

I've been through the VSTS documentation, but I feel like I've missed something on how to set this up to have a new branch per sprint (which is in line with VSTS branching strategy documentation).

So, the questions are:

Our expectation was that the branch that triggers the build is the one that is built. Is this possible?

What is the recommendation for setting branch policy each time a new branch is created off of master? Should we just expect that we will have to configure all of the settings manually every time?

答:
The recommended branching strategy is always use the same branch even for new sprints. As this article, you can always use development branch for different sprints.

Of cause, you can use your branching strategy if the codes are quite different between two sprints. But the disadvantages as:

Set branch policy each time when you create new branch.

As time goes on, there will has amount of branches sprint*, it’s not good to trace the whole project versions easily.

Finally, for your questions (if you still need your current strategy):

Yes, you can still use the format Sprint* in build definition Triggers Tab, then your new created branches Sprint### will also suitable for CI build. And get sources step for build definition won’t affect your CI build, the repo and branch select only for manually queue build.

You need to set branch policy manually for the new created branches every time.

Body:
Our company had been using a git branching strategy that kept a long-running sprint work branch around that looked something like this:

master
  \
   Sprint
     \
      Feature1
      Feature2

With the current sprint, we switched to having a new branch with a new name for each sprint:

master
  \
   Sprint123
     \
      Feature1
      Feature2

With this change some pain points arise:

Policy has to be set up each time a new Sprint### branch is created (which includes continuous integration and pull request settings).

Build definitions have triggers which still work fine via wildcard ("Sprint*"), but the repository source setting for the build doesn't support wildcards.

I've been through the VSTS documentation, but I feel like I've missed something on how to set this up to have a new branch per sprint (which is in line with VSTS branching strategy documentation).

So, the questions are:

Our expectation was that the branch that triggers the build is the one that is built. Is this possible?

What is the recommendation for setting branch policy each time a new branch is created off of master? Should we just expect that we will have to configure all of the settings manually every time?


问:
Reading Mails from Outlook Javamail
Am trying to read the emails from the outlook using javamail

herez the code snippet.

```<code>try {
      Properties props = new Properties();
      props.setProperty("mail.store.protocol", "imap");
      props.setProperty("mail.imaps.starttls.enable", "true");
      props.setProperty("mail.imaps.host", "outlook.office365.com");
      props.setProperty("mail.imaps.port", "143");
      Session mailSession = Session.getInstance(props);
      mailSession.setDebug(true);
      Store mailStore = mailSession.getStore("imaps");
      mailStore.connect("outlook.office365.com", "<username>", "<password>");
  } catch (Exception ex){
      ex.printStackTrace();
  }
</code>```

Exception

javax.mail.MessagingException: Unrecognized SSL message, plaintext connection?;
  nested exception is:
    javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:727)

Any pointers are appreciated.

答: Port 143 (what you're using) is for plain-text IMAP (hence the error message plaintext connection?). IMAPS uses port 993, so try that.

Title: Reading Mails from Outlook Javamail

Body:
Am trying to read the emails from the outlook using javamail

herez the code snippet.

try {
      Properties props = new Properties();
      props.setProperty("mail.store.protocol", "imap");
      props.setProperty("mail.imaps.starttls.enable", "true");
      props.setProperty("mail.imaps.host", "outlook.office365.com");
      props.setProperty("mail.imaps.port", "143");
      Session mailSession = Session.getInstance(props);
      mailSession.setDebug(true);
      Store mailStore = mailSession.getStore("imaps");
      mailStore.connect("outlook.office365.com", "<username>", "<password>");
  } catch (Exception ex){
      ex.printStackTrace();
  }

Exception

javax.mail.MessagingException: Unrecognized SSL message, plaintext connection?;
  nested exception is:
    javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:727)

Any pointers are appreciated.


问:
Which node from TreeView is selected (PySide)?
I have a program with QTreeView and I want to disable/enable some actions in Toolbar depending on which node is selected but I don't know how to get selected node. Can anyone help?</p>

答:
In the following example I show how to know which items are selected in a QTreeView, for this we use the selectionChanged signal that returns the selected and deselected items, then iterates and obtains the QModelIndex, and through this and the model we obtain the data.</p>

```<code>from PySide.QtGui import *
from PySide.QtCore import *

class Main(QTreeView):
    def __init__(self):
        QTreeView.__init__(self)
        model = QFileSystemModel()
        model.setRootPath(QDir.homePath())
        self.setModel(model)
        m = self.selectionModel()
        m.selectionChanged.connect(self.onSelectionChanged)

    def onSelectionChanged(self, selected, deselected):
        for index in selected.indexes():
            print(self.model().data(index))

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    w = Main()
    w.show()
    sys.exit(app.exec_())
</code>```

Body:
In the following example I show how to know which items are selected in a QTreeView, for this we use the selectionChanged signal that returns the selected and deselected items, then iterates and obtains the QModelIndex, and through this and the model we obtain the data.

from PySide.QtGui import *
from PySide.QtCore import *

class Main(QTreeView):
    def __init__(self):
        QTreeView.__init__(self)
        model = QFileSystemModel()
        model.setRootPath(QDir.homePath())
        self.setModel(model)
        m = self.selectionModel()
        m.selectionChanged.connect(self.onSelectionChanged)

    def onSelectionChanged(self, selected, deselected):
        for index in selected.indexes():
            print(self.model().data(index))

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    w = Main()
    w.show()
    sys.exit(app.exec_())


问:
c++ mysql inserting in db
this is my code i am trying to insert ma in sma inside my data base but error occur as:
too many arguments to function 'int mysql_query(MYSQL*,const char*)'
note declared in mysql.h
line in mysql.h :    int STDCALL mysql_query(MYSQL *mysql, const char *q);</p>

```<code>while(true)
    {
        mysql_query(conn, " select close, id from fivemin order by id DESC LIMIT 5 ");
    result = mysql_store_result(conn);
    num_fields = mysql_num_fields(result);
    float sum = 0;
    while((row=mysql_fetch_row(result)))
        {
                 sum += atof(row[0]);
                 last_id = atoi(row[1]);

        }
    float ma;
    ma=sum/5.0;
    if(previous_last_id != last_id)
        {
        cout << "Simple moving Average: " << ma << endl;
        previous_last_id = last_id;
        }

     mysql_query(conn,("insert into sma values('%f')"),ma);
    Sleep(1000);
}
</code>```

答:
mysql_query(conn,("insert into sma values('%f')"),ma) has three arguments.

You need to format your string prior to call mysql_query.

Example:

```<code>char str[80];
sprintf(str, "insert into sma values('%f')", ma);
mysql_query(conn, str);
</code>```

Title: c++ mysql inserting in db

Body:
this is my code i am trying to insert ma in sma inside my data base but error occur as:
too many arguments to function 'int mysql_query(MYSQL*,const char*)'
note declared in mysql.h
line in mysql.h :    int STDCALL mysql_query(MYSQL *mysql, const char *q);

while(true)
    {
        mysql_query(conn, " select close, id from fivemin order by id DESC LIMIT 5 ");
    result = mysql_store_result(conn);
    num_fields = mysql_num_fields(result);
    float sum = 0;
    while((row=mysql_fetch_row(result)))
        {
                 sum += atof(row[0]);
                 last_id = atoi(row[1]);

        }
    float ma;
    ma=sum/5.0;
    if(previous_last_id != last_id)
        {
        cout << "Simple moving Average: " << ma << endl;
        previous_last_id = last_id;
        }

     mysql_query(conn,("insert into sma values('%f')"),ma);
    Sleep(1000);
}

Body:
mysql_query(conn,("insert into sma values('%f')"),ma) has three arguments.

You need to format your string prior to call mysql_query.

Example:

char str[80];
sprintf(str, "insert into sma values('%f')", ma);
mysql_query(conn, str);


问:
Selection.ShapeRange isn't working with ActiveX CommandButton
```<code>Sub sampleButton_Click()
On Error GoTo ErrorHandler

With Selection.ShapeRange
    If .Type = msoGroup Then
        Call setStyleTest(.GroupItems(.GroupItems.Count))
    Else
        For Each shp In ActiveWindow.Selection.ShapeRange
            Call setStyleTest(shp)
        Next shp
    End If
End With
Exit Sub

ErrorHandler:
    MsgBox "Error", vbExclamation

End Sub
</code>```

I use ActiveX CommandButton and have a problem with a testing selection of ShapeRange. What should I change/fix?
Thanks in advance

答:
It is working just fine for me

The value of msoGroup is 6

Till the time the group is selected your code will work. Once you are out of design mode and the group is not selected, your code will not work.

And yes the above two command buttons are ActiveX and not Form Controls

My suggestion: Stick to Form controls.

Body:
Sub sampleButton_Click()
On Error GoTo ErrorHandler

With Selection.ShapeRange
    If .Type = msoGroup Then
        Call setStyleTest(.GroupItems(.GroupItems.Count))
    Else
        For Each shp In ActiveWindow.Selection.ShapeRange
            Call setStyleTest(shp)
        Next shp
    End If
End With
Exit Sub

ErrorHandler:
    MsgBox "Error", vbExclamation

End Sub

I use ActiveX CommandButton and have a problem with a testing selection of ShapeRange. What should I change/fix?
Thanks in advance