问:
TensorFlow uninitialized value error with mse loss
I'm trying to train an autoencoder with mse loss function with TensorFlow r1.2, but I keep getting a FailedPreconditionError which states that one of the variables related to computing the mse is uninitialized (see full stack trace printout below). I'm running this in Jupyter notebook and I'm using Python 3.

I trimmed down my code to a minimal example as follows

```<code>import tensorflow as tf
import numpy as np
from functools import partial

# specify network

def reset_graph(seed=0):
    tf.reset_default_graph()
    tf.set_random_seed(seed)
    np.random.seed(seed)
reset_graph()

n_inputs = 100
n_hidden = 6
n_outputs = n_inputs

learning_rate = 0.001
l2_reg = 0.001

X = tf.placeholder(tf.float32, shape=[None, n_inputs])

he_init = tf.contrib.layers.variance_scaling_initializer()
l2_regularizer = tf.contrib.layers.l2_regularizer(l2_reg)
my_dense_layer = partial(tf.layers.dense,
                         activation=tf.nn.elu,
                         kernel_initializer=he_init,
                         kernel_regularizer=l2_regularizer)

hidden1 = my_dense_layer(X, n_hidden1)
outputs = my_dense_layer(hidden1, n_outputs, activation=None)

reconstruction_loss = tf.reduce_mean(tf.metrics.mean_squared_error(X, outputs))

reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
loss = tf.add_n([reconstruction_loss] + reg_losses)

optimizer = tf.train.AdamOptimizer(learning_rate)
training_op = optimizer.minimize(loss)

init = tf.global_variables_initializer()

# generate 1000 random examples

sample_X = np.random.rand(1000, 100)

# train network

n_epochs = 10
batch_size = 50
with tf.Session() as sess:
    sess.run(init) # init.run()
    for epoch in range(n_epochs):
        n_batches = sample_X.shape[0] // batch_size
        for iteration in range(n_batches):
            start_idx = iteration*batch_size
            if iteration == n_batches-1:
                end_idx = sample_X.shape[0]
            else:
                end_idx = start_idx + batch_size
            sys.stdout.flush()

            X_batch = sample_X[start_idx:end_idx]
            sess.run(training_op, feed_dict={X: X_batch})

            loss_train = reconstruction_loss.eval(feed_dict={X: X_batch})
            print(round(loss_train, 5))
</code>```

When I replace the line that defines reconstruction_loss to not use tf.metrics, as follows

```<code>reconstruction_loss = tf.reduce_mean(tf.square(tf.norm(outputs - X)))
</code>```

I don't get the exception.

I've checked several similar SO questions, but none of them has solved my problem. For example, one possible cause, suggested in an answer at FailedPreconditionError: Attempting to use uninitialized in Tensorflow, is failing to initialize all the variables in the TF graph, but my script initializes all TF variables with init = tf.global_variables_initializer() and then sess.run(init). Another possible cause is that the Adam optimizer creates its own variables, which need to be initialized after specifying the optimizer (see Tensorflow: Using Adam optimizer). However, my script defines the variable initializer after the optimizer, as suggested in the accepted answer to that question, so that also can't be my problem.

Can anyone spot anything wrong with my script or suggest things to try to suss out the cause of this error?

Below is the stack trace from the error.

```<code>---------------------------------------------------------------------------
FailedPreconditionError                   Traceback (most recent call last)
~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1138     try:
-> 1139       return fn(*args)
   1140     except errors.OpError as e:

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1120                                  feed_dict, fetch_list, target_list,
-> 1121                                  status, run_metadata)
   1122

~\AppData\Local\Continuum\Anaconda3\lib\contextlib.py in __exit__(self, type, value, traceback)
     88             try:
---> 89                 next(self.gen)
     90             except StopIteration:

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\framework\errors_impl.py in raise_exception_on_not_ok_status()
    465           compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 466           pywrap_tensorflow.TF_GetCode(status))
    467   finally:

FailedPreconditionError: Attempting to use uninitialized value mean_squared_error/total
     [[Node: mean_squared_error/total/read = Identity[T=DT_FLOAT, _class=["loc:@mean_squared_error/total"], _device="/job:localhost/replica:0/task:0/cpu:0"](mean_squared_error/total)]]

During handling of the above exception, another exception occurred:

FailedPreconditionError                   Traceback (most recent call last)
<ipython-input-55-aac61c488ed8> in <module>()
     64             sess.run(training_op, feed_dict={X: X_batch})
     65
---> 66             loss_train = reconstruction_loss.eval(feed_dict={X: X_batch})
     67             print(round(loss_train, 5))

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in eval(self, feed_dict, session)
    604
    605     """
--> 606     return _eval_using_default_session(self, feed_dict, self.graph, session)
    607
    608

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in _eval_using_default_session(tensors, feed_dict, graph, session)
   3926                        "the tensor's graph is different from the session's "
   3927                        "graph.")
-> 3928   return session.run(tensors, feed_dict)
   3929
   3930

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    787     try:
    788       result = self._run(None, fetches, feed_dict, options_ptr,
--> 789                          run_metadata_ptr)
    790       if run_metadata:
    791         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    995     if final_fetches or final_targets:
    996       results = self._do_run(handle, final_targets, final_fetches,
--> 997                              feed_dict_string, options, run_metadata)
    998     else:
    999       results = []

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1130     if handle is None:
   1131       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1132                            target_list, options, run_metadata)
   1133     else:
   1134       return self._do_call(_prun_fn, self._session, handle, feed_dict,

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1150         except KeyError:
   1151           pass
-> 1152       raise type(e)(node_def, op, message)
   1153
   1154   def _extend_graph(self):

FailedPreconditionError: Attempting to use uninitialized value mean_squared_error/total
     [[Node: mean_squared_error/total/read = Identity[T=DT_FLOAT, _class=["loc:@mean_squared_error/total"], _device="/job:localhost/replica:0/task:0/cpu:0"](mean_squared_error/total)]]

Caused by op 'mean_squared_error/total/read', defined at:
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\ipykernel\__main__.py", line 3, in <module>
    app.launch_new_instance()
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
    app.start()
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\ipykernel\kernelapp.py", line 474, in start
    ioloop.IOLoop.instance().start()
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tornado\ioloop.py", line 888, in start
    handler_func(fd_obj, events)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 390, in execute_request
    user_expressions, allow_stdin)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\ipykernel\zmqshell.py", line 501, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2698, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2802, in run_ast_nodes
    if self.run_code(code, result):
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-55-aac61c488ed8>", line 32, in <module>
    reconstruction_loss = tf.reduce_mean(tf.metrics.mean_squared_error(X, outputs))
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 1054, in mean_squared_error
    updates_collections, name or 'mean_squared_error')
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 331, in mean
    total = _create_local('total', shape=[])
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 196, in _create_local
    validate_shape=validate_shape)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 1679, in variable
    caching_device=caching_device, name=name, dtype=dtype)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\variables.py", line 200, in __init__
    expected_shape=expected_shape)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\variables.py", line 319, in _init_from_args
    self._snapshot = array_ops.identity(self._variable, name="read")
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 1303, in identity
    result = _op_def_lib.apply_op("Identity", input=input, name=name)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 767, in apply_op
    op_def=op_def)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 2506, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1269, in __init__
    self._traceback = _extract_stack()

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value mean_squared_error/total
     [[Node: mean_squared_error/total/read = Identity[T=DT_FLOAT, _class=["loc:@mean_squared_error/total"], _device="/job:localhost/replica:0/task:0/cpu:0"](mean_squared_error/total)]]
</code>```

答:
Looks like you're doing everything right with initialization, so I suspect your error is that you're using tf.metrics.mean_squared_error incorrectly.

The metrics package of classes allows you to compute a value, but also accumulate that value over multiple calls to sess.run. Note the return value of tf.metrics.mean_square_error in the docs:

https://www.tensorflow.org/api_docs/python/tf/metrics/mean_squared_error

You get back both mean_square_error, as you appear to expect, and an update_op. The purpose of the update_op is that you ask tensorflow to compute the update_op and it accumulates the mean square error. Each time you call mean_square_error you get the accumulated value. When you want to reset the value you would run sess.run(tf.local_variables_initializer()) (note local and not global to clear "local" variables as the metrics package defines them).

I don't think the metrics package was intended to be used the way you're using it. I think your intention was to compute the mse only based on the current batch as your loss and not accumulate the value over multiple calls. I'm not even sure how differentiation would work with respect to an accumulated value like this.

So I think the answer to your question is: don't use the metrics package this way. Use metrics for reporting, and for accumulating results over multiple iterations of a test dataset, for example, not for generating a loss function.

I think what you mean to use is tf.losses.mean_squared_error

Body:
I'm trying to train an autoencoder with mse loss function with TensorFlow r1.2, but I keep getting a FailedPreconditionError which states that one of the variables related to computing the mse is uninitialized (see full stack trace printout below). I'm running this in Jupyter notebook and I'm using Python 3.

I trimmed down my code to a minimal example as follows

import tensorflow as tf
import numpy as np
from functools import partial

# specify network

def reset_graph(seed=0):
    tf.reset_default_graph()
    tf.set_random_seed(seed)
    np.random.seed(seed)
reset_graph()

n_inputs = 100
n_hidden = 6
n_outputs = n_inputs

learning_rate = 0.001
l2_reg = 0.001

X = tf.placeholder(tf.float32, shape=[None, n_inputs])

he_init = tf.contrib.layers.variance_scaling_initializer()
l2_regularizer = tf.contrib.layers.l2_regularizer(l2_reg)
my_dense_layer = partial(tf.layers.dense,
                         activation=tf.nn.elu,
                         kernel_initializer=he_init,
                         kernel_regularizer=l2_regularizer)

hidden1 = my_dense_layer(X, n_hidden1)
outputs = my_dense_layer(hidden1, n_outputs, activation=None)

reconstruction_loss = tf.reduce_mean(tf.metrics.mean_squared_error(X, outputs))

reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
loss = tf.add_n([reconstruction_loss] + reg_losses)

optimizer = tf.train.AdamOptimizer(learning_rate)
training_op = optimizer.minimize(loss)

init = tf.global_variables_initializer()

# generate 1000 random examples

sample_X = np.random.rand(1000, 100)

# train network

n_epochs = 10
batch_size = 50
with tf.Session() as sess:
    sess.run(init) # init.run()
    for epoch in range(n_epochs):
        n_batches = sample_X.shape[0] // batch_size
        for iteration in range(n_batches):
            start_idx = iteration*batch_size
            if iteration == n_batches-1:
                end_idx = sample_X.shape[0]
            else:
                end_idx = start_idx + batch_size
            sys.stdout.flush()

            X_batch = sample_X[start_idx:end_idx]
            sess.run(training_op, feed_dict={X: X_batch})

            loss_train = reconstruction_loss.eval(feed_dict={X: X_batch})
            print(round(loss_train, 5))

When I replace the line that defines reconstruction_loss to not use tf.metrics, as follows

reconstruction_loss = tf.reduce_mean(tf.square(tf.norm(outputs - X)))

I don't get the exception.

I've checked several similar SO questions, but none of them has solved my problem. For example, one possible cause, suggested in an answer at FailedPreconditionError: Attempting to use uninitialized in Tensorflow, is failing to initialize all the variables in the TF graph, but my script initializes all TF variables with init = tf.global_variables_initializer() and then sess.run(init). Another possible cause is that the Adam optimizer creates its own variables, which need to be initialized after specifying the optimizer (see Tensorflow: Using Adam optimizer). However, my script defines the variable initializer after the optimizer, as suggested in the accepted answer to that question, so that also can't be my problem.

Can anyone spot anything wrong with my script or suggest things to try to suss out the cause of this error?

Below is the stack trace from the error.

---------------------------------------------------------------------------
FailedPreconditionError                   Traceback (most recent call last)
~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1138     try:
-> 1139       return fn(*args)
   1140     except errors.OpError as e:

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1120                                  feed_dict, fetch_list, target_list,
-> 1121                                  status, run_metadata)
   1122

~\AppData\Local\Continuum\Anaconda3\lib\contextlib.py in __exit__(self, type, value, traceback)
     88             try:
---> 89                 next(self.gen)
     90             except StopIteration:

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\framework\errors_impl.py in raise_exception_on_not_ok_status()
    465           compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 466           pywrap_tensorflow.TF_GetCode(status))
    467   finally:

FailedPreconditionError: Attempting to use uninitialized value mean_squared_error/total
     [[Node: mean_squared_error/total/read = Identity[T=DT_FLOAT, _class=["loc:@mean_squared_error/total"], _device="/job:localhost/replica:0/task:0/cpu:0"](mean_squared_error/total)]]

During handling of the above exception, another exception occurred:

FailedPreconditionError                   Traceback (most recent call last)
<ipython-input-55-aac61c488ed8> in <module>()
     64             sess.run(training_op, feed_dict={X: X_batch})
     65
---> 66             loss_train = reconstruction_loss.eval(feed_dict={X: X_batch})
     67             print(round(loss_train, 5))

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in eval(self, feed_dict, session)
    604
    605     """
--> 606     return _eval_using_default_session(self, feed_dict, self.graph, session)
    607
    608

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in _eval_using_default_session(tensors, feed_dict, graph, session)
   3926                        "the tensor's graph is different from the session's "
   3927                        "graph.")
-> 3928   return session.run(tensors, feed_dict)
   3929
   3930

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    787     try:
    788       result = self._run(None, fetches, feed_dict, options_ptr,
--> 789                          run_metadata_ptr)
    790       if run_metadata:
    791         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    995     if final_fetches or final_targets:
    996       results = self._do_run(handle, final_targets, final_fetches,
--> 997                              feed_dict_string, options, run_metadata)
    998     else:
    999       results = []

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1130     if handle is None:
   1131       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1132                            target_list, options, run_metadata)
   1133     else:
   1134       return self._do_call(_prun_fn, self._session, handle, feed_dict,

~\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1150         except KeyError:
   1151           pass
-> 1152       raise type(e)(node_def, op, message)
   1153
   1154   def _extend_graph(self):

FailedPreconditionError: Attempting to use uninitialized value mean_squared_error/total
     [[Node: mean_squared_error/total/read = Identity[T=DT_FLOAT, _class=["loc:@mean_squared_error/total"], _device="/job:localhost/replica:0/task:0/cpu:0"](mean_squared_error/total)]]

Caused by op 'mean_squared_error/total/read', defined at:
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\ipykernel\__main__.py", line 3, in <module>
    app.launch_new_instance()
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
    app.start()
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\ipykernel\kernelapp.py", line 474, in start
    ioloop.IOLoop.instance().start()
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tornado\ioloop.py", line 888, in start
    handler_func(fd_obj, events)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 390, in execute_request
    user_expressions, allow_stdin)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\ipykernel\zmqshell.py", line 501, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2698, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2802, in run_ast_nodes
    if self.run_code(code, result):
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-55-aac61c488ed8>", line 32, in <module>
    reconstruction_loss = tf.reduce_mean(tf.metrics.mean_squared_error(X, outputs))
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 1054, in mean_squared_error
    updates_collections, name or 'mean_squared_error')
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 331, in mean
    total = _create_local('total', shape=[])
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\metrics_impl.py", line 196, in _create_local
    validate_shape=validate_shape)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 1679, in variable
    caching_device=caching_device, name=name, dtype=dtype)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\variables.py", line 200, in __init__
    expected_shape=expected_shape)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\variables.py", line 319, in _init_from_args
    self._snapshot = array_ops.identity(self._variable, name="read")
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 1303, in identity
    result = _op_def_lib.apply_op("Identity", input=input, name=name)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 767, in apply_op
    op_def=op_def)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 2506, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1269, in __init__
    self._traceback = _extract_stack()

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value mean_squared_error/total
     [[Node: mean_squared_error/total/read = Identity[T=DT_FLOAT, _class=["loc:@mean_squared_error/total"], _device="/job:localhost/replica:0/task:0/cpu:0"](mean_squared_error/total)]]


来源: stackexchange

问:
Azure function output binding destroys collection in Cosmos DB
I am trying to save a document to a collection in CosmosDB using output binding.

The DB was created with MongoDB API access.

I noticed a few issues:

Azure function in JavaScript with output binding doesn't seem to work. Here is the code:

module.exports = function (context, req) {
    if (req.body) {
        context.bindings.outputObject = JSON.stringify({
            name: "Mike P"
        }); // tried outputObjectOut as well, no difference

        context.res = {
            // status: 200, /* Defaults to 200 */
            body: "Hello " + (req.query.name || req.body.name)
        };
    }
    else {
        context.res = {
            status: 400,
            body: "Please pass a name on the query string or in the request body"
        };
    }
    context.done();
};
```

<p>The <strong>function.json</strong> for the JavaScript code is the same as given further below.</p>

<ol start="2">
<li>I wrote equivalent code in C# and noticed that the collection was destroyed (by the binding apparently when the document was saved).</li>
</ol>

<pre class="lang-cs prettyprint-override"><code>public static HttpResponseMessage Run(HttpRequestMessage req,
    out object outputObject, TraceWriter log)
{
    outputObject = new {
        name = "Mike P"
    };

    log.Info("test");

    return req.CreateResponse(HttpStatusCode.OK);
}
</code>```

Here is the function.json

{
  "type": "documentDB",
  "name": "outputObject",
  "databaseName": "newexp",
  "collectionName": "Test",
  "createIfNotExists": true,
  "connection": "newexp_DOCUMENTDB",
  "direction": "out"
}
```

The collection can't be queried any more in the Azure console. Querying through a MongoDB client like 3T failed as well.

I would expect this code to work and a document shows up in the collection in the DB. But instead I am seeing the collection becoming unusable. Is this a bug or am I doing something wrong? Any help or pointers are appreciated.

答: The Azure Function CosmosDB binding is written against the DocumentDB API (or SQL API) for CosmosDB - so doesn't work out-of-the-box with Mongo API. I believe it may work if you add a required _id property in the object. Without an _id field the Mongo API call will fail</p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to save a document to a collection in CosmosDB using output binding.

The DB was created with MongoDB API access.

I noticed a few issues:

Azure function in JavaScript with output binding doesn't seem to work. Here is the code:

module.exports = function (context, req) {
    if (req.body) {
        context.bindings.outputObject = JSON.stringify({
            name: "Mike P"
        }); // tried outputObjectOut as well, no difference

        context.res = {
            // status: 200, /* Defaults to 200 */
            body: "Hello " + (req.query.name || req.body.name)
        };
    }
    else {
        context.res = {
            status: 400,
            body: "Please pass a name on the query string or in the request body"
        };
    }
    context.done();
};

The function.json for the JavaScript code is the same as given further below.

I wrote equivalent code in C# and noticed that the collection was destroyed (by the binding apparently when the document was saved).

public static HttpResponseMessage Run(HttpRequestMessage req,
    out object outputObject, TraceWriter log)
{
    outputObject = new {
        name = "Mike P"
    };

    log.Info("test");

    return req.CreateResponse(HttpStatusCode.OK);
}

Here is the function.json

{
  "type": "documentDB",
  "name": "outputObject",
  "databaseName": "newexp",
  "collectionName": "Test",
  "createIfNotExists": true,
  "connection": "newexp_DOCUMENTDB",
  "direction": "out"
}

The collection can't be queried any more in the Azure console. Querying through a MongoDB client like 3T failed as well.

I would expect this code to work and a document shows up in the collection in the DB. But instead I am seeing the collection becoming unusable. Is this a bug or am I doing something wrong? Any help or pointers are appreciated.


问:
Is there any API to add tracking number and order status from my application to PayPal?
Currently I add tracking number, order status, and shipping company manually using below steps :

Log in to my PayPal account, click "Overview" and then click "Payments Received" to bring up my account's recent activity.
Click the "Print Shipping Label" drop-down menu next to the payment to which I need to submit a tracking number and then select the "Add Tracking Info" option.
Enter the required information in the pop-up window that appears including the tracking number, carrier and shipment status. Click the "Save" button to finish submitting your tracking data to PayPal.

Now I want to automate add tracking information, order status and shipping company using my application.

Please suggest !

答:
No, and here's why:

...So I actually called PayPal myself and they advised that the
  "Tracking number box" on your merchant dashboard is usually only used
  if you're using the PayPal Shipping Label area.

https://www.paypal.com/ca/webapps/mpp/shipping-centre

Meaning, general use for outside providers (like Shopify) is to not
  hand off shipping information, since it's all being processed our side
  (order confirmation/notification) instead of on PayPal.
  PayPal Express Checkout just being the money acceptance, not the
  tracking/fulfillment/shipping for (most) businesses.

ContentLicense: CC BY-SA 4.0


问:
C++ standard library - when should I use it and when shouldn't I?
I was wondering how often people actually use much of the standard c++ library, particularly the stuff in the <algorithm> and <numeric> headers.  The text books seem to recommend them, but I haven't seen any of them used at all in various projects I've sifted through (coincidence?) and personally it seems easier to just write appropriate simple algorithms myself each time rather than memorize or consult a reference to these headers each time. Am just being lazy or stubborn?  Is there actually performance gains etc when using these libraries?

Thanks,

R

答:
When should you use the C++ Standard library? When it provides a function you need.

It's known that some things like for_each aren't supported terribly well by the language- that's what lambdas are for in C++0x.

ContentLicense: CC BY-SA 2.5


问:
using user input to extract data from csv file
I am very new to Python but I'm trying to learn more and my first mini project that I've given myself is to create a code that can receive the input for a given user name and then output the amount of hours they worked on a certain project. I receive a csv at the end of the week for employees in my department  and within that csv I have various projects that they are working on and the hours dedicated to that project. The catch with the csv file is there are duplicate projects for that user so when my csv outputs I need it to only show one project name and ALL the hours associated with that project. How can I get my code to read the duplicates and only count the hours from the duplicates and just use one project name?

Here is the code I've come up with so far:

```<code>import csv
with open('Report.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    firsts = []
    lasts = []
    projects = []
    hours = []
    for row in readCSV:
        first = row[0]
        last = row[1]
        project = row[2]
        hour = row[3]

        firsts.append(first)
        lasts.append(last)
        projects.append(project)
        hours.append(hour)

    First_name = input("Please enter the first name: ")
    First_1 = firsts.index(First_name)
    Last_1 = lasts[First_1]
    project_1 = projects[First_1]
    hours_1 = hours[First_1]
    print(First_1, Last_1, project_1, hours_1)
</code>```

Here is a sample of the csv

```<code>First   Last    Project             Hours
David   Ayers   AD-0002  Training   24
Oriana  Morfitt AD-0002  Training   24
David   Ayers   AD-0003  Personal Time  8
David   Ayers   AD-0004  Sick Time  0
Oriana  Morfitt AD-0005  Vacation   40
Sujatha Kavuri  Beeline Blank   29
Sujatha Kavuri  Beeline Blank   16
Sujatha Kavuri  OPS-0001 General Operational Support    6
Jeff    Moore   OPS-0001 General Operational Support    5
Sri Mantri  SRV-0001 Service Requests for Base and Direct Services  4
Prasanth    Musunuru    SRV-0001 Service Requests for Base and Direct Services  11
Prasanth    Musunuru    SRV-0001 Service Requests for Base and Direct Services  10
Jeff    Moore   SRV-0006 Standards and Processes    5
Jeff    Moore   SRV-0006 Standards and Processes    3
Jeff    Moore   SRV-2503 Internet Access Infrastructure Maintenance & Support   12.5
Jeff    Moore   SRV-2503 Internet Access Infrastructure Maintenance & Support   7
Jeff    Moore   0024495915 Work Instructions (infrastructure) - time tracking   1
Sri Mantri  0026184229 Margin Controlling Java Rewrite  4
Sujatha Kavuri  0029157489 SCRM Life Cycle Extension    3
Jeff    Moore   0031369443 Shopcall Attachment Changes  1
Jeff    Moore   0031500942 MP Strategy 2015 - Spot PO via EDI (time tracking only) - 0031500942 1
</code>```

答:
I bet there's a better way of doing it with pandas, but this will work too:

```<code>import csv

# I've used full name to avoid duplicate first names in report
full_name = input('Enter your full name: ')

with open('Report.csv') as csvfile:
    hour_summation = {}
    read_csv = csv.reader(csvfile, delimiter=',')
    for row in read_csv:
        if ' '.join((row[0], row[1])) == full_name.strip():
            hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(row[3])

print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
    print(k + ': ' + str(v) + ' hours')
</code>```

results for Sujatha Kavuri

Enter your full name: Sujatha Kavuri

  This is Sujatha Kavuri full hours report:

  Beeline Blank: 45 hours

  OPS-0001 General Operational Support: 6 hours

EDIT -
I've only sampled half the file so the results aren't complete.

Hope this helps.

Body:
I am very new to Python but I'm trying to learn more and my first mini project that I've given myself is to create a code that can receive the input for a given user name and then output the amount of hours they worked on a certain project. I receive a csv at the end of the week for employees in my department  and within that csv I have various projects that they are working on and the hours dedicated to that project. The catch with the csv file is there are duplicate projects for that user so when my csv outputs I need it to only show one project name and ALL the hours associated with that project. How can I get my code to read the duplicates and only count the hours from the duplicates and just use one project name?

Here is the code I've come up with so far:

import csv
with open('Report.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    firsts = []
    lasts = []
    projects = []
    hours = []
    for row in readCSV:
        first = row[0]
        last = row[1]
        project = row[2]
        hour = row[3]

        firsts.append(first)
        lasts.append(last)
        projects.append(project)
        hours.append(hour)

    First_name = input("Please enter the first name: ")
    First_1 = firsts.index(First_name)
    Last_1 = lasts[First_1]
    project_1 = projects[First_1]
    hours_1 = hours[First_1]
    print(First_1, Last_1, project_1, hours_1)

Here is a sample of the csv

First   Last    Project             Hours
David   Ayers   AD-0002  Training   24
Oriana  Morfitt AD-0002  Training   24
David   Ayers   AD-0003  Personal Time  8
David   Ayers   AD-0004  Sick Time  0
Oriana  Morfitt AD-0005  Vacation   40
Sujatha Kavuri  Beeline Blank   29
Sujatha Kavuri  Beeline Blank   16
Sujatha Kavuri  OPS-0001 General Operational Support    6
Jeff    Moore   OPS-0001 General Operational Support    5
Sri Mantri  SRV-0001 Service Requests for Base and Direct Services  4
Prasanth    Musunuru    SRV-0001 Service Requests for Base and Direct Services  11
Prasanth    Musunuru    SRV-0001 Service Requests for Base and Direct Services  10
Jeff    Moore   SRV-0006 Standards and Processes    5
Jeff    Moore   SRV-0006 Standards and Processes    3
Jeff    Moore   SRV-2503 Internet Access Infrastructure Maintenance & Support   12.5
Jeff    Moore   SRV-2503 Internet Access Infrastructure Maintenance & Support   7
Jeff    Moore   0024495915 Work Instructions (infrastructure) - time tracking   1
Sri Mantri  0026184229 Margin Controlling Java Rewrite  4
Sujatha Kavuri  0029157489 SCRM Life Cycle Extension    3
Jeff    Moore   0031369443 Shopcall Attachment Changes  1
Jeff    Moore   0031500942 MP Strategy 2015 - Spot PO via EDI (time tracking only) - 0031500942 1

Body:
I bet there's a better way of doing it with pandas, but this will work too:

import csv

# I've used full name to avoid duplicate first names in report
full_name = input('Enter your full name: ')

with open('Report.csv') as csvfile:
    hour_summation = {}
    read_csv = csv.reader(csvfile, delimiter=',')
    for row in read_csv:
        if ' '.join((row[0], row[1])) == full_name.strip():
            hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(row[3])

print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
    print(k + ': ' + str(v) + ' hours')

results for Sujatha Kavuri

Enter your full name: Sujatha Kavuri

  This is Sujatha Kavuri full hours report:

  Beeline Blank: 45 hours

  OPS-0001 General Operational Support: 6 hours

EDIT -
I've only sampled half the file so the results aren't complete.

Hope this helps.


问:
How to merge two the same objects in Ruby
I have two objects that look like this:

```<code>obj1 = { hostname: "test",
         cpu: 20,
         disk_space: nil,
         ram: nil,
         check_time: "2017-12-05 01:28" }

obj2 = { hostname: "test",
         cpu: nil,
         disk_space: 3000,
         ram: nil,
         check_time: "2017-12-05 01:28"}
</code>```

I want to overwrite disk_space: nil with disk_space: 3000 from obj2. I want to basicaly overwrite nils.

```<code>new_obj = { hostname: "test",
            cpu: 20,
            disk_space: 3000,
            ram: nil,
            check_time: "2017-12-05 01:28" }
</code>```

How can I achieve this in Ruby?

答:
With merge?

```<code>obj1.merge(obj2) { |key, oldval, newval| oldval.nil? ? newval : oldval }
=> {:hostname=>"test", :cpu=>20, :disk_space=>3000, :ram=>nil, :check_time=>"2017-12-05 01:28"}
</code>```

In short:

```<code>obj1.merge(obj2) { |_, v, w| v.nil? ? w : v }
</code>```

Body:
I have two objects that look like this:

obj1 = { hostname: "test",
         cpu: 20,
         disk_space: nil,
         ram: nil,
         check_time: "2017-12-05 01:28" }

obj2 = { hostname: "test",
         cpu: nil,
         disk_space: 3000,
         ram: nil,
         check_time: "2017-12-05 01:28"}

I want to overwrite disk_space: nil with disk_space: 3000 from obj2. I want to basicaly overwrite nils.

new_obj = { hostname: "test",
            cpu: 20,
            disk_space: 3000,
            ram: nil,
            check_time: "2017-12-05 01:28" }

How can I achieve this in Ruby?

Body:
With merge?

obj1.merge(obj2) { |key, oldval, newval| oldval.nil? ? newval : oldval }
=> {:hostname=>"test", :cpu=>20, :disk_space=>3000, :ram=>nil, :check_time=>"2017-12-05 01:28"}

In short:

obj1.merge(obj2) { |_, v, w| v.nil? ? w : v }


问:
How to add a 'submitHandler' function when using jQuery Unobtrusive Validation?
I'm validating a form using the new unobtrusive validation features in ASP.NET MVC 3.

So there is no code that I have written to setup jQuery validate to start validating my form.  Its all done by loading the jQuery.validate.unobtrusive.js library.

Unfortunately I need to whack in a 'are you sure?' message box when the form is valid but before submitting.  With jQuery validate you would add the option handleSubmit when initialising like so:

```<code>$("#my_form").validate({
  rules: {
    field1: "required",
    field1: {email: true },
    field2: "required"
  },
  submitHandler: function(form) {
     if(confirm('Are you sure?')) {
       form.submit();
     }
  }
});
</code>```

But you don't need to initialise when using the unobtrusive library.

Any ideas where/how I can add a submit handler in that case?

Thx

答:
The unobtrusive library will attach the validator on all forms, so you have to replace the submitHandler this way:</p>

```<code>$("form").data("validator").settings.submitHandler = function (form) { alert('submit'); form.submit(); };
</code>```

Body:
I'm validating a form using the new unobtrusive validation features in ASP.NET MVC 3.

So there is no code that I have written to setup jQuery validate to start validating my form.  Its all done by loading the jQuery.validate.unobtrusive.js library.

Unfortunately I need to whack in a 'are you sure?' message box when the form is valid but before submitting.  With jQuery validate you would add the option handleSubmit when initialising like so:

$("#my_form").validate({
  rules: {
    field1: "required",
    field1: {email: true },
    field2: "required"
  },
  submitHandler: function(form) {
     if(confirm('Are you sure?')) {
       form.submit();
     }
  }
});

But you don't need to initialise when using the unobtrusive library.

Any ideas where/how I can add a submit handler in that case?

Thx

Body:
The unobtrusive library will attach the validator on all forms, so you have to replace the submitHandler this way:

$("form").data("validator").settings.submitHandler = function (form) { alert('submit'); form.submit(); };


问:
Un-nesting lists within a tibble list column
I have a tibble with a list column where each element contains a list of length 2.  I have tried to use unlist(), unnest() and flatten() and various other combinations but no luck getting my desired outcome.

A minimal working example is below:

```<code>df <- tibble(x = c('A', 'B'),
         preds = list(list(Phi = data.frame(time = 1:2, estimate = c('y1', 'y2')),
                           p = data.frame(time = 1:2, estimate = c('y3', 'y4'))),
                      list(Phi = data.frame(time = 1:2, estimate = c('y5', 'y6')),
                           p = data.frame(time = 1:2, estimate = c('y7', 'y8')))))
</code>```

with an expected outcome:

```<code>output <- tibble(x = rep(c('A', 'B'), each = 4),
             grp = c(rep(c('Phi', 'p'), each = 2 ), rep(c('Phi', 'p'), each = 2 )),
             time = rep(1:2, 4),
             estimate = c('y1', 'y2', 'y3', 'y4', 'y5', 'y6', 'y7', 'y8'))
</code>```

The following code gets me part way and I could easily include the other columns, but its not correct.

```<code>df$preds %>% flatten_df()
</code>```

After a day of googling I'm still stuck.  Please point me in some direction.......many thanks!!!

答:
Building on akrun's already good answer, I offer the following.

```<code>library(tidyr)
library(dplyr)

df %>%
  mutate(
    preds = lapply(
      preds, lapply, mutate, estimate = as.character(estimate)
    ) %>%
    lapply(bind_rows, .id = "grp")
  ) %>%
  unnest

# # A tibble: 8 x 4
#       x   grp  time estimate
#   <chr> <chr> <int>    <chr>
# 1     A   Phi     1       y1
# 2     A   Phi     2       y2
# 3     A     p     1       y3
# 4     A     p     2       y4
# 5     B   Phi     1       y5
# 6     B   Phi     2       y6
# 7     B     p     1       y7
# 8     B     p     2       y8
</code>```

N.B. The only improvement is the conversion of estimate from factor to character. Otherwise, and if this could be addressed in the source data, the map solution by akrun is more concise and easier to reason about.

Body:
I have a tibble with a list column where each element contains a list of length 2.  I have tried to use unlist(), unnest() and flatten() and various other combinations but no luck getting my desired outcome.

A minimal working example is below:

df <- tibble(x = c('A', 'B'),
         preds = list(list(Phi = data.frame(time = 1:2, estimate = c('y1', 'y2')),
                           p = data.frame(time = 1:2, estimate = c('y3', 'y4'))),
                      list(Phi = data.frame(time = 1:2, estimate = c('y5', 'y6')),
                           p = data.frame(time = 1:2, estimate = c('y7', 'y8')))))

with an expected outcome:

output <- tibble(x = rep(c('A', 'B'), each = 4),
             grp = c(rep(c('Phi', 'p'), each = 2 ), rep(c('Phi', 'p'), each = 2 )),
             time = rep(1:2, 4),
             estimate = c('y1', 'y2', 'y3', 'y4', 'y5', 'y6', 'y7', 'y8'))

The following code gets me part way and I could easily include the other columns, but its not correct.

df$preds %>% flatten_df()

After a day of googling I'm still stuck.  Please point me in some direction.......many thanks!!!

Body:
Building on akrun's already good answer, I offer the following.

library(tidyr)
library(dplyr)

df %>%
  mutate(
    preds = lapply(
      preds, lapply, mutate, estimate = as.character(estimate)
    ) %>%
    lapply(bind_rows, .id = "grp")
  ) %>%
  unnest

# # A tibble: 8 x 4
#       x   grp  time estimate
#   <chr> <chr> <int>    <chr>
# 1     A   Phi     1       y1
# 2     A   Phi     2       y2
# 3     A     p     1       y3
# 4     A     p     2       y4
# 5     B   Phi     1       y5
# 6     B   Phi     2       y6
# 7     B     p     1       y7
# 8     B     p     2       y8

N.B. The only improvement is the conversion of estimate from factor to character. Otherwise, and if this could be addressed in the source data, the map solution by akrun is more concise and easier to reason about.


问:
Application Insights trace log to OMS Log Analytics
We have Application Insights connector configured with OMS Log Analytics. We are seeing only CustomEvents & Exceptions Telemetry Type in OMS Log Analytics and I dont see Trace Telemetry type in OMS Log Analytics. Whether Trace is CustomEvent in OMS Log Analytics or Traces are not available in OMS Log Analytics?</p>

答:
Seems like OMS's AI connector can only see,  Custom Events, Requests, PageViews, Availability and Exceptions..

https://learn.microsoft.com/en-us/azure/log-analytics/log-analytics-app-insights-connector#input-data

I'm having same issue,  want to be able to se ALL the AI data in OMS..  Would loved to be proved wrong here..


问:
Handling memory and processor limitations of nodes in Blockchain
In Hyperledger Fabric Network(or someother Blockchain platforms), it is using a distributed ledger to store blocks of transactions. So all the participant nodes will have to maintain a ledger to keep the same copy of the chain of blocks.

Here as time passes there will be more and more transactions, then
*how it is managing the data load on each node?*

Some of the participant nodes might have limitations in memory and all, so
how it is managing properly for its smooth working?

Also some of the participants like Mobile devices may not have much processing power compared to other systems.

How does Blockchain manage these situations effectively?

答:
Yes, that's a valid concern. The Bitcoin blockchain is many gigabytes large. Thus, if you want to do a payment on a mobile device, for example, your mobile device will need some other way to verify the number of coins in your account and others' accounts because it can't download the entire Bitcoin blockchain.

To my understanding, there are nodes that do store the entire blockchain and you can simply ask those nodes that you trust for the current number of coins in certain accounts. There is an element of trust here, but if you don't trust anyone, then you need to download the entire blockchain yourself.


问:
Edit JavaScript blocks of web page... live
I know you can use Firebug in the DOM view to edit JavaScript variables BUT... is there a way I can use (anything else) to edit live JavaScript that is embedded in a HTML page?

Like this kind that is in a .html page:

```<code><script type="text/javascript>
// code here
</script>
</code>```

Thanks.

答:
Well, you won't be able to edit JavaScript code that has been loaded into your browser, except with the help of that same browser. That basically means through a plug-in and I'm not aware of any plug-ins other than FireBug that will let you do that.

Is there a specific reason you can't/won't use FireBug?

Body:
I know you can use Firebug in the DOM view to edit JavaScript variables BUT... is there a way I can use (anything else) to edit live JavaScript that is embedded in a HTML page?

Like this kind that is in a .html page:

Thanks.


问:
Invoke event listener only on inner element (Javascript)
I've got a div inside another div. Both have event listeners attached to run a function on mousedown - call them outerDivFunction and innerDivFunction. When I click the inner div, both functions are invoked; I'd like it to only invoke  innerDivFunction.

How to do this? (Vanilla solutions are preferred to jQuery.)

答:
Use event's stopPropagation() in innerDivFunction. This prevents further propagation of the current event in the capturing and bubbling phases.

For more details: Event Propagation

function outerDivFunction(){
  alert('Outer Div');
}

function innerDivFunction(e){
  e.stopPropagation();
  alert('Inner Div');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.outer{
  border: 1px solid blue;
}
.inner{
  border: 1px solid red;
  margin: 10px;
}</code>```

Outer Div

Inner Div

```

Body:
Use event's stopPropagation() in innerDivFunction. This prevents further propagation of the current event in the capturing and bubbling phases.

For more details: Event Propagation

function outerDivFunction(){
  alert('Outer Div');
}

function innerDivFunction(e){
  e.stopPropagation();
  alert('Inner Div');
}

.outer{
  border: 1px solid blue;
}
.inner{
  border: 1px solid red;
  margin: 10px;
}

<div class="outer" onclick="outerDivFunction()">Outer Div
  <div class="inner" onclick="innerDivFunction(event)">Inner Div</div>
</div>


问:
How to set autolayout so image takes up full screen?
I have the image to cover the page but when you rotate the phone the image does not cover the full screen in landscape. What am I missing?</p>

```<code>func setBackgroundImage() {
    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "newbackground")
    backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
    self.view.insertSubview(backgroundImage, at: 0)
    backgroundImage.translatesAutoresizingMaskIntoConstraints = false
}
</code>```

答:
one more step after translatesAutoresizingMaskIntoConstraints, set up and activate the autolayout constraints.

```<code>func setBackgroundImage() {
    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "newbackground")
    backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
    self.view.insertSubview(backgroundImage, at: 0)

    backgroundImage.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        backgroundImage.leftAnchor.constraint(equalTo: view.leftAnchor),
        backgroundImage.rightAnchor.constraint(equalTo: view.rightAnchor),
        backgroundImage.topAnchor.constraint(equalTo: view.topAnchor),
        backgroundImage.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])

}
</code>```

Body:
I have the image to cover the page but when you rotate the phone the image does not cover the full screen in landscape. What am I missing?

func setBackgroundImage() {
    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "newbackground")
    backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
    self.view.insertSubview(backgroundImage, at: 0)
    backgroundImage.translatesAutoresizingMaskIntoConstraints = false
}

Body:
one more step after translatesAutoresizingMaskIntoConstraints, set up and activate the autolayout constraints.

func setBackgroundImage() {
    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "newbackground")
    backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
    self.view.insertSubview(backgroundImage, at: 0)

    backgroundImage.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        backgroundImage.leftAnchor.constraint(equalTo: view.leftAnchor),
        backgroundImage.rightAnchor.constraint(equalTo: view.rightAnchor),
        backgroundImage.topAnchor.constraint(equalTo: view.topAnchor),
        backgroundImage.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])

}


问:
How to insert into database date and time?
I'm making a website and when the user click on button I want it to send at what time and day the user clicked on my button, here is my code:

Button:

```<code><form method="POST">
    <button name="btn">Click Here</button>
</form>
</code>```

答:
If you are using mysql and have a database for date types setup you can do this:</p>

```<code>if(isset($_POST['btn'])){
$query = "INSERT INTO `time` VALUES ('".date('Y-m-d H:i:s')."')";
//check upload

if(mysql_query($query)){
    echo "Date and Time are added";
}
}
<form method="POST">
<button name="btn">Click Here</button>
</form>
</code>```

Body:
I'm making a website and when the user click on button I want it to send at what time and day the user clicked on my button, here is my code:

Button:

<form method="POST">
    <button name="btn">Click Here</button>
</form>

Body:
If you are using mysql and have a database for date types setup you can do this:

if(isset($_POST['btn'])){
$query = "INSERT INTO `time` VALUES ('".date('Y-m-d H:i:s')."')";
//check upload

if(mysql_query($query)){
    echo "Date and Time are added";
}
}
<form method="POST">
<button name="btn">Click Here</button>
</form>


问:
IBOutlet is nil, but it is connected in storyboard, Swift
Using Swift 1.1 and Xcode 6.2.

I have a UIStoryboard containing a singular, custom UIViewController subclass. On it, I have an @IBOutlet connection of type UIView from that controller to a UIView subclass on the storyboard. I also have similar outlets for subviews of that view. See figure A.

But at run time, these properties are nil (Figure B). Even though I have assured I've connected the outlets in Interface Builder.

Thoughts:

Is it possible that because I am using a subclass of a subclass something messes up with the initialization? I am not overriding any initializers

awakeFromNib: is not getting called for some reason

Maybe it doesn't connecting to subviews on subviews

Things I have tried:

Matching @IBOutlet and storyboard item types exactly (instead of UIView)

Deleting property and outlet and re-added them

Figure A*

Figure B

*The obscured code in Figure A is:

```<code>@IBOutlet private var annotationOptionsView: UIView!
@IBOutlet private var arrivingLeavingSwitch: UISegmentedControl!
</code>```

Thank you.

答:
Yet another case I just ran into. I changed the name of my class for the UIViewController, but I forgot to change the name of the .xib file where the interface was built.

Once I caught this and made the file names reflect the class name, it was all good!

I hope that helps someone.

Body:
Using Swift 1.1 and Xcode 6.2.

I have a UIStoryboard containing a singular, custom UIViewController subclass. On it, I have an @IBOutlet connection of type UIView from that controller to a UIView subclass on the storyboard. I also have similar outlets for subviews of that view. See figure A.

But at run time, these properties are nil (Figure B). Even though I have assured I've connected the outlets in Interface Builder.

Thoughts:

Is it possible that because I am using a subclass of a subclass something messes up with the initialization? I am not overriding any initializers

awakeFromNib: is not getting called for some reason

Maybe it doesn't connecting to subviews on subviews

Things I have tried:

Matching @IBOutlet and storyboard item types exactly (instead of UIView)

Deleting property and outlet and re-added them

Figure A*

Figure B

*The obscured code in Figure A is:

@IBOutlet private var annotationOptionsView: UIView!
@IBOutlet private var arrivingLeavingSwitch: UISegmentedControl!

Thank you.


问:
batch script: including filehandle %%i in DO (subfunction
I'm a bit stuck and need some advice.

I start by doing a FOR loop with %%i as the file variable.

```<code>for %%i in ("C:\*.*") do (
call :function1 "%%i"
goto function2
goto :eof
)
</code>```

the problem is that the file-parameter isn't given to function one..

I have tested with putting an 'echo my echo is %%' in function1 and i get:

```<code>my echo is %i
</code>```

And exacltle the same for the use of %%i in function2

Does anyone has advice for me?  How do i get the file handle to be taken to function in the DO form? By the way, this is windows batch.

答:
```<code>@echo off
for %%i in ("C:\*.*") do (
  call :f "%%i"
)
pause
exit

:f
echo %1
</code>```

Body:
I'm a bit stuck and need some advice.

I start by doing a FOR loop with %%i as the file variable.

for %%i in ("C:\*.*") do (
call :function1 "%%i"
goto function2
goto :eof
)

the problem is that the file-parameter isn't given to function one..

I have tested with putting an 'echo my echo is %%' in function1 and i get:

my echo is %i

And exacltle the same for the use of %%i in function2

Does anyone has advice for me?  How do i get the file handle to be taken to function in the DO form? By the way, this is windows batch.


问:
dplyr filter "cell content" "cell value" is
This is a basic question but I spent 2 hours seaching for the answer and I didnt find how to solve that. I have a Likert scale (0,5,10), but, unfortunately, my dataset has some different values from that (e.g., 800). I wrote a reproductible code.

I want to use dplyr to keep only the rows where I have only 0,5,10 (or to drop the entire row where I have a weird results)

Example
Code:

```<code>dat <- data.frame(v1=c(10,5,0,10),
                  v2=c(10,0,0,800),
                  v3=c(10,0,0,5),
                  v4=c(800,10,5,10),
                  v5=c(0,800,5,10))
</code>```

I know I can use something like that:

```<code>dat2 <- dat %>% filter(rowSums(.) < 50)
</code>```

But I want to "loop" all dataset to drop the rows where I have different numbers from what I´m expecting.

Thanks

Body:
This is a basic question but I spent 2 hours seaching for the answer and I didnt find how to solve that. I have a Likert scale (0,5,10), but, unfortunately, my dataset has some different values from that (e.g., 800). I wrote a reproductible code.

I want to use dplyr to keep only the rows where I have only 0,5,10 (or to drop the entire row where I have a weird results)

Example
Code:

dat <- data.frame(v1=c(10,5,0,10),
                  v2=c(10,0,0,800),
                  v3=c(10,0,0,5),
                  v4=c(800,10,5,10),
                  v5=c(0,800,5,10))

I know I can use something like that:

dat2 <- dat %>% filter(rowSums(.) < 50)

But I want to "loop" all dataset to drop the rows where I have different numbers from what I´m expecting.

Thanks

Body:
Use filter_all with all_vars:

dat
#  v1  v2 v3  v4  v5
#1 10  10 10 800   0
#2  5   0  0  10 800
#3  0   0  0   5   5
#4 10 800  5  10  10

filter_all(dat, all_vars(. %in% c(0,5,10)))
#  v1 v2 v3 v4 v5
#1  0  0  0  5  5


问:
SSIS check if *.csv files exist in a folder
I'm new to SSIS and am learning by the power of Google. I have a package but before it runs, I need to check if any csv exist in a folder.  If they do, then continue, otherwise stop.

I've been watching you tube videos like the below:
https://www.youtube.com/watch?v=qgqyQm6EymU

but this only chekcs for a specific file - I need to check if any csv's exist in a folder regardless of there name - how do I do this?

Thanks.

答:
If you don't want to mess with the SSIS script component, you can use the<br>
File Properties Task on Codeplex. </p>

Body:
If you don't want to mess with the SSIS script component, you can use the

File Properties Task on Codeplex.


答:
Try this, without any guaranties. Regarding your example, expect you want remove last three digits AND dot, unlike your describe to remove three digits AFTER dot. </p>

```<code>@echo off & setlocal ENABLEDELAYEDEXPANSION > out.txt
for /f "tokens=1-15 delims=," %%a in (data.txt) do (
            set "string="
            call :process "%%a" "%%b" "%%c" "%%d" "%%e" "%%f" "%%g" "%%h" "%%i" "%%j" "%%k" "%%l" "%%m" "%%n" "%%o"
            )
exit /B

:process
echo %~1| findstr /R /C:"[0-9]*-[0-9]*-[0-9]* [0-9]*:[0-9]*:[0-9]*\.[0-9][0-9][0-9]" >NUL
if not errorlevel 1 (
            set "str=%~1"
            set "str=!str:~0,-5!"
            if defined string (set "string=!string!,!str!'") else (set "string='!str!'")
            ) else (
            set "str=%~1"
            if defined string (set "string=!string!,!str!") else (set "string='!str!'")
            )
shift
if not "%~1"=="" (goto :process) else (echo !string!>>out.txt)
GOTO:EOF
</code>```

Title: Edit text after dot with batch script

Body:
I want to remove three digits after dot in last 3 columns with batch file (windows). Note that dots can be present in other columns.

This is a sample of my data:

4216118,'0806010709','ljubičasti ','Hita kirška ambnta',1,'Eriiti (vk, kk)','X','Uđaj za heološke prege','Celyn1800 ','Hni Sak','Hemlogja','2016-06-08 11:42:05.040','2016-06-08 11:41:42.122','2016-06-08 11:49:49.370'
4216081,'0806010387','ljubičasti ','Oća doven.amb. - VANJA',1,'Erii (vk, kk)',,'Urj za heoške prage','Adia 120 R','Reni','Hlogija','2016-06-08 08:52:13.962','2016-06-08 08:51:57.067','2016-06-08 11:08:26.504'
4216667,'1506010909','ljčasti ','tna ambuta kke za invne bolesti',1,'Erciti (vk, kk)',,'Uj za hemloške prge','Cell-Dyn 1800 R','Hi','Hemagija','2016-06-15 21:24:14.646','2016-06-15 21:24:03.523','2016-06-15 21:26:58.871'
4213710,'0905010991','ljubičasti ','Hna kira amnta',1,'Eociti (vk, kk)','X','Uđaj za hemloške prage','Cel1800 ','Hi Sak','Hemlogja','2016-05-09 17:52:32.231','2016-05-09 17:52:26.319','2016-05-09 18:31:33.643'

Example:
Before:

'2016-06-08 11:49:49.370'

After:

'2016-06-08 11:49:49'

Body:
Try this, without any guaranties. Regarding your example, expect you want remove last three digits AND dot, unlike your describe to remove three digits AFTER dot.

@echo off & setlocal ENABLEDELAYEDEXPANSION > out.txt
for /f "tokens=1-15 delims=," %%a in (data.txt) do (
            set "string="
            call :process "%%a" "%%b" "%%c" "%%d" "%%e" "%%f" "%%g" "%%h" "%%i" "%%j" "%%k" "%%l" "%%m" "%%n" "%%o"
            )
exit /B

:process
echo %~1| findstr /R /C:"[0-9]*-[0-9]*-[0-9]* [0-9]*:[0-9]*:[0-9]*\.[0-9][0-9][0-9]" >NUL
if not errorlevel 1 (
            set "str=%~1"
            set "str=!str:~0,-5!"
            if defined string (set "string=!string!,!str!'") else (set "string='!str!'")
            ) else (
            set "str=%~1"
            if defined string (set "string=!string!,!str!") else (set "string='!str!'")
            )
shift
if not "%~1"=="" (goto :process) else (echo !string!>>out.txt)
GOTO:EOF


问:
psql: could not connect to server: No such file or directory (Mac OS X)

Upon restarting my Mac I got the dreaded Postgres error:

```<code>psql: could not connect to server: No such file or directory
 Is the server running locally and accepting
 connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
</code>```

The reason this happened is because my macbook froze completely due to an unrelated issue and I had to do a hard reboot using the power button. After rebooting I couldn't start Postgres because of this error.

答:
if your postmaster.pid is gone and you can't restart or anything, do this:

pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

as explained here initially

Body:
Upon restarting my Mac I got the dreaded Postgres error:

psql: could not connect to server: No such file or directory
 Is the server running locally and accepting
 connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

The reason this happened is because my macbook froze completely due to an unrelated issue and I had to do a hard reboot using the power button. After rebooting I couldn't start Postgres because of this error.


问:
How to position components in a JFrame?
```<code>        jframe = new JFrame("Admin");
        jpanel = new JPanel();

        jpanel.setLayout(new FlowLayout());
        jframe.add(jpanel);

        userLabel = new JLabel("Username:");
        jpanel.add(userLabel);
        userLabel.setBounds(100, 100, 30, 30);

        userTxtfield = new JTextField(15);
        jpanel.add(userTxtfield);

        passwordTxtfield = new JTextField(15);
        jpanel.add(userTxtfield);
        jpanel.add(passwordTxtfield);

        passwordLabel = new JLabel("Password:");
        jpanel.add(passwordLabel);
        userLabel.setBounds(100, 100, 30, 30);

        loginButton= new JButton("Login");
        jpanel.add(loginButton);

        jframe.pack();
        jframe.setLocationRelativeTo(null);
        jframe.setSize(350,350);
        jframe.setVisible(true);
</code>```

I am trying to make a neat login area for my program but I can't seem to get the two labels and text fields to line up with the button underneath. Is there a better way of doing this positioning of the components within this JFrame?

答:
Use a JOptionPane to display a log-in dialog. One way to layout the components is to use a GridBagLayout.

The code that produces that is:

```<code>public void login() {
    JPanel loginPanel = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints(
            0, 0, 1, 1, 0, 0,
            GridBagConstraints.BASELINE_TRAILING,
            GridBagConstraints.NONE,
            new Insets(5, 5, 5, 5), 4, 6);
    loginPanel.add(new JLabel("ID"), gbc);
    gbc.gridy = 1;
    loginPanel.add(new JLabel("Password"), gbc);
    gbc.anchor = GridBagConstraints.BASELINE_LEADING;
    gbc.gridx = 1;
    gbc.gridy = 0;
    loginPanel.add(new JTextField("enter ID", 10), gbc);
    gbc.gridy = 1;
    loginPanel.add(new JPasswordField(6), gbc);

    int result = JOptionPane.showConfirmDialog(
            ui, loginPanel, "LogIn", JOptionPane.OK_CANCEL_OPTION);
    if (result == JOptionPane.OK_OPTION) {
        // here a real app would check the results of the ID/password
        cardLayout.show(ui, "loggedin");
    }
}
</code>```

Here is the complete example (an MCVE, as mentioned above).

```<code>import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class BlockTheFrame {

    private JComponent ui = null;
    private CardLayout cardLayout;

    BlockTheFrame() {
        initUI();
    }

    public final void initUI() {
        if (ui != null) {
            return;
        }

        cardLayout = new CardLayout();
        ui = new JPanel(cardLayout);
        ui.setBorder(new EmptyBorder(4, 4, 4, 4));

        JLabel login = new JLabel("Log in");
        login.setFont(login.getFont().deriveFont(200f));
        ui.add(login, "login");

        ui.add(new JLabel("logged in"), "loggedin");
    }

    public void login() {
        JPanel loginPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints(
                0, 0, 1, 1, 0, 0,
                GridBagConstraints.BASELINE_TRAILING,
                GridBagConstraints.NONE,
                new Insets(5, 5, 5, 5), 4, 6);
        loginPanel.add(new JLabel("ID"), gbc);
        gbc.gridy = 1;
        loginPanel.add(new JLabel("Password"), gbc);
        gbc.anchor = GridBagConstraints.BASELINE_LEADING;
        gbc.gridx = 1;
        gbc.gridy = 0;
        loginPanel.add(new JTextField("enter ID", 10), gbc);
        gbc.gridy = 1;
        loginPanel.add(new JPasswordField(6), gbc);

        int result = JOptionPane.showConfirmDialog(
                ui, loginPanel, "LogIn", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            // here a real app would check the results of the ID/password
            cardLayout.show(ui, "loggedin");
        }
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {
                }
                BlockTheFrame o = new BlockTheFrame();

                JFrame f = new JFrame(o.getClass().getSimpleName());
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.setContentPane(o.getUI());
                f.pack();
                f.setMinimumSize(f.getSize());

                f.setVisible(true);
                o.login();
            }
        };
        SwingUtilities.invokeLater(r);
    }
}
</code>```

Title: How to position components in a JFrame?

Body:
        jframe = new JFrame("Admin");
        jpanel = new JPanel();

        jpanel.setLayout(new FlowLayout());
        jframe.add(jpanel);

        userLabel = new JLabel("Username:");
        jpanel.add(userLabel);
        userLabel.setBounds(100, 100, 30, 30);

        userTxtfield = new JTextField(15);
        jpanel.add(userTxtfield);

        passwordTxtfield = new JTextField(15);
        jpanel.add(userTxtfield);
        jpanel.add(passwordTxtfield);

        passwordLabel = new JLabel("Password:");
        jpanel.add(passwordLabel);
        userLabel.setBounds(100, 100, 30, 30);

        loginButton= new JButton("Login");
        jpanel.add(loginButton);

        jframe.pack();
        jframe.setLocationRelativeTo(null);
        jframe.setSize(350,350);
        jframe.setVisible(true);

I am trying to make a neat login area for my program but I can't seem to get the two labels and text fields to line up with the button underneath. Is there a better way of doing this positioning of the components within this JFrame?

Body:
Use a JOptionPane to display a log-in dialog. One way to layout the components is to use a GridBagLayout.

The code that produces that is:

public void login() {
    JPanel loginPanel = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints(
            0, 0, 1, 1, 0, 0,
            GridBagConstraints.BASELINE_TRAILING,
            GridBagConstraints.NONE,
            new Insets(5, 5, 5, 5), 4, 6);
    loginPanel.add(new JLabel("ID"), gbc);
    gbc.gridy = 1;
    loginPanel.add(new JLabel("Password"), gbc);
    gbc.anchor = GridBagConstraints.BASELINE_LEADING;
    gbc.gridx = 1;
    gbc.gridy = 0;
    loginPanel.add(new JTextField("enter ID", 10), gbc);
    gbc.gridy = 1;
    loginPanel.add(new JPasswordField(6), gbc);

    int result = JOptionPane.showConfirmDialog(
            ui, loginPanel, "LogIn", JOptionPane.OK_CANCEL_OPTION);
    if (result == JOptionPane.OK_OPTION) {
        // here a real app would check the results of the ID/password
        cardLayout.show(ui, "loggedin");
    }
}

Here is the complete example (an MCVE, as mentioned above).

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class BlockTheFrame {

    private JComponent ui = null;
    private CardLayout cardLayout;

    BlockTheFrame() {
        initUI();
    }

    public final void initUI() {
        if (ui != null) {
            return;
        }

        cardLayout = new CardLayout();
        ui = new JPanel(cardLayout);
        ui.setBorder(new EmptyBorder(4, 4, 4, 4));

        JLabel login = new JLabel("Log in");
        login.setFont(login.getFont().deriveFont(200f));
        ui.add(login, "login");

        ui.add(new JLabel("logged in"), "loggedin");
    }

    public void login() {
        JPanel loginPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints(
                0, 0, 1, 1, 0, 0,
                GridBagConstraints.BASELINE_TRAILING,
                GridBagConstraints.NONE,
                new Insets(5, 5, 5, 5), 4, 6);
        loginPanel.add(new JLabel("ID"), gbc);
        gbc.gridy = 1;
        loginPanel.add(new JLabel("Password"), gbc);
        gbc.anchor = GridBagConstraints.BASELINE_LEADING;
        gbc.gridx = 1;
        gbc.gridy = 0;
        loginPanel.add(new JTextField("enter ID", 10), gbc);
        gbc.gridy = 1;
        loginPanel.add(new JPasswordField(6), gbc);

        int result = JOptionPane.showConfirmDialog(
                ui, loginPanel, "LogIn", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            // here a real app would check the results of the ID/password
            cardLayout.show(ui, "loggedin");
        }
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {
                }
                BlockTheFrame o = new BlockTheFrame();

                JFrame f = new JFrame(o.getClass().getSimpleName());
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.setContentPane(o.getUI());
                f.pack();
                f.setMinimumSize(f.getSize());

                f.setVisible(true);
                o.login();
            }
        };
        SwingUtilities.invokeLater(r);
    }
}


问:
inline css style width not able to override computed css style's width value
I'm seeing a strange behaviour which i'm not able to figure out.

The webpage that i'm working on has a lot of css styles. So for one of my div's i'm using inline css to make the width as per my requirement (which shows up in the source code just fine). But when i'm inspecting the element in Google Chrome i see that the computed width as slightly less than my value. How do i override the computed value.

Thanks

答:
Could you please provide more sample code. This is not enough information to answer the question properly. As stated by miduga, !important should be enough to override that style.

Are you certain that this element is of the correct display type? Remember that you can't define a width for inline elements.


问:
Modelsim reset all windows
This seems a rather silly question: but I can't find (for more than an hour) now a button to "reset" all standard windows.. I accidentally closed quite a lot of them during a crash. (Especially the "command window" and the signals-in-region during simulation seem to be gone permanently).</p>

答: At the menu bar (main window), click on layout and then choose reset. Most of the windows will be reset.

Title: Modelsim reset all windows


问:
Python: open either zipped or unzipped file using "with"
I'm looking for a solution to open a file using "with". Hoever, I would like to check if the file is either gzipped or not and then either use gzip.open or just open something like:

```<code>if f.endswith(".gz"):
    with gzip.open() as f:
else:
    with open() as f:
for line in f:
</code>```

Any ideas?

答:
As an alternative to creating another context manager, you can simply choose the function within your with statement:

```<code>with (gzip.open if filename.endswith(".gz") else open)(filename) as f:
    for line in f:
        ...
</code>```

(While being aware that ending with .gz does not necessarily make a file a gzip file).

Body:
I'm looking for a solution to open a file using "with". Hoever, I would like to check if the file is either gzipped or not and then either use gzip.open or just open something like:

if f.endswith(".gz"):
    with gzip.open() as f:
else:
    with open() as f:
for line in f:

Any ideas?

Body:
As an alternative to creating another context manager, you can simply choose the function within your with statement:

with (gzip.open if filename.endswith(".gz") else open)(filename) as f:
    for line in f:
        ...

(While being aware that ending with .gz does not necessarily make a file a gzip file).


问:
How do you store "int" values in an NSMutableArray* or NSMutableDictionary*? Chronic problems with JSON data that come in as integers.
How do you store "int" values in an NSMutableArray or NSMutableDictionary?  Chronic problems with JSON data that come in as integers.

Should I try to store these integers as NSNumber objects or just as strings that contain the integer?

How dangerous is it to do a "raw" (int) conversion on the pointers if I know the values will always be Natural Numbers (numbers>=0 including zero for null.)

The integers I'm always working with are Foreign Key Id's from a database.

答: Use NSNumber objects (e.g. using [NSNumber numberWithInt:value])


问:
Routes in Codeigniter not working on different server
Let me inform you this first. This application is working pretty fine on live server currently, however we needed to move it to a different server with a different domain.

Issue is: It gives 404 error on every other page except for index. Loading through index.php works fine.

For an example:

www.test.com/main/login //This gives 404 error

www.test.com/main/index.php/login //This loads fine

Because everything is working fine currently, I made changes only in $config['base_url'] and in database config file. There have been no other changes in any of the files.

Also, this solution provided by somebody in a different questions is already tried out and this doesn't work. Solution is to create .htaccess file with below code & setting $config['index_page']='' :

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

Current server is VPS & provider is GoDaddy. New server is Shared hosting and provider is GoDaddy. I'm not getting the root cause of this happening, can somebody point out to the possible solution?

EDIT

I'm attaching a screenshot for an error, it's not typical 404 error page. In case this helps.

答:
For Godaddy, you need to alter this 2 things.

In your .htaccess file, replace

```<code>RewriteRule ^(.*)$ index.php/$1 [L]
</code>```

With the following:

```<code>RewriteRule ^(.*)$ index.php?/$1 [L]
</code>```

Then is your application/config/config.php :

```<code>$config['index_page'] = '';
</code>```

Both this changes should help you resolve your issue.

Body:
Let me inform you this first. This application is working pretty fine on live server currently, however we needed to move it to a different server with a different domain.

Issue is: It gives 404 error on every other page except for index. Loading through index.php works fine.

For an example:

www.test.com/main/login //This gives 404 error

www.test.com/main/index.php/login //This loads fine

Because everything is working fine currently, I made changes only in $config['base_url'] and in database config file. There have been no other changes in any of the files.

Also, this solution provided by somebody in a different questions is already tried out and this doesn't work. Solution is to create .htaccess file with below code & setting $config['index_page']='' :

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

Current server is VPS & provider is GoDaddy. New server is Shared hosting and provider is GoDaddy. I'm not getting the root cause of this happening, can somebody point out to the possible solution?

EDIT

I'm attaching a screenshot for an error, it's not typical 404 error page. In case this helps.

Body:
For Godaddy, you need to alter this 2 things.

In your .htaccess file, replace

RewriteRule ^(.*)$ index.php/$1 [L]

With the following:

RewriteRule ^(.*)$ index.php?/$1 [L]

Then is your application/config/config.php :

$config['index_page'] = '';

Both this changes should help you resolve your issue.


问:
EntityFrameworkCore and code first with Sqlite including multiple navigation
back in vs2015 i used an external program to create / modify my database and update it in vs with the ef designer.
It is also possible with vs2017 to use the designer with some third party tools, but i want to switch to code first. in this context i want to switch my class library to .net standard.

But i have trouble to get my databases working.
Here is an example, what i see when i open the edmx file.

The ID is not incremented, it is provided by an external service. every user of the service has an unique id and i store it there.

And now my (very simple) code first models:

```<code>    public class Users {
         public int UserID { get; set; }
         public string Name { get; set; }

         public Currency Currency { get; set; }
         public TimeWatched TimeWatched { get; set; }
    }

    public class Currency {
        public int UserID { get; set; }
        public int CurrencyValue { get; set; }

        public Users Users { get; set; }
    }

    public class TimeWatched {
        public int UserID { get; set; }
        public long Time { get; set; }

        public Users Users { get; set; }
    }
</code>```

My DbContext looks like this:

```<code>     using Microsoft.Data.Sqlite;
     using Microsoft.EntityFrameworkCore;

    public class context : DbContext {

    public DbSet<Users> Users { get; set; }
    public DbSet<Currency> Currency { get; set; }
    public DbSet<TimeWatched> TimeWatched { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
        var connectionStringBuilder = new SqliteConnectionStringBuilder { DataSource = "test.db" };
        var connectionString = connectionStringBuilder.ToString();
        var connection = new SqliteConnection(connectionString);

        optionsBuilder.UseSqlite(connection);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Users>()
            .HasKey(c => c.UserID);

        modelBuilder.Entity<Users>()
            .Property(c => c.UserID)
            .ValueGeneratedNever();

        modelBuilder.Entity<Users>()
            .HasOne(a => a.Currency)
            .WithOne(b => b.Users)
            .HasForeignKey<Currency>(b => b.UserID);

        modelBuilder.Entity<Users>()
            .HasOne(a => a.TimeWatched)
            .WithOne(b => b.Users)
            .HasForeignKey<TimeWatched>(b => b.UserID);

        modelBuilder.Entity<Currency>()
            .HasKey(k => k.UserID);

        modelBuilder.Entity<TimeWatched>()
            .HasKey(k => k.UserID);
    }
}
</code>```

It test it like this:

```<code>            using(var context = new testStandard.context()) {

            context.Database.EnsureCreated();

            var user = new Users {
                Name = "test",
                TwitchUser = 123456,
                Currency = new Currency {
                    TwitchUser = 123456,
                    CurrencyValue = 999
                },
                TimeWatched = new TimeWatched {
                    TwitchUser = 123456,
                    Time = 500
                }
            };

            context.Users.Add(user);

            context.SaveChanges();
        }

        using(var context = new context()) {
            var user = context.Users.First();
            // Currency and TimeWatched are always null
        }
</code>```

I dont know why currency and timewatched are always null.
what do i wrong?

答:
Thanks Jamie!
I found a solution:</p>

```<code>using(var context = new context()) {
var user = context.Users
            .Include(c => c.Currency)
            .Include(tw => tw.TimeWatched)
            .First();
}
</code>```

Body:
back in vs2015 i used an external program to create / modify my database and update it in vs with the ef designer.
It is also possible with vs2017 to use the designer with some third party tools, but i want to switch to code first. in this context i want to switch my class library to .net standard.

But i have trouble to get my databases working.
Here is an example, what i see when i open the edmx file.

The ID is not incremented, it is provided by an external service. every user of the service has an unique id and i store it there.

And now my (very simple) code first models:

    public class Users {
         public int UserID { get; set; }
         public string Name { get; set; }

         public Currency Currency { get; set; }
         public TimeWatched TimeWatched { get; set; }
    }

    public class Currency {
        public int UserID { get; set; }
        public int CurrencyValue { get; set; }

        public Users Users { get; set; }
    }

    public class TimeWatched {
        public int UserID { get; set; }
        public long Time { get; set; }

        public Users Users { get; set; }
    }

My DbContext looks like this:

     using Microsoft.Data.Sqlite;
     using Microsoft.EntityFrameworkCore;

    public class context : DbContext {

    public DbSet<Users> Users { get; set; }
    public DbSet<Currency> Currency { get; set; }
    public DbSet<TimeWatched> TimeWatched { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
        var connectionStringBuilder = new SqliteConnectionStringBuilder { DataSource = "test.db" };
        var connectionString = connectionStringBuilder.ToString();
        var connection = new SqliteConnection(connectionString);

        optionsBuilder.UseSqlite(connection);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Users>()
            .HasKey(c => c.UserID);

        modelBuilder.Entity<Users>()
            .Property(c => c.UserID)
            .ValueGeneratedNever();

        modelBuilder.Entity<Users>()
            .HasOne(a => a.Currency)
            .WithOne(b => b.Users)
            .HasForeignKey<Currency>(b => b.UserID);

        modelBuilder.Entity<Users>()
            .HasOne(a => a.TimeWatched)
            .WithOne(b => b.Users)
            .HasForeignKey<TimeWatched>(b => b.UserID);

        modelBuilder.Entity<Currency>()
            .HasKey(k => k.UserID);

        modelBuilder.Entity<TimeWatched>()
            .HasKey(k => k.UserID);
    }
}

It test it like this:

            using(var context = new testStandard.context()) {

            context.Database.EnsureCreated();

            var user = new Users {
                Name = "test",
                TwitchUser = 123456,
                Currency = new Currency {
                    TwitchUser = 123456,
                    CurrencyValue = 999
                },
                TimeWatched = new TimeWatched {
                    TwitchUser = 123456,
                    Time = 500
                }
            };

            context.Users.Add(user);

            context.SaveChanges();
        }

        using(var context = new context()) {
            var user = context.Users.First();
            // Currency and TimeWatched are always null
        }

I dont know why currency and timewatched are always null.
what do i wrong?

Body:
Thanks Jamie!
I found a solution:

using(var context = new context()) {
var user = context.Users
            .Include(c => c.Currency)
            .Include(tw => tw.TimeWatched)
            .First();
}


问:
Why does RecyclerView scroll to top of view when view is focused
I have RecyclerView, some kind of chat. Items are TextViews The layout is reversed. Input field below RecyclerView. When I scroll to the bottom of RecyclerView and click to the bottom item it gets focused (only when it gets focused, not every click) and RecyclerView scrolls automatically to the top of that item (when the text in item is larger than screen height).

Also when the keyboard is visible and I click to RecyclerView item - keyboard hides and recycler view scrolls to the top of that item, how to disable such behavior?

I want it to stay at the same position when it was when the keyboard was opened or where it was when I clicked on some item.

Keyboard is hiding with this method

```<code>* * * *
inputView.setOnFocusChangeListener((v, hasFocus) -> {
        if (!hasFocus){
            hideKeyboard();
        }
    });
* * * *

public void hideKeyboard() {
    InputMethodManager keyboard = (InputMethodManager)

    getSystemService(Context.INPUT_METHOD_SERVICE);
    keyboard.hideSoftInputFromWindow(inputView.getWindowToken(), 0);
}
</code>```

And RecyclerView configured in such way:

```<code>    RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.messageList);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
    linearLayoutManager.setReverseLayout(true);
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setAdapter(chatAdapter = new chatAdapter(getContext()));
</code>```

If I make a button and will call hideKeyBoard() by clicking that button - its ok, it does not scroll, but when I click on RecyclerView item - it gets focused and scroll to top of that item

答:
This answer might be your solution as well: RecyclerView scrolls to top after keyboard hides

```<code><activity
    android:windowSoftInputMode="adjustPan"
</code>```

Android Developer Site link

"adjustResize"

The activity's main window is always resized to make room for the soft
  keyboard on screen.

"adjustPan"

The activity's main window is not resized to make room for the soft
  keyboard. Rather, the contents of the window are automatically panned
  so that the current focus is never obscured by the keyboard and users
  can always see what they are typing. This is generally less desirable
  than resizing, because the user may need to close the soft keyboard to
  get at and interact with obscured parts of the window.

Body:
I have RecyclerView, some kind of chat. Items are TextViews The layout is reversed. Input field below RecyclerView. When I scroll to the bottom of RecyclerView and click to the bottom item it gets focused (only when it gets focused, not every click) and RecyclerView scrolls automatically to the top of that item (when the text in item is larger than screen height).

Also when the keyboard is visible and I click to RecyclerView item - keyboard hides and recycler view scrolls to the top of that item, how to disable such behavior?

I want it to stay at the same position when it was when the keyboard was opened or where it was when I clicked on some item.

Keyboard is hiding with this method

* * * *
inputView.setOnFocusChangeListener((v, hasFocus) -> {
        if (!hasFocus){
            hideKeyboard();
        }
    });
* * * *

public void hideKeyboard() {
    InputMethodManager keyboard = (InputMethodManager)

    getSystemService(Context.INPUT_METHOD_SERVICE);
    keyboard.hideSoftInputFromWindow(inputView.getWindowToken(), 0);
}

And RecyclerView configured in such way:

    RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.messageList);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
    linearLayoutManager.setReverseLayout(true);
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setAdapter(chatAdapter = new chatAdapter(getContext()));

If I make a button and will call hideKeyBoard() by clicking that button - its ok, it does not scroll, but when I click on RecyclerView item - it gets focused and scroll to top of that item

Body:
This answer might be your solution as well: RecyclerView scrolls to top after keyboard hides

<activity
    android:windowSoftInputMode="adjustPan"

Android Developer Site link

"adjustResize"

The activity's main window is always resized to make room for the soft
  keyboard on screen.

"adjustPan"

The activity's main window is not resized to make room for the soft
  keyboard. Rather, the contents of the window are automatically panned
  so that the current focus is never obscured by the keyboard and users
  can always see what they are typing. This is generally less desirable
  than resizing, because the user may need to close the soft keyboard to
  get at and interact with obscured parts of the window.


问:
select2 with jsonform don't work
I'm trying to render Multiple select2 with json form but I can't

```<code>$('#resource-form').jsonForm({
  schema: {
    rest: {
      type: 'object',
        properties: {
          template_id: {
            type: "array",
            items: {
              type: "string",
            }
          }
        }
      }
    }
  }
  form: [
    {
      type: "select",
      key: "rest.template_id[]"
    }
  ]
}

$("select[name='rest.template_id[]']").select2({
  data: data,
  multiple: true
})
</code>```

Select2 work very fine but if i submit form that backend get empty template_id param

```<code>{"rest"=>{"template_id"=>[]}}
</code>```

I think I created incorrect schema and form. Can you help me?

答:
Here is a hack that will work for you. This will get all of the select field and turn it to select2.

```<code>$("select").select2({
  data: data,
  multiple: true
})
</code>```

But if you want something specific, look for the Select field id that jsonform profide and pass it on as so.

```<code>$("@root_something").select2({
  data: data,
  multiple: true
})
</code>```

Title: select2 with jsonform don't work

Body:
I'm trying to render Multiple select2 with json form but I can't

$('#resource-form').jsonForm({
  schema: {
    rest: {
      type: 'object',
        properties: {
          template_id: {
            type: "array",
            items: {
              type: "string",
            }
          }
        }
      }
    }
  }
  form: [
    {
      type: "select",
      key: "rest.template_id[]"
    }
  ]
}

$("select[name='rest.template_id[]']").select2({
  data: data,
  multiple: true
})

Select2 work very fine but if i submit form that backend get empty template_id param

{"rest"=>{"template_id"=>[]}}

I think I created incorrect schema and form. Can you help me?

Body:
Here is a hack that will work for you. This will get all of the select field and turn it to select2.

$("select").select2({
  data: data,
  multiple: true
})

But if you want something specific, look for the Select field id that jsonform profide and pass it on as so.

$("@root_something").select2({
  data: data,
  multiple: true
})


答:
If you are using PHP to insert data into DB use PHP function</p>

```<code>date('Y-m-d h:i:sa')
</code>```

Title: How to insert into database date and time?

Body:
I'm making a website and when the user click on button I want it to send at what time and day the user clicked on my button, here is my code:

Button:

<form method="POST">
    <button name="btn">Click Here</button>
</form>

Body:
If you are using PHP to insert data into DB use PHP function

date('Y-m-d h:i:sa')