问:
ValueError: ConvLSTMCell and dynamic_rnn
I'm trying to build a seq2seq model in tensorflow (1.4) using the tf.contrib.rnn.ConvLSTMCell API together with the tf.nn.dynamic_rnn API, but I got an error with the dimension of the inputs.

My code is:

```<code># features is an image sequence with shape [600, 400, 10],
# so features is a tensor with shape [batch_size, 600, 400, 10]

features = tf.transpose(features, [0,3,1,2])
features = tf.reshape(features, [params['batch_size'],10,600,400])

encoder_cell = tf.contrib.rnn.ConvLSTMCell(conv_ndims=2,
                                           input_shape=[600, 400,1],
                                           output_channels=5,
                                           kernel_shape=[7,7],
                                           skip_connection=False)

_, encoder_state = tf.nn.dynamic_rnn(cell=encoder_cell,
                                     inputs=features,
                                     sequence_length=[10]*params['batch_size'],
                                     dtype=tf.float32)
</code>```

I get the following error

```<code>ValueError: Conv Linear expects all args to be of same Dimension: [[2, 600, 400], [2, 600, 400, 5]]
</code>```

Looking at the tf implementation, it seems that the inputs to dynamic_rnn is only 3-dimensional in contrary to the hidden state, which is 4-dimensional. I tried to pass the input as a nested tuple, but it didn't work.

The problem is similar to TensorFlow dynamic_rnn regressor: ValueError dimension mismatch, it's slightly different though, as they're using a plain LSTMCell (which worked for me).

Can anyone give me a minimal example how to use these 2 APIs together?
Thanks!

答:
In the meantime I figured out how to use the 2 APIs together. The trick is to pass a 5D-Tensor as input to tf.nn.dynamic_rnn(), where the last dimension is the size of the "vector on the spatial grid" (which comes from the transformation of the input from 2D to 3D, inspired by the paper on which the implementation is based: https://arxiv.org/pdf/1506.04214.pdf). In my case the vector size is 1, I have to expand the dimension anyway though.

While fixing this error another issue emerged: In the paper mentioned above in section 3.1 they state the equations for the convLSTM. They use the Hadamard-product for weights connected to the cell outputs C. Printing the weights of my ConvLSTMCell in Tensorflow, it seems like they don't use the weights Wci, Wcf and Wco at all. So, can anybody tell me the exact implementation of the TF ConvLSTMCell?

Btw. the output of the tensorflow ConvSTMCell is C or H (in the notation of the paper)?

Body:
I'm trying to build a seq2seq model in tensorflow (1.4) using the tf.contrib.rnn.ConvLSTMCell API together with the tf.nn.dynamic_rnn API, but I got an error with the dimension of the inputs.

My code is:

# features is an image sequence with shape [600, 400, 10],
# so features is a tensor with shape [batch_size, 600, 400, 10]

features = tf.transpose(features, [0,3,1,2])
features = tf.reshape(features, [params['batch_size'],10,600,400])

encoder_cell = tf.contrib.rnn.ConvLSTMCell(conv_ndims=2,
                                           input_shape=[600, 400,1],
                                           output_channels=5,
                                           kernel_shape=[7,7],
                                           skip_connection=False)

_, encoder_state = tf.nn.dynamic_rnn(cell=encoder_cell,
                                     inputs=features,
                                     sequence_length=[10]*params['batch_size'],
                                     dtype=tf.float32)

I get the following error

ValueError: Conv Linear expects all args to be of same Dimension: [[2, 600, 400], [2, 600, 400, 5]]

Looking at the tf implementation, it seems that the inputs to dynamic_rnn is only 3-dimensional in contrary to the hidden state, which is 4-dimensional. I tried to pass the input as a nested tuple, but it didn't work.

The problem is similar to TensorFlow dynamic_rnn regressor: ValueError dimension mismatch, it's slightly different though, as they're using a plain LSTMCell (which worked for me).

Can anyone give me a minimal example how to use these 2 APIs together?
Thanks!


来源: stackexchange

问:
Strange behaviour of BULK COLLECT
I tinkered together the following PL/SQL BULK-COLLECT which works astonishingly fast for updates on huge tables (>50.000.000). The only problem is, that it does not perform the updates of the remaining < 5000 rows per table. 5000 is the given limit for the FETCH instruction:

```<code>DECLARE
-- source table cursor (only columns to be updated)
  CURSOR base_table_cur IS
  select a.rowid, TARGET_COLUMN from TARGET_TABLE a
                        where TARGET_COLUMN is null;

    TYPE base_type IS
        TABLE OF base_table_cur%rowtype INDEX BY PLS_INTEGER;
    base_tab  base_type;

-- new data
    CURSOR new_data_cur IS
      select a.rowid,
        coalesce(b.SOURCE_COLUMN, 'FILL_VALUE'||a.JOIN_COLUMN) TARGET_COLUMN from TARGET_TABLE a
        left outer join SOURCE_TABLE b
        on a.JOIN_COLUMN=b.JOIN_COLUMN
        where a.TARGET_COLUMN is null;

    TYPE new_data_type IS TABLE OF new_data_cur%rowtype INDEX BY PLS_INTEGER;
    new_data_tab       new_data_type;
    TYPE row_id_type IS TABLE OF ROWID INDEX BY PLS_INTEGER;
    row_id_tab         row_id_type;
    TYPE rt_update_cols IS RECORD (
        TARGET_COLUMN   TARGET_TABLE.TARGET_COLUMN%TYPE
    );
    TYPE update_cols_type IS
        TABLE OF rt_update_cols INDEX BY PLS_INTEGER;
    update_cols_tab    update_cols_type;
    dml_errors EXCEPTION;
    PRAGMA exception_init ( dml_errors,-24381 );

BEGIN
    OPEN base_table_cur;
    OPEN new_data_cur;
    LOOP
        FETCH base_table_cur BULK COLLECT INTO base_tab LIMIT 5000;
        IF base_table_cur%notfound THEN
           DBMS_OUTPUT.PUT_LINE('Nothing to update. Exiting.');
           EXIT;
        END IF;
        FETCH new_data_cur BULK COLLECT INTO new_data_tab LIMIT 5000;
        FOR i IN base_tab.first..base_tab.last LOOP
            row_id_tab(i) := new_data_tab(i).rowid;
            update_cols_tab(i).TARGET_COLUMN := new_data_tab(i).TARGET_COLUMN;
        END LOOP;

        FORALL i IN base_tab.first..base_tab.last SAVE EXCEPTIONS
            UPDATE (SELECT TARGET_COLUMN FROM TARGET_TABLE)
            SET row = update_cols_tab(i)
            WHERE ROWID = row_id_tab(i);

        COMMIT;
        EXIT WHEN base_tab.count < 5000; -- changing to 1 didn't help!
    END LOOP;

    COMMIT;
    CLOSE base_table_cur;
    CLOSE new_data_cur;
EXCEPTION
    WHEN dml_errors THEN
        FOR i IN 1..SQL%bulk_exceptions.count LOOP
            dbms_output.put_line('Some error occured');
        END LOOP;
END;
</code>```

Where is my mistake? It looks correct to me though.

答:
The problem is this line:

```<code>IF base_table_cur%notfound THEN
</code>```

The cursor meets %NOTFOUND when the number of records found is less than the LIMIT value. So if the last fetch is not exactly 5000 those records won't be processed.

It's a common gotcha for people using BULK COLLECT ... LIMIT for the first time. The solution is to change the exit condition to

```<code>EXIT when base_tab.count() = 0;
</code>```

"I need to ensure, that the base_table_cur is not empty and exit if it is. I'l get an error if it is empty"

The new_data_cur cursor includes the table which is selected in base_table_cur cursor. So I don't think you need the two loops. You need a simple test to see whether the first cursor returns something, then just loop round the second cursor.

I'm not entirely clear on your logic, so I have changed as little as possible to demonstrate the sort of structure I think you need. However, the UPDATE statement looks a little odd, so you may still run into issues.

```<code>OPEN base_table_cur;
FETCH base_table_cur BULK COLLECT INTO base_tab LIMIT 1;
if base_table_tab.count = 0 then
    DBMS_OUTPUT.PUT_LINE('Nothing to update. Exiting.');
else
    OPEN new_data_cur;
    LOOP
        FETCH new_data_cur BULK COLLECT INTO new_data_tab LIMIT 5000;
        exit when new_data_tab.count() = 0;

        FOR i IN base_tab.first..base_tab.last LOOP
            row_id_tab(i) := new_data_tab(i).rowid;
            update_cols_tab(i).TARGET_COLUMN := new_data_tab(i).TARGET_COLUMN;
        END LOOP;

        FORALL i IN base_tab.first..base_tab.last SAVE EXCEPTIONS
            UPDATE (SELECT TARGET_COLUMN FROM TARGET_TABLE)
            SET row = update_cols_tab(i)
            WHERE ROWID = row_id_tab(i);

    END LOOP;
    CLOSE new_data_cur;
end if;
COMMIT;
CLOSE base_table_cur;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Strange behaviour of BULK COLLECT

Body:
I tinkered together the following PL/SQL BULK-COLLECT which works astonishingly fast for updates on huge tables (>50.000.000). The only problem is, that it does not perform the updates of the remaining < 5000 rows per table. 5000 is the given limit for the FETCH instruction:

DECLARE
-- source table cursor (only columns to be updated)
  CURSOR base_table_cur IS
  select a.rowid, TARGET_COLUMN from TARGET_TABLE a
                        where TARGET_COLUMN is null;

    TYPE base_type IS
        TABLE OF base_table_cur%rowtype INDEX BY PLS_INTEGER;
    base_tab  base_type;

-- new data
    CURSOR new_data_cur IS
      select a.rowid,
        coalesce(b.SOURCE_COLUMN, 'FILL_VALUE'||a.JOIN_COLUMN) TARGET_COLUMN from TARGET_TABLE a
        left outer join SOURCE_TABLE b
        on a.JOIN_COLUMN=b.JOIN_COLUMN
        where a.TARGET_COLUMN is null;

    TYPE new_data_type IS TABLE OF new_data_cur%rowtype INDEX BY PLS_INTEGER;
    new_data_tab       new_data_type;
    TYPE row_id_type IS TABLE OF ROWID INDEX BY PLS_INTEGER;
    row_id_tab         row_id_type;
    TYPE rt_update_cols IS RECORD (
        TARGET_COLUMN   TARGET_TABLE.TARGET_COLUMN%TYPE
    );
    TYPE update_cols_type IS
        TABLE OF rt_update_cols INDEX BY PLS_INTEGER;
    update_cols_tab    update_cols_type;
    dml_errors EXCEPTION;
    PRAGMA exception_init ( dml_errors,-24381 );

BEGIN
    OPEN base_table_cur;
    OPEN new_data_cur;
    LOOP
        FETCH base_table_cur BULK COLLECT INTO base_tab LIMIT 5000;
        IF base_table_cur%notfound THEN
           DBMS_OUTPUT.PUT_LINE('Nothing to update. Exiting.');
           EXIT;
        END IF;
        FETCH new_data_cur BULK COLLECT INTO new_data_tab LIMIT 5000;
        FOR i IN base_tab.first..base_tab.last LOOP
            row_id_tab(i) := new_data_tab(i).rowid;
            update_cols_tab(i).TARGET_COLUMN := new_data_tab(i).TARGET_COLUMN;
        END LOOP;

        FORALL i IN base_tab.first..base_tab.last SAVE EXCEPTIONS
            UPDATE (SELECT TARGET_COLUMN FROM TARGET_TABLE)
            SET row = update_cols_tab(i)
            WHERE ROWID = row_id_tab(i);

        COMMIT;
        EXIT WHEN base_tab.count < 5000; -- changing to 1 didn't help!
    END LOOP;

    COMMIT;
    CLOSE base_table_cur;
    CLOSE new_data_cur;
EXCEPTION
    WHEN dml_errors THEN
        FOR i IN 1..SQL%bulk_exceptions.count LOOP
            dbms_output.put_line('Some error occured');
        END LOOP;
END;

Where is my mistake? It looks correct to me though.

Body:
The problem is this line:

IF base_table_cur%notfound THEN

The cursor meets %NOTFOUND when the number of records found is less than the LIMIT value. So if the last fetch is not exactly 5000 those records won't be processed.

It's a common gotcha for people using BULK COLLECT ... LIMIT for the first time. The solution is to change the exit condition to

EXIT when base_tab.count() = 0;

"I need to ensure, that the base_table_cur is not empty and exit if it is. I'l get an error if it is empty"

The new_data_cur cursor includes the table which is selected in base_table_cur cursor. So I don't think you need the two loops. You need a simple test to see whether the first cursor returns something, then just loop round the second cursor.

I'm not entirely clear on your logic, so I have changed as little as possible to demonstrate the sort of structure I think you need. However, the UPDATE statement looks a little odd, so you may still run into issues.

OPEN base_table_cur;
FETCH base_table_cur BULK COLLECT INTO base_tab LIMIT 1;
if base_table_tab.count = 0 then
    DBMS_OUTPUT.PUT_LINE('Nothing to update. Exiting.');
else
    OPEN new_data_cur;
    LOOP
        FETCH new_data_cur BULK COLLECT INTO new_data_tab LIMIT 5000;
        exit when new_data_tab.count() = 0;

        FOR i IN base_tab.first..base_tab.last LOOP
            row_id_tab(i) := new_data_tab(i).rowid;
            update_cols_tab(i).TARGET_COLUMN := new_data_tab(i).TARGET_COLUMN;
        END LOOP;

        FORALL i IN base_tab.first..base_tab.last SAVE EXCEPTIONS
            UPDATE (SELECT TARGET_COLUMN FROM TARGET_TABLE)
            SET row = update_cols_tab(i)
            WHERE ROWID = row_id_tab(i);

    END LOOP;
    CLOSE new_data_cur;
end if;
COMMIT;
CLOSE base_table_cur;


问:
"Element Should be Disabled" not working?
I am using Robot Framework and Selenium2Library. I am trying to check that given element is disabled. Code used is :

```<code>Element Should Be Disabled | //div[6]/div[2]/div/div[2]/div[1]/div[2]/div/div/div[2]/div[2]/span[4]
</code>```

This code is giving me following error :

```<code>ERROR: Element //div[6]/div[2]/div/div[2]/div[1]/div[2]/div/div/div[2]/div[2]/span[4] is not an input.
</code>```

Help in solving this problem would be appreciated. Thanks !!

答:
What I did was Used the "Get Element Attribute" keyword on the id of the element follow by the attribute I wanted to access so here it would be @disabled
Get Element Attribute|id@disabled and stored it as a variable. You can then check if the value of that variable is disabled or not. Hope this is helpful</p>

Body:
I am using Robot Framework and Selenium2Library. I am trying to check that given element is disabled. Code used is :

Element Should Be Disabled | //div[6]/div[2]/div/div[2]/div[1]/div[2]/div/div/div[2]/div[2]/span[4]

This code is giving me following error :

ERROR: Element //div[6]/div[2]/div/div[2]/div[1]/div[2]/div/div/div[2]/div[2]/span[4] is not an input.

Help in solving this problem would be appreciated. Thanks !!


问:
Traversing an object in javascript and convert it in specific format
I have the following object structure:

```<code>{
    a: {
        b: "abc",
        c: [
            {
                d: "pqr",
                e: true
            },
            {
                f: 1,
                e: ["xyz", 1]
            }
        ]
    }
}
</code>```

Now I want to convert these structure in specific format that are shown in expected output.

I'm trying to traverse above structure but the constructed path not correct
Here is what I'm doing

```<code>const getFinalNode = function(data, path){
  if (typeof data === 'object'){
    for (let key in data) {
      // console.log(key);
      if (typeof data[key] === 'object'){
        path += key+'/'
        getFinalNode(data[key], path)
        // console.log(true);
      }else{
        console.log({
          value: data[key],
          key: key,
          path:path
        })
      }
    }
  }
}
getFinalNode(data, "");
</code>```

My expected output should be

```<code>[
    {
        name: "b",
        value: "abc",
        path: "a/b"
    },
    {
        name: "d",
        value: "pqr",
        path: "a/c/0/d"
    },
    {
        name: "e",
        value: true,
        path: "a/c/0/e"
    },
    {
        name: "f",
        value: 1,
        path: "a/c/1/f"
    },
    {
        name: "e",
        value: 'xyz',
        path: "a/c/1/e"
    },
    {
        name: "e",
        value: 1,
        path: "a/c/1/e"
    }
]
</code>```

So how can I traverse above structure and convert it in expected output or is there any solution that can I use in my existing code.

Now I getting following output

答:
For fun, dirty solution, kids don't do that at home !

function getFinalNode(node) {
  return (function rec(obj, path='', results=[]) {
    path = path && (path + '/')
    return Object.entries(obj)
      .reduce((arr, [name, value]) => void (typeof value === 'object'
          ? rec(value, path + name, arr)
          : arr.push({ name, value, path: path + name })) || arr,
        results)
  })(node)
}

console.log(getFinalNode({a:{b:"abc",c:[{d:"pqr",e:true},{f:1,e:["xyz",1]}]}}))```
</div>
</div>
</p>

<p>To explain a bit:</p>

```path = path && (path + '/')
```

<p>If <code>path</code> is empty, the first part of the condition will be evaluated, so will get an empty string. Otherwise, the second part is evaluated, and we do the concatenation.</p>

```void (whatEverExpression) || arr
```

void will make whatEverExpression returning undefined, so arr will be returned instead.

(It's a trick, I find handful when reducing something. Even if ESLint forbid the use of void :D)

Edit: Inspired by rock star's answer, with entries, it's even better :D

Body:
I have the following object structure:

{
    a: {
        b: "abc",
        c: [
            {
                d: "pqr",
                e: true
            },
            {
                f: 1,
                e: ["xyz", 1]
            }
        ]
    }
}

Now I want to convert these structure in specific format that are shown in expected output.

I'm trying to traverse above structure but the constructed path not correct
Here is what I'm doing

const getFinalNode = function(data, path){
  if (typeof data === 'object'){
    for (let key in data) {
      // console.log(key);
      if (typeof data[key] === 'object'){
        path += key+'/'
        getFinalNode(data[key], path)
        // console.log(true);
      }else{
        console.log({
          value: data[key],
          key: key,
          path:path
        })
      }
    }
  }
}
getFinalNode(data, "");

My expected output should be

[
    {
        name: "b",
        value: "abc",
        path: "a/b"
    },
    {
        name: "d",
        value: "pqr",
        path: "a/c/0/d"
    },
    {
        name: "e",
        value: true,
        path: "a/c/0/e"
    },
    {
        name: "f",
        value: 1,
        path: "a/c/1/f"
    },
    {
        name: "e",
        value: 'xyz',
        path: "a/c/1/e"
    },
    {
        name: "e",
        value: 1,
        path: "a/c/1/e"
    }
]

So how can I traverse above structure and convert it in expected output or is there any solution that can I use in my existing code.

Now I getting following output

Body:
For fun, dirty solution, kids don't do that at home !

function getFinalNode(node) {
  return (function rec(obj, path='', results=[]) {
    path = path && (path + '/')
    return Object.entries(obj)
      .reduce((arr, [name, value]) => void (typeof value === 'object'
          ? rec(value, path + name, arr)
          : arr.push({ name, value, path: path + name })) || arr,
        results)
  })(node)
}

console.log(getFinalNode({a:{b:"abc",c:[{d:"pqr",e:true},{f:1,e:["xyz",1]}]}}))

To explain a bit:

path = path && (path + '/')

If path is empty, the first part of the condition will be evaluated, so will get an empty string. Otherwise, the second part is evaluated, and we do the concatenation.

void (whatEverExpression) || arr

void will make whatEverExpression returning undefined, so arr will be returned instead.

(It's a trick, I find handful when reducing something. Even if ESLint forbid the use of void :D)

Edit: Inspired by rock star's answer, with entries, it's even better :D


问:
Using three points (x, y), How to find whether it is triangle or not
I have an assignment in codeforces which says:

Like all problem solvers, Ebram loves eating crepe! As we all know, crepe usually served in a triangular shape. Now Ebram wants to know how large can a crepe side be! So he tries to draw a triangle on a plane using three points and calculate the maximum length of the three sides of the triangle. But sometimes he falls asleep as he has been busy with the team preparing the training problems! As a result, the three points he uses may not form a triangle that could represent a piece of crepe! A triangle can represent a piece of crepe only if it has a positive area. So you are here to help Ebram! Given the coordinates Ebram used, determine whether they form a triangle that could represent a piece of crepe or not.

 Input:
Three integer coordinates (X,Y) that represent the three points Ebram used. Each point on a separate line.

Output: If the points form a triangle that can represent a piece of crepe, print the square of the maximum length of the three sides of the triangle. Otherwise print "Poor boy"

Examples

```<code>input
1 1
3 1
3 9
output
68
</code>```

```<code>input
 -10 8
  9 100
  3 8
  output
  8825
</code>```

```<code>input
7 3
3 3
19 3
output
Poor boy
</code>```

Here is my code that I used:

```<code>#include <iostream>
#include <cmath>
using namespace std;
int main () {
   double x1,y1,x2,y2,x3,y3;
    double area;
    double s1,s2,s3;
   double slope1, slope2;
cin >> x1 >> y1;
cin >> x2 >> y2;
cin >> x3 >> y3;
slope1 =((y2-y1)/(x2-x1));
slope2 =((y3-y2)/(x3-x2));
area = 0.5*abs(((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1)));
if (slope1!=slope2 &&  (area)!=0){

    s1 = sqrt(((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2)));
    s2 = sqrt(((x2-x3)*(x2-x3))+((y2-y3)*(y2-y3)));
    s3 = sqrt(((x1-x3)*(x1-x3))+((y1-y3)*(y1-y3)));
     if (s1 > s2 && s1 > s3)
        cout<<s1*s1<<endl;
     if (s2 > s1 && s2 > s3)
        cout<<s2*s2<<endl;
     if (s3 > s1 && s3 > s2)
        cout <<s3*s3<<endl;
}

else
    cout <<"Poor boy";
return 0;

}
</code>```

 First I find the slope1 and slope2 to check if the three points aren't at the same line. So If they're not equal it forms a triangle (crepe).
Using this:

```<code>slope1 =((y2-y1)/(x2-x1));
slope2 =((y3-y2)/(x3-x2));
</code>```

Then I wrote a relation to find the area of triangle using this formula:

```<code>area = 0.5*abs(((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1)));
</code>```

Finally I put the if statements to find if it is a triangle or not and find the length of each side of the triangle then find the maximum length and print the square of it.

```<code>if (slope1!=slope2 &&  (area)!=0){

    s1 = sqrt(((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2)));
    s2 = sqrt(((x2-x3)*(x2-x3))+((y2-y3)*(y2-y3)));
    s3 = sqrt(((x1-x3)*(x1-x3))+((y1-y3)*(y1-y3)));
     if (s1 > s2 && s1 > s3)
        cout<<s1*s1<<endl;
     if (s2 > s1 && s2 > s3)
        cout<<s2*s2<<endl;
     if (s3 > s1 && s3 > s2)
        cout <<s3*s3<<endl;
}

else
    cout <<"Poor boy";
return 0;

}
</code>```

 I tested the code in my compiler and it runs the i/o shown in the example perfectly fine. I submitted the code on codeforces but I stuck wrong answer at test 8 I don't know why?, and my code runs inputs and outputs fine. I will be very pleased if you help guys.

答:
Your biggest problem is that you keep getting division by 0 on inputs where the denominator is 0 when calculating the slope. I.e. Points (3, 4), (3, 5) and (5, 6) will yield -1/0.

Another thing is that you are "over-complicating" things.

This is a step by step example for clarity how to approach this (I.e. not optimal code):

```<code>// Check if any two points are the same. I.e. no triangle
if (x1 == x2 && y1 == y2 || x1 == x3 && y1 == y3 || x2 == x3 && y2 == y3) {
  cout << "Poor boy";
  return 0;
}

// Check if all points are on the same horizontal or vertical line
if (x1 == x2 && x1 == x3 || y1 == y2 && y1 == y3) {
  cout << "Poor boy";
  return 0;
}

// Calculate the nominators and denominators
nominator1 = y2-y1;
denominator1 = x2-x1;
nominator2 = y3-y2;
denominator2 = x3-x2;
nominator3 = y1-y3;
denominator3 = x1-x3;

// Calculate the slopes, if possible.
if (denominator1 == 0) slope1 = 0;
else slope1 = nominator1 / denominator1;
if (denominator2 == 0) slope2 = 0;
else slope2 = nominator2 / denominator2;
if (denominator3 == 0) slope3 = 0;
else slope3 = nominator3 / denominator3;

// Check if the three points form a triangle or a straight line.
// I.e. if all slopes are the same, it is a line.
if ((slope1 == slope2 && slope1 == slope3)) {
  cout << "Poor boy";
  return 0;
}

// Calculate the square of the length of each side
// (No abs is needed since a square of negative numbers is positive.)
// (Also no sqrt is needed since we're only interrested in the square of the longest side.)
side1 = (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1);
side2 = (x3-x2)*(x3-x2) + (y3-y2)*(y3-y2);
side3 = (x1-x3)*(x1-x3) + (y1-y3)*(y1-y3);

// Note: This can be used instead which is the same calculation:
// side1 = denominator1 * denominator1 + nominator1 * nominator1;
// side2 = denominator2 * denominator2 + nominator2 * nominator2;
// side3 = denominator3 * denominator3 + nominator3 * nominator3;

// Get the longest side squared.
maxSide = side1 > side2 ? side1 > side3 ? side1 : side2 > side3 ? side2 : side3;

cout << maxSide;
</code>```

Disclaimer: Code not tested!

Body:
I have an assignment in codeforces which says:

Like all problem solvers, Ebram loves eating crepe! As we all know, crepe usually served in a triangular shape. Now Ebram wants to know how large can a crepe side be! So he tries to draw a triangle on a plane using three points and calculate the maximum length of the three sides of the triangle. But sometimes he falls asleep as he has been busy with the team preparing the training problems! As a result, the three points he uses may not form a triangle that could represent a piece of crepe! A triangle can represent a piece of crepe only if it has a positive area. So you are here to help Ebram! Given the coordinates Ebram used, determine whether they form a triangle that could represent a piece of crepe or not.

 Input:
Three integer coordinates (X,Y) that represent the three points Ebram used. Each point on a separate line.

Output: If the points form a triangle that can represent a piece of crepe, print the square of the maximum length of the three sides of the triangle. Otherwise print "Poor boy"

Examples

input
1 1
3 1
3 9
output
68

input
 -10 8
  9 100
  3 8
  output
  8825

input
7 3
3 3
19 3
output
Poor boy

Here is my code that I used:

#include <iostream>
#include <cmath>
using namespace std;
int main () {
   double x1,y1,x2,y2,x3,y3;
    double area;
    double s1,s2,s3;
   double slope1, slope2;
cin >> x1 >> y1;
cin >> x2 >> y2;
cin >> x3 >> y3;
slope1 =((y2-y1)/(x2-x1));
slope2 =((y3-y2)/(x3-x2));
area = 0.5*abs(((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1)));
if (slope1!=slope2 &&  (area)!=0){

    s1 = sqrt(((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2)));
    s2 = sqrt(((x2-x3)*(x2-x3))+((y2-y3)*(y2-y3)));
    s3 = sqrt(((x1-x3)*(x1-x3))+((y1-y3)*(y1-y3)));
     if (s1 > s2 && s1 > s3)
        cout<<s1*s1<<endl;
     if (s2 > s1 && s2 > s3)
        cout<<s2*s2<<endl;
     if (s3 > s1 && s3 > s2)
        cout <<s3*s3<<endl;
}

else
    cout <<"Poor boy";
return 0;

}

 First I find the slope1 and slope2 to check if the three points aren't at the same line. So If they're not equal it forms a triangle (crepe).
Using this:

slope1 =((y2-y1)/(x2-x1));
slope2 =((y3-y2)/(x3-x2));

Then I wrote a relation to find the area of triangle using this formula:

area = 0.5*abs(((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1)));

Finally I put the if statements to find if it is a triangle or not and find the length of each side of the triangle then find the maximum length and print the square of it.

if (slope1!=slope2 &&  (area)!=0){

    s1 = sqrt(((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2)));
    s2 = sqrt(((x2-x3)*(x2-x3))+((y2-y3)*(y2-y3)));
    s3 = sqrt(((x1-x3)*(x1-x3))+((y1-y3)*(y1-y3)));
     if (s1 > s2 && s1 > s3)
        cout<<s1*s1<<endl;
     if (s2 > s1 && s2 > s3)
        cout<<s2*s2<<endl;
     if (s3 > s1 && s3 > s2)
        cout <<s3*s3<<endl;
}

else
    cout <<"Poor boy";
return 0;

}

 I tested the code in my compiler and it runs the i/o shown in the example perfectly fine. I submitted the code on codeforces but I stuck wrong answer at test 8 I don't know why?, and my code runs inputs and outputs fine. I will be very pleased if you help guys.

Body:
Your biggest problem is that you keep getting division by 0 on inputs where the denominator is 0 when calculating the slope. I.e. Points (3, 4), (3, 5) and (5, 6) will yield -1/0.

Another thing is that you are "over-complicating" things.

This is a step by step example for clarity how to approach this (I.e. not optimal code):

// Check if any two points are the same. I.e. no triangle
if (x1 == x2 && y1 == y2 || x1 == x3 && y1 == y3 || x2 == x3 && y2 == y3) {
  cout << "Poor boy";
  return 0;
}

// Check if all points are on the same horizontal or vertical line
if (x1 == x2 && x1 == x3 || y1 == y2 && y1 == y3) {
  cout << "Poor boy";
  return 0;
}

// Calculate the nominators and denominators
nominator1 = y2-y1;
denominator1 = x2-x1;
nominator2 = y3-y2;
denominator2 = x3-x2;
nominator3 = y1-y3;
denominator3 = x1-x3;

// Calculate the slopes, if possible.
if (denominator1 == 0) slope1 = 0;
else slope1 = nominator1 / denominator1;
if (denominator2 == 0) slope2 = 0;
else slope2 = nominator2 / denominator2;
if (denominator3 == 0) slope3 = 0;
else slope3 = nominator3 / denominator3;

// Check if the three points form a triangle or a straight line.
// I.e. if all slopes are the same, it is a line.
if ((slope1 == slope2 && slope1 == slope3)) {
  cout << "Poor boy";
  return 0;
}

// Calculate the square of the length of each side
// (No abs is needed since a square of negative numbers is positive.)
// (Also no sqrt is needed since we're only interrested in the square of the longest side.)
side1 = (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1);
side2 = (x3-x2)*(x3-x2) + (y3-y2)*(y3-y2);
side3 = (x1-x3)*(x1-x3) + (y1-y3)*(y1-y3);

// Note: This can be used instead which is the same calculation:
// side1 = denominator1 * denominator1 + nominator1 * nominator1;
// side2 = denominator2 * denominator2 + nominator2 * nominator2;
// side3 = denominator3 * denominator3 + nominator3 * nominator3;

// Get the longest side squared.
maxSide = side1 > side2 ? side1 > side3 ? side1 : side2 > side3 ? side2 : side3;

cout << maxSide;

Disclaimer: Code not tested!


问:
How can I check if this object into a JSON document is a simple object or an array using JavaScript?
I am not so into JavaScript and I have the following problem. To solve this problem I can use only pure old JavaScript (not library or framework).

I have a JSON document like this:

```<code>{
    "Commodity": {
        "CommodityInMarket": {
            "market_info": {
                "market_id": 5,
                "market_name": "Tambacounda Market N2",
                "available_market_count": 1
            },
            "commodity_info": {
                "commodity_details_id": 1,
                "commodity_name_en": "Rice-Asia",
                "commodity_name": "Rice-Asia",
                "image_link": "https://firebasestorage.googleapis.com/v0/b/fao-digital-services-portfolio.appspot.com/o/img%2Ficons%2Fagrimarket%2Fcommodity%2Friz.png?alt=media&token=c35e7648-1793-423b-acd2-52d8a1e58c53",
                "description": "Rice-Asia"
            },
            "price_info": {
                "price_serie_id": 29,
                "today_avg_price": 9.3000,
                "yesterday_avg_price": 9.6000,
                "currency": "XOF",
                "measure_unit": "kilogram"
            }
        }
    }
}
</code>```

As you can see this document contains a Commodity object.

In some case it is a simple object (as in the previous code snippet), in some other case it can be an array (this document is returned by a service in this way), so something like this:

```<code>{
    "Commodity": {
        "CommodityInMarket": [{
            .....................................
            .....................................
            .....................................
        },
        {
            .....................................
            .....................................
            .....................................
        }]
    }
}
</code>```

How can I check if this Commodity object into my JSON document is a simple object or an array? I need to do something like this:

If it is a simple object put true into a boolean variable. How can I implement this behavior?

答: As of ECMAScript 5.1 there is also Array.isArray().

Body:
I am not so into JavaScript and I have the following problem. To solve this problem I can use only pure old JavaScript (not library or framework).

I have a JSON document like this:

{
    "Commodity": {
        "CommodityInMarket": {
            "market_info": {
                "market_id": 5,
                "market_name": "Tambacounda Market N2",
                "available_market_count": 1
            },
            "commodity_info": {
                "commodity_details_id": 1,
                "commodity_name_en": "Rice-Asia",
                "commodity_name": "Rice-Asia",
                "image_link": "https://firebasestorage.googleapis.com/v0/b/fao-digital-services-portfolio.appspot.com/o/img%2Ficons%2Fagrimarket%2Fcommodity%2Friz.png?alt=media&token=c35e7648-1793-423b-acd2-52d8a1e58c53",
                "description": "Rice-Asia"
            },
            "price_info": {
                "price_serie_id": 29,
                "today_avg_price": 9.3000,
                "yesterday_avg_price": 9.6000,
                "currency": "XOF",
                "measure_unit": "kilogram"
            }
        }
    }
}

As you can see this document contains a Commodity object.

In some case it is a simple object (as in the previous code snippet), in some other case it can be an array (this document is returned by a service in this way), so something like this:

{
    "Commodity": {
        "CommodityInMarket": [{
            .....................................
            .....................................
            .....................................
        },
        {
            .....................................
            .....................................
            .....................................
        }]
    }
}

How can I check if this Commodity object into my JSON document is a simple object or an array? I need to do something like this:

If it is a simple object put true into a boolean variable. How can I implement this behavior?


问:
Ruby Rest-client keeps correcting the uri
I'm using rest-client to make a post request to a certain address. Unfortunately rest-client keeps correcting the web adres from 'https' to 'http'. Which then gives back an error.

I already looked at the documentation whether this maybe was a setting for the gem. Anyone knows how I can 'force' rest-client to access the desired address.

Thx in advance!

used code is:

```<code>  uri = 'https://sandbox.api.online.unit4.nl/V19/OAuth/Token'

  payload = {
    code: params[:code],
    client_id: '#{@client_id}',
    client_secret: '#{@client_secret}',
    redirect_uri: '#{@client_redirect_url}',
    grant_type: 'authorization_code'
  }

  response = RestClient::Request.execute(method: :post, url: uri,      headers: {params: payload})
</code>```

curl:

```<code>> GET /V19/OAuth/Token HTTP/1.1
> Host: sandbox.api.online.unit4.nl
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 400 Bad Request
< content-length: 27
< content-type: application/json; charset=utf-8
< date: Wed, 06 Dec 2017 15:21:44 GMT
< p3p: CP="NON CUR OTPi OUR NOR UNI"
< server: Microsoft-IIS/7.5
< x-aspnetmvc-version: 5.2
< cache-control: no-cache, no-store, max-age=0, must-revalidate
< access-control-allow-origin: *
< x-powered-by: ASP.NET
< x-aspnet-version: 4.0.30319
< pragma: no-cache
< Set-Cookie: PD_STATEFUL_88eb7504-dfe9-11e2-8624-005056af4a32=sandbox.api.online.unit4.nl; Path=/
< Set-Cookie: LB_online_unit4=1493375404.20480.0000; path=/
</code>```

答:
Could be that your variables aren't getting interpolated. With single quotes '#{@variable}' doesn't work. Try switching the single quotes to double quotes ('' => ""). What is happening is that instead of sending the actual client id and secret, you are sending the string #{@client_id}.

Try

```<code>uri = 'https://sandbox.api.online.unit4.nl/V19/OAuth/Token'

  payload = {
    code: params[:code],
    client_id: @client_id,
    client_secret: @client_secret,
    redirect_uri: @client_redirect_url,
    grant_type: 'authorization_code'
  }

  response = RestClient::Request.execute(method: :post, url: uri, headers: {params: payload})
</code>```

Body:
I'm using rest-client to make a post request to a certain address. Unfortunately rest-client keeps correcting the web adres from 'https' to 'http'. Which then gives back an error.

I already looked at the documentation whether this maybe was a setting for the gem. Anyone knows how I can 'force' rest-client to access the desired address.

Thx in advance!

used code is:

  uri = 'https://sandbox.api.online.unit4.nl/V19/OAuth/Token'

  payload = {
    code: params[:code],
    client_id: '#{@client_id}',
    client_secret: '#{@client_secret}',
    redirect_uri: '#{@client_redirect_url}',
    grant_type: 'authorization_code'
  }

  response = RestClient::Request.execute(method: :post, url: uri,      headers: {params: payload})

curl:

> GET /V19/OAuth/Token HTTP/1.1
> Host: sandbox.api.online.unit4.nl
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 400 Bad Request
< content-length: 27
< content-type: application/json; charset=utf-8
< date: Wed, 06 Dec 2017 15:21:44 GMT
< p3p: CP="NON CUR OTPi OUR NOR UNI"
< server: Microsoft-IIS/7.5
< x-aspnetmvc-version: 5.2
< cache-control: no-cache, no-store, max-age=0, must-revalidate
< access-control-allow-origin: *
< x-powered-by: ASP.NET
< x-aspnet-version: 4.0.30319
< pragma: no-cache
< Set-Cookie: PD_STATEFUL_88eb7504-dfe9-11e2-8624-005056af4a32=sandbox.api.online.unit4.nl; Path=/
< Set-Cookie: LB_online_unit4=1493375404.20480.0000; path=/

Body:
Could be that your variables aren't getting interpolated. With single quotes '#{@variable}' doesn't work. Try switching the single quotes to double quotes ('' => ""). What is happening is that instead of sending the actual client id and secret, you are sending the string #{@client_id}.

Try

uri = 'https://sandbox.api.online.unit4.nl/V19/OAuth/Token'

  payload = {
    code: params[:code],
    client_id: @client_id,
    client_secret: @client_secret,
    redirect_uri: @client_redirect_url,
    grant_type: 'authorization_code'
  }

  response = RestClient::Request.execute(method: :post, url: uri, headers: {params: payload})


问:
How to turn flashlight ON and OFF in swift?
I'd like to add flashlight functionality to my app in Swift. How can I go about doing that?</p>

答:
For xcode 9.1, swift 4 (updated to not crash if no torch):</p>

```<code>   func toggleFlash() {
    let device = AVCaptureDevice.default(for: AVMediaType.video)

    if (device != nil) {
        if (device!.hasTorch) {
            do {
                try device!.lockForConfiguration()
                    if (device!.torchMode == AVCaptureDevice.TorchMode.on) {
                        device!.torchMode = AVCaptureDevice.TorchMode.off
                    } else {
                        do {
                            try device!.setTorchModeOn(level: 1.0)
                            } catch {
                                print(error)
                            }
                    }

                    device!.unlockForConfiguration()
            } catch {
                print(error)
            }
        }
    }
}
</code>```

Body:
For xcode 9.1, swift 4 (updated to not crash if no torch):

   func toggleFlash() {
    let device = AVCaptureDevice.default(for: AVMediaType.video)

    if (device != nil) {
        if (device!.hasTorch) {
            do {
                try device!.lockForConfiguration()
                    if (device!.torchMode == AVCaptureDevice.TorchMode.on) {
                        device!.torchMode = AVCaptureDevice.TorchMode.off
                    } else {
                        do {
                            try device!.setTorchModeOn(level: 1.0)
                            } catch {
                                print(error)
                            }
                    }

                    device!.unlockForConfiguration()
            } catch {
                print(error)
            }
        }
    }
}


答:
I would create consistency by converting the single object into an array containing that object:</p>

```<code>obj.Commodity.CommodityInMarket =
  [].concat(obj.Commodity.CommodityInMarket);
</code>```

Title: How can I check if this object into a JSON document is a simple object or an array using JavaScript?

Body:
I would create consistency by converting the single object into an array containing that object:

obj.Commodity.CommodityInMarket =
  [].concat(obj.Commodity.CommodityInMarket);


问:
Burger button not centering on navigation bar?
This is my code.

<!DOCTYPE HTML>

        <title>Personal Portfolio</title>
            <meta name="viewport" content="width=device-width, initial-scale=1">

            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

        <!- Navbar-->

            <button class="navbar-toggler navbar-toggler-right my-sm-0" type="button" data-toggle="collapse" data-target="#mainNav" aria-controls="mainNav" aria-expanded="false" aria-label="Toggle navigation">

            </button>

                        About

                        Portfolio

                        Contact

```

When the window is full size, all the links are center aligned.But when I make the window smaller, the burger icon does not align to the center of the navbar. How do I resolve this?

答:
.navbar-toggler-right {
position: absolute;
left: 50% !important;
top: 15px;
transform: translate(-50%,-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
        <head>
            <title>Personal Portfolio</title>
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
                <script src="/js/my.js"></script>
                <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
                <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
        </head>
        <body data-spy="scroll" data-target=".navbar" data-offset="100">
            <!- Navbar-->
            <nav class="navbar navbar-toggleable-sm navbar-light" style="background-color:purple;">
                <button class="navbar-toggler navbar-toggler-right my-sm-0" type="button" data-toggle="collapse" data-target="#mainNav" aria-controls="mainNav" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>

                    <img src="qlip.png" style="height:60px;">

                <div class="collapse navbar-collapse" id="mainNav">
                    <ul class="navbar-nav ml-auto">
                        <li class="nav-item">
                            About
                        </li>
                        <li class="nav-item">
                            Portfolio
                        </li>
                        <li class="nav-item">
                            Contact
                        </li>
                    </ul>
                </div>
            </nav>
        </body>
    </html></code>```

Body:
This is my code.

<!DOCTYPE HTML>

        <title>Personal Portfolio</title>
            <meta name="viewport" content="width=device-width, initial-scale=1">

            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

        <!- Navbar-->

            <button class="navbar-toggler navbar-toggler-right my-sm-0" type="button" data-toggle="collapse" data-target="#mainNav" aria-controls="mainNav" aria-expanded="false" aria-label="Toggle navigation">

            </button>

                        About

                        Portfolio

                        Contact

When the window is full size, all the links are center aligned.But when I make the window smaller, the burger icon does not align to the center of the navbar. How do I resolve this?

Body:
.navbar-toggler-right {
position: absolute;
left: 50% !important;
top: 15px;
transform: translate(-50%,-50%);
}

<html>
        <head>
            <title>Personal Portfolio</title>
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
                <script src="/js/my.js"></script>
                <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
                <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
        </head>
        <body data-spy="scroll" data-target=".navbar" data-offset="100">
            <!- Navbar-->
            <nav class="navbar navbar-toggleable-sm navbar-light" style="background-color:purple;">
                <button class="navbar-toggler navbar-toggler-right my-sm-0" type="button" data-toggle="collapse" data-target="#mainNav" aria-controls="mainNav" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <a class="navber-brand" href="#">
                    <img src="qlip.png" style="height:60px;">
                </a>
                <div class="collapse navbar-collapse" id="mainNav">
                    <ul class="navbar-nav ml-auto">
                        <li class="nav-item">
                            <a class="nav-link" href="#">About</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#">Portfolio</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#">Contact</a>
                        </li>
                    </ul>
                </div>
            </nav>
        </body>
    </html>


问:
How to NOT download artifacts from previous stages for build configuration?
I have a gitlab CI build process with 4 steps, in which artifacts produced in first step are packaged into docker image in 2nd step, then the output image is given as the artifact to 3rd step, and there is a 4th step afterwards, that notifies external service.

The 2nd step needs artifacts from step 1, the 3rd step need artifacts from step 2. This is done with 'dependencies'parameter and it works fine.

What is not working is the step 4, that need no artifacts. I've skipped the 'dependencies' block, then I've declared dependencies: [], but in both cases the both artifacts are downloaded!

How do I correct inform gitlab CI that the step has no dependencies? Or is it some bug in Gitlab CI?

答:
As per the gitlab-ci documentation:

```<code>To disable artifact passing, define the job with empty dependencies:

job:
  stage: build
  script: make build
  dependencies: []
</code>```

I've found the same issue here: https://gitlab.com/gitlab-org/gitlab-runner/issues/228

This seems to be fixed in: https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/10359

Please update your CI Runner to a newer version as that should fix it.

Body:
As per the gitlab-ci documentation:

To disable artifact passing, define the job with empty dependencies:

job:
  stage: build
  script: make build
  dependencies: []

I've found the same issue here: https://gitlab.com/gitlab-org/gitlab-runner/issues/228

This seems to be fixed in: https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/10359

Please update your CI Runner to a newer version as that should fix it.


问:
Papa Parse single column error Unable to auto-detect delimiting character; defaulted to ','
I have a csv where only one column exists and I am using Papa Parse library to parse the csv.
I receive the following error Unable to auto-detect delimiting character; defaulted to ','

Since it is only a single column it is not comma separated value. I tried to set delimeter config property to auto delimiter: "", but still the same problem

答: If you set it to a single space delimiter:" " it will parse.


问:
Count number of Special Character in Unix Shell
I have a delimited file that is separated by octal \036 or Hexadecimal value 1e.

I need to count the number of delimiters on each line using a bash shell script.

I was trying to use awk, not sure if this is the best way.

Sample Input (| is a representation of \036)

```<code>Example|Running|123|
</code>```

Expected output:

```<code>3
</code>```

答:
This should work for you:

```<code>awk -F '\036' '{print NF-1}' file

3
</code>```

-F '\036' sets input field delimiter as octal value 036

Body:
I have a delimited file that is separated by octal \036 or Hexadecimal value 1e.

I need to count the number of delimiters on each line using a bash shell script.

I was trying to use awk, not sure if this is the best way.

Sample Input (| is a representation of \036)

Example|Running|123|

Expected output:

3

Body:
This should work for you:

awk -F '\036' '{print NF-1}' file

3

-F '\036' sets input field delimiter as octal value 036


问:
Spring Boot Map with Map Key
I am trying to create a

```<code>Map<String,Map<Map<String,String>,String>> properties2
</code>```

as a configurable property with Spring Boot properties file.

I have been previously been able to get a :

```<code>Map<String, Map<String,String>> properties
</code>```

populated with

```<code>properties.[A].B=C
</code>```

where A is the first key and B the second key with a value of C.

I have already tried

```<code>properties2.[A].[B=C]=D
</code>```

which doesn't allow the later components to start although it doesn't throw errors

Does anyone know how I can populate the properties2 map correctly?

答:
you can nest properties as following

```<code>private final Map<String, Map<String, Map<String, String>>> namespace = new HashMap<>();

namespace.[foo].[bar].a=alpha
</code>```

May be you have error here Map,String>> properties2

```<code>as you you're using Map<String,String> as as key try this instead Map<String, Map<String, Map<String, String>>>
</code>```

Title: Spring Boot Map with Map Key

Body:
I am trying to create a

Map<String,Map<Map<String,String>,String>> properties2

as a configurable property with Spring Boot properties file.

I have been previously been able to get a :

Map<String, Map<String,String>> properties

populated with

properties.[A].B=C

where A is the first key and B the second key with a value of C.

I have already tried

properties2.[A].[B=C]=D

which doesn't allow the later components to start although it doesn't throw errors

Does anyone know how I can populate the properties2 map correctly?

Body:
you can nest properties as following

private final Map<String, Map<String, Map<String, String>>> namespace = new HashMap<>();

namespace.[foo].[bar].a=alpha

May be you have error here Map,String>> properties2

as you you're using Map<String,String> as as key try this instead Map<String, Map<String, Map<String, String>>>


问:
Returning game object on start position

Hi guys,
I am working in Unity (C#) and I have a problem. I have a cube called littleOne that is falling down from start position and another cube that destroys the first cube OnTriggerEnter. When the first cube collides with "destroyer" cube, I want to bring it back to the start position. All game objects are attached correctly to the script. This is my solution:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DestroyObject : MonoBehaviour
{
    public GameObject littleOne;

    public Vector3 startPoint;

    void Start()
    {
        startPoint = littleOne.transform.position;
    }

    // Update is called once per frame
    void Update()
    {
    }

    private void OnTriggerEnter(Collider other)
    {
        if(other.gameObject.name == "littleOne") {
            other.gameObject.transform.position = startPoint; //*not working
            //littleOne.transform.position = startPoint; //*not Working
        }
    }
}
</code>```

Lines that has symbol * does nothing, well with these lines I have a problem. I was searching for solution and I tried this way, but nothing happens.

EDIT: PROBLEM SOLVED: I have solved the problem. This code I have moved to a script with falling operation. It was issue in multiple related script to a object. Thank you for recommendations!

答:
Other object and littleOne are referring to the same object which you are destroying:

Dont destroy it:

```<code>private void OnTriggerEnter(Collider other)
{
    if(other.gameObject.name == "littleOne")
    {
        littleOne.transform.position = startPoint;
    }
}
</code>```

Title: Returning game object on start position

Body:
Hi guys,
I am working in Unity (C#) and I have a problem. I have a cube called littleOne that is falling down from start position and another cube that destroys the first cube OnTriggerEnter. When the first cube collides with "destroyer" cube, I want to bring it back to the start position. All game objects are attached correctly to the script. This is my solution:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DestroyObject : MonoBehaviour
{
    public GameObject littleOne;

    public Vector3 startPoint;

    void Start()
    {
        startPoint = littleOne.transform.position;
    }

    // Update is called once per frame
    void Update()
    {
    }

    private void OnTriggerEnter(Collider other)
    {
        if(other.gameObject.name == "littleOne") {
            other.gameObject.transform.position = startPoint; //*not working
            //littleOne.transform.position = startPoint; //*not Working
        }
    }
}

Lines that has symbol * does nothing, well with these lines I have a problem. I was searching for solution and I tried this way, but nothing happens.

EDIT: PROBLEM SOLVED: I have solved the problem. This code I have moved to a script with falling operation. It was issue in multiple related script to a object. Thank you for recommendations!

Body:
Other object and littleOne are referring to the same object which you are destroying:

Dont destroy it:

private void OnTriggerEnter(Collider other)
{
    if(other.gameObject.name == "littleOne")
    {
        littleOne.transform.position = startPoint;
    }
}


问:
Windows Client vs Web Client
I have a discussion going on in the organisation where I am employed as a consultant.
The discussion revolves around the replacement of an application built using VB6(MDI) thick client.

This application has around 100 screen + 40 reports. Used by approx 400 users the reports and the data are pulled using inline queries while the db structure is pretty normalized. the rest of the code is pretty bad.

While discussing replenishment strategies we are throwing around a few ideas.

J2EE Web application running on Web sphere using Crystal reports for Reports.

ASP.NET web forms web application using crystal reports for reports.

Windows Client application (WPF/Win-forms) with reporting services for  the reports.

While I don't want to start a flame war (Dot net vs. Java or WEb vs. Desktop) it would be nice to know the community thoughts on the matter.
Just to be upfront I feel that option 3 maybe the best version, but I would like to know the opinions of others.

答:
From a deployment and support perspective, 1 or 2: no client install needed.

I'd suggest Winforms only if you need complex presentation or flow that would be hard to capture in a web page. That said, there is Flash and Silverlight etc for that...

Title: Windows Client vs Web Client

ContentLicense: CC BY-SA 2.5


问:
Get unique from list as values in Pandas python
I have a dataframe with more rows and columns but example with one is here: </p>

```<code>id    values
1   [v1, v2, v1]
</code>```

<p>How to get unique values from list in pandas column?
Desired output in second column v1, v2
I have tried with df['values'].unique() but obviously it's not working. </p>

答:
Try

```<code>df['values'] = df['values'].apply(lambda x: list(set(x)))

    id  values
0   1   [v2, v1]
</code>```

Note: values is a pandas attribute so its better to avoid using that as column name.

Time comparison:

```<code>df= pd.DataFrame({'id':[1]*1000,    'values' :[['v1', 'v2', 'v1']]*1000})
%timeit df['values'].agg(np.unique)

34.7 ms ± 2.01 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit df['values'].apply(lambda x: list(set(x)))

1.98 ms ± 259 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

Body:
I have a dataframe with more rows and columns but example with one is here:

id    values
1   [v1, v2, v1]

How to get unique values from list in pandas column?
Desired output in second column v1, v2
I have tried with df['values'].unique() but obviously it's not working.

Body:
Try

df['values'] = df['values'].apply(lambda x: list(set(x)))

    id  values
0   1   [v2, v1]

Note: values is a pandas attribute so its better to avoid using that as column name.

Time comparison:

df= pd.DataFrame({'id':[1]*1000,    'values' :[['v1', 'v2', 'v1']]*1000})
%timeit df['values'].agg(np.unique)

34.7 ms ± 2.01 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit df['values'].apply(lambda x: list(set(x)))

1.98 ms ± 259 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


问:
near "-": syntax error Error inserting {Variables and Parameters} while compiling: INSERT INTO {table-name} (database fields) VALUES (?,?,?,?,?,?,?)

In this activity, we can enter information of a school's test, and add it to others one.

Test.java :

```<code>package com.example.amirmasoudfallahi.testcorrector;

import android.content.ContentValues;
import android.database.Cursor;

/**
 * Created by AmirMasoud Fallahi on 11/18/2017.
 */

public class Test {

  public static final String KEY_ID = "id";
  public static final String KEY_NAME = "name";
  public static final String KEY_SCHOOL_NAME = "schName";
  public static final String KEY_QUESTION_NUM = "quesNum";
  public static final String KEY_PARTICIPANT_NUM = "participantNum";
  public static final String KEY_QUALITY_MARK = "qualityMark";
  public static final String KEY_LESSON_NUM = "lessonNum";

  private int testID;
  private String testName;
  private String schName;
  private int quesNum;
  private int participantNum;
  private float qualityMark = 0;
  private int lessonNum;

  public int getLessonNum() {
    return lessonNum;
  }

  public void setLessonNum(int lessonNum) {
    this.lessonNum = lessonNum;
  }

  public String getName() {
    return testName;
  }

  public void setName(String name) {
    this.testName = name;
  }

  public String getSchName() {
    return schName;
  }

  public void setSchName(String schName) {
    this.schName = schName;
  }

  public int getQuesNum() {
    return quesNum;
  }

  public void setQuesNum(int quesNum) {
    this.quesNum = quesNum;
  }

  public int getParticipantNum() {
    return participantNum;
  }

  public void setParticipantNum(int participantNum) {
    this.participantNum = participantNum;
  }

  public float getQualityMark() {
    return qualityMark;
  }

  public void setQualityMark(float qualityMark) {
    this.qualityMark = qualityMark;
  }

  public int getId() {
    return testID;
  }

  public void setId(int id) {
    this.testID = id;
  }

  @Override
  public String toString() {
    return testName;
  }

  public ContentValues getContentValuesForDb(){
    ContentValues values = new ContentValues();
    values.put(Test.KEY_ID, testID);
    values.put(Test.KEY_NAME, testName);
    values.put(Test.KEY_SCHOOL_NAME, schName);
    values.put(Test.KEY_QUESTION_NUM, quesNum);
    values.put(Test.KEY_LESSON_NUM, lessonNum);
    values.put(Test.KEY_QUALITY_MARK, qualityMark);
    values.put(Test.KEY_PARTICIPANT_NUM, participantNum);
    return values;
  }

  public static Test cursorToTest(Cursor cursor){
    Test test = new Test();
    test.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
    test.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
    test.setQuesNum(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_NUM)));
    test.setParticipantNum(cursor.getInt(cursor.getColumnIndex(KEY_PARTICIPANT_NUM)));
    test.setSchName(cursor.getString(cursor.getColumnIndex(KEY_SCHOOL_NAME)));
    test.setQualityMark(cursor.getInt(cursor.getColumnIndex(KEY_QUALITY_MARK)));
    test.setLessonNum(cursor.getInt(cursor.getColumnIndex(KEY_LESSON_NUM)));
    return test;
  }

}
</code>```

TestDbHelper.java :

```<code>package com.example.amirmasoudfallahi.testcorrector;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by AmirMasoud Fallahi on 11/20/2017.
 */

public class TestDBHelper extends SQLiteOpenHelper {

  private static final String DB_NAME = "test-db";
  private static final int DB_VERSION = 1;

  public static final String TABLE_TESTS = "tb-tests";
  private static final String CMD =
    "CREATE TABLE IF NOT EXISTS '" + TABLE_TESTS + "' ('" +
      Test.KEY_ID + "' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, '" +
      Test.KEY_NAME + "' TEXT, '" +
      Test.KEY_SCHOOL_NAME + "' TEXT, '" +
      Test.KEY_QUESTION_NUM + "' INTEGER, '" +
      Test.KEY_LESSON_NUM + "' INTEGER, '" +
      Test.KEY_QUALITY_MARK + "' REAL, '" +
      Test.KEY_PARTICIPANT_NUM + "' INTEGER " +
      ")";

  private static final String[] allColumns = {Test.KEY_ID, Test.KEY_NAME, Test.KEY_SCHOOL_NAME,
    Test.KEY_QUESTION_NUM, Test.KEY_PARTICIPANT_NUM, Test.KEY_QUALITY_MARK, Test.KEY_LESSON_NUM};

  public TestDBHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    db.execSQL(CMD);
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_TESTS);
    onCreate(db);
  }

  public void insetItem(Test test) {
//    if(getTests(Test.KEY_ID + " = " + test.getId()).isEmpty()) {
    SQLiteDatabase db = getWritableDatabase();
    long insertId = db.insert(TABLE_TESTS, null, test.getContentValuesForDb());
    if(insertId == -1) {
      Log.i("TestDbHelper", "data insertion failed. (item : " + test.toString() + ")");
    } else {
      Log.i("TestDbHelper", "data inserted with id : " + insertId);
    }
    if(db.isOpen()) db.close();
//    }
  }

  public List<Test> getTests(String selection){
    SQLiteDatabase db = getReadableDatabase();
    List<Test> testList = new ArrayList<>();

    Cursor cursor = db.query(TABLE_TESTS, allColumns, selection, null, null, null, null);
    if(cursor.moveToFirst()){
      do{
        Test test = Test.cursorToTest(cursor);
        testList.add(test);
      } while (cursor.moveToNext());
    }
    cursor.close();
    if(db.isOpen()) db.close();
    return testList;
  }

}
</code>```

DefineTestActivity.java :

```<code>package com.example.amirmasoudfallahi.testcorrector;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class DefineTestActivity extends AppCompatActivity {

  TestDBHelper dbHelper;
  EditText inputTestName, inputSchName, inputPrtNum, inputQuesNum, inputLessNum;
  Button subTest;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_define_test);

    dbHelper = new TestDBHelper(this);

    inputTestName = (EditText) findViewById(R.id.txt_testNameIn);
    inputSchName = (EditText) findViewById(R.id.txt_schNameIn);
    inputPrtNum = (EditText) findViewById(R.id.txt_prtcpntNumIn);
    inputQuesNum = (EditText) findViewById(R.id.txt_testQuesNumIn);
    inputLessNum = (EditText) findViewById(R.id.txt_lessNum);
    subTest = (Button) findViewById(R.id.btn_createTestSubmit);

    subTest.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Test test = new Test();
        test.setName(inputTestName.getText().toString().trim());
        test.setSchName(inputSchName.getText().toString().trim());
        test.setQuesNum(Integer.parseInt(inputQuesNum.getText().toString().trim()));
        test.setParticipantNum(Integer.parseInt(inputPrtNum.getText().toString().trim()));
        test.setLessonNum(Integer.parseInt(inputLessNum.getText().toString().trim()));

        dbHelper.insetItem(test);

        Intent intent = new Intent(DefineTestActivity.this, AnswerKeysActivity.class);
        intent.putExtra("lessonNum", test.getLessonNum());
        startActivity(intent);
      }
    });
  }
}
</code>```

Activity Preview:

this is my activity preview

in this case, I'm entering information of new Test to be added to Tests list.
when I press the button it should add a new Test to test's table in database.
as you see, in this line it should add it:

```<code>dbHelper.insetItem(test);
</code>```

is insert function, in this line:

```<code>long insertId = db.insert(TABLE_TESTS, null, test.getContentValuesForDb());
</code>```

it should add it and return a non -1 .
but it return -1, it shows our insertion did failed.

but as you see in Test class, the getContentValuesForDb() function has implemented correctly.

It shows this error:

```<code>12-06 14:27:26.034 15344-15344/com.example.amirmasoudfallahi.testcorrector E/SQLiteLog: (1) near "-": syntax error
12-06 14:27:26.034 15344-15344/com.example.amirmasoudfallahi.testcorrector E/SQLiteDatabase: Error inserting participantNum=34 quesNum=123 id=0 schName=wew qualityMark=0.0 name=hghg lessonNum=4
                                                                                android.database.sqlite.SQLiteException: near "-": syntax error (code 1): , while compiling: INSERT INTO tb-tests(participantNum,quesNum,id,schName,qualityMark,name,lessonNum) VALUES (?,?,?,?,?,?,?)
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                                at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1472)
                                                                                at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1343)
                                                                                at com.example.amirmasoudfallahi.testcorrector.TestDBHelper.insetItem(TestDBHelper.java:56)
                                                                                at com.example.amirmasoudfallahi.testcorrector.DefineTestActivity$1.onClick(DefineTestActivity.java:40)
                                                                                at android.view.View.performClick(View.java:5637)
                                                                                at android.view.View$PerformClick.run(View.java:22429)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

And I actually don't know why it shows this Error. I googled so much and any solution doesn't solve that.

Can anyone be my saving angle??!

答:
The name of the table in the INSERT statement is not a valid SQL identifier due to the hyphen ('-'). The hyphen is not allowed in an unquoted SQL identifier (such as a table name).  It is interpreted as a minus sign instead. Only letters, the underscore, and decimal digits (except in first position) are allowed in unquoted SQL names.  Two possible solutions:

Choose a different name for tb-tests that doesn't include a hyphen. E.g. tb_tests.

Quote the name using in the double quotation marks. e.g. "tb-tests".  The quotation marks are not part of the name, but set it apart and allow the name to be parsed correctly.  This also makes the name case sensitive ("tb-tests" <> "TB-TESTS").

Body:
In this activity, we can enter information of a school's test, and add it to others one.

Test.java :

package com.example.amirmasoudfallahi.testcorrector;

import android.content.ContentValues;
import android.database.Cursor;

/**
 * Created by AmirMasoud Fallahi on 11/18/2017.
 */

public class Test {

  public static final String KEY_ID = "id";
  public static final String KEY_NAME = "name";
  public static final String KEY_SCHOOL_NAME = "schName";
  public static final String KEY_QUESTION_NUM = "quesNum";
  public static final String KEY_PARTICIPANT_NUM = "participantNum";
  public static final String KEY_QUALITY_MARK = "qualityMark";
  public static final String KEY_LESSON_NUM = "lessonNum";

  private int testID;
  private String testName;
  private String schName;
  private int quesNum;
  private int participantNum;
  private float qualityMark = 0;
  private int lessonNum;

  public int getLessonNum() {
    return lessonNum;
  }

  public void setLessonNum(int lessonNum) {
    this.lessonNum = lessonNum;
  }

  public String getName() {
    return testName;
  }

  public void setName(String name) {
    this.testName = name;
  }

  public String getSchName() {
    return schName;
  }

  public void setSchName(String schName) {
    this.schName = schName;
  }

  public int getQuesNum() {
    return quesNum;
  }

  public void setQuesNum(int quesNum) {
    this.quesNum = quesNum;
  }

  public int getParticipantNum() {
    return participantNum;
  }

  public void setParticipantNum(int participantNum) {
    this.participantNum = participantNum;
  }

  public float getQualityMark() {
    return qualityMark;
  }

  public void setQualityMark(float qualityMark) {
    this.qualityMark = qualityMark;
  }

  public int getId() {
    return testID;
  }

  public void setId(int id) {
    this.testID = id;
  }

  @Override
  public String toString() {
    return testName;
  }

  public ContentValues getContentValuesForDb(){
    ContentValues values = new ContentValues();
    values.put(Test.KEY_ID, testID);
    values.put(Test.KEY_NAME, testName);
    values.put(Test.KEY_SCHOOL_NAME, schName);
    values.put(Test.KEY_QUESTION_NUM, quesNum);
    values.put(Test.KEY_LESSON_NUM, lessonNum);
    values.put(Test.KEY_QUALITY_MARK, qualityMark);
    values.put(Test.KEY_PARTICIPANT_NUM, participantNum);
    return values;
  }

  public static Test cursorToTest(Cursor cursor){
    Test test = new Test();
    test.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
    test.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
    test.setQuesNum(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_NUM)));
    test.setParticipantNum(cursor.getInt(cursor.getColumnIndex(KEY_PARTICIPANT_NUM)));
    test.setSchName(cursor.getString(cursor.getColumnIndex(KEY_SCHOOL_NAME)));
    test.setQualityMark(cursor.getInt(cursor.getColumnIndex(KEY_QUALITY_MARK)));
    test.setLessonNum(cursor.getInt(cursor.getColumnIndex(KEY_LESSON_NUM)));
    return test;
  }

}

TestDbHelper.java :

package com.example.amirmasoudfallahi.testcorrector;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by AmirMasoud Fallahi on 11/20/2017.
 */

public class TestDBHelper extends SQLiteOpenHelper {

  private static final String DB_NAME = "test-db";
  private static final int DB_VERSION = 1;

  public static final String TABLE_TESTS = "tb-tests";
  private static final String CMD =
    "CREATE TABLE IF NOT EXISTS '" + TABLE_TESTS + "' ('" +
      Test.KEY_ID + "' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, '" +
      Test.KEY_NAME + "' TEXT, '" +
      Test.KEY_SCHOOL_NAME + "' TEXT, '" +
      Test.KEY_QUESTION_NUM + "' INTEGER, '" +
      Test.KEY_LESSON_NUM + "' INTEGER, '" +
      Test.KEY_QUALITY_MARK + "' REAL, '" +
      Test.KEY_PARTICIPANT_NUM + "' INTEGER " +
      ")";

  private static final String[] allColumns = {Test.KEY_ID, Test.KEY_NAME, Test.KEY_SCHOOL_NAME,
    Test.KEY_QUESTION_NUM, Test.KEY_PARTICIPANT_NUM, Test.KEY_QUALITY_MARK, Test.KEY_LESSON_NUM};

  public TestDBHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    db.execSQL(CMD);
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_TESTS);
    onCreate(db);
  }

  public void insetItem(Test test) {
//    if(getTests(Test.KEY_ID + " = " + test.getId()).isEmpty()) {
    SQLiteDatabase db = getWritableDatabase();
    long insertId = db.insert(TABLE_TESTS, null, test.getContentValuesForDb());
    if(insertId == -1) {
      Log.i("TestDbHelper", "data insertion failed. (item : " + test.toString() + ")");
    } else {
      Log.i("TestDbHelper", "data inserted with id : " + insertId);
    }
    if(db.isOpen()) db.close();
//    }
  }

  public List<Test> getTests(String selection){
    SQLiteDatabase db = getReadableDatabase();
    List<Test> testList = new ArrayList<>();

    Cursor cursor = db.query(TABLE_TESTS, allColumns, selection, null, null, null, null);
    if(cursor.moveToFirst()){
      do{
        Test test = Test.cursorToTest(cursor);
        testList.add(test);
      } while (cursor.moveToNext());
    }
    cursor.close();
    if(db.isOpen()) db.close();
    return testList;
  }

}

DefineTestActivity.java :

package com.example.amirmasoudfallahi.testcorrector;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class DefineTestActivity extends AppCompatActivity {

  TestDBHelper dbHelper;
  EditText inputTestName, inputSchName, inputPrtNum, inputQuesNum, inputLessNum;
  Button subTest;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_define_test);

    dbHelper = new TestDBHelper(this);

    inputTestName = (EditText) findViewById(R.id.txt_testNameIn);
    inputSchName = (EditText) findViewById(R.id.txt_schNameIn);
    inputPrtNum = (EditText) findViewById(R.id.txt_prtcpntNumIn);
    inputQuesNum = (EditText) findViewById(R.id.txt_testQuesNumIn);
    inputLessNum = (EditText) findViewById(R.id.txt_lessNum);
    subTest = (Button) findViewById(R.id.btn_createTestSubmit);

    subTest.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Test test = new Test();
        test.setName(inputTestName.getText().toString().trim());
        test.setSchName(inputSchName.getText().toString().trim());
        test.setQuesNum(Integer.parseInt(inputQuesNum.getText().toString().trim()));
        test.setParticipantNum(Integer.parseInt(inputPrtNum.getText().toString().trim()));
        test.setLessonNum(Integer.parseInt(inputLessNum.getText().toString().trim()));

        dbHelper.insetItem(test);

        Intent intent = new Intent(DefineTestActivity.this, AnswerKeysActivity.class);
        intent.putExtra("lessonNum", test.getLessonNum());
        startActivity(intent);
      }
    });
  }
}

Activity Preview:

this is my activity preview

in this case, I'm entering information of new Test to be added to Tests list.
when I press the button it should add a new Test to test's table in database.
as you see, in this line it should add it:

dbHelper.insetItem(test);

is insert function, in this line:

long insertId = db.insert(TABLE_TESTS, null, test.getContentValuesForDb());

it should add it and return a non -1 .
but it return -1, it shows our insertion did failed.

but as you see in Test class, the getContentValuesForDb() function has implemented correctly.

It shows this error:

12-06 14:27:26.034 15344-15344/com.example.amirmasoudfallahi.testcorrector E/SQLiteLog: (1) near "-": syntax error
12-06 14:27:26.034 15344-15344/com.example.amirmasoudfallahi.testcorrector E/SQLiteDatabase: Error inserting participantNum=34 quesNum=123 id=0 schName=wew qualityMark=0.0 name=hghg lessonNum=4
                                                                                android.database.sqlite.SQLiteException: near "-": syntax error (code 1): , while compiling: INSERT INTO tb-tests(participantNum,quesNum,id,schName,qualityMark,name,lessonNum) VALUES (?,?,?,?,?,?,?)
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                                at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1472)
                                                                                at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1343)
                                                                                at com.example.amirmasoudfallahi.testcorrector.TestDBHelper.insetItem(TestDBHelper.java:56)
                                                                                at com.example.amirmasoudfallahi.testcorrector.DefineTestActivity$1.onClick(DefineTestActivity.java:40)
                                                                                at android.view.View.performClick(View.java:5637)
                                                                                at android.view.View$PerformClick.run(View.java:22429)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

And I actually don't know why it shows this Error. I googled so much and any solution doesn't solve that.

Can anyone be my saving angle??!


问:
Python weird behaviour List of inherited classes
I am building a speech recognition system and for that I build an interface for the commands. They are made up by subjects, verbs, adjectives and wildcards. I implemented it this way:

```<code>class IWord(object):
    strings = []

    def recognize(self, word):
        return word in self.strings

    def add_synonym(self, word):
        self.strings.append(word)

class Verb(IWord):
    def __init__(self, words):
        for word in words:
            self.add_synonym(word)

class Adjective(IWord):
    def __init__(self, words):
        for word in words:
            self.add_synonym(word)

class Object(IWord):
    def __init__(self, words):
        for word in words:
            self.add_synonym(word)

class WildCard(IWord):
    def recognize(self, word):
        return word is not None & word

class ICommand(object):
    words = []
    parameters = []
</code>```

However I got two classes inheriting from ICommand:

```<code>class Command1(ICommand):

    def __init__(self):
        self.words.append(Verb(['do']))
        self.words.append(Object(['some']))
        self.words.append(WildCard())

class Command1(ICommand):

    def __init__(self):
        self.words.append(Verb(['lorem']))
</code>```

When I am debugging this part:

```<code>for command in self.Commands:
    if command.recognize(text):
        return command
</code>```

It seems like command.words contains 'do', 'some', the wildcard and 'lorem'. I don't get what went wrong there.

答:
self.words is the words attribute of the ICommand class (it is not copied when you inherit). So when you append to that, it will append to it on ICommand, which will affect every class inheriting from it.

Probably, though, a better thing to do would be something like:

```<code>class Command(object):
  def __init__(self, words):
    self.words = words
</code>```

Body:
I am building a speech recognition system and for that I build an interface for the commands. They are made up by subjects, verbs, adjectives and wildcards. I implemented it this way:

class IWord(object):
    strings = []

    def recognize(self, word):
        return word in self.strings

    def add_synonym(self, word):
        self.strings.append(word)

class Verb(IWord):
    def __init__(self, words):
        for word in words:
            self.add_synonym(word)

class Adjective(IWord):
    def __init__(self, words):
        for word in words:
            self.add_synonym(word)

class Object(IWord):
    def __init__(self, words):
        for word in words:
            self.add_synonym(word)

class WildCard(IWord):
    def recognize(self, word):
        return word is not None & word

class ICommand(object):
    words = []
    parameters = []

However I got two classes inheriting from ICommand:

class Command1(ICommand):

    def __init__(self):
        self.words.append(Verb(['do']))
        self.words.append(Object(['some']))
        self.words.append(WildCard())

class Command1(ICommand):

    def __init__(self):
        self.words.append(Verb(['lorem']))

When I am debugging this part:

for command in self.Commands:
    if command.recognize(text):
        return command

It seems like command.words contains 'do', 'some', the wildcard and 'lorem'. I don't get what went wrong there.

Body:
self.words is the words attribute of the ICommand class (it is not copied when you inherit). So when you append to that, it will append to it on ICommand, which will affect every class inheriting from it.

Probably, though, a better thing to do would be something like:

class Command(object):
  def __init__(self, words):
    self.words = words


问:
Cloning multiple arraylists referencing the same objects
I have an arraylist a containing certain objects. I also have an arraylist b containing arraylists containing some of these objects. Now, I want to clone the arraylist a, while updating the references in arraylist b to the cloned objects. A pseudo code example:

```<code>a = [object1,object2,object3,object4,object5,object6,object7,object8,object9,object10];
b = [[object3,object8,object5],[object2,object9,object1][object6,object7]];

//now, I can clone arraylist a
aClone = [clone1,clone2,clone3,clone4,clone5,clone6,clone7,clone8,clone9,clone10];

//but how do I get a clone of arraylist b containing references to the clones of the objects like so:
bClone = [[clone3,clone8,clone5],[clone2,clone9,clone1][clone6,clone7]];
</code>```

Something I came up with is the following:

```<code>for(int i = 0; i < a.length; i++){
    o = a.get(i);
    aClone.set(i, o);
    for(int j = 0; j < b.length){
        for(int k = 0; k < b.get(j).length){
            if(b.get(j).get(k).value() == o.value())
                bClone.get(j).set(k, o);
        }
    }
}
</code>```

This code checks after creating each clone if the old object is present in b, and replaces it with the clone. I imagine this would be extremely slow though, so does anyone know how this could be done more efficiently?

答:
Just create a class like this:

```<code>class CloneRepository {
    private final Map<Object, Object> cloneMap = new HashMap<Object, Object>();

    public Object getClone(Object source) {
        Object result = cloneMap.get(source);

        if (result == null) {
            result = source.clone();
            cloneMap.put(source, result);
        }

        return result;
    }
}
</code>```

Then create a new CloneRepository(). When you clone the entries in each list, instead of cloning the object, use the getClone() method instead.

Body:
I have an arraylist a containing certain objects. I also have an arraylist b containing arraylists containing some of these objects. Now, I want to clone the arraylist a, while updating the references in arraylist b to the cloned objects. A pseudo code example:

a = [object1,object2,object3,object4,object5,object6,object7,object8,object9,object10];
b = [[object3,object8,object5],[object2,object9,object1][object6,object7]];

//now, I can clone arraylist a
aClone = [clone1,clone2,clone3,clone4,clone5,clone6,clone7,clone8,clone9,clone10];

//but how do I get a clone of arraylist b containing references to the clones of the objects like so:
bClone = [[clone3,clone8,clone5],[clone2,clone9,clone1][clone6,clone7]];

Something I came up with is the following:

for(int i = 0; i < a.length; i++){
    o = a.get(i);
    aClone.set(i, o);
    for(int j = 0; j < b.length){
        for(int k = 0; k < b.get(j).length){
            if(b.get(j).get(k).value() == o.value())
                bClone.get(j).set(k, o);
        }
    }
}

This code checks after creating each clone if the old object is present in b, and replaces it with the clone. I imagine this would be extremely slow though, so does anyone know how this could be done more efficiently?

Body:
Just create a class like this:

class CloneRepository {
    private final Map<Object, Object> cloneMap = new HashMap<Object, Object>();

    public Object getClone(Object source) {
        Object result = cloneMap.get(source);

        if (result == null) {
            result = source.clone();
            cloneMap.put(source, result);
        }

        return result;
    }
}

Then create a new CloneRepository(). When you clone the entries in each list, instead of cloning the object, use the getClone() method instead.


问:
Can an image have a custom default shm-size?
I have a container which must be run with a /dev/shm larger than the default 64Mb.  It works to run it like this:

```<code>docker run --shm-size=1G my-container
</code>```

It is inconvenient though to have to provide the 'shm-size' argument every time, and easily missed for someone not familiar with the container.  It would be nice if the container itself could have a custom default shm size.  Is this possible?

答:
Starting with docker 17.04 you can use --default-shm-size option. But of course it will have global effect

https://github.com/moby/moby/blob/master/CHANGELOG.md#17040-ce-2017-04-05

Body:
I have a container which must be run with a /dev/shm larger than the default 64Mb.  It works to run it like this:

docker run --shm-size=1G my-container

It is inconvenient though to have to provide the 'shm-size' argument every time, and easily missed for someone not familiar with the container.  It would be nice if the container itself could have a custom default shm size.  Is this possible?


问:
Identify MS Excel or MS Access attachments and warn to check contents
Personal identifying information (PII) is often inadvertently transmitted through non-encrypted emails.  Most of the times these data are stored in Excel or Access spreadsheets.

I'd like to identify Access or Excel attachments after hitting send and ask "There are Access or Excel files attached to this email, are you sure these do not contain PII?"

The criteria for identifying "xlsx" or "accdb" in the attachment name I just don't get.

```<code>Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

If Right([attachment_Name],4) = xlsx then

    answer = MsgBox("There are Access or Excel files attached to this email, are you sure these do not contain PHI?",vbYesNo)

    If answer = vbNo
        Cancel = True
    Else

    End If

End If

End Sub
</code>```

答:
You could use the FileSystemObject to grab the extension:

```<code>Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

    Dim olAtt As Attachment
    Dim oFSO As Object
    Dim sExt As String
    Dim bSafe As Boolean

    If Item.Attachments.Count > 0 Then
        bSafe = True
        Set oFSO = CreateObject("Scripting.FileSystemObject")
        For Each olAtt In Item.Attachments
            sExt = oFSO.GetExtensionName(olAtt.FileName)
            If sExt Like "xls*" Or sExt Like "accd*" Or sExt = "mdb" Then
                bSafe = False
                Exit For
            End If
        Next olAtt

        If Not bSafe Then
            If MsgBox("This email contains an Access or Excel file." & vbCr & _
                      "Do you wish to continue?", vbCritical + vbYesNo) = vbNo Then
                Cancel = True
            End If
        End If

        Set oFSO = Nothing

    End If
End Sub
</code>```

I've included for Access, but pretty sure that doesn't send by default.

Body:
Personal identifying information (PII) is often inadvertently transmitted through non-encrypted emails.  Most of the times these data are stored in Excel or Access spreadsheets.

I'd like to identify Access or Excel attachments after hitting send and ask "There are Access or Excel files attached to this email, are you sure these do not contain PII?"

The criteria for identifying "xlsx" or "accdb" in the attachment name I just don't get.

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

If Right([attachment_Name],4) = xlsx then

    answer = MsgBox("There are Access or Excel files attached to this email, are you sure these do not contain PHI?",vbYesNo)

    If answer = vbNo
        Cancel = True
    Else

    End If

End If

End Sub

Body:
You could use the FileSystemObject to grab the extension:

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

    Dim olAtt As Attachment
    Dim oFSO As Object
    Dim sExt As String
    Dim bSafe As Boolean

    If Item.Attachments.Count > 0 Then
        bSafe = True
        Set oFSO = CreateObject("Scripting.FileSystemObject")
        For Each olAtt In Item.Attachments
            sExt = oFSO.GetExtensionName(olAtt.FileName)
            If sExt Like "xls*" Or sExt Like "accd*" Or sExt = "mdb" Then
                bSafe = False
                Exit For
            End If
        Next olAtt

        If Not bSafe Then
            If MsgBox("This email contains an Access or Excel file." & vbCr & _
                      "Do you wish to continue?", vbCritical + vbYesNo) = vbNo Then
                Cancel = True
            End If
        End If

        Set oFSO = Nothing

    End If
End Sub

I've included for Access, but pretty sure that doesn't send by default.


问:
Parallel operation hangs in scala
Scala noob here:
val pv = (1 to 100).toArray.par

Now I want to apply a map function to this parallel collection pv

pv.map(_ * 2)

However the above operation hangs. Any reason why?

Using Scala version 2.12.4 on a Mac OS X (High Sierra)

答:
Seems this is caused by static initializer deadlock, see:

https://github.com/scala/scala-parallel-collections/issues/34

This issue point out in the repl, when create a parallel collection, repl will generate a wraper for it, when init, it will cause dead lock.

and it also can be reproduce in program from the:

https://github.com/scala/bug/issues/8119

```<code>object Foreacher {
  val n = 0
  val m = List(1).par.foreach(_ => n)
  def main(args: Array[String]): Unit = println("Hello, all")
}
</code>```

Title: Parallel operation hangs in scala

Body:
Seems this is caused by static initializer deadlock, see:

https://github.com/scala/scala-parallel-collections/issues/34

This issue point out in the repl, when create a parallel collection, repl will generate a wraper for it, when init, it will cause dead lock.

and it also can be reproduce in program from the:

https://github.com/scala/bug/issues/8119

object Foreacher {
  val n = 0
  val m = List(1).par.foreach(_ => n)
  def main(args: Array[String]): Unit = println("Hello, all")
}