问:
discord.js bot is deleting all messages
I have the following code running in my bot, as a command that deletes cuss words. However, it seems to make the bot delete any message that's sent no matter what! HELP!</p>

```<code>bot.on('message', message => {
    if (message.content.includes == 'bannedWord1' ||'bannedWord2' || 'bannedWord3' || 'bannedWord4') {
       message.delete(1);
       message.channel.send("That word's not appropriate!");
    }
 });
</code>```

答:
Because you're trying to compare pointer to function with expression
string OR string OR string
which always is true so the if executed for each new message

ContentLicense: CC BY-SA 4.0

Title: discord.js bot is deleting all messages

Body:
I have the following code running in my bot, as a command that deletes cuss words. However, it seems to make the bot delete any message that's sent no matter what! HELP!

bot.on('message', message => {
    if (message.content.includes == 'bannedWord1' ||'bannedWord2' || 'bannedWord3' || 'bannedWord4') {
       message.delete(1);
       message.channel.send("That word's not appropriate!");
    }
 });


来源: stackexchange

问:
How can you predict/get the next ChangeSetId before checking in files using TFS SDK
I have a requirement to build a Custom TFS Policy using C# & the TFS 2010 SDK.  This policy would validate that a custom note (bug #) are populated in the TFS Checkin dialog and then update a Bug Tracking system upon successful validation of the bug #.

Once I have the bug # validated, I would then use the Bug Tracking systems SDK to update the bug # with the names of the source files & the ChangeSetID.

The problem i'm having is that it appears the TFS SDK does not provide the functionality to get me the next available ChangeSetID that will be used as part of the checkin.  There doesn't seem to be a way to get this information.  Direct DB Access is not an option (I was thinking about doing something along the lines of SELECT ChangeSetId.nextVal).

Can someone let me know if this is an option with the TFS SDK?  I am trying to update the bug tracking system at the time my Custom Policy runs so I don't have to create another process to update the bug tracking system after the fact.

I added a client event handler for the TFS Server (CommitCheckin event), and i was able to do what i wanted from there.  Is there any problems that I will run into if I do it client side by subscribing to this event?  CommitCheckin

答:
This sounds like it should be two separate things:

A policy to ensure that the bug number is filled in

A custom event handler to handle the check-in event. This will naturally have access to the changeset number, and can update the bug tracking system.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
php remove from array if property value is in another array
I want to remove all elements from arr2 that have a type contained in arr1:

```<code>    arr1 = ['A', 'B', 'C']

    arr2 = [
        [
        'name' => 'jane',
        'type' => 'X'
        ],
        [
        'name' => 'jon',
        'type' => 'B'
        ]
    ]
</code>```

So jon should be removed. Is there some built in function like array_diff?

答:
One of solutions using array_filter:

```<code>print_r(array_filter(
    $arr2,
    function($v) use($arr1) { return !in_array($v['type'], $arr1); }
));
</code>```

Body:
I want to remove all elements from arr2 that have a type contained in arr1:

    arr1 = ['A', 'B', 'C']

    arr2 = [
        [
        'name' => 'jane',
        'type' => 'X'
        ],
        [
        'name' => 'jon',
        'type' => 'B'
        ]
    ]

So jon should be removed. Is there some built in function like array_diff?

Body:
One of solutions using array_filter:

print_r(array_filter(
    $arr2,
    function($v) use($arr1) { return !in_array($v['type'], $arr1); }
));


问:
How to write to a file in tab delimited manner?
So I have this data frame from a bed file called input.bed:

```<code>     V1       V2       V3  V4
 1 chr1 11323785 11617177 TF1
 2 chr1 12645605 13926923 TF2
 3 chr1 14750216 15119039 TF3
 4 chr1 18102157 19080189 TF1
 5 chr1 29491029 30934636 TF2
 6 chr1 33716472 35395979 TF4
 7 chr1 36712462 37685238 TF5
 8 chr1 37838094 38031209 TF3
</code>```

It's a data frame I read from a .bed file (the .bed file is tab delimited). I want to take each row and output it to a different file. Say row1 I want it to be in input1.bed , row 2 in input2.bed

This has been my attempt:

```<code> for(i in 1:nrow(input.bed))
  {
    file.create(paste("input",i,".bed",sep=""));

   }

 for(i in 1:nrow(input.bed))
 {
    write.table(unlist(input.bed[i,]),paste("input",i,".bed",sep=""),sep="\t");

}
</code>```

For some reason the output of my files ,this is from input1.bed, is:

```<code>    "V1"    "chr1"
    "V2"    "11323785"
    "V3"    "11617177"
    "V4"    "TF1"
</code>```

But I want the output to be tab delimited like this:

```<code>    chr1 11323785 11617177 TF1
</code>```

What am I doing wrong?

答:
You can use just one for loop in the following manner (q is your data frame)

```<code>for(i in 1:nrow(q)){
  write.table(x = q[i,],
              file = paste('input',i,'.bed',sep=''),
              row.names = F,
              col.names = F,
              quote = F,
              sep = '\t')
}
</code>```

Basically your approach was correct, you just need to inform the function that you do not want all default behaviors (i.e. col/rownames, quotes).

Body:
So I have this data frame from a bed file called input.bed:

     V1       V2       V3  V4
 1 chr1 11323785 11617177 TF1
 2 chr1 12645605 13926923 TF2
 3 chr1 14750216 15119039 TF3
 4 chr1 18102157 19080189 TF1
 5 chr1 29491029 30934636 TF2
 6 chr1 33716472 35395979 TF4
 7 chr1 36712462 37685238 TF5
 8 chr1 37838094 38031209 TF3

It's a data frame I read from a .bed file (the .bed file is tab delimited). I want to take each row and output it to a different file. Say row1 I want it to be in input1.bed , row 2 in input2.bed

This has been my attempt:

 for(i in 1:nrow(input.bed))
  {
    file.create(paste("input",i,".bed",sep=""));

   }

 for(i in 1:nrow(input.bed))
 {
    write.table(unlist(input.bed[i,]),paste("input",i,".bed",sep=""),sep="\t");

}

For some reason the output of my files ,this is from input1.bed, is:

    "V1"    "chr1"
    "V2"    "11323785"
    "V3"    "11617177"
    "V4"    "TF1"

But I want the output to be tab delimited like this:

    chr1 11323785 11617177 TF1

What am I doing wrong?

Body:
You can use just one for loop in the following manner (q is your data frame)

for(i in 1:nrow(q)){
  write.table(x = q[i,],
              file = paste('input',i,'.bed',sep=''),
              row.names = F,
              col.names = F,
              quote = F,
              sep = '\t')
}

Basically your approach was correct, you just need to inform the function that you do not want all default behaviors (i.e. col/rownames, quotes).


问:
jQuery checkbox won't update
Here's my html:

```<code><tr>
    <td class="tg-031e"><input type="checkbox" name="sel_a" class="a_qual" data-id23="<?php echo $row["id"]; ?>"
    <?php if($row["a_qual"] == 1) { echo "checked='1'"; } ?>
    ></td>
    <td class="a" colspan="2" data-id3="<?php echo $row["id"]; ?>" contenteditable><?php echo $row["a"] ?></td>
</tr>
</code>```

Here's my jQuery:

```<code>$(document).on('change', '.a_qual', function(){
    var id = $(this).data("id23");
    var a_qual = $("input[type='checkbox']").val();
    edit_data(id, a_qual, "a_qual");
    console.log('my message' + a_qual);
});
</code>```

Here's my edit_data function:

```<code>function edit_data(id, text, column_name)
{
    $.ajax({
        url:"edit.php",
        method:"POST",
        data:{id:id, text:text, column_name:column_name},
        dataType:"text",
        success:function(data){
            fetch_data();
        }
    });
}
</code>```

And here's my edit.php:

```<code>include_once("includes/connection.php");
$sql = "UPDATE questions SET ".$_POST['column_name']."='".$_POST['text']."'
WHERE id='".$_POST['id']."'";

// echo $sql;
if(mysqli_query($connection, $sql))
{
    echo 'Data Inserted';
}
</code>```

I don't know what I'm doing well enough to make this work and I'm really stumped after reading dozens of posts across the internet.  For some reason, I can get it to change my database value to "1" and then it gets stuck there.  In my database I have a column named "a_qual" to store the "quality" of the checkbox and it's set to a TINYINT.  Can anyone figure out my problem?

答:
The rules of checkboxes are to send the "value" when it is checked, otherwise send nothing. So to send '0', in case of not selecting the checkbox, needs to be done manually.  By saying this I mean, on your on('change',....) method, please work around a condition to see if the checkbox is checked or not and then based on that set the value of a_qual.

var a_qual = $("input[type='checkbox']").val();

Hope this will help you.

Title: jQuery checkbox won't update

Body:
Here's my html:

    <input type="checkbox" name="sel_a" class="a_qual" data-id23="<?php echo $row["id"]; ?>"
    <?php if($row["a_qual"] == 1) { echo "checked='1'"; } ?>
    >
    <td class="a" colspan="2" data-id3="<?php echo $row["id"]; ?>" contenteditable><?php echo $row["a"] ?>

Here's my jQuery:

$(document).on('change', '.a_qual', function(){
    var id = $(this).data("id23");
    var a_qual = $("input[type='checkbox']").val();
    edit_data(id, a_qual, "a_qual");
    console.log('my message' + a_qual);
});

Here's my edit_data function:

function edit_data(id, text, column_name)
{
    $.ajax({
        url:"edit.php",
        method:"POST",
        data:{id:id, text:text, column_name:column_name},
        dataType:"text",
        success:function(data){
            fetch_data();
        }
    });
}

And here's my edit.php:

include_once("includes/connection.php");
$sql = "UPDATE questions SET ".$_POST['column_name']."='".$_POST['text']."'
WHERE id='".$_POST['id']."'";

// echo $sql;
if(mysqli_query($connection, $sql))
{
    echo 'Data Inserted';
}

I don't know what I'm doing well enough to make this work and I'm really stumped after reading dozens of posts across the internet.  For some reason, I can get it to change my database value to "1" and then it gets stuck there.  In my database I have a column named "a_qual" to store the "quality" of the checkbox and it's set to a TINYINT.  Can anyone figure out my problem?


问:
Find duplicates in two columns in a table
I just browse this post and tried all the scripts but still i am not getting what i am expecting.

Here is my table

```<code>Name        email
BRIAN MAT   BRIAN.MAT@abc.Com
BRIAN MAT   BRIAN MAT@abc.Com
AMY Lee     AMY.Lee@abc.Com
AMY.Lee     AMY.Lee@abc.Com
Madison Taylor  Madison.Tyl@abc.com

SELECT Name
FROM Employee
GROUP BY Name
HAVING ( COUNT(Name > 1 )
</code>```

result

BRIAN MAT

```<code>SELECT email
FROM Employee
GROUP BY email
HAVING ( COUNT(email> 1 )
</code>```

Result

AMY.Lee@abc.Com

I was trying to group this two script but it shows blank

```<code>SELECT
    Name, email,COUNT(*)
FROM
    Employee
GROUP BY
    Name, email
HAVING
    COUNT(*) > 1
</code>```

Please correct me what i am missing in my script to acheive the result like below

```<code>Name        email
BRIAN MAT   BRIAN.MAT@abc.Com
BRIAN MAT   BRIAN MAT@abc.Com
AMY Lee     AMY.Lee@abc.Com
AMY.Lee     AMY.Lee@abc.Com
</code>```

答:
```<code>SELECT *
FROM Employee
WHERE Name IN (SELECT Name
               FROM Employee
               GROUP BY Name
               HAVING COUNT(Name > 1)
              )
   OR Email IN (SELECT email
                FROM Employee
                GROUP BY email
                HAVING COUNT(email> 1)
              )
</code>```

Body:
I just browse this post and tried all the scripts but still i am not getting what i am expecting.

Here is my table

Name        email
BRIAN MAT   BRIAN.MAT@abc.Com
BRIAN MAT   BRIAN MAT@abc.Com
AMY Lee     AMY.Lee@abc.Com
AMY.Lee     AMY.Lee@abc.Com
Madison Taylor  Madison.Tyl@abc.com

SELECT Name
FROM Employee
GROUP BY Name
HAVING ( COUNT(Name > 1 )

result

BRIAN MAT

SELECT email
FROM Employee
GROUP BY email
HAVING ( COUNT(email> 1 )

Result

AMY.Lee@abc.Com

I was trying to group this two script but it shows blank

SELECT
    Name, email,COUNT(*)
FROM
    Employee
GROUP BY
    Name, email
HAVING
    COUNT(*) > 1

Please correct me what i am missing in my script to acheive the result like below

Name        email
BRIAN MAT   BRIAN.MAT@abc.Com
BRIAN MAT   BRIAN MAT@abc.Com
AMY Lee     AMY.Lee@abc.Com
AMY.Lee     AMY.Lee@abc.Com


问:
"ValueError: setting an array element with a sequence" - When trying to feed list into placeholder in feed_dict
I must admit I am a beginner, but I could not find an answer to my question on any questions asked in StackOverflow or Github. Please do help

The Error:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-33-a9ebf2ee96c3> in <module>()
     19             _, c = sess.run([train_op, loss_op], feed_dict={v_u: np.array(onehot_user),
     20                                                             v_i: np.array(onehot_item),
---> 21                                                             label:label_list})
     22             # Compute average loss
     23             avg_cost += c / total_batch

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    893     try:
    894       result = self._run(None, fetches, feed_dict, options_ptr,
--> 895                          run_metadata_ptr)
    896       if run_metadata:
    897         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1091             feed_handles[subfeed_t] = subfeed_val
   1092           else:
-> 1093             np_val = np.asarray(subfeed_val, dtype=subfeed_dtype)
   1094
   1095           if (not is_tensor_handle_feed and

~/anaconda3/lib/python3.6/site-packages/numpy/core/numeric.py in asarray(a, dtype, order)
    529
    530     """
--> 531     return array(a, dtype, copy=False, order=order)
    532
    533

ValueError: setting an array element with a sequence.

# Loading data
t1 = time()
dataset = Dataset("/Users/shishir/Documents/botconnect_Playground/NCF_Prototype/Data/ml-1m")
train, testRatings, testNegatives = dataset.trainMatrix, dataset.testRatings, dataset.testNegatives
num_users, num_items = train.shape
print("Load data done [%.1f s]. #user=%d, #item=%d, #train=%d, #test=%d"
      %(time()-t1, num_users, num_items, train.nnz, len(testRatings)))
</code>```

"Train" is a Matrix that looks like:[(user_id,item_id) implicit_rating....]

```<code>[  (0, 0)   1.0
  (0, 1)    1.0
  (0, 2)    1.0
  (0, 3)    1.0
  (0, 4)    1.0
  (0, 5)    1.0
  (0, 6)    1.0
  (0, 7)    1.0
  (0, 8)    1.0
  (0, 9)    1.0
  (0, 10)   1.0
  (0, 11)   1.0
  (0, 12)   1.0
  (0, 13)   1.0
  (0, 14)   1.0
  (0, 15)   1.0
  (0, 16)   1.0
  (0, 17)   1.0
  (0, 18)   1.0
  (0, 19)   1.0
  (0, 20)   1.0
  (0, 21)   1.0
  (0, 22)   1.0
  (0, 23)   1.0
  (0, 24)   1.0
  : :
  (0, 28)   1.0
  (0, 29)   1.0
  (0, 30)   1.0
  (0, 31)   1.0
  (0, 32)   1.0
  (0, 33)   1.0
  (0, 34)   1.0
  (0, 35)   1.0
  (0, 36)   1.0
  (0, 37)   1.0
  (0, 38)   1.0
  (0, 39)   1.0
  (0, 40)   1.0.....]
</code>```

Code to build the MLP:

```<code>with tf.name_scope('MLP'):

   # num_layer = [20,10]

    # Network Parameters
    n_input = 1 #Dimensions of concatenated input vector
    n_hidden_1 = 40 # 1st layer number of neurons
    n_hidden_2 = 5 # 2nd layer number of neurons
    n_out = 1

    latent_dim=1

     #Input Variables
    with tf.name_scope('Input'):
        label = tf.placeholder(tf.float32, name='label1')
        v_u = tf.placeholder(tf.int32, [1,num_users], name='user_input')
        v_i = tf.placeholder(tf.int32, [1,num_items], name='item_input')

    with tf.name_scope('Embeddings'):
        P_M = tf.truncated_normal([num_users,n_input], stddev=0.1)
        tf.Variable(P_M,name="P_M")
        embedded_users = tf.matmul(tf.to_float(v_u),P_M)

        Q_M = tf.truncated_normal([num_items,n_input], stddev=0.1)
        tf.Variable(Q_M,name="Q_M")
        embedded_items = tf.matmul( tf.to_float(v_i),Q_M)

    # The 0-th layer is the concatenation of embedding layers
    concat_vector = tf.concat([embedded_users, embedded_items], 0)
    with tf.name_scope("MLP_Layers"):

        # Parameters
        learning_rate = 0.01
        training_epochs = 15
        batch_size = 100
        display_step = 1

        # Store layers weight & bias
        weights = {
            'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1]), name='Weight1'),
            'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2]), name='Weight2'),
            'out': tf.Variable(tf.random_normal([n_hidden_2, n_out]), name='Weight_Output')}
        biases = {
            'b1': tf.Variable(tf.random_normal([n_hidden_1]), name='Bias1'),
            'b2': tf.Variable(tf.random_normal([n_hidden_2]), name='Bias2'),
            'out': tf.Variable(tf.random_normal([n_out]), name='Bias_Output')}
    with tf.name_scope("Model"):

        # Create model
        def mlp(x):
            layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'], name='Layer1')
            layer_1_out = 1/(1 + tf.exp(-layer_1))
            layer_2 = tf.add(tf.matmul(layer_1_out, weights['h2']), biases['b2'], name='Layer2')
            layer_2_out = 1/(1 + tf.exp(-layer_2))
            final_layer = tf.add(tf.matmul(layer_2, weights['out']),biases['out'], name='Output_Layer')
            out_layer = 1/(1 + tf.exp(-final_layer))
            return out_layer
</code>```

Code to Build Inputs from training Matrix:

```<code>def get_training_data(train, num_negatives):
    user_input, item_input, labels = [],[],[]
    num_users = train.shape[0]
    for (u, i) in train.keys():
        # positive instance
        user_input.append(u)
        item_input.append(i)
        labels.append(1)
        # negative instances
        for t in range(num_negatives):
            j = np.random.randint(num_items)
            while (u,j) in train.keys():
                j = np.random.randint(num_items)
            user_input.append(u)
            item_input.append(j)
            labels.append(0)
    return user_input, item_input, labels
</code>```

Building the Model:

```<code># Build model

prediction = mlp(concat_vector)
init = tf.global_variables_initializer()

 # Define loss and optimizer
with tf.name_scope('cross_entropy'):
    loss_op = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=prediction, labels=label))
    tf.summary.scalar('cross_entropy', loss_op)

with tf.name_scope('train'):
    optimizer = tf.train.AdamOptimizer(learning_rate=0.15)
    train_op = optimizer.minimize(loss_op)

# Initializing the variables
init = tf.global_variables_initializer()
</code>```

And finally training (CODE THAT GIVES THE ERROR)

```<code>num_epochs=1
num_negatives=3
# Training model
with tf.Session() as sess:
    for epoch in range(num_epochs):
        t1 = time()
        # Generate training instances
        user_input, item_input, labels = get_training_data(train, num_negatives)
        onehot_user = (tf.one_hot(user_input,len(user_input)))
        onehot_item = (tf.one_hot(item_input,len(item_input)))
        label_list = np.array(labels)

        total_batch = int(len(user_input))
        # Training
        for i in range(total_batch):

            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([train_op, loss_op], feed_dict={v_u: np.array(onehot_user),
                                                            v_i: np.array(onehot_item),
                                                            label:label_list})
            # Compute average loss
            avg_cost += c / total_batch
            print("Batch:", '%04d' % (i),"Completed")
        # Display logs per epoch step
        if epoch % display_step == 0:
            print("Epoch:", '%04d' % (epoch+1), "cost={:.9f}".format(avg_cost))
        print("Optimization Finished!")

        t2 = time()

merged = tf.summary.merge_all()
writer = tf.summary.FileWriter('logs', sess.graph)
</code>```

Any ideas for debugging??

Thank you in advance!

答: Your label_list variable is an array of integers, but the label placeholder is expecting tf.float32 values. If you switch one of the types, it should work properly.

Body:
I must admit I am a beginner, but I could not find an answer to my question on any questions asked in StackOverflow or Github. Please do help

The Error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-33-a9ebf2ee96c3> in <module>()
     19             _, c = sess.run([train_op, loss_op], feed_dict={v_u: np.array(onehot_user),
     20                                                             v_i: np.array(onehot_item),
---> 21                                                             label:label_list})
     22             # Compute average loss
     23             avg_cost += c / total_batch

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    893     try:
    894       result = self._run(None, fetches, feed_dict, options_ptr,
--> 895                          run_metadata_ptr)
    896       if run_metadata:
    897         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1091             feed_handles[subfeed_t] = subfeed_val
   1092           else:
-> 1093             np_val = np.asarray(subfeed_val, dtype=subfeed_dtype)
   1094
   1095           if (not is_tensor_handle_feed and

~/anaconda3/lib/python3.6/site-packages/numpy/core/numeric.py in asarray(a, dtype, order)
    529
    530     """
--> 531     return array(a, dtype, copy=False, order=order)
    532
    533

ValueError: setting an array element with a sequence.

# Loading data
t1 = time()
dataset = Dataset("/Users/shishir/Documents/botconnect_Playground/NCF_Prototype/Data/ml-1m")
train, testRatings, testNegatives = dataset.trainMatrix, dataset.testRatings, dataset.testNegatives
num_users, num_items = train.shape
print("Load data done [%.1f s]. #user=%d, #item=%d, #train=%d, #test=%d"
      %(time()-t1, num_users, num_items, train.nnz, len(testRatings)))

"Train" is a Matrix that looks like:[(user_id,item_id) implicit_rating....]

[  (0, 0)   1.0
  (0, 1)    1.0
  (0, 2)    1.0
  (0, 3)    1.0
  (0, 4)    1.0
  (0, 5)    1.0
  (0, 6)    1.0
  (0, 7)    1.0
  (0, 8)    1.0
  (0, 9)    1.0
  (0, 10)   1.0
  (0, 11)   1.0
  (0, 12)   1.0
  (0, 13)   1.0
  (0, 14)   1.0
  (0, 15)   1.0
  (0, 16)   1.0
  (0, 17)   1.0
  (0, 18)   1.0
  (0, 19)   1.0
  (0, 20)   1.0
  (0, 21)   1.0
  (0, 22)   1.0
  (0, 23)   1.0
  (0, 24)   1.0
  : :
  (0, 28)   1.0
  (0, 29)   1.0
  (0, 30)   1.0
  (0, 31)   1.0
  (0, 32)   1.0
  (0, 33)   1.0
  (0, 34)   1.0
  (0, 35)   1.0
  (0, 36)   1.0
  (0, 37)   1.0
  (0, 38)   1.0
  (0, 39)   1.0
  (0, 40)   1.0.....]

Code to build the MLP:

with tf.name_scope('MLP'):

   # num_layer = [20,10]

    # Network Parameters
    n_input = 1 #Dimensions of concatenated input vector
    n_hidden_1 = 40 # 1st layer number of neurons
    n_hidden_2 = 5 # 2nd layer number of neurons
    n_out = 1

    latent_dim=1

     #Input Variables
    with tf.name_scope('Input'):
        label = tf.placeholder(tf.float32, name='label1')
        v_u = tf.placeholder(tf.int32, [1,num_users], name='user_input')
        v_i = tf.placeholder(tf.int32, [1,num_items], name='item_input')

    with tf.name_scope('Embeddings'):
        P_M = tf.truncated_normal([num_users,n_input], stddev=0.1)
        tf.Variable(P_M,name="P_M")
        embedded_users = tf.matmul(tf.to_float(v_u),P_M)

        Q_M = tf.truncated_normal([num_items,n_input], stddev=0.1)
        tf.Variable(Q_M,name="Q_M")
        embedded_items = tf.matmul( tf.to_float(v_i),Q_M)

    # The 0-th layer is the concatenation of embedding layers
    concat_vector = tf.concat([embedded_users, embedded_items], 0)
    with tf.name_scope("MLP_Layers"):

        # Parameters
        learning_rate = 0.01
        training_epochs = 15
        batch_size = 100
        display_step = 1

        # Store layers weight & bias
        weights = {
            'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1]), name='Weight1'),
            'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2]), name='Weight2'),
            'out': tf.Variable(tf.random_normal([n_hidden_2, n_out]), name='Weight_Output')}
        biases = {
            'b1': tf.Variable(tf.random_normal([n_hidden_1]), name='Bias1'),
            'b2': tf.Variable(tf.random_normal([n_hidden_2]), name='Bias2'),
            'out': tf.Variable(tf.random_normal([n_out]), name='Bias_Output')}
    with tf.name_scope("Model"):

        # Create model
        def mlp(x):
            layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'], name='Layer1')
            layer_1_out = 1/(1 + tf.exp(-layer_1))
            layer_2 = tf.add(tf.matmul(layer_1_out, weights['h2']), biases['b2'], name='Layer2')
            layer_2_out = 1/(1 + tf.exp(-layer_2))
            final_layer = tf.add(tf.matmul(layer_2, weights['out']),biases['out'], name='Output_Layer')
            out_layer = 1/(1 + tf.exp(-final_layer))
            return out_layer

Code to Build Inputs from training Matrix:

def get_training_data(train, num_negatives):
    user_input, item_input, labels = [],[],[]
    num_users = train.shape[0]
    for (u, i) in train.keys():
        # positive instance
        user_input.append(u)
        item_input.append(i)
        labels.append(1)
        # negative instances
        for t in range(num_negatives):
            j = np.random.randint(num_items)
            while (u,j) in train.keys():
                j = np.random.randint(num_items)
            user_input.append(u)
            item_input.append(j)
            labels.append(0)
    return user_input, item_input, labels

Building the Model:

# Build model

prediction = mlp(concat_vector)
init = tf.global_variables_initializer()

 # Define loss and optimizer
with tf.name_scope('cross_entropy'):
    loss_op = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=prediction, labels=label))
    tf.summary.scalar('cross_entropy', loss_op)

with tf.name_scope('train'):
    optimizer = tf.train.AdamOptimizer(learning_rate=0.15)
    train_op = optimizer.minimize(loss_op)

# Initializing the variables
init = tf.global_variables_initializer()

And finally training (CODE THAT GIVES THE ERROR)

num_epochs=1
num_negatives=3
# Training model
with tf.Session() as sess:
    for epoch in range(num_epochs):
        t1 = time()
        # Generate training instances
        user_input, item_input, labels = get_training_data(train, num_negatives)
        onehot_user = (tf.one_hot(user_input,len(user_input)))
        onehot_item = (tf.one_hot(item_input,len(item_input)))
        label_list = np.array(labels)

        total_batch = int(len(user_input))
        # Training
        for i in range(total_batch):

            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([train_op, loss_op], feed_dict={v_u: np.array(onehot_user),
                                                            v_i: np.array(onehot_item),
                                                            label:label_list})
            # Compute average loss
            avg_cost += c / total_batch
            print("Batch:", '%04d' % (i),"Completed")
        # Display logs per epoch step
        if epoch % display_step == 0:
            print("Epoch:", '%04d' % (epoch+1), "cost={:.9f}".format(avg_cost))
        print("Optimization Finished!")

        t2 = time()

merged = tf.summary.merge_all()
writer = tf.summary.FileWriter('logs', sess.graph)

Any ideas for debugging??

Thank you in advance!


问:
PowerShell 5 Copy-Item not working
I am trying to copy all .pdf files from all folders and sub folder (dirs. and subdirs).

```<code>Folder1
  1.pdf
  2.pdf
Folder1\Foder2\3.pdf
Folder1\Folder2\4.pdf
Folder1\Foder2\Folder3\5.pdf
Folder1\Folder2\Folder3\6.pdf
</code>```

First I used

```<code> $source = "c:\Folder1\"
 $desti = "D:\foderA\"
 PS> Get-ChildItem -recurse $source -Filter "*.pdf"
</code>```

It displays all the files in dir and sub dir but when I try to use copy-Item I get the error.

```<code> PS> Get-ChildItem -recurse $source -Filter "*.pdf" | % {Copy-Item $_    -destination $desti}
</code>```

Error: Copy-Item : Cannot find path 'C:\Folder1\Folder2.... because it does not exist. Error points to source being non-existent.
What am I doing wrong?
Is it because I have read only on the source drive\Folder?

Thanks

答:
```<code>cp -Recurse C:\path\to\search\*.pdf C:\path\to\output\copies
</code>```

Title: PowerShell 5 Copy-Item not working

Body:
I am trying to copy all .pdf files from all folders and sub folder (dirs. and subdirs).

Folder1
  1.pdf
  2.pdf
Folder1\Foder2\3.pdf
Folder1\Folder2\4.pdf
Folder1\Foder2\Folder3\5.pdf
Folder1\Folder2\Folder3\6.pdf

First I used

 $source = "c:\Folder1\"
 $desti = "D:\foderA\"
 PS> Get-ChildItem -recurse $source -Filter "*.pdf"

It displays all the files in dir and sub dir but when I try to use copy-Item I get the error.

 PS> Get-ChildItem -recurse $source -Filter "*.pdf" | % {Copy-Item $_    -destination $desti}

Error: Copy-Item : Cannot find path 'C:\Folder1\Folder2.... because it does not exist. Error points to source being non-existent.
What am I doing wrong?
Is it because I have read only on the source drive\Folder?

Thanks


问:
ruby what makes a valid URI?
I'm getting invalid URI issues, so what exactly makes a valid URI?</p>

答:
At the highest level a URI reference (hereinafter simply "URI") in string form has the syntax

```<code>[scheme:]scheme-specific-part[#fragment]
</code>```

If you are interested to know the complete set of rules, read RFC-2396

I doubt whether you need to know all the syntaxes. I have never read the entire RFC and still I am using URI in development and day to day use. So, you better post the URI you are having problem with. Then, people here can point out the specific problem.

Title: ruby what makes a valid URI?

Body:
At the highest level a URI reference (hereinafter simply "URI") in string form has the syntax

[scheme:]scheme-specific-part[#fragment]

If you are interested to know the complete set of rules, read RFC-2396

I doubt whether you need to know all the syntaxes. I have never read the entire RFC and still I am using URI in development and day to day use. So, you better post the URI you are having problem with. Then, people here can point out the specific problem.


问:
Text.Length is not working to find length of String for a webElement
value of "total" is 0 here in this case :
I am not sure why it's not working ?</p>

```<code>List<IWebElement> list = new List<IWebElement>();
list =  ABCPageObject.AbcTextArea().ToList();

foreach (IWebElement Option in list)
{
    Option.Click();
    Option.Clear();
    Option.SendKeys("ThisisTheasdfdsaOutput1234567890ThisisTheVWXYZer!O@ut#pu$tT%hi^sis&The*Tw(i)t<t>er[O]u{t}p/utT/ABCDEFGHIJKLMNOPQRSTU");
    Thread.Sleep(2000);
}
foreach(IWebElement Option in list)
{
    var total = Option.Text.Length;
    // total is 0 here when we debug

    if(total == 116)
    {
        Utility.Logger.Write("Add Out");
    }

}
</code>```

答:
You need to check a value attributte instead of text().

A value of input and textarea tags are stored in value attributte.

Please see a below simple test that shows that.

Here is a simple test page which contains two fields - input and textarea

```<code><div>
  <textarea id="mytextarea"></textarea>
</div>
<div>
  <input id="myinput" />
</div>
</code>```

Here is a simple test code (in java):

```<code>driver.get("https://jsfiddle.net/f89zxd1w/");
driver.switchTo().frame("result");

driver.findElement(By.id("mytextarea")).sendKeys("Some text");

driver.findElement(By.id("myinput")).sendKeys("Some other text");

WebElement textArea = driver.findElement(By.id("mytextarea"));
String areaText = textArea.getText();
String areaValue = textArea.getAttribute("value");

System.out.format("Area text = %s\n", areaText);
System.out.format("Area value = %s\n", areaValue);

WebElement input = driver.findElement(By.id("myinput"));
String inputText = input.getText();
String inputValue = input.getAttribute("value");

System.out.format("Input text = %s\n", inputText);
System.out.format("Input value = %s\n", inputValue);
</code>```

And a result is:

```<code>Area text =
Area value = Some text
Input text =
Input value = Some other text
</code>```

Body:
value of "total" is 0 here in this case :
I am not sure why it's not working ?

List<IWebElement> list = new List<IWebElement>();
list =  ABCPageObject.AbcTextArea().ToList();

foreach (IWebElement Option in list)
{
    Option.Click();
    Option.Clear();
    Option.SendKeys("ThisisTheasdfdsaOutput1234567890ThisisTheVWXYZer!O@ut#pu$tT%hi^sis&The*Tw(i)t<t>er[O]u{t}p/utT/ABCDEFGHIJKLMNOPQRSTU");
    Thread.Sleep(2000);
}
foreach(IWebElement Option in list)
{
    var total = Option.Text.Length;
    // total is 0 here when we debug

    if(total == 116)
    {
        Utility.Logger.Write("Add Out");
    }

}

Body:
You need to check a value attributte instead of text().

A value of input and textarea tags are stored in value attributte.

Please see a below simple test that shows that.

Here is a simple test page which contains two fields - input and textarea

<div>
  <textarea id="mytextarea"></textarea>
</div>
<div>
  <input id="myinput" />
</div>

Here is a simple test code (in java):

driver.get("https://jsfiddle.net/f89zxd1w/");
driver.switchTo().frame("result");

driver.findElement(By.id("mytextarea")).sendKeys("Some text");

driver.findElement(By.id("myinput")).sendKeys("Some other text");

WebElement textArea = driver.findElement(By.id("mytextarea"));
String areaText = textArea.getText();
String areaValue = textArea.getAttribute("value");

System.out.format("Area text = %s\n", areaText);
System.out.format("Area value = %s\n", areaValue);

WebElement input = driver.findElement(By.id("myinput"));
String inputText = input.getText();
String inputValue = input.getAttribute("value");

System.out.format("Input text = %s\n", inputText);
System.out.format("Input value = %s\n", inputValue);

And a result is:

Area text =
Area value = Some text
Input text =
Input value = Some other text


问:
While using where, Include and Select class in Entity framework, got the error as The Include path expression must refer to a navigation property
I am using below code to retrieve the data using Entity Framework.

```<code>BaseTable service = base.dbcontext.BaseTables
    .Include(s => s.Categories.Select(c => c.Definitions
                                        .Select(v => v.Values
                                        .Where(con => con.Id >= 141)
                                        .Select(com => com.Comments))))
    .Where(s => s.Id == id).SingleOrDefault();
</code>```

While running this code i am getting below error.

An exception of type 'System.ArgumentException' occurred in EntityFramework.dll but was not handled in user code
Additional information: The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.

But If i run the above code by removing the condition(.Where(con => con.Id >= 141)), it is working perfectly. Below is working code.

```<code>BaseTable service = base.dbcontext.BaseTables
    .Include(s => s.Categories.Select(c => c.Definitions
                                        .Select(v => v.Values
                                        .Select(com => com.Comments))))
    .Where(s => s.Id == id).SingleOrDefault();
</code>```

But i don't want use working code(which don't have the condition .Where(con => con.Id >= 141)) because it is taking almost 10 seconds to execute the query. This working query is taking lot of time because I have lot of entries in Values and Comments  and this query don't have any condition on these two tables.

答:
Correct usage of .Include()

BaseTable service = base.dbcontext.BaseTables
.Include(s => s.Categories)
```

Body:
I am using below code to retrieve the data using Entity Framework.

BaseTable service = base.dbcontext.BaseTables
    .Include(s => s.Categories.Select(c => c.Definitions
                                        .Select(v => v.Values
                                        .Where(con => con.Id >= 141)
                                        .Select(com => com.Comments))))
    .Where(s => s.Id == id).SingleOrDefault();

While running this code i am getting below error.

An exception of type 'System.ArgumentException' occurred in EntityFramework.dll but was not handled in user code
Additional information: The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.

But If i run the above code by removing the condition(.Where(con => con.Id >= 141)), it is working perfectly. Below is working code.

BaseTable service = base.dbcontext.BaseTables
    .Include(s => s.Categories.Select(c => c.Definitions
                                        .Select(v => v.Values
                                        .Select(com => com.Comments))))
    .Where(s => s.Id == id).SingleOrDefault();

But i don't want use working code(which don't have the condition .Where(con => con.Id >= 141)) because it is taking almost 10 seconds to execute the query. This working query is taking lot of time because I have lot of entries in Values and Comments  and this query don't have any condition on these two tables.


问:
How to make Intellij Idea Coverage display full colored lines?
In Eclipse, most of the coverage plugins, display covered/partially covered/uncovered lines with different colors (i.e. the whole line painted with a color)

In IntelliJ Idea, I couldn't find a way yet to paint the whole line with a descriptive color, only a small, almost imperceptible mark is added on the left hand side, making the visualization of partially covered / uncovered lines really difficult.

Any idea?

答: Thanks for the update I fixed by uncovered lines in Intellij attached the screenshot for reference.


问:
$_SERVER['HTTP_REFERER'] returning correct value but not passing conditional
I have a contact form and a product form. I want to check to verify there is product value ONLY on product form BUT I can get the conditional to pass.

Broken Code

```<code>// If visitor filled out the form on the "Contact Us" page (/contact/index.php) then no 'product' field is required.
if ($_SERVER['HTTP_REFERER'] != "http://www.url.com/contact/index.php" || "http://url.com/contact/index.php") {
    if(strlen($product) < 2) {
        $errors[] = "<font color='red'>Please enter the product requesting.</font>";
    }
}
</code>```

Troubleshooting / Debugging Code

```<code>$serverValue = $_SERVER['HTTP_REFERER'];
print "The value of SERVER is ". $serverValue;
echo "<br />";
print $_SERVER['DOCUMENT_ROOT']."/contact/index.php";
echo "<br />";

if ($_SERVER['HTTP_REFERER'] != "http://www.url.com/contact/index.php" || "http://url.com/contact/index.php" || "/home/url/public_html/contact/index.php") {
//if ($_SERVER['HTTP_REFERER'] != $_SERVER['DOCUMENT_ROOT']."/contact/index.php") {
print "This is NOT the Contact page";
} else {
print "This IS the Contact page";
}
</code>```

Troubleshooting / Debugging Output

The value of SERVER is http://url.com/contact/index.php
  /home/url/public_html/contact/index.php
  This is NOT the Contact page

You can see by the output that the correct HTTP_REFERER is being passed but it just won't evaluate correctly. There is a commented out line in there where I was trying other things. Please go easy on me Im new at PHP.

Alright, I understood what I was doing wrong and tried this with no success

```<code>if ($_SERVER['HTTP_REFERER'] != "http://www.url.com/contact/index.php" || $_SERVER['HTTP_REFERER'] != "http://url.com/contact/index.php") {
if(strlen($product) < 2) {
$errors[] = "<font color='red'>Please enter the product requesting.</font>";
}
}
</code>```

Any other thoughts?

答:
It does evaluate correctly as a non-empty string evaluates to true.

So with:

```<code>if ($_SERVER['HTTP_REFERER'] != "http://www.url.com/contact/index.php"
   || "http://url.com/contact/index.php"
   || "/home/url/public_html/contact/index.php") {
</code>```

it does not matter what the first condition is because the second and the third always evaluate to true:

```<code>if ($_SERVER['HTTP_REFERER'] != "http://www.url.com/contact/index.php"
   || true
   || true) {
</code>```

Results in:

```<code>if (true) {
</code>```

If you don't want the referrer to be any of these 3 strings, you can use something like:

```<code>if (!in_array($_SERVER['HTTP_REFERER'] , [
    'http://www.url.com/contact/index.php',
    'http://url.com/contact/index.php',
    '/home/url/public_html/contact/index.php'
]) {
</code>```

Body:
I have a contact form and a product form. I want to check to verify there is product value ONLY on product form BUT I can get the conditional to pass.

Broken Code

// If visitor filled out the form on the "Contact Us" page (/contact/index.php) then no 'product' field is required.
if ($_SERVER['HTTP_REFERER'] != "http://www.url.com/contact/index.php" || "http://url.com/contact/index.php") {
    if(strlen($product) < 2) {
        $errors[] = "Please enter the product requesting.";
    }
}

Troubleshooting / Debugging Code

$serverValue = $_SERVER['HTTP_REFERER'];
print "The value of SERVER is ". $serverValue;
echo "
";
print $_SERVER['DOCUMENT_ROOT']."/contact/index.php";
echo "
";

if ($_SERVER['HTTP_REFERER'] != "http://www.url.com/contact/index.php" || "http://url.com/contact/index.php" || "/home/url/public_html/contact/index.php") {
//if ($_SERVER['HTTP_REFERER'] != $_SERVER['DOCUMENT_ROOT']."/contact/index.php") {
print "This is NOT the Contact page";
} else {
print "This IS the Contact page";
}

Troubleshooting / Debugging Output

The value of SERVER is http://url.com/contact/index.php
  /home/url/public_html/contact/index.php
  This is NOT the Contact page

You can see by the output that the correct HTTP_REFERER is being passed but it just won't evaluate correctly. There is a commented out line in there where I was trying other things. Please go easy on me Im new at PHP.

Alright, I understood what I was doing wrong and tried this with no success

if ($_SERVER['HTTP_REFERER'] != "http://www.url.com/contact/index.php" || $_SERVER['HTTP_REFERER'] != "http://url.com/contact/index.php") {
if(strlen($product) < 2) {
$errors[] = "Please enter the product requesting.";
}
}

Any other thoughts?

Body:
It does evaluate correctly as a non-empty string evaluates to true.

So with:

if ($_SERVER['HTTP_REFERER'] != "http://www.url.com/contact/index.php"
   || "http://url.com/contact/index.php"
   || "/home/url/public_html/contact/index.php") {

it does not matter what the first condition is because the second and the third always evaluate to true:

if ($_SERVER['HTTP_REFERER'] != "http://www.url.com/contact/index.php"
   || true
   || true) {

Results in:

if (true) {

If you don't want the referrer to be any of these 3 strings, you can use something like:

if (!in_array($_SERVER['HTTP_REFERER'] , [
    'http://www.url.com/contact/index.php',
    'http://url.com/contact/index.php',
    '/home/url/public_html/contact/index.php'
]) {


问:
Divide values by lists of three and comparing elements in it
I have some values coming from sensor. My task is to divide them into lists of three elements.  If two consecutive elements differ by at least 10, I should ignore the rest of the list.

From this:

```<code>values = [1,3,6,8,9,11,15,17,28,29]
</code>```

I should get:

```<code>[1,3,6]
[8,9,11]
[15,17]
</code>```

I've managed to divide values by list of three:

```<code>list_of_values = [1,3,6,8,9,11,15,17,28,29]
def divide(values, size):
    return (values[pos:pos + size] for pos in range(0, len(values), size))
for group in divide(list_of_values, 3):
    print(group)
</code>```

But I can't figure out how to compare previous and next value like the task says.

答:
Here is an alternative approach. You can find the absolute difference between consecutive elements using a list comprehension,

```<code>diff = [abs(values[i+1]-values[i]) for i in range(len(values)-1)]
</code>```

The you can find occurrence of the first difference greater than 10 using a generator, which is based on this post,

```<code>ind = (i for i,v in enumerate(diff) if v >= 10).next()
lst = values[:ind+1];
</code>```

lst is now your shortened list - i.e. list until and not inclusive the first value different by 10.

Finally, using an approach from this post the shortened list lst can be split into chunks smaller or equal to 3,

```<code>n = 3
print [lst[i:i + n] for i in range(0, len(lst), n)]
</code>```

Body:
I have some values coming from sensor. My task is to divide them into lists of three elements.  If two consecutive elements differ by at least 10, I should ignore the rest of the list.

From this:

values = [1,3,6,8,9,11,15,17,28,29]

I should get:

[1,3,6]
[8,9,11]
[15,17]

I've managed to divide values by list of three:

list_of_values = [1,3,6,8,9,11,15,17,28,29]
def divide(values, size):
    return (values[pos:pos + size] for pos in range(0, len(values), size))
for group in divide(list_of_values, 3):
    print(group)

But I can't figure out how to compare previous and next value like the task says.

Body:
Here is an alternative approach. You can find the absolute difference between consecutive elements using a list comprehension,

diff = [abs(values[i+1]-values[i]) for i in range(len(values)-1)]

The you can find occurrence of the first difference greater than 10 using a generator, which is based on this post,

ind = (i for i,v in enumerate(diff) if v >= 10).next()
lst = values[:ind+1];

lst is now your shortened list - i.e. list until and not inclusive the first value different by 10.

Finally, using an approach from this post the shortened list lst can be split into chunks smaller or equal to 3,

n = 3
print [lst[i:i + n] for i in range(0, len(lst), n)]


问:
How to do Insert/Delete remotely through a SPARQL endpoint?
Is there a way to update data by (INSERT DATA and DELETE DATA) remotely through a SPARQL endpoint? I'm aware that we can use SERVICE to do distributed and federated query, but I got errors when i tried to use SERVICE to remotely update data as:

```<code>INSERT DATA
{SERVICE <SparqlEndpoint1> {
subject, predicate, object
}}
</code>```

Thank you very much for your help.

答: The Federated SPARQL SERVICE clause only supports SELECT operations.  SERVICE clauses cannot be used for INSERT, UPDATE, DELETE, or other SPARQL Update operations on remote endpoints.  See the SPARQL 1.1 grammar and the other linked documents for more details.

Body:
Is there a way to update data by (INSERT DATA and DELETE DATA) remotely through a SPARQL endpoint? I'm aware that we can use SERVICE to do distributed and federated query, but I got errors when i tried to use SERVICE to remotely update data as:

INSERT DATA
{SERVICE <SparqlEndpoint1> {
subject, predicate, object
}}

Thank you very much for your help.


问:
JavaScript Cell Does not Match Row
I have a table where the user is able to add customers and when a customer is added, a unique ID is given to the row and each cell within the row.

As you can see, when you add a row, I have logged the row.id and the cell.id, however, the cell.id is supposed to be 'cell_' + rowCount + '_' + i but the rowCount in the cell does not match the one in the row.

// add customer or item
// append row to the HTML table
var rowCount = 1;
var cellCount = 0;

function appendRow(id, style) {
  var table = document.getElementById(id); // table reference
  length = table.length,
    row = table.insertRow(table.rows.length); // append table row
  row.setAttribute('id', style);
  var i;
  row.id = 'row' + rowCount;
  rowCount++
  // insert table cells to the new row
  for (i = 0; i < table.rows[0].cells.length; i++) {
    createCell(row.insertCell(i), i, 'cell_' + rowCount + '.' + i); // starts over when row changes
    cellCount++
  }
}

function createCell(cell, text, style) {
  var div = document.createElement('div'), // create DIV element
    txt = document.createTextNode('_'); // create text node
  div.appendChild(txt); // append text node to the DIV
  div.setAttribute('id', style); // set DIV class attribute
  div.setAttribute('idName', style); // set DIV class attribute for IE (?!)
  cell.appendChild(div); // append DIV to the table cell
  console.log(row.id + ' ' + div.id);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  text-align: center;
}
td  {
  width: 100px;
}

tr:nth-child(even) {
  background-color: #fff;
}
tr:nth-child(odd) {
  background-color: #eee;
}</code>```

<button id="addCust" class="addSort" onclick="appendRow('custList')">add customer</button>

      Customers
      Work #
      Cell #
      Main Location

      Someone
      903-636-0000
      903-626-0000
      something

```

答:
You have

  row.id = 'row' + rowCount;
  rowCount++

followed by

'cell_' + rowCount

You are first using rowCount on the row when it's set to 1, then setting it to 2, then using it on the cell when it's set to 2.

Title: JavaScript Cell Does not Match Row

Body:
I have a table where the user is able to add customers and when a customer is added, a unique ID is given to the row and each cell within the row.

As you can see, when you add a row, I have logged the row.id and the cell.id, however, the cell.id is supposed to be 'cell_' + rowCount + '_' + i but the rowCount in the cell does not match the one in the row.

// add customer or item
// append row to the HTML table
var rowCount = 1;
var cellCount = 0;

function appendRow(id, style) {
  var table = document.getElementById(id); // table reference
  length = table.length,
    row = table.insertRow(table.rows.length); // append table row
  row.setAttribute('id', style);
  var i;
  row.id = 'row' + rowCount;
  rowCount++
  // insert table cells to the new row
  for (i = 0; i < table.rows[0].cells.length; i++) {
    createCell(row.insertCell(i), i, 'cell_' + rowCount + '.' + i); // starts over when row changes
    cellCount++
  }
}

function createCell(cell, text, style) {
  var div = document.createElement('div'), // create DIV element
    txt = document.createTextNode('_'); // create text node
  div.appendChild(txt); // append text node to the DIV
  div.setAttribute('id', style); // set DIV class attribute
  div.setAttribute('idName', style); // set DIV class attribute for IE (?!)
  cell.appendChild(div); // append DIV to the table cell
  console.log(row.id + ' ' + div.id);
}

table {
  text-align: center;
}
td  {
  width: 100px;
}

tr:nth-child(even) {
  background-color: #fff;
}
tr:nth-child(odd) {
  background-color: #eee;
}

<button id="addCust" class="addSort" onclick="appendRow('custList')">add customer</button>

      Customers
      Work #
      Cell #
      Main Location

      Someone
      903-636-0000
      903-626-0000
      something


问:
Should I use multiple Router components to create multi-level navigation?
Let's say I have the following app structure:

```<code>+--+--+ login
   |
   +--+ signup
   |
   +--+ inner main
      |
      +--+ settings/user
      |
      +--+ settings/app
      |
      +--+ settings/about
      |...
</code>```

inner will wrap everything below it, but when I get to /settings I will have 3 tabs that will use a router. I want settings to have another wrapper for all the routes below it, so if I am logged in, and go to www.myapp.com/settings/user I will get innerWrapper -> settingsWrapper -> userSettings

Should settings use a Route component of their own, since I'm not sure if there is a way to keep its components wrapped in one router component setup. Doing something like this seems bad:

```<code><Route path="/settings/user" {...rest} render={props => (
    <wrapper>
      <User {...props}/>
    </wrapper>
)}/>
<Route path="/settings/app" {...rest} render={props => (
    <wrapper>
      <App {...props}/>
    </wrapper>
)}/>
</code>```

答:
In React Router V4 you put sub routes inside components.

So, in your InnerWrapper component, where your router is, you can have a route to the '/settings' page which renders the SettingsWrapper component:

```<code><BrowserRouter>
  <Route path='/settings' component={ SettingsWrapper } />
  // Other routes
</BrowserRouter>
</code>```

Then in your SettingsWrapper component, you can have sub routes which will render other components inside it:

```<code><Route path='/settings/user' component={ UserSettings } />
<Route path='/settings/app' component={ AppSettings } />
</code>```

I hope this helps.

Body:
Let's say I have the following app structure:

+--+--+ login
   |
   +--+ signup
   |
   +--+ inner main
      |
      +--+ settings/user
      |
      +--+ settings/app
      |
      +--+ settings/about
      |...

inner will wrap everything below it, but when I get to /settings I will have 3 tabs that will use a router. I want settings to have another wrapper for all the routes below it, so if I am logged in, and go to www.myapp.com/settings/user I will get innerWrapper -> settingsWrapper -> userSettings

Should settings use a Route component of their own, since I'm not sure if there is a way to keep its components wrapped in one router component setup. Doing something like this seems bad:

<Route path="/settings/user" {...rest} render={props => (
    <wrapper>
      <User {...props}/>
    </wrapper>
)}/>
<Route path="/settings/app" {...rest} render={props => (
    <wrapper>
      <App {...props}/>
    </wrapper>
)}/>

Body:
In React Router V4 you put sub routes inside components.

So, in your InnerWrapper component, where your router is, you can have a route to the '/settings' page which renders the SettingsWrapper component:

<BrowserRouter>
  <Route path='/settings' component={ SettingsWrapper } />
  // Other routes
</BrowserRouter>

Then in your SettingsWrapper component, you can have sub routes which will render other components inside it:

<Route path='/settings/user' component={ UserSettings } />
<Route path='/settings/app' component={ AppSettings } />

I hope this helps.


问:
why the regression doesnt work? (MATLAB)
I have a accelerometer signal as below:

and I have a walking signal as below:

I tried to regress these two signal using regression. Here is the code:

```<code>regMat=zeros(size(walkVec,1),size(walkVec,2));
for i=1:size(data,1)
   b=regress(walkAcc', walkVec(i,:)');
    regMat(i,:)=walkVec(i,:)-repmat(b,1,length(walkAcc));
    regData(i,:)=[data(i,1:(ipt(1)-1)),regMat(i,:), data(i,
     (ipt(2)+1):size(data,2) ) ];
 end

 figure(1),hold on, plot(data(1,:),'r'), plot(regData(1,:)), title
('regressed (b) and raw(r) ')
legend('raw','regressed')
 xlabel('samples')
ylabel('Intensity')
</code>```

and here is the reslts:

as you can see the regression doesnt really work. Do you have any idea why and how I can fix it?

Thanks a lot and kind Regards

答: Check if regData has any data in the first column. This can also happen if one data is several magnitudes higher or lower. It becomes negligible in the same chart. I tried your code with dummy data and it works.</p>

Body:
I have a accelerometer signal as below:

and I have a walking signal as below:

I tried to regress these two signal using regression. Here is the code:

regMat=zeros(size(walkVec,1),size(walkVec,2));
for i=1:size(data,1)
   b=regress(walkAcc', walkVec(i,:)');
    regMat(i,:)=walkVec(i,:)-repmat(b,1,length(walkAcc));
    regData(i,:)=[data(i,1:(ipt(1)-1)),regMat(i,:), data(i,
     (ipt(2)+1):size(data,2) ) ];
 end

 figure(1),hold on, plot(data(1,:),'r'), plot(regData(1,:)), title
('regressed (b) and raw(r) ')
legend('raw','regressed')
 xlabel('samples')
ylabel('Intensity')

and here is the reslts:

as you can see the regression doesnt really work. Do you have any idea why and how I can fix it?

Thanks a lot and kind Regards


问:
Redirect to Notification Access Settings
I'm currently developing an app for Android that uses the NotificationListenerService,  which requires that the user will enable notification access for my app under Setting -> Security -> Notification Access.

My question is that can I redirect the user to this place so they will enable it? So far I only managed to direct them to Setting -> Security window.

Also, is it possible to first check if the user enabled notification access for my app already and only then redirect them?

答:
You can always use the notification manager to check if notifications are enabled at the OS level:</p>

```<code>NotificationManagerCompat.from(context).areNotificationsEnabled()
</code>```

Body:
You can always use the notification manager to check if notifications are enabled at the OS level:

NotificationManagerCompat.from(context).areNotificationsEnabled()


问:
Get vmId via pyVmomi
Currently Im using vim-cmd to perform multiple operations in my VMware center.

I'm using SSH paramiko module to connect and retrieve vim-cmd command status:

```<code>vim-cmd vmsvc/getallvms
vim-cmd vmsvc/power.getstate 13
vim-cmd vmsvc/power.on 13
vim-cmd vmsvc/power.off 13
vim-cmd vmsvc/destroy 13
</code>```

I want to use pyVmomi library to run some commands and for this it is required to provide the vmId identifier:

```<code>from pyvim import connect
from pyVmomi import vim
from pyVmomi import vmodl

vim-cmd vmsvc/get.summary 13
Listsummary:

(vim.vm.Summary) {
   dynamicType = <unset>,
   vm = 'vim.VirtualMachine:13',
</code>```

What command can I use to get the vmId?

答:
I've encountered the same thing,

I know it has been a while but I suggest this

hack which works fine for me, I hope you can use it.

```<code>buf = ("%s" % (vm.summary.vm))
</code>```

which for example gives

```<code>vim.VirtualMachine:11
</code>```

now, we wish to extract the number and for python3 it is recommended using regular expression.

```<code>import re #regular expression
re.findall('\d+', buf)
</code>```

which result with a list with 1 element

'11'

type(buf)

<class 'list'>

Title: Get vmId via pyVmomi

Body:
Currently Im using vim-cmd to perform multiple operations in my VMware center.

I'm using SSH paramiko module to connect and retrieve vim-cmd command status:

vim-cmd vmsvc/getallvms
vim-cmd vmsvc/power.getstate 13
vim-cmd vmsvc/power.on 13
vim-cmd vmsvc/power.off 13
vim-cmd vmsvc/destroy 13

I want to use pyVmomi library to run some commands and for this it is required to provide the vmId identifier:

from pyvim import connect
from pyVmomi import vim
from pyVmomi import vmodl

vim-cmd vmsvc/get.summary 13
Listsummary:

(vim.vm.Summary) {
   dynamicType = <unset>,
   vm = 'vim.VirtualMachine:13',

What command can I use to get the vmId?

Body:
I've encountered the same thing,

I know it has been a while but I suggest this

hack which works fine for me, I hope you can use it.

buf = ("%s" % (vm.summary.vm))

which for example gives

vim.VirtualMachine:11

now, we wish to extract the number and for python3 it is recommended using regular expression.

import re #regular expression
re.findall('\d+', buf)

which result with a list with 1 element

'11'

type(buf)<br/>

<class 'list'>


问:
How do I open an iOS simulator local .realm file in Realm Studio
Using realm browser I was able to print the path of the .realm file in the simulator and open it from the terminal (macOS) using:

```<code>open /Users/.../long path/.../default.realm
</code>```

This doesn't seem to work with Realm Studio (it still tries to open with Realm Browser). Realm Studio has an "Open a local Realm" option on the splash screen, but that takes me to macOS's awful finder, which doesn't allow me to type in a path (Windows +1). Maybe I don't properly understand macOS's file structure, but it doesn't appear to be showing one of the directories I would need to navigate into to find the .realm

Does Realm Studio have a cli tool or cli method of opening?

答:
The fact that Realm Studio does not yet open files in response to the open AppleEvent (sent by double-clicking on a Realm file in the finder, or using open on a .realm file) is a known issue.

In the mean time, you can open it via Realm Studio's Open panel by first copying the path, typing / when the Open panel is showing, then pasting the copied path into the text field that has appeared.

Body:
Using realm browser I was able to print the path of the .realm file in the simulator and open it from the terminal (macOS) using:

open /Users/.../long path/.../default.realm

This doesn't seem to work with Realm Studio (it still tries to open with Realm Browser). Realm Studio has an "Open a local Realm" option on the splash screen, but that takes me to macOS's awful finder, which doesn't allow me to type in a path (Windows +1). Maybe I don't properly understand macOS's file structure, but it doesn't appear to be showing one of the directories I would need to navigate into to find the .realm

Does Realm Studio have a cli tool or cli method of opening?


问:
Ruby on Rails Display Amount of Characters Remaining for f.text_area
In my Ruby on Rails application I am trying to display the amount of characters remaining for the following text box in the view:

```<code><%= f.label :review_text, 'Review Text:' %>
</code>```

And am trying to do so through this java:

```<code>$(document).ready(function() {
  $("#review_text").keyup(function() {
   $("#counter").text(2000 - $(this).val().length);
  });
});
</code>```

Which displays the amount left through:

```<code>chars left : <span id="counter"><%= maxcounter=2000 %></span>
</code>```

This does not work, but this text field does:

```<code><%= text_field_tag :review_text %>
</code>```

If I change the above to:

```<code><%= f.text_field_tag :review_text %>
</code>```

I get the following error:

```<code>NoMethodError in Reviews#new
undefined method `text_field_tag' for   <ActionView::Helpers::FormBuilder:0x6b44020>
</code>```

Can someone please help.

Below is the full view:

```<code><%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>
<div id="contentWrapper">
    <div id="content">
    <div class='large_panel'>
        <table>
            <%= form_for @review do |f| %>
                <%= f.hidden_field :user_id %>
                <%= f.hidden_field :film_id %>
                <%= image_tag "thor_hammer.jpg",:size => "900x250" %>
                <h1>REVIEW <%= @review.film.title %>:</h1>
                <tr>
                    <td width="500px">
                        <%= f.label :review_text, 'Review Text:' %></br>
                    </td>
                </tr>
                <tr>
                    <td>
                        <%= f.text_area :review_text, :size=>"50x10" %></br></br>
                    </td>
                </tr>
                <tr>
                <td width="100px">
                        <%= f.label :no_of_stars, 'Stars:' %></br>
                    </td>
                </tr>
                <tr>
                    <td>
                        <%= f.select :no_of_stars, 1..5 %></br></br>
                    </td>
                </tr>
                <tr>
                    <td>
                    chars left : <span id="counter"><%= maxcounter=2000 %></span>
                    <%= text_field_tag :review_text %>
                        <div class="actions">
                          <%= f.submit 'Submit' %>
                        </div>
                        <div class="actions">
                          <%= link_to 'Back', reviews_path %>
                        </div>
                        </br></br>
                        <%= render "/error_messages", :message_header => "Cannot save: ", :target => @review %>
                    </td>
                </tr>
            <% end %>
            </table><br>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
  $("#review_text").keyup(function() {
    $("#counter").text(2000 - $(this).val().length);
  });
});
</script>
</code>```

答:
The accepted answers works as mentioned, however if your text_field is pre-populated with data, then when the page loads, the counter will not contain the correct count, to fix this add the following line just above review_text.keyup()

```<code>counter.text(max_length - review_text.val().length);
</code>```

or just use the following updated script:

```<code><script>
$(document).ready(function() {
  var review_text = $("#review_text");
  var counter     = $("#counter");
  var max_length  = counter.data("maximum-length");

  counter.text(max_length - review_text.val().length);
  review_text.keyup(function() {
      counter.text(max_length - $(this).val().length);
  });

});
</script>
</code>```

Body:
In my Ruby on Rails application I am trying to display the amount of characters remaining for the following text box in the view:

<%= f.label :review_text, 'Review Text:' %>

And am trying to do so through this java:

$(document).ready(function() {
  $("#review_text").keyup(function() {
   $("#counter").text(2000 - $(this).val().length);
  });
});

Which displays the amount left through:

chars left : <%= maxcounter=2000 %>

This does not work, but this text field does:

<%= text_field_tag :review_text %>

If I change the above to:

<%= f.text_field_tag :review_text %>

I get the following error:

NoMethodError in Reviews#new
undefined method `text_field_tag' for   <ActionView::Helpers::FormBuilder:0x6b44020>

Can someone please help.

Below is the full view:

<%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>

            <%= form_for @review do |f| %>
                <%= f.hidden_field :user_id %>
                <%= f.hidden_field :film_id %>
                <%= image_tag "thor_hammer.jpg",:size => "900x250" %>

REVIEW <%= @review.film.title %>:

                        <%= f.label :review_text, 'Review Text:' %>

                        <%= f.text_area :review_text, :size=>"50x10" %>

                        <%= f.label :no_of_stars, 'Stars:' %>

                        <%= f.select :no_of_stars, 1..5 %>

                    chars left : <%= maxcounter=2000 %>
                    <%= text_field_tag :review_text %>

                          <%= f.submit 'Submit' %>

                          <%= link_to 'Back', reviews_path %>

                        <%= render "/error_messages", :message_header => "Cannot save: ", :target => @review %>

            <% end %>

Body:
The accepted answers works as mentioned, however if your text_field is pre-populated with data, then when the page loads, the counter will not contain the correct count, to fix this add the following line just above review_text.keyup()

counter.text(max_length - review_text.val().length);

or just use the following updated script:

<script>
$(document).ready(function() {
  var review_text = $("#review_text");
  var counter     = $("#counter");
  var max_length  = counter.data("maximum-length");

  counter.text(max_length - review_text.val().length);
  review_text.keyup(function() {
      counter.text(max_length - $(this).val().length);
  });

});
</script>


问:
In Xamarin.Forms, how to allow for autocompletion for bindings in XAML code in the case you can't instantiate the BindingContext from XAML?
Given the following project:

MainPage.xaml

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="A.MainPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:A">
    <ContentPage.Content>
        <StackLayout>
            <StackLayout>
                <Button Clicked="Greet" Text="Greet" />
            </StackLayout>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
</code>```

MainPage.xaml.cs

```<code>using System;
using Xamarin.Forms;

namespace A
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void Greet(object sender, EventArgs e)
        {
            Navigation.PushModalAsync(new SubPage
            {
                BindingContext = new SubPageViewModel("World")
            });
        }
    }
}
</code>```

SubPage.xaml

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="A.SubPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
    <ContentPage.Content>
        <StackLayout>
            <Label
                HorizontalOptions="CenterAndExpand"
                Text="{Binding Greeting}"
                VerticalOptions="CenterAndExpand" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
</code>```

SubPage.xaml.cs

```<code>using Xamarin.Forms;

namespace A
{
    public partial class SubPage : ContentPage
    {
        public SubPage ()
        {
            InitializeComponent ();
        }
    }
}
</code>```

SubPageViewModel.cs

```<code>using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace A
{
    public class SubPageViewModel : INotifyPropertyChanged
    {
        private string place;

        public string Place
        {
            get => place;
            set
            {
                if(place != value)
                    return;
                place = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(Greeting));
            }
        }

        public SubPageViewModel(string place)
        {
            this.place = place;
        }

        public string Greeting => $"Hello, {place}";

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
</code>```

Visual Studio won't autocomplete bindings in SubPage.xaml and will be complaining that it "Cannot resolve symbol 'Greeting' due to unknown DataContext", because the syntax highlighter doesn't know the type at the compile time. Typically, I'd use the following syntax:

```<code><ContentPage.BindingContext>
    <a:SubPageViewModel />
</ContentPage.BindingContext>
</code>```

however, this isn't applicable here, since the ViewModel is not default constructible.

If this was WPF, I'd be using mc:Ignorable="d" together with d:DesignInstance, however, DesignInstance doesn't seem to be implemented in XF.

How do I make autocompletion work?

答:
You can try:</p>

```<code><ContentPage.BindingContext>
    <x:Type Type="a:SubPageViewModel " />
</ContentPage.BindingContext>
</code>```

Body:
Given the following project:

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="A.MainPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:A">
    <ContentPage.Content>
        <StackLayout>
            <StackLayout>
                <Button Clicked="Greet" Text="Greet" />
            </StackLayout>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

MainPage.xaml.cs

using System;
using Xamarin.Forms;

namespace A
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void Greet(object sender, EventArgs e)
        {
            Navigation.PushModalAsync(new SubPage
            {
                BindingContext = new SubPageViewModel("World")
            });
        }
    }
}

SubPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="A.SubPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
    <ContentPage.Content>
        <StackLayout>

        </StackLayout>
    </ContentPage.Content>
</ContentPage>

SubPage.xaml.cs

using Xamarin.Forms;

namespace A
{
    public partial class SubPage : ContentPage
    {
        public SubPage ()
        {
            InitializeComponent ();
        }
    }
}

SubPageViewModel.cs

using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace A
{
    public class SubPageViewModel : INotifyPropertyChanged
    {
        private string place;

        public string Place
        {
            get => place;
            set
            {
                if(place != value)
                    return;
                place = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(Greeting));
            }
        }

        public SubPageViewModel(string place)
        {
            this.place = place;
        }

        public string Greeting => $"Hello, {place}";

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Visual Studio won't autocomplete bindings in SubPage.xaml and will be complaining that it "Cannot resolve symbol 'Greeting' due to unknown DataContext", because the syntax highlighter doesn't know the type at the compile time. Typically, I'd use the following syntax:

<ContentPage.BindingContext>

</ContentPage.BindingContext>

however, this isn't applicable here, since the ViewModel is not default constructible.

If this was WPF, I'd be using mc:Ignorable="d" together with d:DesignInstance, however, DesignInstance doesn't seem to be implemented in XF.

How do I make autocompletion work?

Body:
You can try:

<ContentPage.BindingContext>
    <x:Type Type="a:SubPageViewModel " />
</ContentPage.BindingContext>


问:
Adding Two Numbers using Two Threads

I want to add just two numbers using two threads,but i didn't understand where i am wrong.

   My output is wrong.And i know problem is with synchronized but not able solve.

```<code>import java.io.*;

class GFG {
public static void main (String[] args) throws InterruptedException {
    final Addition a=new Addition();

    Thread t1 = new Thread(new Runnable()
    {
        public void run(){
            try {
               a.add(1,10);
            } catch(Exception e) {
            }
        }
    });

    Thread t2 = new Thread(new Runnable()
    {
        public void run(){
            try {
                a.add(1,4);
            } catch(Exception e) {
            }
        }
    });

    t1.start();
    t2.start();

    t1.join();
    t2.join();
}

public static class Addition{
    int a, b;
    int sum=0;
    public void add(int a, int b) throws InterruptedException{
        synchronized(this){
            for (int i=a;i<=b;i++){
                sum=sum+i;
                Thread.sleep(1000);
            }
            System.out.println("Sum="+sum);
        }
     }
  }
}
</code>```

Output:

```<code> Sum=55
 Sum=65
</code>```

And by seeing output I can say that... After completing the task of THREAD t1, THREAD t2 is adding its result to the t1...??

答:
This was designed by someone to be deliberately misleading (Perhaps it belongs in puzzles overflow?).  The indenting doesn't match the braces.

You can tell that "sum" will only be initialized to zero once and never re-initialized to zero because Addition is only constructed once (new Addition only happens once).

If you want the Addition object to work independently, set some to zero inside the synchronized.

I kinda hate that I answered this because it's obviously a constructed puzzle/homework type of thing, but you can have this one as a freebie I guess

Title: Adding Two Numbers using Two Threads

Body:
I want to add just two numbers using two threads,but i didn't understand where i am wrong.

   My output is wrong.And i know problem is with synchronized but not able solve.

import java.io.*;

class GFG {
public static void main (String[] args) throws InterruptedException {
    final Addition a=new Addition();

    Thread t1 = new Thread(new Runnable()
    {
        public void run(){
            try {
               a.add(1,10);
            } catch(Exception e) {
            }
        }
    });

    Thread t2 = new Thread(new Runnable()
    {
        public void run(){
            try {
                a.add(1,4);
            } catch(Exception e) {
            }
        }
    });

    t1.start();
    t2.start();

    t1.join();
    t2.join();
}

public static class Addition{
    int a, b;
    int sum=0;
    public void add(int a, int b) throws InterruptedException{
        synchronized(this){
            for (int i=a;i<=b;i++){
                sum=sum+i;
                Thread.sleep(1000);
            }
            System.out.println("Sum="+sum);
        }
     }
  }
}

Output:

 Sum=55
 Sum=65

And by seeing output I can say that... After completing the task of THREAD t1, THREAD t2 is adding its result to the t1...??


问:
Simple Rails Conditional Statement
Pretty simple I'm sure... but I can't figure out why it wouldn't work.

```<code><tr<% if film.viewed == true %> class="viewed"<% end %>>
</code>```

The film.viewed is a boolean but its not rendering the class if its true. Probably a syntax error. Any help? Also is there an easier way to write this without opening and closing? I tried using:

```<code><tr<% if film.viewed == true puts class=\"viewed\" end %>>
</code>```

Again probably a syntax error. I'm coming from PHP so I'm still learning.

Thanks.

答:
Your best bet would be something like the following...

```<code><tr <%= 'class="viewed"' if film.viewed? -%>>
</code>```

All boolean ActiveRecord columns get a question mark method that will return a true or false.  As MySQL stores booleans as 1/0, I usually use the question mark method just to be safe.

Title: Simple Rails Conditional Statement

Body:
Pretty simple I'm sure... but I can't figure out why it wouldn't work.

<tr<% if film.viewed == true %> class="viewed"<% end %>>

The film.viewed is a boolean but its not rendering the class if its true. Probably a syntax error. Any help? Also is there an easier way to write this without opening and closing? I tried using:

<tr<% if film.viewed == true puts class=\"viewed\" end %>>

Again probably a syntax error. I'm coming from PHP so I'm still learning.

Thanks.

Body:
Your best bet would be something like the following...

<tr <%= 'class="viewed"' if film.viewed? -%>>

All boolean ActiveRecord columns get a question mark method that will return a true or false.  As MySQL stores booleans as 1/0, I usually use the question mark method just to be safe.


问:
What is difference between these approaches in python?
First approach

```<code>n, m = [int(n), int(m)]
</code>```

Second approach

```<code>n, m = int(n), int(m)
</code>```

Both lines gives the same output. Then, is it necessary to close parameters under square bracket?

答: int(n), int(m) creates a 2-item tuple. [int(n), int(m)] creates a 2-item list.  Once you break the pair apart into 2 items, as part of the assignments, there is no difference left.

Body:
First approach

n, m = [int(n), int(m)]

Second approach

n, m = int(n), int(m)

Both lines gives the same output. Then, is it necessary to close parameters under square bracket?


问:
Get data by using a query from a website
Using Python or R, how can the following website's data be downloaded into a dataframe or similar format? I assume this is not web scraping, but rather making a request to GET the data using a query.

https://www.michigantrafficcrashfacts.org/querytool/lists/0#q1;0;2016;;

答:
You do not need to make web scraper, i observed all requests to that site, and then I decoded those requests with my tools...., see:

1) https://www.michigantrafficcrashfacts.org/qjson?q=1;0;2016;;&v=list&p=0,0:0,77|0|90|0,asc:1,asc   || 90 Records as json

2) https://www.michigantrafficcrashfacts.org/qjson?q=1;0;2016;;&v=list&p=0,0:0,77|0|2000|0,asc:1,asc
    ||  2000 Records as json

```<code>import json, requests

your_records = 3000  # change this record with that number you want ( that website said the max value is 312172 )

URL = "https://www.michigantrafficcrashfacts.org/qjson?q=1;0;2016;;&v=list&p=0,0:0,77|0|{0}|0,asc:1,asc".format(your_records)

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

get_data = requests.get(URL, headers=headers)

raw_data = str(get_data.content, encoding="utf-8")

dict_data = json.loads(raw_data)

for items, values in dict_data.items():
    print(items, values)
</code>```

NOTE : Please do not use it in illegal or hacky cases.

Body:
You do not need to make web scraper, i observed all requests to that site, and then I decoded those requests with my tools...., see:

1) https://www.michigantrafficcrashfacts.org/qjson?q=1;0;2016;;&v=list&p=0,0:0,77|0|90|0,asc:1,asc   || 90 Records as json

2) https://www.michigantrafficcrashfacts.org/qjson?q=1;0;2016;;&v=list&p=0,0:0,77|0|2000|0,asc:1,asc
    ||  2000 Records as json

import json, requests

your_records = 3000  # change this record with that number you want ( that website said the max value is 312172 )

URL = "https://www.michigantrafficcrashfacts.org/qjson?q=1;0;2016;;&v=list&p=0,0:0,77|0|{0}|0,asc:1,asc".format(your_records)

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

get_data = requests.get(URL, headers=headers)

raw_data = str(get_data.content, encoding="utf-8")

dict_data = json.loads(raw_data)

for items, values in dict_data.items():
    print(items, values)

NOTE : Please do not use it in illegal or hacky cases.


问:
Find duplicates in two columns in a table
I just browse this post and tried all the scripts but still i am not getting what i am expecting.

Here is my table

```<code>Name        email
BRIAN MAT   BRIAN.MAT@abc.Com
BRIAN MAT   BRIAN MAT@abc.Com
AMY Lee     AMY.Lee@abc.Com
AMY.Lee     AMY.Lee@abc.Com
Madison Taylor  Madison.Tyl@abc.com

SELECT Name
FROM Employee
GROUP BY Name
HAVING ( COUNT(Name > 1 )
</code>```

result

BRIAN MAT

```<code>SELECT email
FROM Employee
GROUP BY email
HAVING ( COUNT(email> 1 )
</code>```

Result

AMY.Lee@abc.Com

I was trying to group this two script but it shows blank

```<code>SELECT
    Name, email,COUNT(*)
FROM
    Employee
GROUP BY
    Name, email
HAVING
    COUNT(*) > 1
</code>```

Please correct me what i am missing in my script to acheive the result like below

```<code>Name        email
BRIAN MAT   BRIAN.MAT@abc.Com
BRIAN MAT   BRIAN MAT@abc.Com
AMY Lee     AMY.Lee@abc.Com
AMY.Lee     AMY.Lee@abc.Com
</code>```

答:
You could use windowed COUNT:

```<code>WITH cte  AS (
   SELECT *,
         COUNT(*) OVER(PARTITION BY name)  AS c_name,
         COUNT(*) OVER(PARTITION BY Email) AS c_email
   FROM Employee
)
SELECT name, email
FROM cte
WHERE c_name > 1 OR c_email > 1;
</code>```

Body:
I just browse this post and tried all the scripts but still i am not getting what i am expecting.

Here is my table

Name        email
BRIAN MAT   BRIAN.MAT@abc.Com
BRIAN MAT   BRIAN MAT@abc.Com
AMY Lee     AMY.Lee@abc.Com
AMY.Lee     AMY.Lee@abc.Com
Madison Taylor  Madison.Tyl@abc.com

SELECT Name
FROM Employee
GROUP BY Name
HAVING ( COUNT(Name > 1 )

result

BRIAN MAT

SELECT email
FROM Employee
GROUP BY email
HAVING ( COUNT(email> 1 )

Result

AMY.Lee@abc.Com

I was trying to group this two script but it shows blank

SELECT
    Name, email,COUNT(*)
FROM
    Employee
GROUP BY
    Name, email
HAVING
    COUNT(*) > 1

Please correct me what i am missing in my script to acheive the result like below

Name        email
BRIAN MAT   BRIAN.MAT@abc.Com
BRIAN MAT   BRIAN MAT@abc.Com
AMY Lee     AMY.Lee@abc.Com
AMY.Lee     AMY.Lee@abc.Com

Body:
You could use windowed COUNT:

WITH cte  AS (
   SELECT *,
         COUNT(*) OVER(PARTITION BY name)  AS c_name,
         COUNT(*) OVER(PARTITION BY Email) AS c_email
   FROM Employee
)
SELECT name, email
FROM cte
WHERE c_name > 1 OR c_email > 1;


答:
```<code><tr <%= film.viewed ? 'class="viewed"' : 'class="notviewed" %> >
</code>```

So, some notes.

To do a full if ... end you would have needed a ";" or newline before the end.

Do you actually have a local variable or parameter called film?

You need <%= and not just <% in order to interpolate the final result of your template code.

I imagine the erb template driver calls the to_s method on whatever result it gets, and since nil.to_s returns "" then you are safe with a stand-alone false if statement, which has the effect as an expression of returning nil. But somehow having the expression always return a value one would be willing to see interpolated would seem to make sense.

Title: Simple Rails Conditional Statement

Body:
<tr <%= film.viewed ? 'class="viewed"' : 'class="notviewed" %> >

So, some notes.

To do a full if ... end you would have needed a ";" or newline before the end.

Do you actually have a local variable or parameter called film?

You need <%= and not just <% in order to interpolate the final result of your template code.

I imagine the erb template driver calls the to_s method on whatever result it gets, and since nil.to_s returns "" then you are safe with a stand-alone false if statement, which has the effect as an expression of returning nil. But somehow having the expression always return a value one would be willing to see interpolated would seem to make sense.


问:
Need to install mysql-devel in the server that has cPanel - `libmysqlclient_16' not found
I have a Python script in cPanel and need to connect my script to MYSQL, for connecting Python to MYSQL I need to have libmysqlclient

When I run my code, the system shows me the following error

```<code>File "/usr/lib64/python3.6/site-packages/MySQLdb/init.py", line 19, in <module>
import _mysql
ImportError: /usr/lib64/libmysqlclient.so.18: version `libmysqlclient_16' not found (required by /usr/lib64/python3.6/site-packages/_mysql.cpython-36m-x86_64-linux-gnu.so)
</code>```

server-os: Centos 6.9

cpanel-version: 68.0.13

list of libmysqlclient in /usr/lib64

```<code>/usr/lib64/libmysqlclient_r.so.15
/usr/lib64/libmysqlclient.so
/usr/lib64/libmysqlclient.so.16.0.0
/usr/lib64/libmysqlclient_r.so.16.0.0
/usr/lib64/libmysqlclient.so.15.0.0
/usr/lib64/libmysqlclient_r.so.18
/usr/lib64/libmysqlclient_r.so.18.1.0
/usr/lib64/libmysqlclient.so.15
/usr/lib64/libmysqlclient_r.so.15.0.0
/usr/lib64/mysql/libmysqlclient.a
/usr/lib64/mysql/libmysqlclient_r.a
/usr/lib64/libmysqlclient.so.16
/usr/lib64/libmysqlclient_r.so
/usr/lib64/libmysqlclient_r.so.16
/usr/lib64/libmysqlclient.so.18
/usr/lib64/libmysqlclient.so.18.1.0
</code>```

答:
You can use mysql.connector

On ubuntu: sudo apt-get install python-mysql.connector or python3-mysql.connector for python 3

Then:

```<code>import mysql.connector
mysql.connector.connect(host='localhost',database='mysql',user='root',password='')
</code>```

Body:
I have a Python script in cPanel and need to connect my script to MYSQL, for connecting Python to MYSQL I need to have libmysqlclient

When I run my code, the system shows me the following error

File "/usr/lib64/python3.6/site-packages/MySQLdb/init.py", line 19, in <module>
import _mysql
ImportError: /usr/lib64/libmysqlclient.so.18: version `libmysqlclient_16' not found (required by /usr/lib64/python3.6/site-packages/_mysql.cpython-36m-x86_64-linux-gnu.so)

server-os: Centos 6.9

cpanel-version: 68.0.13

list of libmysqlclient in /usr/lib64

/usr/lib64/libmysqlclient_r.so.15
/usr/lib64/libmysqlclient.so
/usr/lib64/libmysqlclient.so.16.0.0
/usr/lib64/libmysqlclient_r.so.16.0.0
/usr/lib64/libmysqlclient.so.15.0.0
/usr/lib64/libmysqlclient_r.so.18
/usr/lib64/libmysqlclient_r.so.18.1.0
/usr/lib64/libmysqlclient.so.15
/usr/lib64/libmysqlclient_r.so.15.0.0
/usr/lib64/mysql/libmysqlclient.a
/usr/lib64/mysql/libmysqlclient_r.a
/usr/lib64/libmysqlclient.so.16
/usr/lib64/libmysqlclient_r.so
/usr/lib64/libmysqlclient_r.so.16
/usr/lib64/libmysqlclient.so.18
/usr/lib64/libmysqlclient.so.18.1.0

Body:
You can use mysql.connector

On ubuntu: sudo apt-get install python-mysql.connector or python3-mysql.connector for python 3

Then:

import mysql.connector
mysql.connector.connect(host='localhost',database='mysql',user='root',password='')


问:
what's the right type for viper
I have the following yaml file and want to iterate over the cameraids.---

```<code>---
profiles:
  HDready: ' -vcodec libx264 -pix_fmt yuv420p -crf 23 -s 1280x720 '
  mobile: ' -vcodec libx264 -pix_fmt yuv420p -crf 23 -s 480x270 '

cameraids:
  111:
    fps: 30
  191:
    fps: 50
  851:
    fps: 50
</code>```

I want now to iterate over the cameraids and profiles therefore I declare the variable for cameraids like this

var camids map[string]interface{}

The same as the fmt.Println(reflect.TypeOf(viper.Get("cameraids"))) prints but I always get the following error no new variables on left side of := when I try to get the map from viper

camids := viper.GetStringMap("cameraids")

Please can you explain and help me what I misunderstand, thanks.

答:
If you've declared camids

```<code>var camids map[string]interface{}
</code>```

above, you don't need to use := since the variable camids has been already declared.

So just write:

```<code>camids = viper.GetStringMap("cameraids")
</code>```

:= is used when you want to declare the variable and assigns the value to it at the same time.

= is used when you've already declared the variable beforehand and you're just assigning the value to it.

Title: what's the right type for viper

Body:
I have the following yaml file and want to iterate over the cameraids.---

---
profiles:
  HDready: ' -vcodec libx264 -pix_fmt yuv420p -crf 23 -s 1280x720 '
  mobile: ' -vcodec libx264 -pix_fmt yuv420p -crf 23 -s 480x270 '

cameraids:
  111:
    fps: 30
  191:
    fps: 50
  851:
    fps: 50

I want now to iterate over the cameraids and profiles therefore I declare the variable for cameraids like this

var camids map[string]interface{}

The same as the fmt.Println(reflect.TypeOf(viper.Get("cameraids"))) prints but I always get the following error no new variables on left side of := when I try to get the map from viper

camids := viper.GetStringMap("cameraids")

Please can you explain and help me what I misunderstand, thanks.

Body:
If you've declared camids

var camids map[string]interface{}

above, you don't need to use := since the variable camids has been already declared.

So just write:

camids = viper.GetStringMap("cameraids")

:= is used when you want to declare the variable and assigns the value to it at the same time.

= is used when you've already declared the variable beforehand and you're just assigning the value to it.


问:
Trying to use controllers in AngularJS
I have implemented auto-complete feature, now I am trying to integrate into my main application. This is the controller function which I designed.

```<code>(function() {
      'use strict';
      angular
        .module('MyApp')
        .controller('DemoCtrl', DemoCtrl);

      function DemoCtrl($http) {
        this.querySearch = function (query) {
           return $http.get('http://127.0.0.1:8888/autocomplete/' + escape(query)).then(function(result) {
              return result.data;
            });
        }
      }
    })();
</code>```

This is my HTML for the first scenario:

```<code><div class="autocompletedemoFloatingLabel" ng-controller="DemoCtrl as ctrl" ng-app="MyApp" layout="column" ng-cloak="">
      <md-content class="md-padding">
        <form name="searchForm" ng-submit="$event.preventDefault()">
            <div layout-gt-sm="row">
            <md-input-container flex="">
            </md-input-container>

            <md-autocomplete md-floating-label=""
                            flex=""
                            md-item-text="item.Symbol"
                            md-items="item in ctrl.querySearch(ctrl.searchText)"
                            md-search-text="ctrl.searchText"
                            md-selected-item="ctrl.selectedItem"
                            md-no-cache="ctrl.noCache"
                            md-input-name="autocompleteField"
                            required="">
              <input>
              <md-item-template>
                <span md-highlight-text="ctrl.searchText">{{item.Symbol+" - "+item.Name+" ("+item.Exchange+")"}}</span>
              </md-item-template>
              <div ng-messages="searchForm.autocompleteField.$error" ng-if="searchForm.autocompleteField.$touched">
                <div ng-message="required">You <b>must</b> have a favorite movie.</div>
                <div ng-message="minlength">Your entry is not long enough.</div>
                <div ng-message="maxlength">Your entry is too long.</div>
              </div>
            </md-autocomplete>
          </input>
          </div>
    </form>
  </md-content>
</div>
</code>```

Now the application currently contains controller in this format:

```<code>var app = angular.module("assign8", ["ngAnimate"]);
app.controller("MyCtrl", function ($scope) {
$scope.myValue=false;
$scope.myValue_sec = false;
});
</code>```

I am very new to angular, I am unable to map the first format to the second one. Kindly let me know how can I map first to second. TIA.

答:
There are two manners to make the binding in AngularJS.

The controller as that is what is done in the first format, you can see DemoCtrl as ctrl in html the ctrl variable represent your controller, in your controller, you see this, every attribut of this can be accessed via ctrl in html. for example: ctrl.myAttribut.

The second manner is the use of $scope service. that is what is done in the second format. every attribut of $scope can be accessed in html as long as the corresponding controller is called. For example: if in your controller you have $scope.myAttribut, in your html you can access like this {{myAttribut}}.

Title: Trying to use controllers in AngularJS

Body:
I have implemented auto-complete feature, now I am trying to integrate into my main application. This is the controller function which I designed.

(function() {
      'use strict';
      angular
        .module('MyApp')
        .controller('DemoCtrl', DemoCtrl);

      function DemoCtrl($http) {
        this.querySearch = function (query) {
           return $http.get('http://127.0.0.1:8888/autocomplete/' + escape(query)).then(function(result) {
              return result.data;
            });
        }
      }
    })();

This is my HTML for the first scenario:

      <md-content class="md-padding">
        <form name="searchForm" ng-submit="$event.preventDefault()">

            <md-input-container flex="">
            </md-input-container>

            <md-autocomplete md-floating-label=""
                            flex=""
                            md-item-text="item.Symbol"
                            md-items="item in ctrl.querySearch(ctrl.searchText)"
                            md-search-text="ctrl.searchText"
                            md-selected-item="ctrl.selectedItem"
                            md-no-cache="ctrl.noCache"
                            md-input-name="autocompleteField"
                            required="">
              <input>
              <md-item-template>
                {{item.Symbol+" - "+item.Name+" ("+item.Exchange+")"}}
              </md-item-template>

You must have a favorite movie.

Your entry is not long enough.

Your entry is too long.

            </md-autocomplete>
          </input>

    </form>
  </md-content>

Now the application currently contains controller in this format:

var app = angular.module("assign8", ["ngAnimate"]);
app.controller("MyCtrl", function ($scope) {
$scope.myValue=false;
$scope.myValue_sec = false;
});

I am very new to angular, I am unable to map the first format to the second one. Kindly let me know how can I map first to second. TIA.


问:
count string and print to new outfile
I am attempting to count the occurrences of a particular string "PhD" within a file 'X', take that count# (e.g. 3), and print/cat to the beginning of another file, 3 times, this particular string

```<code>Graduate StudentID 1
Graduate StudentID 2
Graduate StudentID 3
</code>```

The numbers after StudentID reflect the counting.

My hopeless attempt to this point is ($OUT was supposed to the file written to) and I am not sure how to resolve the (obvious) resultant errors.

```<code>find /home/college/Applications/Graduate -name "*.inp" -exec sed 's/[PhD]//g' input | uniq -c print >$OUT {$1} \;
</code>```

答:
Here is how I would do it:

```<code>#!/bin/bash

# Count number of occurrences
# Use -o | wc -l instead of -c to count multiple occurrences in same line
count=$(grep -ro 'PhD' --include='*.inp' /home/college/Applications/Graduate | wc -l)

# Intermediate file
tmp=$(tempfile)

# Output file
out=outfile.txt

{
    # Print header lines
    for (( i = 1; i <= count; ++i )); do
        printf '%s %d\n' 'Graduate StudentID' "$i"
    done

    # Print existing contents
    cat "$out"
} > "$tmp"

# Rename intermediate file
mv "$tmp" "$out"
</code>```

This assumes that your output file name is outfile.txt

Title: count string and print to new outfile

Body:
I am attempting to count the occurrences of a particular string "PhD" within a file 'X', take that count# (e.g. 3), and print/cat to the beginning of another file, 3 times, this particular string

Graduate StudentID 1
Graduate StudentID 2
Graduate StudentID 3

The numbers after StudentID reflect the counting.

My hopeless attempt to this point is ($OUT was supposed to the file written to) and I am not sure how to resolve the (obvious) resultant errors.

find /home/college/Applications/Graduate -name "*.inp" -exec sed 's/[PhD]//g' input | uniq -c print >$OUT {$1} \;

Body:
Here is how I would do it:

#!/bin/bash

# Count number of occurrences
# Use -o | wc -l instead of -c to count multiple occurrences in same line
count=$(grep -ro 'PhD' --include='*.inp' /home/college/Applications/Graduate | wc -l)

# Intermediate file
tmp=$(tempfile)

# Output file
out=outfile.txt

{
    # Print header lines
    for (( i = 1; i <= count; ++i )); do
        printf '%s %d\n' 'Graduate StudentID' "$i"
    done

    # Print existing contents
    cat "$out"
} > "$tmp"

# Rename intermediate file
mv "$tmp" "$out"

This assumes that your output file name is outfile.txt