问:
You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [?,784] for MNIST dataset
Here is the example I am testing on MNIST dataset for quantization. I am testing my model using below code:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.python.framework import graph_util
from tensorflow.core.framework import graph_pb2
import numpy as np

def test_model(model_file,x_in):
    with tf.Session() as sess:
        with open(model_file, "rb") as f:
            output_graph_def = graph_pb2.GraphDef()
            output_graph_def.ParseFromString(f.read())
            _ = tf.import_graph_def(output_graph_def, name="")
        x = sess.graph.get_tensor_by_name('Placeholder_1:0')
        y = sess.graph.get_tensor_by_name('softmax_cross_entropy_with_logits:0')
        new_scores = sess.run(y, feed_dict={x:x_in.test.images})
        print((orig_scores - new_scores) < 1e-6)
        find_top_pred(orig_scores)
        find_top_pred(new_scores)

#print(epoch_x.shape)
mnist = input_data.read_data_sets("/tmp/data/", one_hot = True)
test_model('mnist_cnn1.pb',mnist)
```

<p>I am not getting where I am providing incorrect values. Here I have added the complete track of error code. Below is the error:</p>

<pre class="lang-py prettyprint-override"><code>Extracting /tmp/data/train-images-idx3-ubyte.gz
Extracting /tmp/data/train-labels-idx1-ubyte.gz
Extracting /tmp/data/t10k-images-idx3-ubyte.gz
Extracting /tmp/data/t10k-labels-idx1-ubyte.gz
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1323, in _do_call
    return fn(*args)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1302, in _run_fn
    status, run_metadata)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/errors_impl.py", line 473, in __exit__
    c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [?,784]
     [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[?,784], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
</code>```

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "tmp.py", line 26, in <module>
    test_model('/home/shringa/tensorflowdata/mnist_cnn1.pb',mnist)
  File "tmp.py", line 19, in test_model
    new_scores = sess.run(y, feed_dict={x:x_in.test.images})
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 889, in run
    run_metadata_ptr)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1120, in _run
    feed_dict_tensor, options, run_metadata)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1317, in _do_run
    options, run_metadata)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1336, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [?,784]
     [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[?,784], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

Caused by op 'Placeholder', defined at:
  File "tmp.py", line 26, in <module>
    test_model('/home/shringa/tensorflowdata/mnist_cnn1.pb',mnist)
  File "tmp.py", line 16, in test_model
    _ = tf.import_graph_def(output_graph_def, name="")
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/util/deprecation.py", line 316, in new_func
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/importer.py", line 411, in import_graph_def
    op_def=op_def)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 3069, in create_op
    op_def=op_def)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 1579, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [?,784]
     [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[?,784], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
```

<p>As shown above I am using <code>mnist_cnn1.pb</code> file to extract my model and to test it on mnist test images but it is throwing error of shape of the placeholder.</p>

<p>Below shown is my cnn model:</p>

<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot = True)
print(type(mnist));

n_classes = 10
batch_size = 128

x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32)

def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding= 'SAME')

def maxpool2d(x):
    #                           size of window      movement of window
    return tf.nn.max_pool(x, ksize =[1,2,2,1], strides= [1,2,2,1], padding = 'SAME')

def convolutional_network_model(x):
    weights = {'W_conv1':tf.Variable(tf.random_normal([5,5,1,32])),
    'W_conv2':tf.Variable(tf.random_normal([5,5,32,64])),
    'W_fc':tf.Variable(tf.random_normal([7*7*64,1024])),
    'out':tf.Variable(tf.random_normal([1024, n_classes]))}

    biases = {'B_conv1':tf.Variable(tf.random_normal([32])),
    'B_conv2':tf.Variable(tf.random_normal([64])),
    'B_fc':tf.Variable(tf.random_normal([1024])),
    'out':tf.Variable(tf.random_normal([n_classes]))}

    x = tf.reshape(x, shape=[-1,28,28,1])
    conv1 =  conv2d(x, weights['W_conv1'])
    conv1 =  maxpool2d(conv1)

    conv2 =  conv2d(conv1, weights['W_conv2'])
    conv2 =  maxpool2d(conv2)

    fc =tf.reshape(conv2,[-1,7*7*64])
    fc = tf.nn.relu(tf.matmul(fc, weights['W_fc'])+ biases['B_fc'])

    output =  tf.matmul(fc, weights['out']+biases['out'])

    return output

def train_neural_network(x):
    prediction = convolutional_network_model(x)
    # OLD VERSION:
    #cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(prediction,y) )
    # NEW:
    cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits_v2(logits=prediction, labels=y) )
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    hm_epochs = 25
    with tf.Session() as sess:
        # OLD:
        #sess.run(tf.initialize_all_variables())
        # NEW:
        sess.run(tf.global_variables_initializer())

        for epoch in range(hm_epochs):
            epoch_loss = 0
            for _ in range(int(mnist.train.num_examples/batch_size)):
                epoch_x, epoch_y = mnist.train.next_batch(batch_size)
                _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y})
                epoch_loss += c

            print('Epoch', epoch, 'completed out of',hm_epochs,'loss:',epoch_loss)

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))

        accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
        print('Accuracy:',accuracy.eval({x:mnist.test.images, y:mnist.test.labels}))

train_neural_network(x)
</code>```

and by using bazel I have created mnist_cnn1.pb file:

python3 tensorflow/tools/quantization/quantize_graph.py   --input=/home/shringa/tensorflowdata/mnist_cnn.pb  --output=/home/shringa/tensorflowdata/mnist_cnn1.pb   --output_node_names=softmax_cross_entropy_with_logits  --mode=eightbit
bazel-bin/tensorflow/tools/graph_transforms/summarize_graph --in_graph=/home/shringa/tensorflowdata/mnist_cnn1.pb
```

答:
Reason

The cause of your problem is that you didn't give names to your variables / nodes and, as a result, got confused.

When you define the placeholders:

x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32)
```

<p>... <code>x</code> and <code>y</code> get assigned the following names by tensorflow:</p>

<pre class="lang-py prettyprint-override"><code>Tensor("Placeholder:0", shape=(?, 784), dtype=float32)  <-- x
Tensor("Placeholder_1:0", dtype=float32)                <-- y
</code>```

As a result, on test time, the following line pulls the wrong node:

x = sess.graph.get_tensor_by_name('Placeholder_1:0')  # this is y!
```

<p>That's why tensorflow complains about not feeding the placeholder: it needs <code>x</code>, not <code>y</code>.</p>

<h2>Solution</h2>

<p>Make it explicit:</p>

<pre class="lang-py prettyprint-override"><code>x = tf.placeholder(tf.float32, [None, 784], name='x')
y = tf.placeholder(tf.float32, name='y')
...
x = sess.graph.get_tensor_by_name('x')
</code>```

I'd also provide the name to softmax_cross_entropy_with_logits op as well to make all inference nodes easily accessible.

Body:
Here is the example I am testing on MNIST dataset for quantization. I am testing my model using below code:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.python.framework import graph_util
from tensorflow.core.framework import graph_pb2
import numpy as np

def test_model(model_file,x_in):
    with tf.Session() as sess:
        with open(model_file, "rb") as f:
            output_graph_def = graph_pb2.GraphDef()
            output_graph_def.ParseFromString(f.read())
            _ = tf.import_graph_def(output_graph_def, name="")
        x = sess.graph.get_tensor_by_name('Placeholder_1:0')
        y = sess.graph.get_tensor_by_name('softmax_cross_entropy_with_logits:0')
        new_scores = sess.run(y, feed_dict={x:x_in.test.images})
        print((orig_scores - new_scores) < 1e-6)
        find_top_pred(orig_scores)
        find_top_pred(new_scores)

#print(epoch_x.shape)
mnist = input_data.read_data_sets("/tmp/data/", one_hot = True)
test_model('mnist_cnn1.pb',mnist)

I am not getting where I am providing incorrect values. Here I have added the complete track of error code. Below is the error:

Extracting /tmp/data/train-images-idx3-ubyte.gz
Extracting /tmp/data/train-labels-idx1-ubyte.gz
Extracting /tmp/data/t10k-images-idx3-ubyte.gz
Extracting /tmp/data/t10k-labels-idx1-ubyte.gz
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1323, in _do_call
    return fn(*args)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1302, in _run_fn
    status, run_metadata)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/errors_impl.py", line 473, in __exit__
    c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [?,784]
     [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[?,784], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "tmp.py", line 26, in <module>
    test_model('/home/shringa/tensorflowdata/mnist_cnn1.pb',mnist)
  File "tmp.py", line 19, in test_model
    new_scores = sess.run(y, feed_dict={x:x_in.test.images})
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 889, in run
    run_metadata_ptr)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1120, in _run
    feed_dict_tensor, options, run_metadata)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1317, in _do_run
    options, run_metadata)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1336, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [?,784]
     [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[?,784], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

Caused by op 'Placeholder', defined at:
  File "tmp.py", line 26, in <module>
    test_model('/home/shringa/tensorflowdata/mnist_cnn1.pb',mnist)
  File "tmp.py", line 16, in test_model
    _ = tf.import_graph_def(output_graph_def, name="")
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/util/deprecation.py", line 316, in new_func
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/importer.py", line 411, in import_graph_def
    op_def=op_def)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 3069, in create_op
    op_def=op_def)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 1579, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [?,784]
     [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[?,784], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

As shown above I am using mnist_cnn1.pb file to extract my model and to test it on mnist test images but it is throwing error of shape of the placeholder.

Below shown is my cnn model:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot = True)
print(type(mnist));

n_classes = 10
batch_size = 128

x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32)

def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding= 'SAME')

def maxpool2d(x):
    #                           size of window      movement of window
    return tf.nn.max_pool(x, ksize =[1,2,2,1], strides= [1,2,2,1], padding = 'SAME')

def convolutional_network_model(x):
    weights = {'W_conv1':tf.Variable(tf.random_normal([5,5,1,32])),
    'W_conv2':tf.Variable(tf.random_normal([5,5,32,64])),
    'W_fc':tf.Variable(tf.random_normal([7*7*64,1024])),
    'out':tf.Variable(tf.random_normal([1024, n_classes]))}

    biases = {'B_conv1':tf.Variable(tf.random_normal([32])),
    'B_conv2':tf.Variable(tf.random_normal([64])),
    'B_fc':tf.Variable(tf.random_normal([1024])),
    'out':tf.Variable(tf.random_normal([n_classes]))}

    x = tf.reshape(x, shape=[-1,28,28,1])
    conv1 =  conv2d(x, weights['W_conv1'])
    conv1 =  maxpool2d(conv1)

    conv2 =  conv2d(conv1, weights['W_conv2'])
    conv2 =  maxpool2d(conv2)

    fc =tf.reshape(conv2,[-1,7*7*64])
    fc = tf.nn.relu(tf.matmul(fc, weights['W_fc'])+ biases['B_fc'])

    output =  tf.matmul(fc, weights['out']+biases['out'])

    return output

def train_neural_network(x):
    prediction = convolutional_network_model(x)
    # OLD VERSION:
    #cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(prediction,y) )
    # NEW:
    cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits_v2(logits=prediction, labels=y) )
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    hm_epochs = 25
    with tf.Session() as sess:
        # OLD:
        #sess.run(tf.initialize_all_variables())
        # NEW:
        sess.run(tf.global_variables_initializer())

        for epoch in range(hm_epochs):
            epoch_loss = 0
            for _ in range(int(mnist.train.num_examples/batch_size)):
                epoch_x, epoch_y = mnist.train.next_batch(batch_size)
                _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y})
                epoch_loss += c

            print('Epoch', epoch, 'completed out of',hm_epochs,'loss:',epoch_loss)

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))

        accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
        print('Accuracy:',accuracy.eval({x:mnist.test.images, y:mnist.test.labels}))

train_neural_network(x)

and by using bazel I have created mnist_cnn1.pb file:

python3 tensorflow/tools/quantization/quantize_graph.py   --input=/home/shringa/tensorflowdata/mnist_cnn.pb  --output=/home/shringa/tensorflowdata/mnist_cnn1.pb   --output_node_names=softmax_cross_entropy_with_logits  --mode=eightbit
bazel-bin/tensorflow/tools/graph_transforms/summarize_graph --in_graph=/home/shringa/tensorflowdata/mnist_cnn1.pb

Body:
Reason

The cause of your problem is that you didn't give names to your variables / nodes and, as a result, got confused.

When you define the placeholders:

x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32)

... x and y get assigned the following names by tensorflow:

Tensor("Placeholder:0", shape=(?, 784), dtype=float32)  <-- x
Tensor("Placeholder_1:0", dtype=float32)                <-- y

As a result, on test time, the following line pulls the wrong node:

x = sess.graph.get_tensor_by_name('Placeholder_1:0')  # this is y!

That's why tensorflow complains about not feeding the placeholder: it needs x, not y.

Solution

Make it explicit:

x = tf.placeholder(tf.float32, [None, 784], name='x')
y = tf.placeholder(tf.float32, name='y')
...
x = sess.graph.get_tensor_by_name('x')

I'd also provide the name to softmax_cross_entropy_with_logits op as well to make all inference nodes easily accessible.


来源: stackexchange

问:
Change the lightness of a color to a specific value
I'm trying to change a specific color's lightness to a specific percentage.

For example:

myFunction( hsl(218, 100%, 63%), 80% );

will turn hsl(218, 100%, 63%) to hsl(218, 100%, 80%).

I couldn't find any color operation function that does that; as tint() changes the saturation too, and lighten() is relative to the current lightness (adds to the current value).

Is there any way to achieve this using LESS?

Thanks!

答:
Well, I have found a workaround:

```<code>background-color: lighten( @color, 80% - lightness(@color) );
</code>```

the 80% represents the desired lightness value.

This should work with hue and saturation too:

```<code>// Hue:
background-color: spin( @color, 100 - hue(@color) ); // (100 degrees).

// Saturation:
background-color: saturate( @color, 80% - saturation(@color) );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Well, I have found a workaround:

background-color: lighten( @color, 80% - lightness(@color) );

the 80% represents the desired lightness value.

This should work with hue and saturation too:

// Hue:
background-color: spin( @color, 100 - hue(@color) ); // (100 degrees).

// Saturation:
background-color: saturate( @color, 80% - saturation(@color) );


问:
Why LegacyFormHelper in FOSUserBundle removed
we have a Symofny 2.8 application, and on serval places we use the LegacyFormHelper from the OS\UserBundle\Util\LegacyFormHelper.

It seems, that in the actual update this class has removed, and I wonder why.

So actually, I'm looking for a possibility to use a RepeatedType in a FormType, which is acutally coded like

```<code>->add('plainPassword', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\RepeatedType'), array(
                    'type' => LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\PasswordType'),
                    'options' => array('translation_domain' => 'FOSUserBundle'),
                    'first_options' => array('label' => 'form.password', 'attr' => array('placeholder' => 'Passwort')),
                    'second_options' => array('label' => 'form.password_confirmation'),
                    'invalid_message' => 'fos_user.password.mismatch',
                    'required' => false
                ))
</code>```

And now we want to code that without the LegacyFormHelper.

Has Somebody an idea?

Regards
Thomas

答:
And somtimes I can answer my own questions ;-)

I simply do

```<code>->add('plainPassword', RepeatedType::class, array(
                    'type' => PasswordType::class,
                    'options' => array('translation_domain' => 'FOSUserBundle'),
                    'first_options' => array('label' => 'form.password', 'attr' => array('placeholder' => 'Passwort')),
                    'second_options' => array('label' => 'form.password_confirmation'),
                    'invalid_message' => 'fos_user.password.mismatch',
                    'required' => false
                ))
</code>```

So if somebody has as similar problem with the LegacyFormHelper, the solution is easy!

Body:
we have a Symofny 2.8 application, and on serval places we use the LegacyFormHelper from the OS\UserBundle\Util\LegacyFormHelper.

It seems, that in the actual update this class has removed, and I wonder why.

So actually, I'm looking for a possibility to use a RepeatedType in a FormType, which is acutally coded like

->add('plainPassword', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\RepeatedType'), array(
                    'type' => LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\PasswordType'),
                    'options' => array('translation_domain' => 'FOSUserBundle'),
                    'first_options' => array('label' => 'form.password', 'attr' => array('placeholder' => 'Passwort')),
                    'second_options' => array('label' => 'form.password_confirmation'),
                    'invalid_message' => 'fos_user.password.mismatch',
                    'required' => false
                ))

And now we want to code that without the LegacyFormHelper.

Has Somebody an idea?

Regards
Thomas

Body:
And somtimes I can answer my own questions ;-)

I simply do

->add('plainPassword', RepeatedType::class, array(
                    'type' => PasswordType::class,
                    'options' => array('translation_domain' => 'FOSUserBundle'),
                    'first_options' => array('label' => 'form.password', 'attr' => array('placeholder' => 'Passwort')),
                    'second_options' => array('label' => 'form.password_confirmation'),
                    'invalid_message' => 'fos_user.password.mismatch',
                    'required' => false
                ))

So if somebody has as similar problem with the LegacyFormHelper, the solution is easy!


问:
Laravel Eager Loading Relation With Additional ->where()
This is my relation method in my model:

```<code>public function relation()
{
    return $this->belongsTo('App\Table', 'table_2_id', 'table_2_id')->where('table_1_id', $this->table_1_id);
}
</code>```

So, both the model above and Table2 have the same column, but there is the possibility of many entries, so I want to then filter on a second column that is shared by both tables, table_1_id.

It seems to work perfectly on the command line, but when eager loading the relationship is empty.

If I remove the additional ->where() from the relationship method then the eager loading works.

The way I am eager-loading is by doing

```<code>->with('relation.nestedRelation');
</code>```

I've also tried

```<code>->with(['relation' => function ($q) {
    $q->with('nestedRelation');
}])
</code>```

I've just tried adding it as an attribute to see if that helped but still no joy.

答:
You can use the whereColumn() function :

```<code>->whereColumn('table_1.table_1_id', 'table_2.table_1_id')
</code>```

Or you can use that :

```<code>public function filterRelation(){
     return $this->relation->where('table_1_id', $this->table_1_id);

}
</code>```

Body:
This is my relation method in my model:

public function relation()
{
    return $this->belongsTo('App\Table', 'table_2_id', 'table_2_id')->where('table_1_id', $this->table_1_id);
}

So, both the model above and Table2 have the same column, but there is the possibility of many entries, so I want to then filter on a second column that is shared by both tables, table_1_id.

It seems to work perfectly on the command line, but when eager loading the relationship is empty.

If I remove the additional ->where() from the relationship method then the eager loading works.

The way I am eager-loading is by doing

->with('relation.nestedRelation');

I've also tried

->with(['relation' => function ($q) {
    $q->with('nestedRelation');
}])

I've just tried adding it as an attribute to see if that helped but still no joy.

Body:
You can use the whereColumn() function :

->whereColumn('table_1.table_1_id', 'table_2.table_1_id')

Or you can use that :

public function filterRelation(){
     return $this->relation->where('table_1_id', $this->table_1_id);

}


问:
Domain validation using the notification pattern
Historically I have performed validation of my objects within their constructors and thrown an exception when validation fails.  For example:

```<code>class Name
{
    const MIN_LENGTH = 1;

    const MAX_LENGTH = 120;

    private $value;

    public function __construct(string $name)
    {
        if (!$this->isValidNameLength($name)) {
            throw new InvalidArgumentException(
                sprintf('The name must be between %d and %d characters long', self::MIN_LENGTH, self::MAX_LENGTH)
            );
        }
        $this->value = $name;
    }

    public function changeName(string $name)
    {
        return new self($name);
    }

    private function isValidNameLength(string $name)
    {
        return strlen($name) >= self::MIN_LENGTH && strlen($name) <= self::MAX_LENGTH;
    }
}
</code>```

Whilst I like this approach as my object is responsible for enforcing its consistency and ensuring it is always-valid, I've never been overly enthusiastic about the use of exceptions.  Whilst there are people who would argue for and against the use of exceptions as above, it does limit the number of validation messages I can return when performing validation over multiple objects.  For example:

```<code>class Room
{
    private $name;

    private $description;

    public function __construct(Name $name, Description $description)
    {
        $this->name = $name;
        $this->description = $description;
    }
}

class Name
{
    public function __construct(string $name)
    {
        // do some validation
    }
}

class Description
{
    public function __construct(string $description)
    {
        // do some validation
    }
}
</code>```

Should both Name and Description fail validation, I want to be able to return the failure messages for both objects, not just a single exception from whichever object failed first.

Having done some reading on the notification pattern I feel this would be a good fit for my scenario.  Where I become stuck is how I perform validation and prevent my object from entering an invalid state should validation fail.

```<code>class Name
{
    const MIN_LENGTH = 1;

    const MAX_LENGTH = 120;

    private $notification;

    private $value;

    public function __construct(string $name, Notification $notification)
    {
        $this->notification = $notification;
        $this->setName($name);
    }

    private function setName(string $name)
    {
        if ($this->isValidNameLength($name)) {
            $this->value = $name;
        }
    }

    private function isValidNameLength(string $name)
    {
        if (strlen($name) < self::MIN_LENGTH || strlen($name) > self::MAX_LENGTH) {
            $this->notification->addError('NAME_LENGTH_INVALID');
            return false;
        }
        return true;
    }

    public function hasError()
    {
        return $this->notification->hasError();
    }

    public function getError()
    {
        return $this->notification->getError();
    }
}
</code>```

I have a few concerns about the above:

If validation fails, then the object is still constructed but its $value is null which is not a valid state.

After creating a Name, I must remember to call hasError to determine if a validation error has occured.

I am now pebbling my domain objects with hasError/getError functions which I'm not sure is good practice.

Is there a piece of this puzzle I am missing?  How would I got about utilising the notification pattern but ensuring that my object can not enter an invalid state?

答:
What about calling the notification.hasError function and throw an exception afterwards?

This way you can handle any errors using your notification handling, and because of the exception it will be guaranteed that you won't have a valid object.

Body:
Historically I have performed validation of my objects within their constructors and thrown an exception when validation fails.  For example:

class Name
{
    const MIN_LENGTH = 1;

    const MAX_LENGTH = 120;

    private $value;

    public function __construct(string $name)
    {
        if (!$this->isValidNameLength($name)) {
            throw new InvalidArgumentException(
                sprintf('The name must be between %d and %d characters long', self::MIN_LENGTH, self::MAX_LENGTH)
            );
        }
        $this->value = $name;
    }

    public function changeName(string $name)
    {
        return new self($name);
    }

    private function isValidNameLength(string $name)
    {
        return strlen($name) >= self::MIN_LENGTH && strlen($name) <= self::MAX_LENGTH;
    }
}

Whilst I like this approach as my object is responsible for enforcing its consistency and ensuring it is always-valid, I've never been overly enthusiastic about the use of exceptions.  Whilst there are people who would argue for and against the use of exceptions as above, it does limit the number of validation messages I can return when performing validation over multiple objects.  For example:

class Room
{
    private $name;

    private $description;

    public function __construct(Name $name, Description $description)
    {
        $this->name = $name;
        $this->description = $description;
    }
}

class Name
{
    public function __construct(string $name)
    {
        // do some validation
    }
}

class Description
{
    public function __construct(string $description)
    {
        // do some validation
    }
}

Should both Name and Description fail validation, I want to be able to return the failure messages for both objects, not just a single exception from whichever object failed first.

Having done some reading on the notification pattern I feel this would be a good fit for my scenario.  Where I become stuck is how I perform validation and prevent my object from entering an invalid state should validation fail.

class Name
{
    const MIN_LENGTH = 1;

    const MAX_LENGTH = 120;

    private $notification;

    private $value;

    public function __construct(string $name, Notification $notification)
    {
        $this->notification = $notification;
        $this->setName($name);
    }

    private function setName(string $name)
    {
        if ($this->isValidNameLength($name)) {
            $this->value = $name;
        }
    }

    private function isValidNameLength(string $name)
    {
        if (strlen($name) < self::MIN_LENGTH || strlen($name) > self::MAX_LENGTH) {
            $this->notification->addError('NAME_LENGTH_INVALID');
            return false;
        }
        return true;
    }

    public function hasError()
    {
        return $this->notification->hasError();
    }

    public function getError()
    {
        return $this->notification->getError();
    }
}

I have a few concerns about the above:

If validation fails, then the object is still constructed but its $value is null which is not a valid state.

After creating a Name, I must remember to call hasError to determine if a validation error has occured.

I am now pebbling my domain objects with hasError/getError functions which I'm not sure is good practice.

Is there a piece of this puzzle I am missing?  How would I got about utilising the notification pattern but ensuring that my object can not enter an invalid state?


问:
How to retrieve a Sharing Information object from SharePoint Online using CSOM?
I'm using the SharePoint Client Object Model to login into SharePoint online and then retrieve the Lists to get Documents on SharePoint. I then want to get the shared link for these documents. Here's how I am doing it at the moment:

```<code>using (var context = new ClientContext(siteURL))
{
     context.Credentials = new SharePointOnlineCredentials(login, securePassword);
     context.Load(context.Web, w => w.Title);
     context.ExecuteQuery();

     List docList = context.Web.Lists.GetByTitle("Documents");
     context.Load(docList);
     // This creates a CamlQuery that has a RowLimit of 100, and also specifies Scope="RecursiveAll"
     // so that it grabs all list items, regardless of the folder they are in.
     CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
     ListItemCollection items = docList.GetItems(query);

     // Retrieve all items in the ListItemCollection from List.GetItems(Query).
     context.Load(items);
     context.ExecuteQuery();
     foreach (ListItem listItem in items)
     {
          var sharingInfo = ObjectSharingInformation.GetListItemSharingInformation(
             context, docList.Id, listItem.Id, false, true, false, true, true, true);

          context.Load(sharingInfo);
          context.ExecuteQuery();
          string str = sharingInfo.AnonymousEditLink;
     }
}
</code>```

The issue here is that sharingInfo object has a field called AnonymousEditLink but it is an empty string. I'm not sure why this is an empty string. Is this the right way of going about generating a sharing link?

I have also tried this (but to no avail):

```<code>var sharingInfo = ObjectSharingInformation.GetObjectSharingInformation(
                    context, listItem, false, true, false, true, true, true, true);
</code>```

I am referring to the method shown here: https://sharepoint.stackexchange.com/questions/143612/how-to-retrieve-the-shared-link-of-a-file-programmatically

答:
I've been doing some work/testing with GetListItemSharingInformation and the AnonymousEditLink appears to get populated once the user has accessed the link the have received via email.

The same occurs with the SharedWithUsersCollection. Essentially, once the user has accessed the link. You'll find the properties are populated.

ContentLicense: CC BY-SA 4.0

Body:
I'm using the SharePoint Client Object Model to login into SharePoint online and then retrieve the Lists to get Documents on SharePoint. I then want to get the shared link for these documents. Here's how I am doing it at the moment:

using (var context = new ClientContext(siteURL))
{
     context.Credentials = new SharePointOnlineCredentials(login, securePassword);
     context.Load(context.Web, w => w.Title);
     context.ExecuteQuery();

     List docList = context.Web.Lists.GetByTitle("Documents");
     context.Load(docList);
     // This creates a CamlQuery that has a RowLimit of 100, and also specifies Scope="RecursiveAll"
     // so that it grabs all list items, regardless of the folder they are in.
     CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
     ListItemCollection items = docList.GetItems(query);

     // Retrieve all items in the ListItemCollection from List.GetItems(Query).
     context.Load(items);
     context.ExecuteQuery();
     foreach (ListItem listItem in items)
     {
          var sharingInfo = ObjectSharingInformation.GetListItemSharingInformation(
             context, docList.Id, listItem.Id, false, true, false, true, true, true);

          context.Load(sharingInfo);
          context.ExecuteQuery();
          string str = sharingInfo.AnonymousEditLink;
     }
}

The issue here is that sharingInfo object has a field called AnonymousEditLink but it is an empty string. I'm not sure why this is an empty string. Is this the right way of going about generating a sharing link?

I have also tried this (but to no avail):

var sharingInfo = ObjectSharingInformation.GetObjectSharingInformation(
                    context, listItem, false, true, false, true, true, true, true);

I am referring to the method shown here: https://sharepoint.stackexchange.com/questions/143612/how-to-retrieve-the-shared-link-of-a-file-programmatically


问:
My Python function isn't working as wanted
I am making a function that takes a string and replace "put" and "get" with "xput()" and "xget()". I know it isn't the most efficient, but I want to start with making it work. It currently replace the words ad puts the brackets, but it puts brackets on every newline and I don't see why. Can someone help me?

Code:

```<code>import re

def replaceFunctions(string):
    split=re.split('(\n)', string)
    for i in range (0,len(split)):
        split[i] = re.split('(")',split[i])

    split = [item for sublist in split for item in sublist]

    for i in range (0,len(split)):
        split[i]=re.split('( )', split[i])

    split = [item for sublist in split for item in sublist]

    for i in range (0,len(split)):
        split[i]=re.split('(\t)', split[i])

    split = [item for sublist in split for item in sublist]
    split.append("\n")

    for i in range (0,len(split)):
        if split[i] == "put":
            split[i] = "xput ("
            for o in range (i,len(split)):
                if split[o] == "\n":
                    split[o] = ")\n"
                    break

        else:
            if split[i] == "get":
                split[i] = "xget ("
                for o in range (i,len(split)):
                    if split[o] == "\n":
                        split[o] = ")\n"
                        break

    string = ""

    for i in range (0,len(split)):
        string += split[i]

    return string

print "get (put)"
print replaceFunctions("get (put)")

print "put \"put this\"\nput put (get)\n\n\nput\n"
print replaceFunctions("put \"put this\"\nput put (get)\n\n\nput")
</code>```

Output:

```<code>get (put)
xget ( (put))

put "put this"
put put (get)

put

xput ( "xput ( this")
xput ( xput ( (get))
)
)
xput ()
</code>```

Desired Output:

```<code>get (put)
xget ( (put))

put "put this"
put put (get)

put

xput ( "xput ( this")
xput ( xput ( (get))

xput ()
</code>```

Thanks in advance!

答:
Not so compact as @SciGuyMcQ but more "scalable":

```<code>txt = 'this is a text with get, some more get and even a put or two put'
table = {'get': 'get()',
         'put': 'xput()'}

result = txt[:]
for key in table:
    result = result.replace(key, table[key])
</code>```

outputs:

```<code>>>> result
'This is a text with get(), more get() and also xput() and xput() again.'
</code>```

Body:
I am making a function that takes a string and replace "put" and "get" with "xput()" and "xget()". I know it isn't the most efficient, but I want to start with making it work. It currently replace the words ad puts the brackets, but it puts brackets on every newline and I don't see why. Can someone help me?

Code:

import re

def replaceFunctions(string):
    split=re.split('(\n)', string)
    for i in range (0,len(split)):
        split[i] = re.split('(")',split[i])

    split = [item for sublist in split for item in sublist]

    for i in range (0,len(split)):
        split[i]=re.split('( )', split[i])

    split = [item for sublist in split for item in sublist]

    for i in range (0,len(split)):
        split[i]=re.split('(\t)', split[i])

    split = [item for sublist in split for item in sublist]
    split.append("\n")

    for i in range (0,len(split)):
        if split[i] == "put":
            split[i] = "xput ("
            for o in range (i,len(split)):
                if split[o] == "\n":
                    split[o] = ")\n"
                    break

        else:
            if split[i] == "get":
                split[i] = "xget ("
                for o in range (i,len(split)):
                    if split[o] == "\n":
                        split[o] = ")\n"
                        break

    string = ""

    for i in range (0,len(split)):
        string += split[i]

    return string

print "get (put)"
print replaceFunctions("get (put)")

print "put \"put this\"\nput put (get)\n\n\nput\n"
print replaceFunctions("put \"put this\"\nput put (get)\n\n\nput")

Output:

get (put)
xget ( (put))

put "put this"
put put (get)

put

xput ( "xput ( this")
xput ( xput ( (get))
)
)
xput ()

Desired Output:

get (put)
xget ( (put))

put "put this"
put put (get)

put

xput ( "xput ( this")
xput ( xput ( (get))

xput ()

Thanks in advance!

Body:
Not so compact as @SciGuyMcQ but more "scalable":

txt = 'this is a text with get, some more get and even a put or two put'
table = {'get': 'get()',
         'put': 'xput()'}

result = txt[:]
for key in table:
    result = result.replace(key, table[key])

outputs:

>>> result
'This is a text with get(), more get() and also xput() and xput() again.'


问:
C# Questions Regarding Lists?
I have two classes: consumableItems.cs and items.cs
So basically, all I have to do is inherit the properties of items.cs to consumableItems.cs

Here's what I done so far:

```<code>class Item
{
    public List<string> itemNames = new List<string>();
    public List<int> itemEffects = new List<int>();
}

class consumableItems : Item
{
    new public List<string> itemNames = new List<string>() { "Apple", "Orange", "Grapes" };
    new public List<int> itemEffects = new List<int>() { 15, 30, 40 };
}
</code>```

What I want to achieve is, whenever I type "Apple", the console window shows both "Apple" and "15"; same for when I type "Orange", the console window shows both "Orange" and "30". Any ideas? Sorry, just started C# programming and I'm getting lost. >< Oh, and last question, is the way I inherit correct? :/ Thanks. ^^

答:
Same business problem can easily be solved by using any collection of Key-Value pair.. I mean using dictionary like:

```<code>public Dictionary<string, int> FruitsEffect= new Dictionary<string, int>()
FruitsEffect.Add("FruitsName",25);
</code>```

The Dictionary has pairs of keys and values.Dictionary is used with different elements. We specify its key type and its value type (string, int).
Populate the dictionary and get the value by key.

Title: C# Questions Regarding Lists?

Body:
I have two classes: consumableItems.cs and items.cs
So basically, all I have to do is inherit the properties of items.cs to consumableItems.cs

Here's what I done so far:

class Item
{
    public List<string> itemNames = new List<string>();
    public List<int> itemEffects = new List<int>();
}

class consumableItems : Item
{
    new public List<string> itemNames = new List<string>() { "Apple", "Orange", "Grapes" };
    new public List<int> itemEffects = new List<int>() { 15, 30, 40 };
}

What I want to achieve is, whenever I type "Apple", the console window shows both "Apple" and "15"; same for when I type "Orange", the console window shows both "Orange" and "30". Any ideas? Sorry, just started C# programming and I'm getting lost. >< Oh, and last question, is the way I inherit correct? :/ Thanks. ^^

Body:
Same business problem can easily be solved by using any collection of Key-Value pair.. I mean using dictionary like:

public Dictionary<string, int> FruitsEffect= new Dictionary<string, int>()
FruitsEffect.Add("FruitsName",25);

The Dictionary has pairs of keys and values.Dictionary is used with different elements. We specify its key type and its value type (string, int).
Populate the dictionary and get the value by key.


问:
django template white page
Help me
after add my {% extends "menu.html" %>

the rest of my page is white I can not see my content anymore
resultat

答:
Maybe you forgot to wrap page which extends menu.html?

menu.html file

```<code><html>
    <body>
        some menu code here
        {% block content %}
        {% endblock %}
    </body>
</html>
</code>```

file_which_extends_menu.html

```<code>{% extends 'menu.html' %}
{% block content %}
    your content
{% endblock %}
</code>```

Title: django template white page

Body:
Maybe you forgot to wrap page which extends menu.html?

menu.html file

<html>
    <body>
        some menu code here
        {% block content %}
        {% endblock %}
    </body>
</html>

file_which_extends_menu.html

{% extends 'menu.html' %}
{% block content %}
    your content
{% endblock %}


问:
How to remove default value of input on focus
I have an input box that has default value text assigned to it. How can I remove this text when the user focuses on the field::

CoDE

```<code><input type="text" name="kp1_description" value="Enter Keypress Description">
</code>```

答:
Plain JavaScript:

```<code>(function () {
  let input = document.querySelector ("input[name='kp1_description']");
  input.onfocus = function () {
    this.placeholder = this.value;
    this.value = '';
  };
})();
</code>```

This keeps the value in the placeholder instead of removing it completely. If you do not like this, remove the placeholder line.

ContentLicense: CC BY-SA 2.5

Body:
I have an input box that has default value text assigned to it. How can I remove this text when the user focuses on the field::

CoDE

<input type="text" name="kp1_description" value="Enter Keypress Description">

Body:
Plain JavaScript:

(function () {
  let input = document.querySelector ("input[name='kp1_description']");
  input.onfocus = function () {
    this.placeholder = this.value;
    this.value = '';
  };
})();

This keeps the value in the placeholder instead of removing it completely. If you do not like this, remove the placeholder line.


问:
Accessing Laravel .env variables in blade
I am trying to get some API keys which I have stored in my .env file to use in the blade javascript. I have added two keys like:

```<code>APP_ENV=local
APP_KEY=////
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
APP_GOOGLE_MAPS=////
APP_OVERHEID_IO=////
</code>```

In blade I need to use the Google Maps API and OverheidIO API key. I have tried getting one of the default .env variables just in case I have formatted the custom .env variables wrong.:

```<code>{{ env('APP.ENV') }} // nothing
{{ env('APP_ENV') }} // nothing
{{ env('APP_ENV'), 'test' }} // returns 'test'
</code>```

Could someone help me call the google maps api and overheidio api key in the blade?

答:
```<code>php artisan config:clear
</code>```

should fix it

Body:
I am trying to get some API keys which I have stored in my .env file to use in the blade javascript. I have added two keys like:

APP_ENV=local
APP_KEY=////
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
APP_GOOGLE_MAPS=////
APP_OVERHEID_IO=////

In blade I need to use the Google Maps API and OverheidIO API key. I have tried getting one of the default .env variables just in case I have formatted the custom .env variables wrong.:

{{ env('APP.ENV') }} // nothing
{{ env('APP_ENV') }} // nothing
{{ env('APP_ENV'), 'test' }} // returns 'test'

Could someone help me call the google maps api and overheidio api key in the blade?

Body:
php artisan config:clear

should fix it


问:
I am using `max()` to get the highest value from n digits?
My teacher solved this question "Write a function which takes a n digits number as an input and return True if the biggest digit in this number is divisible by 3" like this:

```<code>def is_divisable(n):
    a = str(n)
    b = 0
    for i in a:
        if int(i)>b:
            b = int(i)

    if b % 3 == 0:
        return "True"
print is_divisable(67479)
</code>```

I have thought of it in another way but my code is not working and
I am getting an error says:

"TypeError: 'int' object is not iterable"

```<code>def is_dvo(n):

    if max(n) % 3 == 0:
        return True

print is_dvo(67479)
</code>```

Body:
My teacher solved this question "Write a function which takes a n digits number as an input and return True if the biggest digit in this number is divisible by 3" like this:

def is_divisable(n):
    a = str(n)
    b = 0
    for i in a:
        if int(i)>b:
            b = int(i)

    if b % 3 == 0:
        return "True"
print is_divisable(67479)

I have thought of it in another way but my code is not working and
I am getting an error says:

"TypeError: 'int' object is not iterable"

def is_dvo(n):

    if max(n) % 3 == 0:
        return True

print is_dvo(67479)

Body:
Try:

max(str(n), key=int) in {'3', '6', '9'}


问:
Smooth scroll to ID using jQuery
Struggling to implement a smooth scroll feature when navigating to an ID using my navbar.  Instead, it makes the default jump, which is a bit of an eye sore.

I am very inexperienced using jQuery, so any pointers in the right direction would be much appreciated.

I have made an attempt to get this implemented however, as I have said, it is 'jumping' as opposed to scrolling.

HTML

```<code><li>
  <a href="#popular">Most Popular</a>
</li>
<div class="col-sm-12" id="popular">
<h3><i aria-hidden="true" class="fa fa-fire"></i> Most Popular</h3>
</div>
</code>```

jQuery

```<code>$(document).ready(function() {
  $("#popular").on('click', function(event) {
    if (this.hash !== "") {
      event.preventDefault();
      var hash = this.hash;
      $('col-sm-12').animate({
        scrollTop: $(hash).offset().top
      }, 800, function() {
        window.location.hash = hash;
      });
    }
</code>```

答:
Maybe try specifying the easing option.

Something like this:

```<code>$("#popular").click(function() {
    $('html, body').animate({
        scrollTop: $("#popular").offset().top
    }, 800, 'linear');
});
</code>```

Or:

```<code>$(document).ready(function () {
    $("#popular").on('click', function (e) {
        $('.col-sm-12').animate({
            scrollTop: $(this).offset().top
        }, 800);
    });
});
</code>```

Title: Smooth scroll to ID using jQuery

Body:
Struggling to implement a smooth scroll feature when navigating to an ID using my navbar.  Instead, it makes the default jump, which is a bit of an eye sore.

I am very inexperienced using jQuery, so any pointers in the right direction would be much appreciated.

I have made an attempt to get this implemented however, as I have said, it is 'jumping' as opposed to scrolling.

HTML

  Most Popular

 Most Popular

jQuery

$(document).ready(function() {
  $("#popular").on('click', function(event) {
    if (this.hash !== "") {
      event.preventDefault();
      var hash = this.hash;
      $('col-sm-12').animate({
        scrollTop: $(hash).offset().top
      }, 800, function() {
        window.location.hash = hash;
      });
    }

Body:
Maybe try specifying the easing option.

Something like this:

$("#popular").click(function() {
    $('html, body').animate({
        scrollTop: $("#popular").offset().top
    }, 800, 'linear');
});

Or:

$(document).ready(function () {
    $("#popular").on('click', function (e) {
        $('.col-sm-12').animate({
            scrollTop: $(this).offset().top
        }, 800);
    });
});


问:
"syntax error near unexpected token `do'" in Bash script
I'm writing a Bash script. When I run it, I get a syntax error I don't understand.

Here my script:

```<code>#!/bin/bash
i=1
while [ $i -le "6" ]
 do
 j=1
 i=`expr $i +1`
 echo \
 while [ $j -le "$i" ]
   do
   echo $i
   j=`expr $j+1`
 done
done
echo \enter code here
</code>```

Here the error:

```<code>./test.sh: line 9: syntax error near unexpected token `do'
./test.sh: line 9: `do'
</code>```

What am I doing wrong?

答:
The first thing if to remove the backslash from line 8, since it's an escape character (and it would escape the newline after it). In the final line, the backslash doesn't have that impact because it's followed by an e.

Also, in the expr expression, you need to surround the + sign with spaces. I also show a second way to increment j.

```<code>#!/bin/bash
i=1
while [ $i -le "6" ]
 do
 j=1
 ((i++))
 echo something-else
 while [ $j -le "$i" ]
   do
   echo $i
   ((j++))
 done
done
</code>```

Output:

```<code>$ ./so_test.sh
something-else
2
2
something-else
3
3
3
something-else
4
4
4
4
something-else
5
5
5
5
5
something-else
6
6
6
6
6
6
something-else
7
7
7
7
7
7
7
</code>```

Body:
I'm writing a Bash script. When I run it, I get a syntax error I don't understand.

Here my script:

#!/bin/bash
i=1
while [ $i -le "6" ]
 do
 j=1
 i=`expr $i +1`
 echo \
 while [ $j -le "$i" ]
   do
   echo $i
   j=`expr $j+1`
 done
done
echo \enter code here

Here the error:

./test.sh: line 9: syntax error near unexpected token `do'
./test.sh: line 9: `do'

What am I doing wrong?

Body:
The first thing if to remove the backslash from line 8, since it's an escape character (and it would escape the newline after it). In the final line, the backslash doesn't have that impact because it's followed by an e.

Also, in the expr expression, you need to surround the + sign with spaces. I also show a second way to increment j.

#!/bin/bash
i=1
while [ $i -le "6" ]
 do
 j=1
 ((i++))
 echo something-else
 while [ $j -le "$i" ]
   do
   echo $i
   ((j++))
 done
done

Output:

$ ./so_test.sh
something-else
2
2
something-else
3
3
3
something-else
4
4
4
4
something-else
5
5
5
5
5
something-else
6
6
6
6
6
6
something-else
7
7
7
7
7
7
7


问:
AbstractMethodError with jTDS JDBC Driver on Tomcat 8
I am deploying a web app (WAR) to a Tomcat 8 web container.

The WAR includes in the '/WEB-INF/lib' directory the following jTDS JDBC driver:

```<code><dependency org="net.sourceforge.jtds" name="jtds" rev="1.3.1" />
</code>```

(file is: jtds-1.3.1.jar).

This is how the resource is defined in META-INF/context.xml:

```<code><Resource name="jdbc/jtds/sybase/somedb"
          auth="Container"
          type="javax.sql.DataSource"
          driverClassName="net.sourceforge.jtds.jdbc.Driver"
          url="jdbc:jtds:sybase://localhost:2501/somedb"
          username="someuser" password="somepassword"
/>
</code>```

In my code I obtain the javax.sql.DataSource the normal way:

```<code>InitialContext cxt = new InitialContext();
if ( cxt == null ) {
    throw new RuntimeException("Uh oh -- no context!");
}
DataSource ds = (DataSource) cxt.lookup( lookupName );
</code>```

I further verify (by printing) that the DataSource object ds is of the expected type:

```<code>org.apache.tomcat.dbcp.dbcp2.BasicDataSource
</code>```

… but when I try to get a connection out of it:

```<code>Connection conn = ds.getConnection();
</code>```

… I get the following trace:

```<code>java.lang.AbstractMethodError
net.sourceforge.jtds.jdbc.JtdsConnection.isValid(JtdsConnection.java:2833)
org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.isValid(DelegatingConnection.java:924)
org.apache.tomcat.dbcp.dbcp2.PoolableConnection.validate(PoolableConnection.java:282)
org.apache.tomcat.dbcp.dbcp2.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:359)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2316)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2299)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2043)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1543)
</code>```

What gives?

答:
The answer mentioned above by Marcus worked for me when I encountered this problem. To give a specific example of how the validationQuery setting looks in the context.xml file:

```<code>    <Resource name="jdbc/myDB" auth="Container" type="javax.sql.DataSource"
            driverClassName="net.sourceforge.jtds.jdbc.Driver"
            url="jdbc:jtds:sqlserver://SQLSERVER01:1433/mydbname;instance=MYDBINSTANCE"
            username="dbuserid" password="dbpassword"
            validationQuery="select 1"
            />
</code>```

The validationQuery setting goes in with each driver setting for your db connections. So each time you add another db entry to your context.xml file, you will need to include this setting with the driver settings.

Body:
I am deploying a web app (WAR) to a Tomcat 8 web container.

The WAR includes in the '/WEB-INF/lib' directory the following jTDS JDBC driver:

<dependency org="net.sourceforge.jtds" name="jtds" rev="1.3.1" />

(file is: jtds-1.3.1.jar).

This is how the resource is defined in META-INF/context.xml:

<Resource name="jdbc/jtds/sybase/somedb"
          auth="Container"
          type="javax.sql.DataSource"
          driverClassName="net.sourceforge.jtds.jdbc.Driver"
          url="jdbc:jtds:sybase://localhost:2501/somedb"
          username="someuser" password="somepassword"
/>

In my code I obtain the javax.sql.DataSource the normal way:

InitialContext cxt = new InitialContext();
if ( cxt == null ) {
    throw new RuntimeException("Uh oh -- no context!");
}
DataSource ds = (DataSource) cxt.lookup( lookupName );

I further verify (by printing) that the DataSource object ds is of the expected type:

org.apache.tomcat.dbcp.dbcp2.BasicDataSource

… but when I try to get a connection out of it:

Connection conn = ds.getConnection();

… I get the following trace:

java.lang.AbstractMethodError
net.sourceforge.jtds.jdbc.JtdsConnection.isValid(JtdsConnection.java:2833)
org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.isValid(DelegatingConnection.java:924)
org.apache.tomcat.dbcp.dbcp2.PoolableConnection.validate(PoolableConnection.java:282)
org.apache.tomcat.dbcp.dbcp2.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:359)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2316)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2299)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2043)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1543)

What gives?

Body:
The answer mentioned above by Marcus worked for me when I encountered this problem. To give a specific example of how the validationQuery setting looks in the context.xml file:

    <Resource name="jdbc/myDB" auth="Container" type="javax.sql.DataSource"
            driverClassName="net.sourceforge.jtds.jdbc.Driver"
            url="jdbc:jtds:sqlserver://SQLSERVER01:1433/mydbname;instance=MYDBINSTANCE"
            username="dbuserid" password="dbpassword"
            validationQuery="select 1"
            />

The validationQuery setting goes in with each driver setting for your db connections. So each time you add another db entry to your context.xml file, you will need to include this setting with the driver settings.


问:
clang-format: how to prevent all function arguments on next line?
I have a C++ function call that I've manually and intentionally formatted like
this:

```<code>DoSomethingForAPurposeThatCausesALongFunctionName(
    arg_0,
    arg_1,
    arg_2);
</code>```

clang-format wants to re-format it like this:

```<code>DoSomethingForAPurposeThatCausesALongFunctionName(
    arg_0, arg_1, arg_2)
</code>```

I do not want this. AllowAllParametersOfDeclarationOnNextLine appears to
control this behavior for function declarations, but what about function calls?
Is there a corresponding setting?

My .clang-format looks like this:

```<code>BasedOnStyle: Google
BinPackArguments: false
BinPackParameters: false
AllowAllParametersOfDeclarationOnNextLine: false
AlignAfterOpenBracket: AlwaysBreak
</code>```

答:
The following configuration is correct to get your desired formatting with clang-format 5.0.</p>

```<code>AlignAfterOpenBracket: AlwaysBreak
AllowAllParametersOfDeclarationOnNextLine: false
BinPackParameters: false
</code>```

Body:
I have a C++ function call that I've manually and intentionally formatted like
this:

DoSomethingForAPurposeThatCausesALongFunctionName(
    arg_0,
    arg_1,
    arg_2);

clang-format wants to re-format it like this:

DoSomethingForAPurposeThatCausesALongFunctionName(
    arg_0, arg_1, arg_2)

I do not want this. AllowAllParametersOfDeclarationOnNextLine appears to
control this behavior for function declarations, but what about function calls?
Is there a corresponding setting?

My .clang-format looks like this:

BasedOnStyle: Google
BinPackArguments: false
BinPackParameters: false
AllowAllParametersOfDeclarationOnNextLine: false
AlignAfterOpenBracket: AlwaysBreak

Body:
The following configuration is correct to get your desired formatting with clang-format 5.0.

AlignAfterOpenBracket: AlwaysBreak
AllowAllParametersOfDeclarationOnNextLine: false
BinPackParameters: false


问:
index(max(my_list)) in list comprehension gives all instances of the max value instead of just the first occurrence
Consider the following code snippet -->

```<code>li = [3,1,2,3]
print([x+99 if li.index(x)!=li.index(max(li)) else x-(99*(len(li)-1)) for x in li ])
</code>```

I was expecting the output to be :

```<code>[-294, 100, 101, 102]
</code>```

but the actual output on running the program was :

```<code>[-294, 100, 101, -294]
</code>```

Why do i get both instances of the maximum value in the list instead of just the first occurrence?

How exactly are list comprehensions evaluated and how is that responsible for the output in my program ?

答:
You have multiple 3s in your list. The implementation of index is such that it finds only the index of the first occurrence of the value passed to it. Instead, use enumerate:

```<code>li = [3,1,2,3]
l1 = [x+99 if i!=li.index(max(li)) else x-(99*(len(li)-1)) for i, x in enumerate(li)]
</code>```

Output:

```<code>[-294, 100, 101, 102]
</code>```

Body:
Consider the following code snippet -->

li = [3,1,2,3]
print([x+99 if li.index(x)!=li.index(max(li)) else x-(99*(len(li)-1)) for x in li ])

I was expecting the output to be :

[-294, 100, 101, 102]

but the actual output on running the program was :

[-294, 100, 101, -294]

Why do i get both instances of the maximum value in the list instead of just the first occurrence?

How exactly are list comprehensions evaluated and how is that responsible for the output in my program ?

Body:
You have multiple 3s in your list. The implementation of index is such that it finds only the index of the first occurrence of the value passed to it. Instead, use enumerate:

li = [3,1,2,3]
l1 = [x+99 if i!=li.index(max(li)) else x-(99*(len(li)-1)) for i, x in enumerate(li)]

Output:

[-294, 100, 101, 102]


问:
Set a default value to a property
Is it possible to set a default value without the body of a property? Preferably with annotations.</p>

```<code>[SetTheDefaultValueTo(true)]
public bool IsTrue { get; set; }

[SetTheDefaultValueTo(false)]
public bool IsFalse { get; set; }

public void Something()
{
    var isTrue = this.IsTrue;
    var isFalse = this.IsFalse;
}
</code>```

答:
If you are using C#5 and earlier, you have to do it in a constructor.

but since C# 6.0, the ability to have auto property initializers is included, and the syntax is:

```<code>public int myage { get; set; } = 33;
</code>```

Title: Set a default value to a property

Body:
Is it possible to set a default value without the body of a property? Preferably with annotations.

[SetTheDefaultValueTo(true)]
public bool IsTrue { get; set; }

[SetTheDefaultValueTo(false)]
public bool IsFalse { get; set; }

public void Something()
{
    var isTrue = this.IsTrue;
    var isFalse = this.IsFalse;
}

Body:
If you are using C#5 and earlier, you have to do it in a constructor.

but since C# 6.0, the ability to have auto property initializers is included, and the syntax is:

public int myage { get; set; } = 33;


问:
Spring boot automated build with Docker cloud
I am trying to achieve Continuous Integration/Delivery with Docker Cloud.

On Docker Cloud i connected my bit bucket repository, so on every commit docker build will initiate on Docker Cloud, but automated build are failing, these are the logs

ERROR: Build failed: ADD failed: stat
  /var/lib/docker/tmp/docker-builder406751627/target/springtest.jar: no
  such file or directory ERROR: Build failed with exit code 2 ERROR:
  Build in 'master' (094341b2) failed in 0:02:10

This is my Docker File

```<code>FROM java:8
VOLUME /tmp
ADD /target/springtest.jar springtest.jar
ENTRYPOINT ["java","-jar","springtest.jar"]
</code>```

However if i try to build the same thing on my Local Docker Terminal i am not getting Issues, i am using this command mvn package docker:build and its creating Images Successfully

So why with the same Dockerfile automated build ? Any other step i need to do?

答:
Do you have springtest.jar in your local?

From error seems to be Docker Cloud is not able to find springtest.jar file.

Body:
I am trying to achieve Continuous Integration/Delivery with Docker Cloud.

On Docker Cloud i connected my bit bucket repository, so on every commit docker build will initiate on Docker Cloud, but automated build are failing, these are the logs

ERROR: Build failed: ADD failed: stat
  /var/lib/docker/tmp/docker-builder406751627/target/springtest.jar: no
  such file or directory ERROR: Build failed with exit code 2 ERROR:
  Build in 'master' (094341b2) failed in 0:02:10

This is my Docker File

FROM java:8
VOLUME /tmp
ADD /target/springtest.jar springtest.jar
ENTRYPOINT ["java","-jar","springtest.jar"]

However if i try to build the same thing on my Local Docker Terminal i am not getting Issues, i am using this command mvn package docker:build and its creating Images Successfully

So why with the same Dockerfile automated build ? Any other step i need to do?


问:
Why is Files.list() parallel stream performing so much slower than using Collection.parallelStream()?
The following code fragment is part of a method that gets a directory listing, calls an extract method on each file and serializes the resulting drug object to xml.

```<code>try(Stream<Path> paths = Files.list(infoDir)) {
    paths
        .parallel()
        .map(this::extract)
        .forEachOrdered(drug -> {
            try {
                marshaller.write(drug);
            } catch (JAXBException ex) {
                ex.printStackTrace();
            }
        });
}
</code>```

Here is the exact same code doing the exact same thing but using a plain .list() call to get the directory listing and calling .parallelStream() on the resulting list.

```<code>Arrays.asList(infoDir.toFile().list())
    .parallelStream()
    .map(f -> infoDir.resolve(f))
    .map(this::extract)
    .forEachOrdered(drug -> {
        try {
            marshaller.write(drug);
        } catch (JAXBException ex) {
            ex.printStackTrace();
    }
});
</code>```

My machine is a quad core MacBook Pro, Java v 1.8.0_60 (build 1.8.0_60-b27).

I am processing ~ 7000 files. The averages of 3 runs:

First version:
With .parallel():  20 seconds. Without .parallel(): 41 seconds

Second version:
With .parallelStream(): 12 seconds. With .stream(): 41 seconds.

Those 8 seconds in parallel mode seem like an enormous difference given that the extract method that reads from the stream and does all the heavy work and the write call doing the final writes are unchanged.

答:
Another alternative to your workaround is to use .collect(Collectors.toList()).parallelStream() on your stream like

```<code>try(Stream<Path> paths = Files.list(infoDir)) {
    paths
        .collect(Collectors.toList())
        .parallelStream()
        .map(this::extract)
        .forEachOrdered(drug -> {
            try {
                marshaller.write(drug);
            } catch (JAXBException ex) {
                ex.printStackTrace();
            }
        });
}
</code>```

With this you don't need to call  .map(f -> infoDir.resolve(f)) and the performance should be similar to your second solution.

Body:
The following code fragment is part of a method that gets a directory listing, calls an extract method on each file and serializes the resulting drug object to xml.

try(Stream<Path> paths = Files.list(infoDir)) {
    paths
        .parallel()
        .map(this::extract)
        .forEachOrdered(drug -> {
            try {
                marshaller.write(drug);
            } catch (JAXBException ex) {
                ex.printStackTrace();
            }
        });
}

Here is the exact same code doing the exact same thing but using a plain .list() call to get the directory listing and calling .parallelStream() on the resulting list.

Arrays.asList(infoDir.toFile().list())
    .parallelStream()
    .map(f -> infoDir.resolve(f))
    .map(this::extract)
    .forEachOrdered(drug -> {
        try {
            marshaller.write(drug);
        } catch (JAXBException ex) {
            ex.printStackTrace();
    }
});

My machine is a quad core MacBook Pro, Java v 1.8.0_60 (build 1.8.0_60-b27).

I am processing ~ 7000 files. The averages of 3 runs:

First version:
With .parallel():  20 seconds. Without .parallel(): 41 seconds

Second version:
With .parallelStream(): 12 seconds. With .stream(): 41 seconds.

Those 8 seconds in parallel mode seem like an enormous difference given that the extract method that reads from the stream and does all the heavy work and the write call doing the final writes are unchanged.

Body:
Another alternative to your workaround is to use .collect(Collectors.toList()).parallelStream() on your stream like

try(Stream<Path> paths = Files.list(infoDir)) {
    paths
        .collect(Collectors.toList())
        .parallelStream()
        .map(this::extract)
        .forEachOrdered(drug -> {
            try {
                marshaller.write(drug);
            } catch (JAXBException ex) {
                ex.printStackTrace();
            }
        });
}

With this you don't need to call  .map(f -> infoDir.resolve(f)) and the performance should be similar to your second solution.


问:
Asynchronous filtering an array of Promises
I have an array of strings let symbols = ['abc', 'cde', 'edf', 'qqe', 'hrt'] that I pass as an argument to the function:

```<code>async function fetchDetails(symbols) {
  let promises = symbols.map((s, i) => {
    return fetch(URL + s)
      .then(res => return res.json())
      .then(json => Object.assign({}, { [s]: json }))
  });
  console.log('promise:', promises)
  return Promise.all(promises);
}
</code>```

I fetch data from URL/'abc', URL/'cde' etc. and save it into promises array.

But there is an % probability that from the server I will not get all 5 resolved objects. Then in console.log the promises array looks like this:

And I would like to have array containg only 4 resolved items (that I pass to the Promise.all(), instead of 5 (including 4 resolved and 1 with pending status).

If it was a synchronous function, I would simply have to have filtered the array. But I have no access to the [[PromiseStatus]] properties and have no idea how to do this.

Since I am quite new to the Javascript I would appreciate any help with this Async thing. Any scrap or code, or advise where to search for the answer :)

Edit:
Maybe this will help a bit, the route I send a query to, is built like this:

```<code>app.get('/data/:symbol', async (req, res) => {
  const { params: { symbol } } = req
  const data = await stocks.getData(symbol, new Date())
  res.send(data)
})
</code>```

So in the case of error, it doesn't send any error right?
And that's why I could potentially have Pending Status instead of Reject?

SOLUTION OF THE TASK

Hey guys, so I solved this issue with 2 things:
1. Thanks to @Bergi, who pointed to the fact that Pending Status is not something that can be omitted - I checked server side and there was a first problem - Errors were not handled.
2. Then after fixing Server side, since I could separate Resolved Promises from Rejected - I was abble to return Array containing only Resolved promises - using this custom Promise_all solution: https://stackoverflow.com/a/46024590

So my final code looks something like this:

```<code>async function fetchDetails(symbols) {
  let promises = symbols.map(async (s, i) => {
    return await fetch(URL + s)
      .then((res)=> {
        if (!res.ok) {
          throw new Error('Error with fetch')
        } else {
          return res.json();
        }
      })
      .then(json => Object.assign({}, { [s]: json }))
      .catch(err => {
        return Promise.reject()})
  });

  const Promise_all = promises => {
    return new Promise((resolve, reject) => {
      const results = [];
      let count = 0;
      promises.forEach((promise, idx) => {
        promise
          .catch(err => {
            return err;
          })
          .then(valueOrError => {
            results[idx] = valueOrError;
            count += 1;
            if (count === promises.length) resolve(results);
          });
      });
    });
  };

  const results = await Promise_all(promises)
  const validResults = results.filter(result => result !== undefined);

  return validResults;
}
</code>```

Thank you very much to everyone who was writing here!

答:
If you want to fail after a certain timeout you could do this:

```<code>const failIn = milliseconds =>
  setTimeout(
    _=>Promise.reject("timed out")
    ,milliseconds
  );

const Fail = function(details){this.details=details;};

const fetchDetails = symbols =>
  Promise.all(
    symbols.map((s, i) => {
      return Promise.race([
        fetch(URL + s),
        ,failIn(2000)//fail in 2 seconds
      ])
      .then(
        response=>[response,s],
        err = [new fail([err,URL+s]),s]
      )
    })
  )
  .then(
    responses =>
      responses.map(//map to json object from response or Fail type
        ([response,s]) =>
          (response && response.constructor === Fail)
            ? response
            : Object.assign({}, { [s]: response.json() })
      )
  );
</code>```

The Fail objects are still included in the result, you could use filter to take them out if you're just going to ignore them:

```<code>  .then(
    responses =>
      responses.filter(
        ([response,s]) => (response && response.constructor !== Fail)
      )
      .map(
        ([response,s]) =>
          Object.assign({}, { [s]: response.json() })
      )
  )
</code>```

Body:
I have an array of strings let symbols = ['abc', 'cde', 'edf', 'qqe', 'hrt'] that I pass as an argument to the function:

async function fetchDetails(symbols) {
  let promises = symbols.map((s, i) => {
    return fetch(URL + s)
      .then(res => return res.json())
      .then(json => Object.assign({}, { [s]: json }))
  });
  console.log('promise:', promises)
  return Promise.all(promises);
}

I fetch data from URL/'abc', URL/'cde' etc. and save it into promises array.

But there is an % probability that from the server I will not get all 5 resolved objects. Then in console.log the promises array looks like this:

And I would like to have array containg only 4 resolved items (that I pass to the Promise.all(), instead of 5 (including 4 resolved and 1 with pending status).

If it was a synchronous function, I would simply have to have filtered the array. But I have no access to the [[PromiseStatus]] properties and have no idea how to do this.

Since I am quite new to the Javascript I would appreciate any help with this Async thing. Any scrap or code, or advise where to search for the answer :)

Edit:
Maybe this will help a bit, the route I send a query to, is built like this:

app.get('/data/:symbol', async (req, res) => {
  const { params: { symbol } } = req
  const data = await stocks.getData(symbol, new Date())
  res.send(data)
})

So in the case of error, it doesn't send any error right?
And that's why I could potentially have Pending Status instead of Reject?

SOLUTION OF THE TASK

Hey guys, so I solved this issue with 2 things:
1. Thanks to @Bergi, who pointed to the fact that Pending Status is not something that can be omitted - I checked server side and there was a first problem - Errors were not handled.
2. Then after fixing Server side, since I could separate Resolved Promises from Rejected - I was abble to return Array containing only Resolved promises - using this custom Promise_all solution: https://stackoverflow.com/a/46024590

So my final code looks something like this:

async function fetchDetails(symbols) {
  let promises = symbols.map(async (s, i) => {
    return await fetch(URL + s)
      .then((res)=> {
        if (!res.ok) {
          throw new Error('Error with fetch')
        } else {
          return res.json();
        }
      })
      .then(json => Object.assign({}, { [s]: json }))
      .catch(err => {
        return Promise.reject()})
  });

  const Promise_all = promises => {
    return new Promise((resolve, reject) => {
      const results = [];
      let count = 0;
      promises.forEach((promise, idx) => {
        promise
          .catch(err => {
            return err;
          })
          .then(valueOrError => {
            results[idx] = valueOrError;
            count += 1;
            if (count === promises.length) resolve(results);
          });
      });
    });
  };

  const results = await Promise_all(promises)
  const validResults = results.filter(result => result !== undefined);

  return validResults;
}

Thank you very much to everyone who was writing here!

Body:
If you want to fail after a certain timeout you could do this:

const failIn = milliseconds =>
  setTimeout(
    _=>Promise.reject("timed out")
    ,milliseconds
  );

const Fail = function(details){this.details=details;};

const fetchDetails = symbols =>
  Promise.all(
    symbols.map((s, i) => {
      return Promise.race([
        fetch(URL + s),
        ,failIn(2000)//fail in 2 seconds
      ])
      .then(
        response=>[response,s],
        err = [new fail([err,URL+s]),s]
      )
    })
  )
  .then(
    responses =>
      responses.map(//map to json object from response or Fail type
        ([response,s]) =>
          (response && response.constructor === Fail)
            ? response
            : Object.assign({}, { [s]: response.json() })
      )
  );

The Fail objects are still included in the result, you could use filter to take them out if you're just going to ignore them:

  .then(
    responses =>
      responses.filter(
        ([response,s]) => (response && response.constructor !== Fail)
      )
      .map(
        ([response,s]) =>
          Object.assign({}, { [s]: response.json() })
      )
  )


问:
TinyMCE inline mode showing raw HTML rather than formatted output
I'm attempting to use the inline mode of TinyMCE with an MVC 5 page.  I created the HTML content using a TinyMCE editor in the standard mode as follows:

That data is saved back to the database and then retrieved and displayed on a different page.  On that page I've set up an instance of TinyMCE to display that content in the inline view as follows:

```<code>  <div id="myeditablediv">@Model.LongDescription</div>

  <script src="~/scripts/tinymce/tinymce.min.js"></script>

  <script type="text/javascript">
    tinymce.init({
      selector: '#myeditablediv',
      entity_encoding: 'raw',

      inline: true
    });
  </script>
</code>```

I'd expected that to show the formatted HTML in a clickable TinyMCE control with no toolbars, but instead it's just showing the raw HTML:

Clicking on the control does switch it into edit mode and the toolbar appears etc:

so it looks like I'm not passing the data to be rendered to the control correctly when setting up the div with
@Model.LongDescription
?

答:
I am guessing that your code is escaping the HTML when inserting it back into the page.  I don't know ASP.NET but there is likely something you can do to @Model.LongDescription to have it place the raw HTML into the page.

A quick google search suggest this might be the answer:

```<code>@Html.Raw(@Model.LongDescription)
</code>```

Body:
I'm attempting to use the inline mode of TinyMCE with an MVC 5 page.  I created the HTML content using a TinyMCE editor in the standard mode as follows:

That data is saved back to the database and then retrieved and displayed on a different page.  On that page I've set up an instance of TinyMCE to display that content in the inline view as follows:

@Model.LongDescription

I'd expected that to show the formatted HTML in a clickable TinyMCE control with no toolbars, but instead it's just showing the raw HTML:

Clicking on the control does switch it into edit mode and the toolbar appears etc:

so it looks like I'm not passing the data to be rendered to the control correctly when setting up the div with
@Model.LongDescription
?

Body:
I am guessing that your code is escaping the HTML when inserting it back into the page.  I don't know ASP.NET but there is likely something you can do to @Model.LongDescription to have it place the raw HTML into the page.

A quick google search suggest this might be the answer:

@Html.Raw(@Model.LongDescription)


问:
sortBy of collection and orderBy of Eloquent, which one is faster in Laravel
I have a users table and I have associated User model for it. Now to get all the user from that table ordered by updated_at I can follow two following ways:

1. Using Eloquent(DB): let's say MySQL

User::orderBy('updated_at')->get();

2. Using collection method(PHP)

User::get()->sortBy('updated_at');

Between this tow ways, which one is better/faster? and why?

答:
Usually, using your database driver is much faster than using the collection because it is his purpose to fetch and order Datas :)

Laravel Collection is just arrays on steroid, but with a database driver, you can even increase performance by adding indexes to your columns.


问:
Confused About Laravel Providers and Contracts
Hi I am new to Laravel and I am try to grasp the concept of creating and using service providers and contracts in my development. I was reading this article

How to Create a Service Provider in Laravel 5.1

It talked about how they are both created and used but I still have a hard time grasping the idea of it.

The article mention this hopefully someone can discuss this more indepth

So why bother making a contract? Well, one of the amazing features in Laravel is that you can type hint the contract, and the service provider will return an instance of whatever concrete class you have bound to it.

They also mention this

Ok, now we need to create the service provider, which will bind the contract and the concrete class.

What is this binding? how does it work from top to bottom? Whats the point of doing a bind?

Is dependency injection only for services?

答:
I find some of the Laravel terminology confusing.  To me, service provider is not really an intuitive description of what it does.

Also, the whole idea of contracts seems almost pointless for smaller projects done by just one or two people which is quite common.  Laravel assumes everything is going to be huge and complicated and developed by multiple people.

I get the philosophy behind OOP but at some point trying to separate things out and bending over backwards to not duplicate anything goes too far and makes the code more difficult to follow.

One other area where laravel kind of bugs me is this idea that it wants coders to think of themselves as artists.  So they use these fancy names like eloquent and illuminate and artisan. Those are kind of intimidating words to new developers. It goes against the idea of trying to simplify things.  If they really want to prioritize simplification over thinking of themselves as web artists then maybe start with the terminology.

It's not art like painting.  If you get a spot of paint somewhere it does not ruin the painting.  If you forget a semicolon in your code the whole thing crashes. If you want to call it art then call it art for robots because you have to be robotic and precise in your syntax.


问:
Why does space in Bash string subscripts matter here?
I'm experimenting with bash scripting and noticed the following behavior:

```<code>file="test.jar"
echo "${file: -4}" #prints .jar
echo "${file:-4}"  #prints test.jar
</code>```

Very confusing behavior actually. Can someone explain why the second case prints the whole test.jar?

答:
This is a compromise due to the timeline of features being added to Bash.

The ${parameter:-word} or ${parameter-word} syntax for "replace parameter with word if parameter is null or unset (:-) / null (-)" was around for pretty much always; the - version was already in the Version 7 Bourne Shell.

The ${parameter:offset:length} and ${parameter:offset} syntax for "substring of parameter starting at offset (with optional length length)" was introduced in Bash 2.0 (no conflict so far).

Negative offsets and length specifications for the substring construct were introduced in Bash 4.2. This leads to a problem:

```<code>$ string=01234567890abcdefgh
$ echo ${string:7:-2}           # Not ambiguous
7890abcdef
$ echo ${string:-7}             # Interpreted as "undefined/null, or..."
01234567890abcdefgh
$ echo ${string: -7}            # Interpreted as offset from the end
bcdefgh
$ echo ${string:(-7)}           # Interpreted as offset from the end
bcdefgh
</code>```

The space before - or the parentheses around the negative offset are there to tell the expansion apart from the :- (default value) expansion.

If the space is not there, the expansion ${file:-4} is interpreted as "print 4 if the parameter file is null or unset, and the expansion of file otherwise".

References:

BashFAQ/061: Is there a list of which features were added to specific releases (versions) of Bash?

Bash hackers wiki: Bash changes

Shell parameter expansion in the bash manual

Bash NEWS file describing feature added per version

Body:
I'm experimenting with bash scripting and noticed the following behavior:

file="test.jar"
echo "${file: -4}" #prints .jar
echo "${file:-4}"  #prints test.jar

Very confusing behavior actually. Can someone explain why the second case prints the whole test.jar?

Body:
This is a compromise due to the timeline of features being added to Bash.

The ${parameter:-word} or ${parameter-word} syntax for "replace parameter with word if parameter is null or unset (:-) / null (-)" was around for pretty much always; the - version was already in the Version 7 Bourne Shell.

The ${parameter:offset:length} and ${parameter:offset} syntax for "substring of parameter starting at offset (with optional length length)" was introduced in Bash 2.0 (no conflict so far).

Negative offsets and length specifications for the substring construct were introduced in Bash 4.2. This leads to a problem:

$ string=01234567890abcdefgh
$ echo ${string:7:-2}           # Not ambiguous
7890abcdef
$ echo ${string:-7}             # Interpreted as "undefined/null, or..."
01234567890abcdefgh
$ echo ${string: -7}            # Interpreted as offset from the end
bcdefgh
$ echo ${string:(-7)}           # Interpreted as offset from the end
bcdefgh

The space before - or the parentheses around the negative offset are there to tell the expansion apart from the :- (default value) expansion.

If the space is not there, the expansion ${file:-4} is interpreted as "print 4 if the parameter file is null or unset, and the expansion of file otherwise".

References:

BashFAQ/061: Is there a list of which features were added to specific releases (versions) of Bash?

Bash hackers wiki: Bash changes

Shell parameter expansion in the bash manual

Bash NEWS file describing feature added per version


问:
Why is my white space being stripped out from my HTML?
I have just noticed that my rails app is now stripping out all seemingly unnecessary white space from my fields. It never used to do this, and I have (perhaps foolishly) some javascript that is relying on this white space which is now not working.

How can I turn this off?

答: I've never seen Rails doing this. Perhaps your server is trying to minimize html and stripping out unnecessary whitespaces?</p>


问:
Saving iOS Calendar Event is now giving an error
```<code>Error pushing dirty properties for EKPersistentLocation to daemon: Error Domain=NSMachErrorDomain Code=4097 "unknown error code"
Connection interrupted!
</code>```

Any ideas as to why I cannot save my events anymore?

```<code>    NSString *eventIdentifier = ...
    EKEventStore *store = [EKEventStore new];
    EKEvent *event = [store eventWithIdentifier:eventIdentifier];
    if(event == nil) {
        event = [EKEvent eventWithEventStore:store];
    }

    //fill event code here

    //save event
    NSError *error = nil;
    BOOL success = [store saveEvent:event span:EKSpanThisEvent commit:YES error:&error];
    if(error) {
        @throw error;
    }

    if(!success) {
        @throw [Error ERROR_EVENT_SYNC_FAILED_NO_ERROR];
    }
</code>```

Interestingly, no error object is generated but success is NO. The error code and message are not particularly helpful. I am not sure what it means by dirty properties but I am not reusing an old event but grabbing one from the store or making a new one every time. I also do not know what Connection Interrupted means.

Any help would be appreciated.

答:
For the benefit of other people searching NSMachErrorDomain Code=4097 in relation to EventKit, I recently started seeing this code when updating the startDate and endDate properties of a repeating event with a span of .futureEvents, but not committing the changes right away.

Calling:

try eventStore.save(event, span: span, commit: false)

and later when dismissing the edit screen:

try eventStore.save(event, span: span, commit: true)

The second call throws an error, does not commit the changes, and shows this output in the console:

Month 13 is out of bounds
[EventKit] Failed to get melted object for frozen object related by key detachedItems. Event store is nil
[EventKit] Connection interrupted!
[CADXPCProxyHelper] Received error from calaccessd connection: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.calaccessd" UserInfo={NSDebugDescription=connection to service named com.apple.calaccessd}. Attempting to call any reply handler.
[EventKit] Error committing event store: [Error Domain=NSMachErrorDomain Code=4097 "unknown error code"]

Edit: I found out that the real problem was that my initial call with commit: false was using .futureEvents, but my function wasn't updating the selected span, so the second call was defaulting to .thisEvent. It seems that this mismatch between the spans was causing the error.

Body:
Error pushing dirty properties for EKPersistentLocation to daemon: Error Domain=NSMachErrorDomain Code=4097 "unknown error code"
Connection interrupted!

Any ideas as to why I cannot save my events anymore?

    NSString *eventIdentifier = ...
    EKEventStore *store = [EKEventStore new];
    EKEvent *event = [store eventWithIdentifier:eventIdentifier];
    if(event == nil) {
        event = [EKEvent eventWithEventStore:store];
    }

    //fill event code here

    //save event
    NSError *error = nil;
    BOOL success = [store saveEvent:event span:EKSpanThisEvent commit:YES error:&error];
    if(error) {
        @throw error;
    }

    if(!success) {
        @throw [Error ERROR_EVENT_SYNC_FAILED_NO_ERROR];
    }

Interestingly, no error object is generated but success is NO. The error code and message are not particularly helpful. I am not sure what it means by dirty properties but I am not reusing an old event but grabbing one from the store or making a new one every time. I also do not know what Connection Interrupted means.

Any help would be appreciated.


问:
What is the difference between airflow trigger rule "all_done" and "all_success"?
One of the requirement in the workflow I am working on is to wait for some event to happen for given time, if it does not happen mark the task as failed still the downstream task should be executed.

I am wondering if "all_done" means all the dependency tasks are done no matter if they have succeeded or not.

答:
SUMMARY

The tasks are "all done" if the count of SUCCESS, FAILED, UPSTREAM_FAILED, SKIPPED tasks is greater than or equal to the count of all upstream tasks.

Not sure why it would be greater than? Perhaps subdags do something weird to the counts.

Tasks are "all success" if the count of upstream tasks and the count of success upstream tasks is the same.

DETAILS

The code for evaluating trigger rules is here https://github.com/apache/incubator-airflow/blob/master/airflow/ti_deps/deps/trigger_rule_dep.py#L72

ALL_DONE

The following code runs the qry and returns the first row (the query is an aggregation that will only ever return one row anyway) into the following variables:

```<code>successes, skipped, failed, upstream_failed, done = qry.first()
</code>```

the "done" column in the query corresponds to this: func.count(TI.task_id) in other words a count of all the tasks matching the filter.
The filter specifies that it is counting only upstream tasks, from the current dag, from the current execution date and this:

```<code> TI.state.in_([
                    State.SUCCESS, State.FAILED,
                    State.UPSTREAM_FAILED, State.SKIPPED])
</code>```

So done is a count of the upstream tasks with one of those 4 states.

Later there is this code

```<code>upstream = len(task.upstream_task_ids)
...
upstream_done = done >= upstream
</code>```

And the actual trigger rule only fails on this

```<code>if not upstream_done
</code>```

ALL_SUCCESS

The code is fairly straightforward and the concept is intuitive

```<code>num_failures = upstream - successes
if num_failures > 0:
... it fails
</code>```

Body:
SUMMARY

The tasks are "all done" if the count of SUCCESS, FAILED, UPSTREAM_FAILED, SKIPPED tasks is greater than or equal to the count of all upstream tasks.

Not sure why it would be greater than? Perhaps subdags do something weird to the counts.

Tasks are "all success" if the count of upstream tasks and the count of success upstream tasks is the same.

DETAILS

The code for evaluating trigger rules is here https://github.com/apache/incubator-airflow/blob/master/airflow/ti_deps/deps/trigger_rule_dep.py#L72

ALL_DONE

The following code runs the qry and returns the first row (the query is an aggregation that will only ever return one row anyway) into the following variables:

successes, skipped, failed, upstream_failed, done = qry.first()

the "done" column in the query corresponds to this: func.count(TI.task_id) in other words a count of all the tasks matching the filter.
The filter specifies that it is counting only upstream tasks, from the current dag, from the current execution date and this:

 TI.state.in_([
                    State.SUCCESS, State.FAILED,
                    State.UPSTREAM_FAILED, State.SKIPPED])

So done is a count of the upstream tasks with one of those 4 states.

Later there is this code

upstream = len(task.upstream_task_ids)
...
upstream_done = done >= upstream

And the actual trigger rule only fails on this

if not upstream_done

ALL_SUCCESS

The code is fairly straightforward and the concept is intuitive

num_failures = upstream - successes
if num_failures > 0:
... it fails


问:
Useless isolation checks in the beginning of every transaction in Hibernate
Is there any way to disable them? I am losing microseconds for doing nothing. I am sure what is the isolation lavel on my db. I don't need to check it every time.

```<code>2017-12-08 12:35:46.979 QUERY duration: 17 connection: 3834 resultset: 1075 message: SELECT @@session.tx_isolation
</code>```

I use READ COMMITTED which is default on my db and is set in my persistence.xml

```<code>  <property name="hibernate.connection.isolation" value="2"/>
</code>```

答:
Simply remove

```<code><property name="hibernate.connection.isolation" value="2"/>
</code>```

READ_COMMITED is the default of JDBC as well and you don't need to tell Hibernate about. That's probably why Hibernate is executing the statement

Body:
Is there any way to disable them? I am losing microseconds for doing nothing. I am sure what is the isolation lavel on my db. I don't need to check it every time.

2017-12-08 12:35:46.979 QUERY duration: 17 connection: 3834 resultset: 1075 message: SELECT @@session.tx_isolation

I use READ COMMITTED which is default on my db and is set in my persistence.xml

  <property name="hibernate.connection.isolation" value="2"/>

Body:
Simply remove

<property name="hibernate.connection.isolation" value="2"/>

READ_COMMITED is the default of JDBC as well and you don't need to tell Hibernate about. That's probably why Hibernate is executing the statement


问:
Regex - Split the string on most right slash occurrence [Hive]
I want to split the path string based on the rightmost slash occurrence. The folders depths is variable - I can't know how many slashes I have. Is it possible to create the regex for this? I use it in HIVE queries for SPLIT function.

For example:

original string

```<code>/IP/backup_jun20_2017/proddb/application_profile/mth_end_dt=2016-10-31/000000_0
</code>```

After split:

string 1:

```<code>/IP/backup_jun20_2017/proddb/application_profile/mth_end_dt=2016-10-31
</code>```

string 2:

```<code>000000_0
</code>```

答:
Try to use this regex (.*)\/(.*?)$ or (.*)\/([^\/]+)

Which match two groups (.*) the first one before the last slash, the second group after the last slash you can get it like this \/(.*?)$ or ([^\/]+)

Body:
I want to split the path string based on the rightmost slash occurrence. The folders depths is variable - I can't know how many slashes I have. Is it possible to create the regex for this? I use it in HIVE queries for SPLIT function.

For example:

original string

/IP/backup_jun20_2017/proddb/application_profile/mth_end_dt=2016-10-31/000000_0

After split:

string 1:

/IP/backup_jun20_2017/proddb/application_profile/mth_end_dt=2016-10-31

string 2:

000000_0