问:
Subset sum Problem
recently I became interested in the subset-sum problem which is finding a zero-sum subset in a superset. I found some solutions on SO, in addition, I came across a particular solution which uses the dynamic programming approach. I translated his solution in python based on his qualitative descriptions. I'm trying to optimize this for larger lists which eats up a lot of my memory. Can someone recommend optimizations or other techniques to solve this particular problem? Here's my attempt in python:</p>

```<code>import random
from time import time
from itertools import product

time0 = time()

# create a zero matrix of size a (row), b(col)
def create_zero_matrix(a,b):
    return [[0]*b for x in xrange(a)]

# generate a list of size num with random integers with an upper and lower bound
def random_ints(num, lower=-1000, upper=1000):
    return [random.randrange(lower,upper+1) for i in range(num)]

# split a list up into N and P where N be the sum of the negative values and P the sum of the positive values.
# 0 does not count because of additive identity
def split_sum(A):
    N_list = []
    P_list = []
    for x in A:
        if x < 0:
            N_list.append(x)
        elif x > 0:
            P_list.append(x)
    return [sum(N_list), sum(P_list)]

# since the column indexes are in the range from 0 to P - N
# we would like to retrieve them based on the index in the range N to P
# n := row, m := col
def get_element(table, n, m, N):
    if n < 0:
        return 0
    try:
        return table[n][m - N]
    except:
        return 0

# same definition as above
def set_element(table, n, m, N, value):
    table[n][m - N] = value

# input array
#A = [1, -3, 2, 4]
A = random_ints(200)

[N, P] = split_sum(A)

# create a zero matrix of size m (row) by n (col)
#
# m := the number of elements in A
# n := P - N + 1 (by definition N <= s <= P)
#
# each element in the matrix will be a value of either 0 (false) or 1 (true)
m = len(A)
n = P - N + 1;
table = create_zero_matrix(m, n)

# set first element in index (0, A[0]) to be true
# Definition: Q(1,s) := (x1 == s). Note that index starts at 0 instead of 1.
set_element(table, 0, A[0], N, 1)

# iterate through each table element
#for i in xrange(1, m): #row
#    for s in xrange(N, P + 1): #col
for i, s in product(xrange(1, m), xrange(N, P + 1)):
    if get_element(table, i - 1, s, N) or A[i] == s or get_element(table, i - 1, s - A[i], N):
        #set_element(table, i, s, N, 1)
        table[i][s - N] = 1

# find zero-sum subset solution
s = 0
solution = []
for i in reversed(xrange(0, m)):
    if get_element(table, i - 1, s, N) == 0 and get_element(table, i, s, N) == 1:
        s = s - A[i]
        solution.append(A[i])

print "Solution: ",solution

time1 = time()

print "Time execution: ", time1 - time0
</code>```

答:
I'm not quite sure if your solution is exact or a PTA (poly-time approximation).

But, as someone pointed out, this problem is indeed NP-Complete.

Meaning, every known (exact) algorithm has an exponential time behavior on the size of the input.

Meaning, if you can process 1 operation in .01 nanosecond then, for a list of 59 elements it'll take:

```<code>2^59 ops -->     2^59     seconds -->     2^26      years -->      1 year
            --------------           ---------------
            10.000.000.000           3600 x 24 x 365
</code>```

You can find heuristics, which give you just a CHANCE of finding an exact solution in polynomial time.

On the other side, if you restrict the problem (to another) using bounds for the values of the numbers in the set, then the problem complexity reduces to polynomial time.  But even then the memory space consumed will be a polynomial of VERY High Order.

The memory consumed will be much larger than the few gigabytes you have in memory.
And even much larger than the few tera-bytes on your hard drive.

( That's for small values of the bound for the value of the elements in the set )

May be this is the case of your Dynamic programing algorithm.

It seemed to me that you were using a bound of 1000 when building your initialization matrix.

You can try a smaller bound.  That is... if your input is consistently consist of small values.

Good Luck!

Title: Subset sum Problem

Body:
recently I became interested in the subset-sum problem which is finding a zero-sum subset in a superset. I found some solutions on SO, in addition, I came across a particular solution which uses the dynamic programming approach. I translated his solution in python based on his qualitative descriptions. I'm trying to optimize this for larger lists which eats up a lot of my memory. Can someone recommend optimizations or other techniques to solve this particular problem? Here's my attempt in python:

import random
from time import time
from itertools import product

time0 = time()

# create a zero matrix of size a (row), b(col)
def create_zero_matrix(a,b):
    return [[0]*b for x in xrange(a)]

# generate a list of size num with random integers with an upper and lower bound
def random_ints(num, lower=-1000, upper=1000):
    return [random.randrange(lower,upper+1) for i in range(num)]

# split a list up into N and P where N be the sum of the negative values and P the sum of the positive values.
# 0 does not count because of additive identity
def split_sum(A):
    N_list = []
    P_list = []
    for x in A:
        if x < 0:
            N_list.append(x)
        elif x > 0:
            P_list.append(x)
    return [sum(N_list), sum(P_list)]

# since the column indexes are in the range from 0 to P - N
# we would like to retrieve them based on the index in the range N to P
# n := row, m := col
def get_element(table, n, m, N):
    if n < 0:
        return 0
    try:
        return table[n][m - N]
    except:
        return 0

# same definition as above
def set_element(table, n, m, N, value):
    table[n][m - N] = value

# input array
#A = [1, -3, 2, 4]
A = random_ints(200)

[N, P] = split_sum(A)

# create a zero matrix of size m (row) by n (col)
#
# m := the number of elements in A
# n := P - N + 1 (by definition N <= s <= P)
#
# each element in the matrix will be a value of either 0 (false) or 1 (true)
m = len(A)
n = P - N + 1;
table = create_zero_matrix(m, n)

# set first element in index (0, A[0]) to be true
# Definition: Q(1,s) := (x1 == s). Note that index starts at 0 instead of 1.
set_element(table, 0, A[0], N, 1)

# iterate through each table element
#for i in xrange(1, m): #row
#    for s in xrange(N, P + 1): #col
for i, s in product(xrange(1, m), xrange(N, P + 1)):
    if get_element(table, i - 1, s, N) or A[i] == s or get_element(table, i - 1, s - A[i], N):
        #set_element(table, i, s, N, 1)
        table[i][s - N] = 1

# find zero-sum subset solution
s = 0
solution = []
for i in reversed(xrange(0, m)):
    if get_element(table, i - 1, s, N) == 0 and get_element(table, i, s, N) == 1:
        s = s - A[i]
        solution.append(A[i])

print "Solution: ",solution

time1 = time()

print "Time execution: ", time1 - time0

Body:
I'm not quite sure if your solution is exact or a PTA (poly-time approximation).

But, as someone pointed out, this problem is indeed NP-Complete.

Meaning, every known (exact) algorithm has an exponential time behavior on the size of the input.

Meaning, if you can process 1 operation in .01 nanosecond then, for a list of 59 elements it'll take:

2^59 ops -->     2^59     seconds -->     2^26      years -->      1 year
            --------------           ---------------
            10.000.000.000           3600 x 24 x 365

You can find heuristics, which give you just a CHANCE of finding an exact solution in polynomial time.

On the other side, if you restrict the problem (to another) using bounds for the values of the numbers in the set, then the problem complexity reduces to polynomial time.  But even then the memory space consumed will be a polynomial of VERY High Order.

The memory consumed will be much larger than the few gigabytes you have in memory.
And even much larger than the few tera-bytes on your hard drive.

( That's for small values of the bound for the value of the elements in the set )

May be this is the case of your Dynamic programing algorithm.

It seemed to me that you were using a bound of 1000 when building your initialization matrix.

You can try a smaller bound.  That is... if your input is consistently consist of small values.

Good Luck!


来源: stackexchange

问:
Connect to docker mysql with golang
Running docker mysql

docker run --name mysql -e MYSQL_ROOT_PASSWORD=root -d mysql:5.7

[mysql docker running container][1]

Go Code:

package main

```<code>import (
"database/sql"

_ "github.com/go-sql-driver/mysql"
)

func main() {

db, err := sql.Open("mysql", "root:root@tcp(172.17.0.2:3306)/test-db")
if err != nil {
    panic(err)
}
defer db.Close()
err = db.ping()
if err != nil {
   log.Print(err)
}
</code>```

ping is throwing up ETIMEDOUT . The IP is correct is container IP.

答:
It must expose a port for docker internal IP however IP can be changed on every restart. To map a port to the localhost you can use the flag -p 127.0.0.1:3306:3306

To specify IP for docker container you can create your own user-defined virtual network and bind IP on this network when starting your containers.

```<code>docker network create --subnet=192.168.101.0/24 test
docker run -d --name db1 --network test --ip=192.168.101.10 -e MYSQL_ROOT_PASSWORD=12345 mysql:5.7
mysql -h 192.168.101.10 -uroot -p12345
</code>```

Also, be sure MySQL is started. You can check the status with docker ps and logs with docker logs db1. Where db1 the name specified with the flag --name.

ContentLicense: CC BY-SA 4.0

Title: Connect to docker mysql with golang

Body:
Running docker mysql

docker run --name mysql -e MYSQL_ROOT_PASSWORD=root -d mysql:5.7

[mysql docker running container][1]

Go Code:

package main

import (
"database/sql"

_ "github.com/go-sql-driver/mysql"
)

func main() {

db, err := sql.Open("mysql", "root:root@tcp(172.17.0.2:3306)/test-db")
if err != nil {
    panic(err)
}
defer db.Close()
err = db.ping()
if err != nil {
   log.Print(err)
}

ping is throwing up ETIMEDOUT . The IP is correct is container IP.

Body:
It must expose a port for docker internal IP however IP can be changed on every restart. To map a port to the localhost you can use the flag -p 127.0.0.1:3306:3306

To specify IP for docker container you can create your own user-defined virtual network and bind IP on this network when starting your containers.

docker network create --subnet=192.168.101.0/24 test
docker run -d --name db1 --network test --ip=192.168.101.10 -e MYSQL_ROOT_PASSWORD=12345 mysql:5.7
mysql -h 192.168.101.10 -uroot -p12345

Also, be sure MySQL is started. You can check the status with docker ps and logs with docker logs db1. Where db1 the name specified with the flag --name.


问:
Public attribute appears as undefined when dynamically assigning click event to element in Angular
I have a problem adding events inside a canvas. I have a canvas with several images and I have the ID of all of them in my "diagram" variable. I would like to click on the element, I look for the ID in the diagram array, and display this description. In the code below my diagram appears as undefined and I don't understand why. Thank you very much in advance</p>

```<code>export class EngineComponent implements OnInit {

  public diagram = [
    {itemName: 'st', itemType: 'start', description: 'Beginning of the manufacturing process'},
    {
      itemName: 'op2',
      itemType: 'operation',
      description: 'Production process of the items'
    },
    {
      itemName: 'op3',
      itemType: 'operation',
      description: 'Error in the product packaging process'
    }
  ]

  click(item: any) {
    const itemName = item.target.parentElement.id;

    item = this.diagram.find(p => p.itemName === itemName);

    if (item) {
      this.showDescription = item.description;
    }
  }

  ngOnInit(): void {
    this.diagram.forEach(item => {
      document.getElementById(item.itemName)
        .addEventListener('click', this.click.bind(this.diagram));
    });
  }
}
</code>```

答:
From documentation:

The bind() method creates a new function that, when called, has its
  this keyword set to the provided value, with a given sequence of
  arguments preceding any provided when the new function is called.

So replacing your click() function with following should work as expected

```<code>public click(event: any) {
  const itemName = event.currentTarget.id;

  Object.keys(this).some((key) =>  {
    if (this[key].itemName === itemName) {
      this.showDescription = this[key].description;
    }
  });
}
</code>```

Working example: Stackblitz

Body:
I have a problem adding events inside a canvas. I have a canvas with several images and I have the ID of all of them in my "diagram" variable. I would like to click on the element, I look for the ID in the diagram array, and display this description. In the code below my diagram appears as undefined and I don't understand why. Thank you very much in advance

export class EngineComponent implements OnInit {

  public diagram = [
    {itemName: 'st', itemType: 'start', description: 'Beginning of the manufacturing process'},
    {
      itemName: 'op2',
      itemType: 'operation',
      description: 'Production process of the items'
    },
    {
      itemName: 'op3',
      itemType: 'operation',
      description: 'Error in the product packaging process'
    }
  ]

  click(item: any) {
    const itemName = item.target.parentElement.id;

    item = this.diagram.find(p => p.itemName === itemName);

    if (item) {
      this.showDescription = item.description;
    }
  }

  ngOnInit(): void {
    this.diagram.forEach(item => {
      document.getElementById(item.itemName)
        .addEventListener('click', this.click.bind(this.diagram));
    });
  }
}

Body:
From documentation:

The bind() method creates a new function that, when called, has its
  this keyword set to the provided value, with a given sequence of
  arguments preceding any provided when the new function is called.

So replacing your click() function with following should work as expected

public click(event: any) {
  const itemName = event.currentTarget.id;

  Object.keys(this).some((key) =>  {
    if (this[key].itemName === itemName) {
      this.showDescription = this[key].description;
    }
  });
}

Working example: Stackblitz


问:
Why are braces needed for preprocessor in order to have statement?
Having this code:

```<code>#define GREATER(a, b, res) ( \ /* no braces here */
    asm("cmp %1, %2\n\t" \
         "jge 0f\n\t" \
         "movl %1, %0\n\t" \
         "jmp 1f\n" \
         "0:\n\t" \
         "movl %2, %0\n" \
         "1:" \
         : "=r"(res) \
         : "r"(a), "r"(b)); )
</code>```

Error:
c.c:4:2: error: expected expression before ‘asm’
  asm("cmp %1, %2\n\t" \

But this one (only changed braces, everything else is left - the code is otherwise correct):

```<code>#define GREATER(a, b, res) ({ \ /* used braces here - correct */
    asm("cmp %1, %2\n\t" \
         "jge 0f\n\t" \
         "movl %1, %0\n\t" \
         "jmp 1f\n" \
         "0:\n\t" \
         "movl %2, %0\n" \
         "1:" \
         : "=r"(res) \
         : "r"(a), "r"(b)); })
</code>```

Will compile with no error.
But the only changed is added braces. So why are they needed? What does the preprocessor assume to be statement? (If only means being in braces.) I have seen other macro functions declared only in parenthesis (no curly braces), so why this one should have ones?

答:
If you compile the code fragment as posted, you will indeed get an error as the macro is defined as #define GREATER(a, b, res) ( \ /* no braces here */ and the remainder of the fragment is parsed as a separate line of source code because the \ is not the last character on the #define line.

You should be careful with the comment placement.

More generally, the asm statement is not an expression, it is a statement, hence it cannot occur between parentheses. If you wish to use the macro in an expression context, you must convert the statement to an statement-expression by surrounding it with ({ and }), a gcc extension, just like the asm statement.  For the result to be used in an expression context, you must specify the value:

```<code>/* used braces here - correct */
#define GREATER(a, b, res) ({ \
    asm("cmp %1, %2\n\t" \
         "jge 0f\n\t" \
         "movl %1, %0\n\t" \
         "jmp 1f\n" \
         "0:\n\t" \
         "movl %2, %0\n" \
         "1:" \
         : "=r"(res) \
         : "r"(a), "r"(b)); res; })
</code>```

Finally, the assembly code to compute the greater of a and b is inefficient. The compiler will likely generate better code from res = greater(a, b) with greater defined as static inline int greater(int a, int b) { return a > b ? a : b; }

Body:
Having this code:

#define GREATER(a, b, res) ( \ /* no braces here */
    asm("cmp %1, %2\n\t" \
         "jge 0f\n\t" \
         "movl %1, %0\n\t" \
         "jmp 1f\n" \
         "0:\n\t" \
         "movl %2, %0\n" \
         "1:" \
         : "=r"(res) \
         : "r"(a), "r"(b)); )

Error:
c.c:4:2: error: expected expression before ‘asm’
  asm("cmp %1, %2\n\t" \

But this one (only changed braces, everything else is left - the code is otherwise correct):

#define GREATER(a, b, res) ({ \ /* used braces here - correct */
    asm("cmp %1, %2\n\t" \
         "jge 0f\n\t" \
         "movl %1, %0\n\t" \
         "jmp 1f\n" \
         "0:\n\t" \
         "movl %2, %0\n" \
         "1:" \
         : "=r"(res) \
         : "r"(a), "r"(b)); })

Will compile with no error.
But the only changed is added braces. So why are they needed? What does the preprocessor assume to be statement? (If only means being in braces.) I have seen other macro functions declared only in parenthesis (no curly braces), so why this one should have ones?

Body:
If you compile the code fragment as posted, you will indeed get an error as the macro is defined as #define GREATER(a, b, res) ( \ /* no braces here */ and the remainder of the fragment is parsed as a separate line of source code because the \ is not the last character on the #define line.

You should be careful with the comment placement.

More generally, the asm statement is not an expression, it is a statement, hence it cannot occur between parentheses. If you wish to use the macro in an expression context, you must convert the statement to an statement-expression by surrounding it with ({ and }), a gcc extension, just like the asm statement.  For the result to be used in an expression context, you must specify the value:

/* used braces here - correct */
#define GREATER(a, b, res) ({ \
    asm("cmp %1, %2\n\t" \
         "jge 0f\n\t" \
         "movl %1, %0\n\t" \
         "jmp 1f\n" \
         "0:\n\t" \
         "movl %2, %0\n" \
         "1:" \
         : "=r"(res) \
         : "r"(a), "r"(b)); res; })

Finally, the assembly code to compute the greater of a and b is inefficient. The compiler will likely generate better code from res = greater(a, b) with greater defined as static inline int greater(int a, int b) { return a > b ? a : b; }


问:
php - problem with set_error_handler
I'm trying to setup a custom landing error page in the event there is php errros, I'm using:

```<code>function xhandler($number,$string,$file,$line,$context){
  include('/path/to/error_text_page.tpl');
  exit;
}
error_reporting(E_ALL ^ E_NOTICE);
set_error_handler('xhandler',E_ALL ^ E_NOTICE);
</code>```

This isn't working though, anyone know what I'm doing wrong?

答:
You need to know that not every error-type can be handled by set_error_handler, e.g. parse/fatal errors.

Try

```<code>trigger_error("Testing xhandler", E_USER_ERROR);
</code>```

for testing.

ContentLicense: CC BY-SA 3.0

Title: php - problem with set_error_handler

Body:
I'm trying to setup a custom landing error page in the event there is php errros, I'm using:

function xhandler($number,$string,$file,$line,$context){
  include('/path/to/error_text_page.tpl');
  exit;
}
error_reporting(E_ALL ^ E_NOTICE);
set_error_handler('xhandler',E_ALL ^ E_NOTICE);

This isn't working though, anyone know what I'm doing wrong?

Body:
You need to know that not every error-type can be handled by set_error_handler, e.g. parse/fatal errors.

Try

trigger_error("Testing xhandler", E_USER_ERROR);

for testing.


问:
How to replace duplicates from array
What is the way to remove duplicates from an array that generates random numbers? I've made random number generator that allows the user to type min/max values and how many numbers to generate. I also removed duplicates but if the user types 5 numbers to generate and there is 1 duplicate it will generate 4 numbers. How to add another number to replace the duplicate?

    Min:
    <input type="text" id="Min">

    Max:
    <input type="text" id="Max">

    Generate:
    <input type="text" id="size">
    numbers

    Sort numbers:
    <select id="Sort">
      <option value="Do not sort">Do not sort</option>
      <option value="Ascending">Ascending</option>
      <option value="Descending">Descending</option>
    </select>

    Allow Duplicates:
    <select id="Duplicates">
      <option value="No">No</option>
      <option value="Yes">Yes</option>
    </select>

    <button onclick="func()">Generate</button>

```

答:
As you know, a Set doesn't allow duplicate values:

let ary = [1,1,2,2,3,3,4,4,5,5];
let set = new Set(ary);
let newAry = Array.from(set);
console.log(newAry); // outputs: [1,2,3,4,5]```
</div>
</div>
</p>

<p>You can get a set to contain the desired amount of numbers by using its <code>size</code> property:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function randomNumberBetween(iLowest,iHighest)
{
 var iChoices = iHighest - iLowest + 1;
 return Math.floor(Math.random() * iChoices + iLowest);
}

let max = 10;
let min = 1

let amountOfNumbers = max - min;
let set = new Set();

while (set.size < amountOfNumbers)
{
 set.add(randomNumberBetween(min,max));
}
console.log(Array.from(set));</code>```

However, it is more efficient to randomize an already existing array, because it avoids all the random duplicates rejected by the set:

function randomNumberBetween(iLowest,iHighest)
{
 var iChoices = iHighest - iLowest + 1;
 return Math.floor(Math.random() * iChoices + iLowest);
}

function randomizeArray(ary)
{
 var intialLength = ary.length;
 var aryNew = new Array();
 var iCurrent;
 while (aryNew.length < intialLength)
 {
  iCurrent = randomNumberBetween(0, ary.length - 1);
  aryNew.push(ary[iCurrent]);
  ary.splice(iCurrent, 1);
 }
 return aryNew;
}

let ary = [1,1,2,2,3,3,4,4,5,5];
let set = new Set(ary);
ary = Array.from(set);
let randomAry = randomizeArray(ary)
console.log(randomAry);```

Title: How to replace duplicates from array

Body:
As you know, a Set doesn't allow duplicate values:

let ary = [1,1,2,2,3,3,4,4,5,5];
let set = new Set(ary);
let newAry = Array.from(set);
console.log(newAry); // outputs: [1,2,3,4,5]

You can get a set to contain the desired amount of numbers by using its size property:

function randomNumberBetween(iLowest,iHighest)
{
 var iChoices = iHighest - iLowest + 1;
 return Math.floor(Math.random() * iChoices + iLowest);
}

let max = 10;
let min = 1

let amountOfNumbers = max - min;
let set = new Set();

while (set.size < amountOfNumbers)
{
 set.add(randomNumberBetween(min,max));
}
console.log(Array.from(set));

However, it is more efficient to randomize an already existing array, because it avoids all the random duplicates rejected by the set:

function randomNumberBetween(iLowest,iHighest)
{
 var iChoices = iHighest - iLowest + 1;
 return Math.floor(Math.random() * iChoices + iLowest);
}

function randomizeArray(ary)
{
 var intialLength = ary.length;
 var aryNew = new Array();
 var iCurrent;
 while (aryNew.length < intialLength)
 {
  iCurrent = randomNumberBetween(0, ary.length - 1);
  aryNew.push(ary[iCurrent]);
  ary.splice(iCurrent, 1);
 }
 return aryNew;
}

let ary = [1,1,2,2,3,3,4,4,5,5];
let set = new Set(ary);
ary = Array.from(set);
let randomAry = randomizeArray(ary)
console.log(randomAry);


问:
deduplicate messages whil reading from kafka
Kafka log compaction is not working for me.
I used the following code to create the topic : </p>

```<code>bin/kafka-topics.sh --create --zookeeper z-3.gfxiq-dev-totalflex-rd.6b5t67.c4.kafka.eu-west-3.amazonaws.com:2181,z-1.gfxiq-dev-totalflex-rd.6b5t67.c4.kafka.eu-west-3.amazonaws.com:2181,z-2.gfxiq-dev-totalflex-rd.6b5t67.c4.kafka.eu-west-3.amazonaws.com:2181  --topic  finals  --replication-factor 1  --partitions 1   --config cleanup.policy=compact   --config min.cleanable.dirty.ratio=0.001  --config segment.ms=5000
</code>```

<p>It keeps reading the records having the same key. </p>

答:
Compaction is not a key value database; same keys are not immediately updated.

Kafka partitions are stored as segments, a head, compacted segment and an uncompacted tail. By default, segments sizes are 1G. Compaction only happens on "closed segments". Meaning, as you consume across both head, there are no duplicate keys, but you will see them as you read the tail segment.

If you really want to consume something with no duplicate keys, read the topic into a map or KV store

Body:
Kafka log compaction is not working for me.
I used the following code to create the topic :

bin/kafka-topics.sh --create --zookeeper z-3.gfxiq-dev-totalflex-rd.6b5t67.c4.kafka.eu-west-3.amazonaws.com:2181,z-1.gfxiq-dev-totalflex-rd.6b5t67.c4.kafka.eu-west-3.amazonaws.com:2181,z-2.gfxiq-dev-totalflex-rd.6b5t67.c4.kafka.eu-west-3.amazonaws.com:2181  --topic  finals  --replication-factor 1  --partitions 1   --config cleanup.policy=compact   --config min.cleanable.dirty.ratio=0.001  --config segment.ms=5000

It keeps reading the records having the same key.


问:
git central repository and Team
I have been playing around with GIT on my local computer.

As I have gain a bit of knowledge using GIT like add, commit, merge, branch, checkout, status.

I still have more to learn but im confuse one thing.. how does git handle team?

For example:

Developer A computer

Developer B computer

Developer C computer

Central repository (Server)

All Developers working on the same project.

From what I understood (correct me if im wrong).. A ,B and C developers push their branch (master?) to central repository via SSH remote.

But on the central repository, how do I get information or which files (or branch?) that has been pushed from the developers... What would it look like on the central repository?

On the central repository, how would handle merges developers work?

Thanks.

答:
A great description of how to organize your repository and how to handle team branches can be found at:

http://nvie.com/posts/a-successful-git-branching-model/

Title: git central repository and Team


问:
How to Check If a Value Already Exists in a Text Field in Javascript
I have a set of users. Each time the delete button is click it is added up to the input text field which I already implemented. If the users is already on the deleted_user field, how can I display the remaining unselected users.

Ex. If Jan and Mike are already on deleted_user field. Next is clicking the submit users button, only Sam will appear

```<code>        <td><button onclick="deleteVal('Jan');" > Delete </button></td>
        <td><input type="text" name="users[]" value="Jan"> </td>

        <td><button onclick="deleteVal('Mike');"> Delete </button></td>
        <td> <input type="text" name="users[]" value="Mike"> </td>

        <td><button onclick="deleteVal('Sam');"> Delete </button></td>
        <td> <input type="text" name="users[]" value="Sam"> </td>

Deleted Users: <input type="text" id="deleted_user">

<button type="button" id="submit_users"> Submit Users </button>
Final Users:<input type="text" id="final_users">
</code>```

This is my code.

```<code> function deleteVal(val) {
    var delete_id = val;
    var deleted_user = document.getElementById('deleted_user').value

    if(!deleted_user.includes(delete_id)) {
       var tempVal = document.getElementById('deleted_user').value += val + ',';
    }
  }
</code>```

答:
you can use this code for check inputs fields</p>

```<code>var inputs = document.getElementsByTagName("input");
    for(var i=0;i<inputs.length;i++){
        if(inputs[i]){
            alert("valid");
        }
        else{
            alert("not valid");
        }
    }
</code>```

Body:
I have a set of users. Each time the delete button is click it is added up to the input text field which I already implemented. If the users is already on the deleted_user field, how can I display the remaining unselected users.

Ex. If Jan and Mike are already on deleted_user field. Next is clicking the submit users button, only Sam will appear

        <button onclick="deleteVal('Jan');" > Delete </button>
        <input type="text" name="users[]" value="Jan">

        <button onclick="deleteVal('Mike');"> Delete </button>
         <input type="text" name="users[]" value="Mike">

        <button onclick="deleteVal('Sam');"> Delete </button>
         <input type="text" name="users[]" value="Sam">

Deleted Users: <input type="text" id="deleted_user">

<button type="button" id="submit_users"> Submit Users </button>
Final Users:<input type="text" id="final_users">

This is my code.

 function deleteVal(val) {
    var delete_id = val;
    var deleted_user = document.getElementById('deleted_user').value

    if(!deleted_user.includes(delete_id)) {
       var tempVal = document.getElementById('deleted_user').value += val + ',';
    }
  }

Body:
you can use this code for check inputs fields

var inputs = document.getElementsByTagName("input");
    for(var i=0;i<inputs.length;i++){
        if(inputs[i]){
            alert("valid");
        }
        else{
            alert("not valid");
        }
    }


问:
Ruby and "You must recompile Ruby with OpenSSL support or change the sources in your Gemfile"
Using rvm I upgraded my ruby to 1.9.3-p392, also added 2.0.0, anytime I try to use this version when I run my bundle command I get this error.

```<code>Could not load OpenSSL.
You must recompile Ruby with OpenSSL support or change the sources in your Gemfile from 'https' to 'http'. Instructions for compiling with OpenSSL using RVM are
available at rvm.io/packages/openssl.
</code>```

I have followed several different instructions on how to fix this. I have tried removing the version and installing it with the rvm options

```<code>--with-openssl-dir=$HOME/.rvm/usr
</code>```

I have installed OpenSSL with rvm, and macports. Both have not helped the problem. I even changed the file location of the ssl cert using this:

```<code>export SSL_CERT_FILE=/Users/DarkLord/.rvm/usr/ssl/cert.pem
</code>```

No matter what I do I continue to get the error.
Can someone please help me fix this?

答: I specified a more recent Ruby version in my Gemfile, then ran bundle install. All good now.</p>

Body:
Using rvm I upgraded my ruby to 1.9.3-p392, also added 2.0.0, anytime I try to use this version when I run my bundle command I get this error.

Could not load OpenSSL.
You must recompile Ruby with OpenSSL support or change the sources in your Gemfile from 'https' to 'http'. Instructions for compiling with OpenSSL using RVM are
available at rvm.io/packages/openssl.

I have followed several different instructions on how to fix this. I have tried removing the version and installing it with the rvm options

--with-openssl-dir=$HOME/.rvm/usr

I have installed OpenSSL with rvm, and macports. Both have not helped the problem. I even changed the file location of the ssl cert using this:

export SSL_CERT_FILE=/Users/DarkLord/.rvm/usr/ssl/cert.pem

No matter what I do I continue to get the error.
Can someone please help me fix this?


问:
Restlet and Jersey co-exist together?
I have seen few examples such as Using Spring and Jersey together. I am working on a scenario where I have a Jersey project which is packaged into a different WAR. I want to move that one into another WAR which is based on Restlet framework. The following updates I made:
1) Added the Jersey project to the POM as dependency.
2) Added the Configuration file JerseyApplication.java

```<code>public class JerseyApplication extends Application {

@Override
public Set<Class<?>> getClasses() {
    final JAXRSResourceConfig instance = JAXRSResourceConfig.getInstance();
    return SetUtils.newSet(instance.getClasses());
}

}
</code>```

Now there are two configuration file. One to load Jersey resources which is mentioned above and one which was present for the restlet.Folowing is the restlet config file:

```<code>public class Application extends org.restlet.Application {
@Override
public void handle(final Request request, final Response response) {
    super.handle(request, response);
}

public Application(final Context context) {
    super(context);
}

@Override
public Restlet createRoot() {
    final Context context = getContext();
    final Router root = new Router(context);
    // Add JaxRS resources
    final JaxRsRestlet jaxRS = new JaxRsRestlet(context, getMetadataService());
    jaxRS.addClass(XYZ.class);
    return root;
}
}
</code>```

3) Updated web.xml :

```<code>    <context-param>
    <param-name>org.restlet.application</param-name>
    <param-value><Application.java PATH></param-value>
</context-param>

<!-- Restlet adapter -->
<servlet>
    <servlet-name>ServerServlet</servlet-name>
    <servlet-class>com.noelios.restlet.ext.servlet.ServerServlet</servlet-class>
    <init-param>
        <param-name>org.restlet.attribute.application</param-name>
        <param-value><PACKAGE_PATH></param-value>
    </init-param>
</servlet>

<!-- Jersey adapter -->
<servlet>
    <servlet-name>myservlet</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value><CLASS PATH></param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
</code>```

I want to know that is it possible that Restlet and Jersey projects both can co-exist together in a WAR packaging? I know that we can configure multiple servlets. Thanks in advance for any leads and suggestions on this one.

答: I don't see any reason why Restlet and Jersey would not be able to co-exist, I have a Restlet-based backend which has standard servlet code which works just fine. It will all boil down to the web.xml configuration.

Title: Restlet and Jersey co-exist together?

Body:
I have seen few examples such as Using Spring and Jersey together. I am working on a scenario where I have a Jersey project which is packaged into a different WAR. I want to move that one into another WAR which is based on Restlet framework. The following updates I made:
1) Added the Jersey project to the POM as dependency.
2) Added the Configuration file JerseyApplication.java

public class JerseyApplication extends Application {

@Override
public Set<Class<?>> getClasses() {
    final JAXRSResourceConfig instance = JAXRSResourceConfig.getInstance();
    return SetUtils.newSet(instance.getClasses());
}

}

Now there are two configuration file. One to load Jersey resources which is mentioned above and one which was present for the restlet.Folowing is the restlet config file:

public class Application extends org.restlet.Application {
@Override
public void handle(final Request request, final Response response) {
    super.handle(request, response);
}

public Application(final Context context) {
    super(context);
}

@Override
public Restlet createRoot() {
    final Context context = getContext();
    final Router root = new Router(context);
    // Add JaxRS resources
    final JaxRsRestlet jaxRS = new JaxRsRestlet(context, getMetadataService());
    jaxRS.addClass(XYZ.class);
    return root;
}
}

3) Updated web.xml :

    <context-param>
    <param-name>org.restlet.application</param-name>
    <param-value><Application.java PATH></param-value>
</context-param>

<servlet>
    <servlet-name>ServerServlet</servlet-name>
    <servlet-class>com.noelios.restlet.ext.servlet.ServerServlet</servlet-class>
    <init-param>
        <param-name>org.restlet.attribute.application</param-name>
        <param-value><PACKAGE_PATH></param-value>
    </init-param>
</servlet>

<servlet>
    <servlet-name>myservlet</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value><CLASS PATH></param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

I want to know that is it possible that Restlet and Jersey projects both can co-exist together in a WAR packaging? I know that we can configure multiple servlets. Thanks in advance for any leads and suggestions on this one.


问:
curl POST not giving me result
I'm trying to do a curl POST request for json-rpc however it's not giving me any error when I use it and I'm unsure what I'm doing incorrectly. Been trying to figure out how to do it for an hour

The request I'm trying to perform:

```<code>http post https://rpc.nearprotocol.com jsonrpc=2.0
method=query params:='["account/near.test", ""]' id=dontcare
</code>```

I've tried:

```<code>curl -X POST https://rpc.nearprotocol.com -d
'{"jsonrpc":"2.0","id":"0","method":"query",
"account/near.test”:”snailbail45"}' -H 'Content-Type: application/json'```
```

<p>However it's just returning the next line.</p>

<p>This Works for me though:</p>

```curl -X POST https://rpc.nearprotocol.com -d
'{"jsonrpc":"2.0","id":"0","method":"status"}' -H 'Content-Type:
application/json'
```

What am I doing incorrectly in the first one?

答:
You have stylized quotation marks (” instead of ") between test and snailbail45:

```<code>"account/near.test”:”snailbail45"
</code>```

Title: curl POST not giving me result

Body:
I'm trying to do a curl POST request for json-rpc however it's not giving me any error when I use it and I'm unsure what I'm doing incorrectly. Been trying to figure out how to do it for an hour

The request I'm trying to perform:

http post https://rpc.nearprotocol.com jsonrpc=2.0
method=query params:='["account/near.test", ""]' id=dontcare

I've tried:

curl -X POST https://rpc.nearprotocol.com -d
'{"jsonrpc":"2.0","id":"0","method":"query",
"account/near.test”:”snailbail45"}' -H 'Content-Type: application/json'```

However it's just returning the next line.

This Works for me though:

curl -X POST https://rpc.nearprotocol.com -d
'{"jsonrpc":"2.0","id":"0","method":"status"}' -H 'Content-Type:
application/json'

What am I doing incorrectly in the first one?

Body:
You have stylized quotation marks (” instead of ") between test and snailbail45:

"account/near.test”:”snailbail45"


问:
Readline functionality on windows with python 2.7
I need to import the readline functionality in a program written in python. I am currently using version 2.7 and the 3rd party packages I have seen only work up to version 2.6. Does anyone know of a 3rd party readline package for Windows with Python 2.7?</p>

答:
I believe pyreadline was designed just for this.

easy_install pyreadline

or:

pip install pyreadline

http://pypi.python.org/pypi/pyreadline

Also, use the following for forward/reverse compatibility:

```<code>try:
  import readline
except ImportError:
  import pyreadline as readline
</code>```

Body:
I believe pyreadline was designed just for this.

easy_install pyreadline

or:

pip install pyreadline

http://pypi.python.org/pypi/pyreadline

Also, use the following for forward/reverse compatibility:

try:
  import readline
except ImportError:
  import pyreadline as readline


问:
use of atoi() function in c++
when I pass a string variable in the below code, g++ gives an error:

cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string}’ to ‘const char*’ for argument ‘1’ to ‘int atoi(const char*)’

My code is:

```<code>#include<iostream>
#include<stdlib.h>
using namespace std;

int main()
{
    string a = "10";
    int b = atoi(a);
    cout<<b<<"\n";
    return 0;
}
</code>```

But if I change the code to :

```<code>#include<iostream>
#include<stdlib.h>
using namespace std;

int main()
{
    char a[3] = "10";
    int b = atoi(a);
    cout<<b<<"\n";
    return 0;
}
</code>```

It works completely fine.

Please explain why string doesn't work. Is there any difference between string a and char a[]?

答:
There is a difference between them.
For each one there are different functions:

String

As said before, for string there is the stoi function:

```<code>string s("20");
cout << stoi(s) * 2; // output: 40
</code>```

char*

In the past, atoi used to handle char* conversion.

However, now atoi is replaced by strtol which gets 3 parameters:

char* of the characters to parse to long,

char** that returns pointer to after the parsed string,

int for the base the number should be parsed from (2, 10, 16, or whatever).

```<code>char c[]="20";
char* end;
cout << strtol(c, &end, 16); // output: 32
</code>```

There are whole bunch of functions like strtol like strtof, strtod, or strtoll which converts to float, double, long, and long long.

The main advantages of those new functions are mostly error-handling, and multi-base support.

The main disadvantage is that there isn't a function that converts to int, only to long (besides other types).

For more details, see https://stackoverflow.com/a/22866001/12893141

Title: use of atoi() function in c++

Body:
when I pass a string variable in the below code, g++ gives an error:

cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string}’ to ‘const char*’ for argument ‘1’ to ‘int atoi(const char*)’

My code is:

#include<iostream>
#include<stdlib.h>
using namespace std;

int main()
{
    string a = "10";
    int b = atoi(a);
    cout<<b<<"\n";
    return 0;
}

But if I change the code to :

#include<iostream>
#include<stdlib.h>
using namespace std;

int main()
{
    char a[3] = "10";
    int b = atoi(a);
    cout<<b<<"\n";
    return 0;
}

It works completely fine.

Please explain why string doesn't work. Is there any difference between string a and char a[]?

Body:
There is a difference between them.
For each one there are different functions:

String

As said before, for string there is the stoi function:

string s("20");
cout << stoi(s) * 2; // output: 40

char*

In the past, atoi used to handle char* conversion.

However, now atoi is replaced by strtol which gets 3 parameters:

char* of the characters to parse to long,

char** that returns pointer to after the parsed string,

int for the base the number should be parsed from (2, 10, 16, or whatever).

char c[]="20";
char* end;
cout << strtol(c, &end, 16); // output: 32

There are whole bunch of functions like strtol like strtof, strtod, or strtoll which converts to float, double, long, and long long.

The main advantages of those new functions are mostly error-handling, and multi-base support.

The main disadvantage is that there isn't a function that converts to int, only to long (besides other types).

For more details, see https://stackoverflow.com/a/22866001/12893141


问:
Is there a better way than using a generic WildCard as a method parameter?
I need my getNextId() method for three different maps:

```<code>private final Map<Integer, Track> tracks;
private final Map<Integer, Train> trains;

private final Map<Integer, Coach> coaches;
</code>```

So far, I had three different methods but that's obviously unnecessary. Is there a better way than using the generic wildcard ? if the method only needs to be working for the above maps?

```<code>public int getNextId(Map<Integer, ?> givenMap) {
            int id = 1;
        for (int key : givenMap.keySet()) {
            if (key > id) break;
            id = key + 1;
        }
        return id;
}
</code>```

The getNextId() method basically gets the smallest available ID >=1. If trainIDs 1, 2, 3, 4 exist and the user deletes train with ID 2, the next added train gets ID 2.

答:
Write an interface or class (let's call it MyBase) that is inhertited by call three Track, Train and Coach.

Then modify your method:

```<code>public int getNextId(Map<Integer, ? extends MyBase> givenMap) {
    ...
}
</code>```

Body:
I need my getNextId() method for three different maps:

private final Map<Integer, Track> tracks;
private final Map<Integer, Train> trains;

private final Map<Integer, Coach> coaches;

So far, I had three different methods but that's obviously unnecessary. Is there a better way than using the generic wildcard ? if the method only needs to be working for the above maps?

public int getNextId(Map<Integer, ?> givenMap) {
            int id = 1;
        for (int key : givenMap.keySet()) {
            if (key > id) break;
            id = key + 1;
        }
        return id;
}

The getNextId() method basically gets the smallest available ID >=1. If trainIDs 1, 2, 3, 4 exist and the user deletes train with ID 2, the next added train gets ID 2.

Body:
Write an interface or class (let's call it MyBase) that is inhertited by call three Track, Train and Coach.

Then modify your method:

public int getNextId(Map<Integer, ? extends MyBase> givenMap) {
    ...
}


问:
How to create a common frontend for multiple microservices in ASP.NET?
I've been reading up on microservices for a bit and started to develop some small services in ASP.NET web framework in the MVC pattern. What I'm struggling to figure out though is, how to create a shared UI for these services?

Currently every microservice has their own views and css, but I'd like a common frontend so I can use a single css for every service.

I'd be happy about any ideas on how to approach this problem, book recommendations to read up on it or maybe some example applications. Thank you.

答:
As far as I can see there is no consensus on the best way of doing this securely, but I have worked in an org that used this pattern:

https://learn.microsoft.com/en-us/dotnet/architecture/microservices/architect-microservice-container-applications/microservice-based-composite-ui-shape-layout


问:
how to design PlayerActivity layout in each inch device
I want to be my Player Activity in the way that main things show user(such as play button ,rewind,forward ,cover ,date) and other things show when user scroll activity in all device with each inch size.I do that in way that I get screen height of device in pixel and give to relative layout programmatically and other things put below of this relative layout.Is that true?</p>

答:
if you ask about how to support different screen size it is devices

you should not add any layout_width or layout_height fixed size

and use weights in linear layout

Use best practices in dimensions use “dp” and in text size use “sp”.

Use nested layouts for better control and to make your activity xml less complex

You can make two designs one for big screens and one for small ones.

it is for layout , I hope it will help you .


问:
Set default timeout on a per test basis
I'm looking for a way to set the default timeout on a per-test basis.

I'm writing some end to end tests in nightwatch.  One of the tests requires hitting an API a few times to set up the initial test conditions.  Its necessary to populate some user data in order to run the test.  This happens in the before() method.

The problem is, before() will timeout when it hits the default timeout interval.  I've read the documentation for setting the global default timeout, but I don't want to increase it everywhere. How can I do this on a per-test basis?

Async Before/After

https://nightwatchjs.org/guide/#asynchronous-before-each-and-after-each-

Setting Global asyncHookTimeout

https://github.com/nightwatchjs/nightwatch/blob/master/examples/globalsModule.js#L20

The test code is as follows:

```<code>const { TEST_USER } = require('../../definitions/users');
const { TEST_USER_DATA } = require('../../definitions/users/data');

module.exports = {
    async before(browser, done) {
        // the default interval is here, but changing it doesn't have any effect
        console.log(browser.options.globals.asyncHookTimeout); // 10000

        const usersPO = browser.page.users();

        // get the user from the API to test with
        const testUser = await usersPO.getUser(TEST_USER);

        // post test data to the user
        await usersPO.postUserData(testUser.id, TEST_USER_DATA); // this will exceed the timeout.

        // finished with async test setup
        done();
    },
    // Tests

};
</code>```

答:
One Way you can do that is setting browser.options.globals.asyncHookTimeout value in every test which will override the default value from the config file.

I hope this will help you.

Cheers!

Title: Set default timeout on a per test basis

Body:
I'm looking for a way to set the default timeout on a per-test basis.

I'm writing some end to end tests in nightwatch.  One of the tests requires hitting an API a few times to set up the initial test conditions.  Its necessary to populate some user data in order to run the test.  This happens in the before() method.

The problem is, before() will timeout when it hits the default timeout interval.  I've read the documentation for setting the global default timeout, but I don't want to increase it everywhere. How can I do this on a per-test basis?

Async Before/After

https://nightwatchjs.org/guide/#asynchronous-before-each-and-after-each-

Setting Global asyncHookTimeout

https://github.com/nightwatchjs/nightwatch/blob/master/examples/globalsModule.js#L20

The test code is as follows:

const { TEST_USER } = require('../../definitions/users');
const { TEST_USER_DATA } = require('../../definitions/users/data');

module.exports = {
    async before(browser, done) {
        // the default interval is here, but changing it doesn't have any effect
        console.log(browser.options.globals.asyncHookTimeout); // 10000

        const usersPO = browser.page.users();

        // get the user from the API to test with
        const testUser = await usersPO.getUser(TEST_USER);

        // post test data to the user
        await usersPO.postUserData(testUser.id, TEST_USER_DATA); // this will exceed the timeout.

        // finished with async test setup
        done();
    },
    // Tests

};


问:
Map scale on Gmap.net
How to get the map scale on Gmap.net?
I need the scale to calculate the dimensions of an image in relation to the map dimension.
Is it possible to obtain this data on Gmap.net?</p>

答:
I had same problem when I went to add custom marker to GMap(scaling width, height, pen size, ...). You can use below code to get GMap.Net Overlayer scale value.

```<code>double scale = Overlay.Control.MapProvider.Projection.GetGroundResolution((int)Overlay.Control.Zoom, Position.Lat));
</code>```

And use below to scaling your dimensions.

```<code>var h = Height/scale;
var w = Width/scale;
Pen pen = new Pen(Color.Red, 10/scale);
</code>```

I hope this help

Title: Map scale on Gmap.net

Body:
I had same problem when I went to add custom marker to GMap(scaling width, height, pen size, ...). You can use below code to get GMap.Net Overlayer scale value.

double scale = Overlay.Control.MapProvider.Projection.GetGroundResolution((int)Overlay.Control.Zoom, Position.Lat));

And use below to scaling your dimensions.

var h = Height/scale;
var w = Width/scale;
Pen pen = new Pen(Color.Red, 10/scale);

I hope this help


问:
How to initialize the starting point of a background image in css?
I want to add a background image to my web page. The image that I want to use has around 20% transparent padding on all four sides. What attribute should I use so that the background image has an edge-to-edge fit (avoiding the transparent part)? </p>

```<code>body{
    background-image: url("bg.png");
    background-size: 90%;
    background-repeat: no-repeat;
}

</code>```

答:
You can change background image size, and fix them to center:</p>

```<code>body{
    background-image: url( "bg.png" );
    background-size: 60% 60%; /* 100% - 40% (top/left + bottom/right paddings) */
    background-position: center;
    background-repeat: no-repeat;
}
</code>```

Body:
I want to add a background image to my web page. The image that I want to use has around 20% transparent padding on all four sides. What attribute should I use so that the background image has an edge-to-edge fit (avoiding the transparent part)?

body{
    background-image: url("bg.png");
    background-size: 90%;
    background-repeat: no-repeat;
}

Body:
You can change background image size, and fix them to center:

body{
    background-image: url( "bg.png" );
    background-size: 60% 60%; /* 100% - 40% (top/left + bottom/right paddings) */
    background-position: center;
    background-repeat: no-repeat;
}


答:
As other users have pointed out, you should avoid using that format if you can because most JSON parsers will consider that as a dictionary and thus keys must be unique.

Here is a way to test this by creating a string with the right format and then encoding it to JSON:

```<code>import json

proxies = [
  "188.166.78.120:8080",
  "18.210.69.172:3128",
  "178.128.166.50:8118"
]

p = []

p.append('{')

for i, proxy in enumerate(proxies):
    p.append('"http": "http://{0}", "https": "https://{0}"'.format(proxy))
    if not i == len(proxies) - 1:
        p.append(',')

p.append('}')

text_format = ''.join(p)

print (text_format)
</code>```

The output is the format you are looking for:

```<code>{"http": "http://188.166.78.120:8080", "https": "https://188.166.78.120:8080","http": "http://18.210.69.172:3128", "https": "https://18.210.69.172:3128","http": "http://178.128.166.50:8118", "https": "https://178.128.166.50:8118"}
</code>```

Now let's convert that string into JSON:

```<code>json_format = json.loads(text_format)

print (json_format)
</code>```

Only the first key is present as it is not allowed to have repeated keys:

```<code>{'http': 'http://178.128.166.50:8118', 'https': 'https://178.128.166.50:8118'}
</code>```

So you could just use the string generated above or use an alternative valid way to encode this, for example:

```<code>import json

proxies = [
  "188.166.78.120:8080",
  "18.210.69.172:3128",
  "178.128.166.50:8118"
]

p = [{'http': 'http://{0}'.format(item), 'https': 'https://{0}'.format(item)} for item in proxies]

j = json.dumps(p)

print (j)
</code>```

Output:

```<code>[{"http": "http://188.166.78.120:8080", "https": "https://188.166.78.120:8080"}, {"http": "http://18.210.69.172:3128", "https": "https://18.210.69.172:3128"}, {"http": "http://178.128.166.50:8118", "https": "https://178.128.166.50:8118"}]
</code>```

Title: How can I turn list of proxies into json of proxies

Body:
I have a list of proxies:

proxies = [
  "188.166.78.120:8080",
  "18.210.69.172:3128",
  "178.128.166.50:8118"
]

But for a library I need JSON like this:

proxies = {
  "http":  "http://188.166.78.120:8080",
  "https": "http://188.166.78.120:8080",
  "http":  "http://18.210.69.172:3128",
  "https": "http://18.210.69.172:3128",
  "http":  "http://178.128.166.50:8118",
  "https": "http://178.128.166.50:8118"
}

How can I make that?
I have tried this but I only get last one

new = {}

    for i in proxies:
        proxy = {
                "http":"http/"+i,
                "https":"http/"+i
        }
        new.update(proxy)

Body:
As other users have pointed out, you should avoid using that format if you can because most JSON parsers will consider that as a dictionary and thus keys must be unique.

Here is a way to test this by creating a string with the right format and then encoding it to JSON:

import json

proxies = [
  "188.166.78.120:8080",
  "18.210.69.172:3128",
  "178.128.166.50:8118"
]

p = []

p.append('{')

for i, proxy in enumerate(proxies):
    p.append('"http": "http://{0}", "https": "https://{0}"'.format(proxy))
    if not i == len(proxies) - 1:
        p.append(',')

p.append('}')

text_format = ''.join(p)

print (text_format)

The output is the format you are looking for:

{"http": "http://188.166.78.120:8080", "https": "https://188.166.78.120:8080","http": "http://18.210.69.172:3128", "https": "https://18.210.69.172:3128","http": "http://178.128.166.50:8118", "https": "https://178.128.166.50:8118"}

Now let's convert that string into JSON:

json_format = json.loads(text_format)

print (json_format)

Only the first key is present as it is not allowed to have repeated keys:

{'http': 'http://178.128.166.50:8118', 'https': 'https://178.128.166.50:8118'}

So you could just use the string generated above or use an alternative valid way to encode this, for example:

import json

proxies = [
  "188.166.78.120:8080",
  "18.210.69.172:3128",
  "178.128.166.50:8118"
]

p = [{'http': 'http://{0}'.format(item), 'https': 'https://{0}'.format(item)} for item in proxies]

j = json.dumps(p)

print (j)

Output:

[{"http": "http://188.166.78.120:8080", "https": "https://188.166.78.120:8080"}, {"http": "http://18.210.69.172:3128", "https": "https://18.210.69.172:3128"}, {"http": "http://178.128.166.50:8118", "https": "https://178.128.166.50:8118"}]


问:
Using up bandwidth when calling readfile() on a different server?
I have a question about how servers communicate with each other and how it takes up bandwidth.  I'll use an example to better explain my question.

I have two sites: www.jojoedad.com and resources.jojoedad.com.  Each site resides on a separate server (with different IPs and on different machines).  "www| is used mainly for handling front-end tasks such as serving up different web pages.  "resources" stores a whole bunch of video files and is meant to only serve up large video files.

Assume that I code it correctly so only "www" can be accessed by the public and "resources" can only be accessed by calling scripts on "www".  Will large bandwidths of "www" be taken up if users retrieve videos on "resources" through www.jojoedad.com like this:

```<code>http://www.jojoedad.com/getVideo.php?filename=myVideo.mp4
</code>```

and in getVideo.php, I have something like this:

```<code>header("Content-Type..."); // I didn't fill in details for this line
header("Content-disposition..."); // I didn't fill in details for this line
header("COntent-description..."); // I didn't fill in details for this line
readfile("http://resources.jojoedad.com/video_files/{$_GET['filename']}");
</code>```

Thanks in advance!

答:
Yes, because as the process is now, you're doing this:

www connects to resources

www downloads video from resources

www streams video to user

Meaning you're doubling your work. The script that puts out the video files should be on resources.joedad.com and use your header calls plus readfile using the path to the video file. An example would be:

```<code>readfile('/home/user/videos/myVideo.mp4)
</code>```

so it doesn't have to make a connection to itself.

Body:
I have a question about how servers communicate with each other and how it takes up bandwidth.  I'll use an example to better explain my question.

I have two sites: www.jojoedad.com and resources.jojoedad.com.  Each site resides on a separate server (with different IPs and on different machines).  "www| is used mainly for handling front-end tasks such as serving up different web pages.  "resources" stores a whole bunch of video files and is meant to only serve up large video files.

Assume that I code it correctly so only "www" can be accessed by the public and "resources" can only be accessed by calling scripts on "www".  Will large bandwidths of "www" be taken up if users retrieve videos on "resources" through www.jojoedad.com like this:

http://www.jojoedad.com/getVideo.php?filename=myVideo.mp4

and in getVideo.php, I have something like this:

header("Content-Type..."); // I didn't fill in details for this line
header("Content-disposition..."); // I didn't fill in details for this line
header("COntent-description..."); // I didn't fill in details for this line
readfile("http://resources.jojoedad.com/video_files/{$_GET['filename']}");

Thanks in advance!

Body:
Yes, because as the process is now, you're doing this:

www connects to resources

www downloads video from resources

www streams video to user

Meaning you're doubling your work. The script that puts out the video files should be on resources.joedad.com and use your header calls plus readfile using the path to the video file. An example would be:

readfile('/home/user/videos/myVideo.mp4)

so it doesn't have to make a connection to itself.


答:
Instead of producing random numbers independently, create an array with all values between min and max, shuffle it, and then pick the number of values from it that you need:

So replace this:

```<code>const rand = [];
for (var i = 0; i <= size - 1; i++) {
    rand.push(Math.floor(Math.random() * max) + min);
}
</code>```

...with this:

```<code>const rand = shuffle(Array.from({length: max - min + 1}, (_, i) => i + min).slice(0, size);
</code>```

You can take the shuffle function from this answer:

```<code>function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}
</code>```

Be aware that you cannot slice more values than that are present in the min-to-max array. There is of course no way to take 10 unique integers from the range [4...6].

Title: How to replace duplicates from array

Body:
What is the way to remove duplicates from an array that generates random numbers? I've made random number generator that allows the user to type min/max values and how many numbers to generate. I also removed duplicates but if the user types 5 numbers to generate and there is 1 duplicate it will generate 4 numbers. How to add another number to replace the duplicate?

    Min:
    <input type="text" id="Min">

    Max:
    <input type="text" id="Max">

    Generate:
    <input type="text" id="size">
    numbers

    Sort numbers:
    <select id="Sort">
      <option value="Do not sort">Do not sort</option>
      <option value="Ascending">Ascending</option>
      <option value="Descending">Descending</option>
    </select>

    Allow Duplicates:
    <select id="Duplicates">
      <option value="No">No</option>
      <option value="Yes">Yes</option>
    </select>

    <button onclick="func()">Generate</button>

Body:
Instead of producing random numbers independently, create an array with all values between min and max, shuffle it, and then pick the number of values from it that you need:

So replace this:

const rand = [];
for (var i = 0; i <= size - 1; i++) {
    rand.push(Math.floor(Math.random() * max) + min);
}

...with this:

const rand = shuffle(Array.from({length: max - min + 1}, (_, i) => i + min).slice(0, size);

You can take the shuffle function from this answer:

function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

Be aware that you cannot slice more values than that are present in the min-to-max array. There is of course no way to take 10 unique integers from the range [4...6].


问:
How to set a handler for all loggers within a project?
I want to use a memory logger in my project. It keeps track of the last n logging records. A minimal example main file looks like this:

```<code>import sys
import logging
from logging import StreamHandler
from test_module import do_stuff

logger = logging.getLogger(__name__)

class MemoryHandler(StreamHandler):
    def __init__(self, n_logs: int):

        StreamHandler.__init__(self)
        self.n_logs = n_logs
        self.my_records = []

    def emit(self, record):
        self.my_records.append(self.format(record))
        self.my_records = self.my_records[-self.n_logs:]

    def to_string(self):
        return '\n'.join(self.my_records)

if __name__ == '__main__':
    logging.basicConfig(stream=sys.stdout, level=logging.INFO)

    mem_handler = MemoryHandler(n_logs=10)
    logger.addHandler(mem_handler)
    logger.info('hello')
    do_stuff()

    print(mem_handler.to_string())
</code>```

The test module I am importing do_stuff from looks like this:

import logging

logger = logging.getLogger(__name__)

def do_stuff():
    logger.info('doing stuff')
```

<p>When I run the main function two log statements appear. The one from main and the one from doing stuff, but the memory logger only receives "hello" and not "doing stuff":</p>

```INFO:__main__:hello
INFO:test_module:doing stuff
hello
```

<p>I assume that this is because mem_handler is not added to the test_module logger. I can fix this by adding the mem_handler explicitely:</p>

```logging.getLogger('test_module').addHandler(mem_handler)
```

But in general I don't want to list all modules and add the mem_handler manually. How can I add the mem_handler to all loggers in my project?

答:
The Python logging system is federated. That means there is a tree like structure similar to the package structure. This structure works by logger name and the levels are separated by dots.

If you use the module's __name__ to get the logger it will be equivalant to the dotted name of the package. for example:

```<code>package.subpackage.module
</code>```

In this federated system a message is send up the loggers structure (unless one of the loggers is explicitly configured with propagate=False).

So, the best way to add a handler is to add it to the root logger on the top of the structure and make sure all loggers below propagate.

You can get the root logger with logging.getLogger() (without any name) and then add handlers or other configuration as you like.

Body:
I want to use a memory logger in my project. It keeps track of the last n logging records. A minimal example main file looks like this:

import sys
import logging
from logging import StreamHandler
from test_module import do_stuff

logger = logging.getLogger(__name__)

class MemoryHandler(StreamHandler):
    def __init__(self, n_logs: int):

        StreamHandler.__init__(self)
        self.n_logs = n_logs
        self.my_records = []

    def emit(self, record):
        self.my_records.append(self.format(record))
        self.my_records = self.my_records[-self.n_logs:]

    def to_string(self):
        return '\n'.join(self.my_records)

if __name__ == '__main__':
    logging.basicConfig(stream=sys.stdout, level=logging.INFO)

    mem_handler = MemoryHandler(n_logs=10)
    logger.addHandler(mem_handler)
    logger.info('hello')
    do_stuff()

    print(mem_handler.to_string())

The test module I am importing do_stuff from looks like this:

import logging

logger = logging.getLogger(__name__)

def do_stuff():
    logger.info('doing stuff')

When I run the main function two log statements appear. The one from main and the one from doing stuff, but the memory logger only receives "hello" and not "doing stuff":

INFO:__main__:hello
INFO:test_module:doing stuff
hello

I assume that this is because mem_handler is not added to the test_module logger. I can fix this by adding the mem_handler explicitely:

logging.getLogger('test_module').addHandler(mem_handler)

But in general I don't want to list all modules and add the mem_handler manually. How can I add the mem_handler to all loggers in my project?

Body:
The Python logging system is federated. That means there is a tree like structure similar to the package structure. This structure works by logger name and the levels are separated by dots.

If you use the module's __name__ to get the logger it will be equivalant to the dotted name of the package. for example:

package.subpackage.module

In this federated system a message is send up the loggers structure (unless one of the loggers is explicitly configured with propagate=False).

So, the best way to add a handler is to add it to the root logger on the top of the structure and make sure all loggers below propagate.

You can get the root logger with logging.getLogger() (without any name) and then add handlers or other configuration as you like.


问:
Map of an array in a functional component and access to a specific object
```<code>function TypeArticleOne(props) {
let apiData = props.apiData;
const [ therapists, setTherapists ] = useState(apiData.topProfiles.therapists);
const [speciality, setSpeciality]= useState('ABA');
const [pageLoading, setPageLoading]= useState(true);

const topProfilesUrl = 'therapists/top/profiles'

useEffect(() => {
    console.log(speciality);
    getTopTherapists();
    window.scrollTo(0, 0);

}, []);

const getTopTherapists = () => {
    setPageLoading(true);
    loadTopTherapists();

};

const loadTopTherapists = () => {
    console.log("second");
    props.actions.reqGetTherapistsTopProfiles({
        body: {},
        headers: null,
        resource: `${topProfilesUrl}`
    })
};

useEffect(() => {

    if (apiData.topProfiles && apiData.topProfiles.success) {
        const therapistsLoad = apiData.topProfiles.therapists;
        setPageLoading(false);
        setTherapists([therapists].concat(therapistsLoad));
    }
    }, []);
</code>```

How to map an array in a functional component? I want to map the therapists array from the functional component above. React is suggesting me to use UseRef(), because I have a functional component and I am using hooks, but it's not clear for me.
I call the therapists in an array from an database and I need to map them to render in a card, inside a functional component. For now I can access the array elements, but I need to access some specific parameters of the objects. Could you help me guys?

```<code>const renderTherapists = (props) => {
    const items = props.therapists.map( (t, idx) => (
        <TherapistCard therapist={t} key={idx} />
    ))

    return (
        <div ref={0} className="therapist-list">
            { items }
        </div>
    )
}
</code>```

答:
Rather than declaring a const, it is better to directly map the props like this:

```<code>const RenderTherapists = props => {
    return (
        <div className="therapist-list">
         { props.therapists.map((t, idx) => {
               return <TherapistCard therapist={t} key={idx} />
         })}
        </div>
    )
}

export default RenderTherapists;
</code>```

Body:
function TypeArticleOne(props) {
let apiData = props.apiData;
const [ therapists, setTherapists ] = useState(apiData.topProfiles.therapists);
const [speciality, setSpeciality]= useState('ABA');
const [pageLoading, setPageLoading]= useState(true);

const topProfilesUrl = 'therapists/top/profiles'

useEffect(() => {
    console.log(speciality);
    getTopTherapists();
    window.scrollTo(0, 0);

}, []);

const getTopTherapists = () => {
    setPageLoading(true);
    loadTopTherapists();

};

const loadTopTherapists = () => {
    console.log("second");
    props.actions.reqGetTherapistsTopProfiles({
        body: {},
        headers: null,
        resource: `${topProfilesUrl}`
    })
};

useEffect(() => {

    if (apiData.topProfiles && apiData.topProfiles.success) {
        const therapistsLoad = apiData.topProfiles.therapists;
        setPageLoading(false);
        setTherapists([therapists].concat(therapistsLoad));
    }
    }, []);

How to map an array in a functional component? I want to map the therapists array from the functional component above. React is suggesting me to use UseRef(), because I have a functional component and I am using hooks, but it's not clear for me.
I call the therapists in an array from an database and I need to map them to render in a card, inside a functional component. For now I can access the array elements, but I need to access some specific parameters of the objects. Could you help me guys?

const renderTherapists = (props) => {
    const items = props.therapists.map( (t, idx) => (
        <TherapistCard therapist={t} key={idx} />
    ))

    return (

            { items }

    )
}

Body:
Rather than declaring a const, it is better to directly map the props like this:

const RenderTherapists = props => {
    return (
        <div className="therapist-list">
         { props.therapists.map((t, idx) => {
               return <TherapistCard therapist={t} key={idx} />
         })}
        </div>
    )
}

export default RenderTherapists;


问:
How to extract elements from JSON File with python?
I have the JSON file below and i am trying to extract the value dob_year from each item if the name element is jim.

This is my try:

```<code>import json

with open('j.json') as json_file:
    data = json.load(json_file)
    if data['name'] == 'jim'
        print(data['dob_year'])
</code>```

Error:

```<code>File "extractjson.py", line 6 if data['name'] == 'jim' ^ SyntaxError: invalid syntax
</code>```

this is my file.

```<code>[
      {
        "name": "jim",
        "age": "10",
        "sex": "male",
        "dob_year": "2007",
        "ssn": "123-23-1234"
      },
      {
        "name": "jill",
        "age": "6",
        "sex": "female",
        "dob_year": "2011",
        "ssn": "123-23-1235"
      }
    ]
</code>```

答:
I suggest to use list comprehension: </p>

```<code>import json

with open('j.json') as json_file:
    data = json.load(json_file)

print([item["dob_year"] for item in a if item["name"] == "jim"])
</code>```

Body:
I have the JSON file below and i am trying to extract the value dob_year from each item if the name element is jim.

This is my try:

import json

with open('j.json') as json_file:
    data = json.load(json_file)
    if data['name'] == 'jim'
        print(data['dob_year'])

Error:

File "extractjson.py", line 6 if data['name'] == 'jim' ^ SyntaxError: invalid syntax

this is my file.

[
      {
        "name": "jim",
        "age": "10",
        "sex": "male",
        "dob_year": "2007",
        "ssn": "123-23-1234"
      },
      {
        "name": "jill",
        "age": "6",
        "sex": "female",
        "dob_year": "2011",
        "ssn": "123-23-1235"
      }
    ]

Body:
I suggest to use list comprehension:

import json

with open('j.json') as json_file:
    data = json.load(json_file)

print([item["dob_year"] for item in a if item["name"] == "jim"])


问:
Abort insert if the insert date is same day as another row with same id
I'm new to postgresql and dont know what the best way to do this would be.

I have a table with conserts, all conserts have an band id(INTEGER) and a start date(TIMESTAMP).

I want to make sure to only be able to insert a new consert with same band id as other conserts if the time between them is > 24 hours.

Shorter: A band should only be able to play in a consert every 24 hours.

Is it best to create some kinda trigger for this? I also read some about rules for postgresql.

Conserts table

Thank you for help!

答:
The wording of your question makes it clear to me you are not talking about calendar days, but actual 24 hour time intervals.  You can preclude this using an EXCLUDE constraint.  Since you are storing a timestamp, not a range, in the table, you will have to dynamically create the range from the timestamp for it to be used in the constraint.</p>

```<code>create extension btree_gist ;
alter table concerts add constraint blah exclude using gist
    (band_id with =, tsrange(starttime, starttime+interval '24 hours') with &&);
</code>```

Body:
The wording of your question makes it clear to me you are not talking about calendar days, but actual 24 hour time intervals.  You can preclude this using an EXCLUDE constraint.  Since you are storing a timestamp, not a range, in the table, you will have to dynamically create the range from the timestamp for it to be used in the constraint.

create extension btree_gist ;
alter table concerts add constraint blah exclude using gist
    (band_id with =, tsrange(starttime, starttime+interval '24 hours') with &&);