问:
tensorflow: Fail to find dnn implementation
I'm trying to run my code Keras CuDNNGRU on tensorflow using gpu but it always get error "Fail to find dnn implementation" even though I already installed CUDA and CuDNN.

I already reinstall both CUDA and CuDNN for several times and upgrading CuDNN version from 7.2.1 to 7.5.0 but it doesnt fix anything. I also try to run my code on Jupyter Notebook and in python compiler (on terminal) and both results are same. Here are the details of hardware and software of mine.

Tesla V100 PCIE 16GB

Ubuntu 18.04

NVIDIA-SMI 384.183

CUDA 9.0

CuDNN 7.5.0

Miniconda 3

Python 3.6

Tensorflow 1.12

Keras 2.1.6

Here is my code.

```<code>encoder_LSTM = tf.keras.layers.CuDNNGRU(hidden_unit,return_sequences=True,return_state=True)
encoder_LSTM_rev=tf.keras.layers.CuDNNGRU(hidden_unit,return_state=True,return_sequences=True,go_backwards=True)

encoder_outputs, state_h = encoder_LSTM(x)
encoder_outputsR, state_hR = encoder_LSTM_rev(x)
</code>```

And this is the error message.

```<code>2019-05-27 19:08:06.814896: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1511] Adding visible gpu devices: 0
2019-05-27 19:08:06.814956: I tensorflow/core/common_runtime/gpu/gpu_device.cc:982] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-05-27 19:08:06.814971: I tensorflow/core/common_runtime/gpu/gpu_device.cc:988]      0
2019-05-27 19:08:06.814978: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1001] 0:   N
2019-05-27 19:08:06.815279: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 14678 MB memory) -> physical GPU (device: 0, name: Tesla V100-PCIE-16GB, pci bus id: 0000:00:05.0, compute capability: 7.0)
2019-05-27 19:08:08.050226: E tensorflow/stream_executor/cuda/cuda_dnn.cc:373] Could not create cudnn handle: CUDNN_STATUS_NOT_INITIALIZED
2019-05-27 19:08:08.050350: E tensorflow/stream_executor/cuda/cuda_dnn.cc:381] Possibly insufficient driver version: 384.183.0
2019-05-27 19:08:08.050378: W tensorflow/core/framework/op_kernel.cc:1273] OP_REQUIRES failed at cudnn_rnn_ops.cc:1214 : Unknown: Fail to find the dnn implementation.
2019-05-27 19:08:08.050483: E tensorflow/stream_executor/cuda/cuda_dnn.cc:373] Could not create cudnn handle: CUDNN_STATUS_NOT_INITIALIZED
2019-05-27 19:08:08.050523: E tensorflow/stream_executor/cuda/cuda_dnn.cc:381] Possibly insufficient driver version: 384.183.0
2019-05-27 19:08:08.050541: W tensorflow/core/framework/op_kernel.cc:1273] OP_REQUIRES failed at cudnn_rnn_ops.cc:1214 : Unknown: Fail to find the dnn implementation.
Traceback (most recent call last):
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1334, in _do_call
    return fn(*args)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1319, in _run_fn
    options, feed_dict, fetch_list, target_list, run_metadata)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1407, in _call_tf_sessionrun
    run_metadata)
tensorflow.python.framework.errors_impl.UnknownError: Fail to find the dnn implementation.
     [[{{node cu_dnngru/CudnnRNN}} = CudnnRNN[T=DT_FLOAT, direction="unidirectional", dropout=0, input_mode="linear_input", is_training=true, rnn_mode="gru", seed=0, seed2=0, _device="/job:localhost/replica:0/task:0/device:GPU:0"](cu_dnngru/transpose, cu_dnngru/ExpandDims, gradients/while/Shape/Enter_grad/zeros/Const, cu_dnngru/concat)]]
     [[{{node mean_squared_error/value/_37}} = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_1756_mean_squared_error/value", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "ta_skenario1.py", line 271, in <module>
    losss, op = sess.run([loss, optimizer], feed_dict={x:data,y_label:label,initial_input:begin_sentence})
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 929, in run
    run_metadata_ptr)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1152, in _run
    feed_dict_tensor, options, run_metadata)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1328, in _do_run
    run_metadata)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1348, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.UnknownError: Fail to find the dnn implementation.
     [[node cu_dnngru/CudnnRNN (defined at ta_skenario1.py:205)  = CudnnRNN[T=DT_FLOAT, direction="unidirectional", dropout=0, input_mode="linear_input", is_training=true, rnn_mode="gru", seed=0, seed2=0, _device="/job:localhost/replica:0/task:0/device:GPU:0"](cu_dnngru/transpose, cu_dnngru/ExpandDims, gradients/while/Shape/Enter_grad/zeros/Const, cu_dnngru/concat)]]
     [[{{node mean_squared_error/value/_37}} = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_1756_mean_squared_error/value", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

Caused by op 'cu_dnngru/CudnnRNN', defined at:
  File "ta_skenario1.py", line 205, in <module>
    encoder_outputs, state_h = encoder_LSTM(x)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/keras/layers/recurrent.py", line 619, in __call__
    return super(RNN, self).__call__(inputs, **kwargs)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py", line 757, in __call__
    outputs = self.call(inputs, *args, **kwargs)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/keras/layers/cudnn_recurrent.py", line 109, in call
    output, states = self._process_batch(inputs, initial_state)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/keras/layers/cudnn_recurrent.py", line 299, in _process_batch
    rnn_mode='gru')
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/ops/gen_cudnn_rnn_ops.py", line 116, in cudnn_rnn
    is_training=is_training, name=name)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py", line 488, in new_func
    return func(*args, **kwargs)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 3274, in create_op
    op_def=op_def)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1770, in __init__
    self._traceback = tf_stack.extract_stack()

UnknownError (see above for traceback): Fail to find the dnn implementation.
     [[node cu_dnngru/CudnnRNN (defined at ta_skenario1.py:205)  = CudnnRNN[T=DT_FLOAT, direction="unidirectional", dropout=0, input_mode="linear_input", is_training=true, rnn_mode="gru", seed=0, seed2=0, _device="/job:localhost/replica:0/task:0/device:GPU:0"](cu_dnngru/transpose, cu_dnngru/ExpandDims, gradients/while/Shape/Enter_grad/zeros/Const, cu_dnngru/concat)]]
     [[{{node mean_squared_error/value/_37}} = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_1756_mean_squared_error/value", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
</code>```

Any idea? Thank you

UPDATE: I tried to downgrade CuDNN version from 7.5.0 to 7.1.4 but the result is remain same.

答:
Did you tested your installations (cuda, cudnn, tensorflow-gpu) ?

Test cuda:
Check first if:

```<code>$ nvcc -V
</code>```

display the right version of your cuda toolkit.
Then you can test it with the following process:

First (it takes few minutes):

```<code> $ cd ~/NVIDIA_CUDA-9.0_Samples
 $ make
</code>```

and then:

```<code>$ cd ~/NVIDIA_CUDA-9.0_Samples/bin/x86_64/linux/release
$./deviceQuery
</code>```

If you get: "Result: pass" at the end, you're all good!

Test cudnn:

```<code>$ cp -r /usr/src/cudnn_samples_v7/ $HOME
$ cd $HOME/cudnn_samples_v7/mnistCUDNN
$ make clean && make
$ ./mnistCUDNN
</code>```

You should have as result: 'Test passed!'

Test tensorflow-gpu:

If cuda and cudnn are working, you can test your tensorflow installation with:

```<code>from tensorflow.python.client import device_lib
device_lib.list_local_devices()
</code>```

I advice you to install tensorflow in a conda environment using:

```<code>conda create --name tf_gpu tensorflow-gpu
</code>```

For me (and after a lot of problems) it was working very well.

Sources:
gpu installation for Ubuntu 18.04, tensorflow-gpu installation

Body:
I'm trying to run my code Keras CuDNNGRU on tensorflow using gpu but it always get error "Fail to find dnn implementation" even though I already installed CUDA and CuDNN.

I already reinstall both CUDA and CuDNN for several times and upgrading CuDNN version from 7.2.1 to 7.5.0 but it doesnt fix anything. I also try to run my code on Jupyter Notebook and in python compiler (on terminal) and both results are same. Here are the details of hardware and software of mine.

Tesla V100 PCIE 16GB

Ubuntu 18.04

NVIDIA-SMI 384.183

CUDA 9.0

CuDNN 7.5.0

Miniconda 3

Python 3.6

Tensorflow 1.12

Keras 2.1.6

Here is my code.

encoder_LSTM = tf.keras.layers.CuDNNGRU(hidden_unit,return_sequences=True,return_state=True)
encoder_LSTM_rev=tf.keras.layers.CuDNNGRU(hidden_unit,return_state=True,return_sequences=True,go_backwards=True)

encoder_outputs, state_h = encoder_LSTM(x)
encoder_outputsR, state_hR = encoder_LSTM_rev(x)

And this is the error message.

2019-05-27 19:08:06.814896: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1511] Adding visible gpu devices: 0
2019-05-27 19:08:06.814956: I tensorflow/core/common_runtime/gpu/gpu_device.cc:982] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-05-27 19:08:06.814971: I tensorflow/core/common_runtime/gpu/gpu_device.cc:988]      0
2019-05-27 19:08:06.814978: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1001] 0:   N
2019-05-27 19:08:06.815279: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 14678 MB memory) -> physical GPU (device: 0, name: Tesla V100-PCIE-16GB, pci bus id: 0000:00:05.0, compute capability: 7.0)
2019-05-27 19:08:08.050226: E tensorflow/stream_executor/cuda/cuda_dnn.cc:373] Could not create cudnn handle: CUDNN_STATUS_NOT_INITIALIZED
2019-05-27 19:08:08.050350: E tensorflow/stream_executor/cuda/cuda_dnn.cc:381] Possibly insufficient driver version: 384.183.0
2019-05-27 19:08:08.050378: W tensorflow/core/framework/op_kernel.cc:1273] OP_REQUIRES failed at cudnn_rnn_ops.cc:1214 : Unknown: Fail to find the dnn implementation.
2019-05-27 19:08:08.050483: E tensorflow/stream_executor/cuda/cuda_dnn.cc:373] Could not create cudnn handle: CUDNN_STATUS_NOT_INITIALIZED
2019-05-27 19:08:08.050523: E tensorflow/stream_executor/cuda/cuda_dnn.cc:381] Possibly insufficient driver version: 384.183.0
2019-05-27 19:08:08.050541: W tensorflow/core/framework/op_kernel.cc:1273] OP_REQUIRES failed at cudnn_rnn_ops.cc:1214 : Unknown: Fail to find the dnn implementation.
Traceback (most recent call last):
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1334, in _do_call
    return fn(*args)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1319, in _run_fn
    options, feed_dict, fetch_list, target_list, run_metadata)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1407, in _call_tf_sessionrun
    run_metadata)
tensorflow.python.framework.errors_impl.UnknownError: Fail to find the dnn implementation.
     [[{{node cu_dnngru/CudnnRNN}} = CudnnRNN[T=DT_FLOAT, direction="unidirectional", dropout=0, input_mode="linear_input", is_training=true, rnn_mode="gru", seed=0, seed2=0, _device="/job:localhost/replica:0/task:0/device:GPU:0"](cu_dnngru/transpose, cu_dnngru/ExpandDims, gradients/while/Shape/Enter_grad/zeros/Const, cu_dnngru/concat)]]
     [[{{node mean_squared_error/value/_37}} = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_1756_mean_squared_error/value", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "ta_skenario1.py", line 271, in <module>
    losss, op = sess.run([loss, optimizer], feed_dict={x:data,y_label:label,initial_input:begin_sentence})
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 929, in run
    run_metadata_ptr)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1152, in _run
    feed_dict_tensor, options, run_metadata)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1328, in _do_run
    run_metadata)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1348, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.UnknownError: Fail to find the dnn implementation.
     [[node cu_dnngru/CudnnRNN (defined at ta_skenario1.py:205)  = CudnnRNN[T=DT_FLOAT, direction="unidirectional", dropout=0, input_mode="linear_input", is_training=true, rnn_mode="gru", seed=0, seed2=0, _device="/job:localhost/replica:0/task:0/device:GPU:0"](cu_dnngru/transpose, cu_dnngru/ExpandDims, gradients/while/Shape/Enter_grad/zeros/Const, cu_dnngru/concat)]]
     [[{{node mean_squared_error/value/_37}} = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_1756_mean_squared_error/value", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

Caused by op 'cu_dnngru/CudnnRNN', defined at:
  File "ta_skenario1.py", line 205, in <module>
    encoder_outputs, state_h = encoder_LSTM(x)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/keras/layers/recurrent.py", line 619, in __call__
    return super(RNN, self).__call__(inputs, **kwargs)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py", line 757, in __call__
    outputs = self.call(inputs, *args, **kwargs)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/keras/layers/cudnn_recurrent.py", line 109, in call
    output, states = self._process_batch(inputs, initial_state)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/keras/layers/cudnn_recurrent.py", line 299, in _process_batch
    rnn_mode='gru')
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/ops/gen_cudnn_rnn_ops.py", line 116, in cudnn_rnn
    is_training=is_training, name=name)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py", line 488, in new_func
    return func(*args, **kwargs)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 3274, in create_op
    op_def=op_def)
  File "/home/paperspace/.conda/envs/gpu/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1770, in __init__
    self._traceback = tf_stack.extract_stack()

UnknownError (see above for traceback): Fail to find the dnn implementation.
     [[node cu_dnngru/CudnnRNN (defined at ta_skenario1.py:205)  = CudnnRNN[T=DT_FLOAT, direction="unidirectional", dropout=0, input_mode="linear_input", is_training=true, rnn_mode="gru", seed=0, seed2=0, _device="/job:localhost/replica:0/task:0/device:GPU:0"](cu_dnngru/transpose, cu_dnngru/ExpandDims, gradients/while/Shape/Enter_grad/zeros/Const, cu_dnngru/concat)]]
     [[{{node mean_squared_error/value/_37}} = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_1756_mean_squared_error/value", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

Any idea? Thank you

UPDATE: I tried to downgrade CuDNN version from 7.5.0 to 7.1.4 but the result is remain same.

Body:
Did you tested your installations (cuda, cudnn, tensorflow-gpu) ?

Test cuda:
Check first if:

$ nvcc -V

display the right version of your cuda toolkit.
Then you can test it with the following process:

First (it takes few minutes):

 $ cd ~/NVIDIA_CUDA-9.0_Samples
 $ make

and then:

$ cd ~/NVIDIA_CUDA-9.0_Samples/bin/x86_64/linux/release
$./deviceQuery

If you get: "Result: pass" at the end, you're all good!

Test cudnn:

$ cp -r /usr/src/cudnn_samples_v7/ $HOME
$ cd $HOME/cudnn_samples_v7/mnistCUDNN
$ make clean && make
$ ./mnistCUDNN

You should have as result: 'Test passed!'

Test tensorflow-gpu:

If cuda and cudnn are working, you can test your tensorflow installation with:

from tensorflow.python.client import device_lib
device_lib.list_local_devices()

I advice you to install tensorflow in a conda environment using:

conda create --name tf_gpu tensorflow-gpu

For me (and after a lot of problems) it was working very well.

Sources:
gpu installation for Ubuntu 18.04, tensorflow-gpu installation


来源: stackexchange

问:
Calculate new column in pandas based on certain criteria
I am trying to multiple a two df based on certain values.

```<code>data = {'a':10,'b':20,'c':30} .
</code>```

df1:

```<code>id,tag,factor
1,a ,20
2,b ,22
3,c ,25
</code>```

my final result should look like something below:

```<code>id,factor,calc
1,20,200
2,22,440
3,24,750
</code>```

The steps I have tried but giving error.

df['calc'] = df['factor'] * data.get(df['tag'])

答:
```<code>df1['calc']=df1.factor*df1.tag.map(data)
</code>```

df1.tag.map(data) check the data dictionary values and replaces them by the associated key, thus giving you a new Series that can be multiplied by df1.factor

ContentLicense: CC BY-SA 4.0

Body:
I am trying to multiple a two df based on certain values.

data = {'a':10,'b':20,'c':30} .

df1:

id,tag,factor
1,a ,20
2,b ,22
3,c ,25

my final result should look like something below:

id,factor,calc
1,20,200
2,22,440
3,24,750

The steps I have tried but giving error.

df['calc'] = df['factor'] * data.get(df['tag'])

Body:
df1['calc']=df1.factor*df1.tag.map(data)

df1.tag.map(data) check the data dictionary values and replaces them by the associated key, thus giving you a new Series that can be multiplied by df1.factor


问:
Build fail for Asp.Net Core 3 (Blazor client side)
I've start to develop a web application with ASP.NET Core 3 and Blazor framework.
During few days/weeks, I could build my application.
Since preview 5 announced, I couldn't build my application (with dotnet build command).
I've the next error:

C:\Users\a\.nuget\packages\microsoft.aspnetcore.blazor.build\3.0.0-preview5-19227-01\targets\Blazor.MonoRuntime.targets(439,5): error MSB3073: The command "dotnet "" -l
-o "D:\Repos\IdeaStudio.Website.Client\obj\Debug\netstandard2.0\linker/"
-x "C:\Users\a\.nuget\packages\microsoft.aspnetcore.blazor.build\3.0.0-preview5-19227-01\targets\BuiltInBclLinkerDescriptor.xml"
-x "D:\Repos\IdeaStudio.Website.Client\obj\Debug\netstandard2.0\linker.descriptor.xml"
-a "C:\Users\a\.nuget\packages\microsoft.aspnetcore.blazor\3.0.0-preview5-19227-01\lib\netstandard2.0\Microsoft.AspNetCore.Blazor.dll"
-a "C:\Users\a\.nuget\packages\microsoft.aspnetcore.components\3.0.0-preview5-19227-01\lib\netstandard2.0\Microsoft.AspNetCore.Components.dll"
-a "C:\Users\a\.nuget\packages\microsoft.aspnetcore.components.browser\3.0.0-preview5-19227-01\lib\netstandard2.0\Microsoft.AspNetCore.Components.Browser.dll"
-a "C:\Users\a\.nuget\packages\microsoft.extensions.dependencyinjection\3.0.0-preview5.19227.9\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.dll"
-a "C:\Users\a\.nuget\packages\microsoft.extensions.dependencyinjection.abstractions\3.0.0-preview5.19227.9\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll"
-a "C:\Users\a\.nuget\packages\microsoft.jsinterop\3.0.0-preview5.19227.9\lib\netstandard2.0\Microsoft.JSInterop.dll"
-a "C:\Users\a\.nuget\packages\mono.webassembly.interop\3.0.0-preview5.19227.9\lib\netstandard2.0\Mono.WebAssembly.Interop.dll"
-a "C:\Users\a\.nuget\packages\system.componentmodel.annotations\4.6.0-preview5.19224.8\lib\netstandard2.0\System.ComponentModel.Annotations.dll"
-a "D:\Repos\IdeaStudio.Website.Client\obj\Debug\netstandard2.0\IdeaStudio.Website.Client.dll"" exited with code 1.
[D:\Repos\IdeaStudio.Website.Client\IdeaStudio.Website.Client.csproj]
```

<p>My <code>csproj</code> looks like :</p>

<pre class="lang-xml prettyprint-override"><code><Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <RestoreAdditionalProjectSources>
      https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json;
      https://dotnet.myget.org/F/blazor-dev/api/v3/index.json;
    </RestoreAdditionalProjectSources>
    <LangVersion>7.3</LangVersion>
    <RazorLangVersion>3.0</RazorLangVersion>
    <TargetLatestRuntimePatch>true</TargetLatestRuntimePatch>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>netstandard2.0</TargetFrameworks>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.5.1" />
    <PackageReference Include="Microsoft.AspNetCore.Blazor" Version="3.0.0-preview5-19227-01" />
    <PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="3.0.0-preview5-19227-01" PrivateAssets="all" />
    <PackageReference Include="Microsoft.AspNetCore.Blazor.DevServer" Version="3.0.0-preview5-19227-01" PrivateAssets="all" />
  </ItemGroup>
</Project>
</code>```

I did not understand for several days until...

答:
This issue on the Mono GitHub is related.

Basically, as far as I understand it, somewhere in Mono the IL Linker fails and throws this cryptic error message. We can see hints to this in your error message.

As of now, michaelccote on GitHub solved the problem by adding the <BlazorLinkOnBuild>false</BlazorLinkOnBuild> element inside the <PropertyGroup>...</PropertyGroup> tags of the .csproj file

Body:
I've start to develop a web application with ASP.NET Core 3 and Blazor framework.
During few days/weeks, I could build my application.
Since preview 5 announced, I couldn't build my application (with dotnet build command).
I've the next error:

C:\Users\a\.nuget\packages\microsoft.aspnetcore.blazor.build\3.0.0-preview5-19227-01\targets\Blazor.MonoRuntime.targets(439,5): error MSB3073: The command "dotnet "" -l
-o "D:\Repos\IdeaStudio.Website.Client\obj\Debug\netstandard2.0\linker/"
-x "C:\Users\a\.nuget\packages\microsoft.aspnetcore.blazor.build\3.0.0-preview5-19227-01\targets\BuiltInBclLinkerDescriptor.xml"
-x "D:\Repos\IdeaStudio.Website.Client\obj\Debug\netstandard2.0\linker.descriptor.xml"
-a "C:\Users\a\.nuget\packages\microsoft.aspnetcore.blazor\3.0.0-preview5-19227-01\lib\netstandard2.0\Microsoft.AspNetCore.Blazor.dll"
-a "C:\Users\a\.nuget\packages\microsoft.aspnetcore.components\3.0.0-preview5-19227-01\lib\netstandard2.0\Microsoft.AspNetCore.Components.dll"
-a "C:\Users\a\.nuget\packages\microsoft.aspnetcore.components.browser\3.0.0-preview5-19227-01\lib\netstandard2.0\Microsoft.AspNetCore.Components.Browser.dll"
-a "C:\Users\a\.nuget\packages\microsoft.extensions.dependencyinjection\3.0.0-preview5.19227.9\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.dll"
-a "C:\Users\a\.nuget\packages\microsoft.extensions.dependencyinjection.abstractions\3.0.0-preview5.19227.9\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll"
-a "C:\Users\a\.nuget\packages\microsoft.jsinterop\3.0.0-preview5.19227.9\lib\netstandard2.0\Microsoft.JSInterop.dll"
-a "C:\Users\a\.nuget\packages\mono.webassembly.interop\3.0.0-preview5.19227.9\lib\netstandard2.0\Mono.WebAssembly.Interop.dll"
-a "C:\Users\a\.nuget\packages\system.componentmodel.annotations\4.6.0-preview5.19224.8\lib\netstandard2.0\System.ComponentModel.Annotations.dll"
-a "D:\Repos\IdeaStudio.Website.Client\obj\Debug\netstandard2.0\IdeaStudio.Website.Client.dll"" exited with code 1.
[D:\Repos\IdeaStudio.Website.Client\IdeaStudio.Website.Client.csproj]

My csproj looks like :

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <RestoreAdditionalProjectSources>
      https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json;
      https://dotnet.myget.org/F/blazor-dev/api/v3/index.json;
    </RestoreAdditionalProjectSources>
    <LangVersion>7.3</LangVersion>
    <RazorLangVersion>3.0</RazorLangVersion>
    <TargetLatestRuntimePatch>true</TargetLatestRuntimePatch>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>netstandard2.0</TargetFrameworks>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.5.1" />
    <PackageReference Include="Microsoft.AspNetCore.Blazor" Version="3.0.0-preview5-19227-01" />
    <PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="3.0.0-preview5-19227-01" PrivateAssets="all" />
    <PackageReference Include="Microsoft.AspNetCore.Blazor.DevServer" Version="3.0.0-preview5-19227-01" PrivateAssets="all" />
  </ItemGroup>
</Project>

I did not understand for several days until...


问:
TypeError: notes.push is not a function
I am running a simple piece of code as shown below.

Basically I want to read the data that is already in 'notes-data.json' and then append it.

```<code>node notes.js
</code>```

```<code>console.log('Starting notes.js');

const fs =  require('fs');

var addNote = (title, body) => {
    var notesString = fs.readFileSync('playground/notes-data.json');
    var notes;
    notes = JSON.parse(notesString);
    var note = {
        title,
        body
    };
    notes.push(note);
    fs.writeFileSync('playground/notes-data.json', JSON.stringify(note));

};

addNote("Hi", "There");

module.exports = {
    addNote: addNote
};
</code>```

Expected: When I run this program it has to add "Hi There".

Actual: Getting the below error.

```<code>(base) prakashp:newproject2 prakashp$ node notes.js
Starting notes.js
/Users/prakashp/training/nodejs/practise/newproject2/notes.js:13
    notes.push(note);
          ^

TypeError: notes.push is not a function
    at addNote (/Users/prakashp/training/nodejs/practise/newproject2/notes.js:13:11)
    at Object.<anonymous> (/Users/prakashp/training/nodejs/practise/newproject2/notes.js:18:1)
    at Module._compile (internal/modules/cjs/loader.js:721:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)
    at executeUserCode (internal/bootstrap/node.js:499:15)
    at startMainThreadExecution (internal/bootstrap/node.js:436:3)
</code>```

If I comment the below line, I am not getting any errors.

```<code>notes = JSON.parse(notesString);
</code>```

Please help.

答:
I think you should let us see what ./playground/notes-data.json looks like.

If the json file isn't an array, then you would most likely not be able to push anything onto it.

Title: TypeError: notes.push is not a function

Body:
I am running a simple piece of code as shown below.

Basically I want to read the data that is already in 'notes-data.json' and then append it.

node notes.js

console.log('Starting notes.js');

const fs =  require('fs');

var addNote = (title, body) => {
    var notesString = fs.readFileSync('playground/notes-data.json');
    var notes;
    notes = JSON.parse(notesString);
    var note = {
        title,
        body
    };
    notes.push(note);
    fs.writeFileSync('playground/notes-data.json', JSON.stringify(note));

};

addNote("Hi", "There");

module.exports = {
    addNote: addNote
};

Expected: When I run this program it has to add "Hi There".

Actual: Getting the below error.

(base) prakashp:newproject2 prakashp$ node notes.js
Starting notes.js
/Users/prakashp/training/nodejs/practise/newproject2/notes.js:13
    notes.push(note);
          ^

TypeError: notes.push is not a function
    at addNote (/Users/prakashp/training/nodejs/practise/newproject2/notes.js:13:11)
    at Object.<anonymous> (/Users/prakashp/training/nodejs/practise/newproject2/notes.js:18:1)
    at Module._compile (internal/modules/cjs/loader.js:721:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)
    at executeUserCode (internal/bootstrap/node.js:499:15)
    at startMainThreadExecution (internal/bootstrap/node.js:436:3)

If I comment the below line, I am not getting any errors.

notes = JSON.parse(notesString);

Please help.


问:
Advanced table-layout to CSS
I have gotten the assignment to code a website from tables to CSS. While this is easy I have one question on how to recreate one of the site's biggest detail.

Site is: www.optimizer.dk.

How can I recreate the labels coming out of the left side, while still having the content in the middle?

Rest of the site is no worries.

Is the solution to:

```<code>     padding-left: 200000px;
     margin-left: -200000px;
</code>```

To fake the expansion to the left?

答: You need 3 divs with float:left to create the 3 columns</p>

ContentLicense: CC BY-SA 3.0

Title: Advanced table-layout to CSS

Body:
I have gotten the assignment to code a website from tables to CSS. While this is easy I have one question on how to recreate one of the site's biggest detail.

Site is: www.optimizer.dk.

How can I recreate the labels coming out of the left side, while still having the content in the middle?

Rest of the site is no worries.

Is the solution to:

     padding-left: 200000px;
     margin-left: -200000px;

To fake the expansion to the left?


问:
Python: How to copy and insert a xml element at a specific location
I'm using xml.etree.ElementTree to parse XML-files. I would now like to
copy a specific XML element and insert it at my desired destination.

What the XML-file basically looks like:

```<code><file>
   <page id="1">
      <text id="1"> sample text </text>
      <text id="2"> sample text II </text>
   </page>
   <page id="2">
      <text id="1"> sample text copy</text>
      <text id="2"> sample text me </text>
   </page>
   <page id="3">
      <text id="1"> sample text hello </text>
      <text id="2"> sample text world </text>
   </page>
   <page id="4">
      <text id="1"> sample text game </text>
      <text id="2"> sample text over </text>
   </page>
</file>
</code>```

For example, I want to copy the page-element where id="2" and insert it after the page-element where id="3". Additionally, I want to change the id of the new element.

What the result should look like:

```<code><file>
   <page id="1">
      <text id="1"> sample text </text>
      <text id="2"> sample text II </text>
   </page>
   <page id="2">
      <text id="1"> sample text copy</text>
      <text id="2"> sample text me </text>
   </page>
   <page id="3">
      <text id="1"> sample text hello </text>
      <text id="2"> sample text world </text>
   </page>
   *<page id="2.1">
      <text id="1"> sample text copy</text>
      <text id="2"> sample text me </text>
   </page>*
   <page id="4">
      <text id="1"> sample text game </text>
      <text id="2"> sample text over </text>
   </page>
</file>
</code>```

*the inserted element

I've already tried some variations of this, but I always had issues with the attributes (in this case the id).
Currently I'm using xml.etree.ElementTree and it would be great if someone can help me solving my problem with this package, but I take every package that solves the problem.

答:
To find a specific node, use find() with some XPath to get the page node with id=2:

```<code># Find element to copy
member1 = root.find(".//page[@id='2']")

# Create copy
member2 = copy.deepcopy(member1)
</code>```

To change the value of the id attribute, use :

```<code>member2.set('id' , '2.1')
</code>```

Now you can insert the new element as the 4th element. For this use insert instead of the append used in the answer you linked.

```<code>root.insert(3, member2)
</code>```

The output is:

```<code><file>
   <page id="1">
      <text id="1"> sample text </text>
      <text id="2"> sample text II </text>
   </page>
   <page id="2">
      <text id="1"> sample text copy</text>
      <text id="2"> sample text me </text>
   </page>
   <page id="3">
      <text id="1"> sample text hello </text>
      <text id="2"> sample text world </text>
   </page>
   <page id="2.1">
      <text id="1"> sample text copy</text>
      <text id="2"> sample text me </text>
   </page>
   <page id="4">
      <text id="1"> sample text game </text>
      <text id="2"> sample text over </text>
   </page>
</file>
</code>```

Body:
I'm using xml.etree.ElementTree to parse XML-files. I would now like to
copy a specific XML element and insert it at my desired destination.

What the XML-file basically looks like:

<file>
   <page id="1">
      <text id="1"> sample text </text>
      <text id="2"> sample text II </text>
   </page>
   <page id="2">
      <text id="1"> sample text copy</text>
      <text id="2"> sample text me </text>
   </page>
   <page id="3">
      <text id="1"> sample text hello </text>
      <text id="2"> sample text world </text>
   </page>
   <page id="4">
      <text id="1"> sample text game </text>
      <text id="2"> sample text over </text>
   </page>
</file>

For example, I want to copy the page-element where id="2" and insert it after the page-element where id="3". Additionally, I want to change the id of the new element.

What the result should look like:

<file>
   <page id="1">
      <text id="1"> sample text </text>
      <text id="2"> sample text II </text>
   </page>
   <page id="2">
      <text id="1"> sample text copy</text>
      <text id="2"> sample text me </text>
   </page>
   <page id="3">
      <text id="1"> sample text hello </text>
      <text id="2"> sample text world </text>
   </page>
   *<page id="2.1">
      <text id="1"> sample text copy</text>
      <text id="2"> sample text me </text>
   </page>*
   <page id="4">
      <text id="1"> sample text game </text>
      <text id="2"> sample text over </text>
   </page>
</file>

*the inserted element

I've already tried some variations of this, but I always had issues with the attributes (in this case the id).
Currently I'm using xml.etree.ElementTree and it would be great if someone can help me solving my problem with this package, but I take every package that solves the problem.

Body:
To find a specific node, use find() with some XPath to get the page node with id=2:

# Find element to copy
member1 = root.find(".//page[@id='2']")

# Create copy
member2 = copy.deepcopy(member1)

To change the value of the id attribute, use :

member2.set('id' , '2.1')

Now you can insert the new element as the 4th element. For this use insert instead of the append used in the answer you linked.

root.insert(3, member2)

The output is:

<file>
   <page id="1">
      <text id="1"> sample text </text>
      <text id="2"> sample text II </text>
   </page>
   <page id="2">
      <text id="1"> sample text copy</text>
      <text id="2"> sample text me </text>
   </page>
   <page id="3">
      <text id="1"> sample text hello </text>
      <text id="2"> sample text world </text>
   </page>
   <page id="2.1">
      <text id="1"> sample text copy</text>
      <text id="2"> sample text me </text>
   </page>
   <page id="4">
      <text id="1"> sample text game </text>
      <text id="2"> sample text over </text>
   </page>
</file>


问:
sed - Replace string with special characters
I want to replace the first string with the next

```<code>FindText[1]=/Folder 1/01. SubFolder/Demo(Object)

ReplaceText[1]=/Folder 1/01. SubFolder/02. SubFolder/Demo(Object)
</code>```

I have tried this option with "|" but doesn't work.

```<code>>>sed -i 's|FindText[1]=/Folder 1/01. SubFolder/Demo(Object)|ReplaceText[1]=/Folder 1/01. SubFolder/02. SubFolder/Demo(Object)|g' filename.txt
</code>```

The square brackets in the find expression doesn't seem to be found.

答:
try this:

```<code>sed -i 's|FindText\[1\]=/Folder 1/01. SubFolder/Demo(Object)|ReplaceText\[1\]=\/Folder 1\/01\. SubFolder\/02\. SubFolder\/Demo\(Object\)|g' filename.txt
</code>```

special characters like \, [, ], (, ) and . must be escaped!

Body:
I want to replace the first string with the next

FindText[1]=/Folder 1/01. SubFolder/Demo(Object)

ReplaceText[1]=/Folder 1/01. SubFolder/02. SubFolder/Demo(Object)

I have tried this option with "|" but doesn't work.

>>sed -i 's|FindText[1]=/Folder 1/01. SubFolder/Demo(Object)|ReplaceText[1]=/Folder 1/01. SubFolder/02. SubFolder/Demo(Object)|g' filename.txt

The square brackets in the find expression doesn't seem to be found.

Body:
try this:

sed -i 's|FindText\[1\]=/Folder 1/01. SubFolder/Demo(Object)|ReplaceText\[1\]=\/Folder 1\/01\. SubFolder\/02\. SubFolder\/Demo\(Object\)|g' filename.txt

special characters like \, [, ], (, ) and . must be escaped!


问:
How to initialize and use function pointer in Swift
Let's say I have this code snipped in the playground

```<code>import UIKit

internal final class TestClass {
    internal final var funcPointer: () -> Void

    init() {
        self.funcPointer = self.func1() //Cannot assign value of type '()' to type '() -> Void'
    }

    internal final func func1() {
        print("func1 is called!")
    }
}

var testClass: TestClass = TestClass()
testClass.funcPointer()
</code>```

Why do I get the shown error message within the init() method and how to initialize a function pointer correctly?

I have already seen this SO post and this tutorial but anyway I don't get it to work for a (Void) -> Void function...

答:
To assign the closure to the property you have to remove the parentheses

```<code>self.funcPointer = self.func1
</code>```

The subsequent error

self' used in method call 'func1' before all stored properties are initialized

can be fixed by declaring funcPointer implicit unwrapped optional

```<code>internal final var funcPointer: (() -> Void)!
</code>```

Body:
Let's say I have this code snipped in the playground

import UIKit

internal final class TestClass {
    internal final var funcPointer: () -> Void

    init() {
        self.funcPointer = self.func1() //Cannot assign value of type '()' to type '() -> Void'
    }

    internal final func func1() {
        print("func1 is called!")
    }
}

var testClass: TestClass = TestClass()
testClass.funcPointer()

Why do I get the shown error message within the init() method and how to initialize a function pointer correctly?

I have already seen this SO post and this tutorial but anyway I don't get it to work for a (Void) -> Void function...

Body:
To assign the closure to the property you have to remove the parentheses

self.funcPointer = self.func1

The subsequent error

self' used in method call 'func1' before all stored properties are initialized

can be fixed by declaring funcPointer implicit unwrapped optional

internal final var funcPointer: (() -> Void)!


问:
Cursor Position between close and open tags
I want to know if it is possible to set caret between closed HTML tag and opened HTML tag.

This is my HTML:

 Hello
     Foo

      Bar

        From Baz

```

So, if the cursor is at the end of green tag From Baz (how to get if cursor position at the end of the anchorNode?), by pressing right arrow key, it moves to the parent span which has blue color.

Even with using setStart on range variable at the beginning of the green span,it sets the cursor to the end of the blue span (Bar), then with writing it will be blue (expected was to be on the beginning of the green span).

The question is, is it possible to control cursor position between the tags or not?

Update

1 - I need pure Javascript solution.
2 - It also behaves differently depending on browser. So, it needs a solution that only depends on Javascript, in other word, the question will be, "How it is possible to take control of cursor?"

答:
Here is an approach with zero width non-joiner () character is used. it solves the problem but adds an extra character which doesn't change the looks but has a problem when using arrows to move caret left and right, hope it helps.

 Hello
    Foo
    Bar
      From Baz

```
</div>
</div>
</p>

<hr>

<h2>Edit</h2>

<p>Here is another approach which doesn't have the problem above:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div contentEditable="true">
  <div> Hello<span style="color: red;">
    Foo</span><span style="color: blue;">
    Bar<span style="color: green;">
    From Baz</span>
    </span>
  </div>
</div></code>```

Edit 2

You could also do the following using Javascript:

function RemoveSpaces(myQuery, parentNodeName){
  var myElement = document.querySelector(myQuery);
  var iterator = document.createNodeIterator(myElement, NodeFilter.SHOW_TEXT, node => {
    if (node.parentElement.nodeName == parentNodeName) {
      return NodeFilter.FILTER_ACCEPT;
    }
    return NodeFilter.FILTER_REJECT;
  });

  var toBeRemoved = [];
  let next = iterator.nextNode();
  while(next) {
    toBeRemoved.push(next);
    next = iterator.nextNode();
  }

  toBeRemoved.forEach(n => RemoveFunction(n));
}

function RemoveFunction(c){
    if (!c.nodeValue.replace(/\s/g, '').length){
     c.remove();
    }
    else{
     c.nodeValue = "\n" + c.nodeValue.trim();
    }
}

RemoveSpaces('div[contenteditable="true"] div', 'DIV');
RemoveSpaces('div[contenteditable="true"] div', 'SPAN');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div contentEditable="true">
  <div>Hello
    <span style="color: red;"> Foo </span>
    <span style="color: blue;">
      Bar
      <span style="color: green;">
        From Baz
      </span>
    </span>
  </div>
</div></code>```

Edit 3

For the issue mentioned in the comments, we can combine the first approach (), with the third approach which was JS.
So the idea is to add  after each child span, so we can use its weakness (which was adding an invisible space which needed an extra right arrow) as its strength, so when the user hits the right arrow at the end of the green span, he would go after the  character which is in the parent (blue) span.

so the HTML which we are generating should look like this:

```<code><div>
Hello<span style="color: red;">
Foo</span><span style="color: blue;">
Bar<span style="color: green;">
From Baz</span></span></div>
</code>```

And This is the complete code to achieve that:

function RemoveSpaces(myQuery, parentNodeName){
  var myElement = document.querySelector(myQuery);
  var iterator = document.createNodeIterator(myElement, NodeFilter.SHOW_TEXT, node => {
    if (node.parentElement.nodeName == parentNodeName) {
      return NodeFilter.FILTER_ACCEPT;
    }
    return NodeFilter.FILTER_REJECT;
  });

  var toBeRemoved = [];
  let next = iterator.nextNode();
  while(next) {
    toBeRemoved.push(next);
    next = iterator.nextNode();
  }

  toBeRemoved.forEach(n => RemoveFunction(n));
}
function RemoveFunction(c){
  if (!c.nodeValue.replace(/\s/g, '').length){
    c.remove();
  }
  else{
    c.nodeValue = "\n" + c.nodeValue.trim();
  }
}

RemoveSpaces('div[contenteditable="true"] div', 'DIV');
RemoveSpaces('div[contenteditable="true"] div', 'SPAN');

//Added Code

var childrenspans = document.querySelector("div[contenteditable='true']").getElementsByTagName("span");
var newNode = document.createTextNode('\u200c');
childrenspans[childrenspans.length-1].parentNode.insertBefore(newNode, childrenspans[childrenspans.length-1].nextSibling);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div contentEditable="true">
  <div>Hello
    <span style="color: red;"> Foo </span>
    <span style="color: blue;">
      Bar
      <span style="color: green;">
        From Baz
      </span>
    </span>
  </div>
</div></code>```

Note that we are using '\u200c' instead of '', it's because of the createTextNode, and we have to use it's Unicode which is u200c.

Edit 4

As mentioned in the comments, The Edit 3 code works but after adding text after the green span, it would have the same problem as before with the first approach
which means there is an extra  in the middle of the texts.

We can track inputs every time user inputs something, and we can remove the  character if it's beside a space character.

It doesn't completely fix it, but helps.
Here is the code:

function RemoveSpaces(myQuery, parentNodeName){
  var myElement = document.querySelector(myQuery);
  var iterator = document.createNodeIterator(myElement, NodeFilter.SHOW_TEXT, node => {
    if (node.parentElement.nodeName == parentNodeName) {
      return NodeFilter.FILTER_ACCEPT;
    }
    return NodeFilter.FILTER_REJECT;
  });

  var toBeRemoved = [];
  let next = iterator.nextNode();
  while(next) {
    toBeRemoved.push(next);
    next = iterator.nextNode();
  }

  toBeRemoved.forEach(n => RemoveFunction(n));
}
function RemoveFunction(c){
  if (!c.nodeValue.replace(/\s/g, '').length){
    c.remove();
  }
  else{
    c.nodeValue = "\n" + c.nodeValue.trim();
  }
}

RemoveSpaces('div[contenteditable="true"] div', 'DIV');
RemoveSpaces('div[contenteditable="true"] div', 'SPAN');

var childrenspans = document.querySelector("div[contenteditable='true']").getElementsByTagName("span");
var newNode = document.createTextNode('\u200c');
childrenspans[childrenspans.length-1].parentNode.insertBefore(newNode, childrenspans[childrenspans.length-1].nextSibling);

//Added Code

function saveCaretPosition(context){
    var selection = window.getSelection();
    var range = selection.getRangeAt(0);
    range.setStart(  context, 0 );
    var len = range.toString().length;

    return function restore(x){
        var pos = getTextNodeAtPosition(context, len);
        selection.removeAllRanges();
        var range = new Range();
        if(x)
          range.setStart(pos.node ,pos.position-1);
        else
          range.setStart(pos.node ,pos.position);
        selection.addRange(range);
    }
}
function getTextNodeAtPosition(root, index){
    var lastNode = null;
    var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT,function next(elem) {
        if(index >= elem.textContent.length){
            index -= elem.textContent.length;
            lastNode = elem;
            return NodeFilter.FILTER_REJECT
        }
        return NodeFilter.FILTER_ACCEPT;
    });
    var c = treeWalker.nextNode();
    return {
        node: c? c: root,
        position: c? index:  0
    };
}

function RemoveCharCodeIfBesideCharacter(str, charCode, besideCharacter){
  function SortNumber(a, b) {return a - b;}
  var indexesToRemove = [];
  for (var i = 0; i < str.length; i++) {
   var strchar = str.charCodeAt(i);
    if(strchar == charCode && i != 0 && i != str.length-1){
      if(str.charAt(i-1) == besideCharacter || str.charAt(i+1) == besideCharacter)
        indexesToRemove.push(i);
    }
  }
  indexesToRemove.sort(SortNumber);
  var removeCount = 0;
  for(var i=0; i < indexesToRemove.length; i++){
   str = str.slice(0, indexesToRemove[i]-removeCount) + str.slice(indexesToRemove[i]+1-removeCount);
    removeCount++;
  }
  return str;
}

document.querySelector("div[contenteditable='true']").addEventListener("input", function() {
    var restore = saveCaretPosition(this);
    var before = this.innerHTML;
    this.innerHTML = RemoveCharCodeIfBesideCharacter(this.innerHTML, "8204", " ");
    restore(before != this.innerHTML);
}, false);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div contentEditable="true">
  <div>Hello
    <span style="color: red;"> Foo </span>
    <span style="color: blue;">
      Bar
      <span style="color: green;">
        From Baz
      </span>
    </span>
  </div>
</div></code>```

Body:
I want to know if it is possible to set caret between closed HTML tag and opened HTML tag.

This is my HTML:

 Hello
     Foo

      Bar

        From Baz

So, if the cursor is at the end of green tag From Baz (how to get if cursor position at the end of the anchorNode?), by pressing right arrow key, it moves to the parent span which has blue color.

Even with using setStart on range variable at the beginning of the green span,it sets the cursor to the end of the blue span (Bar), then with writing it will be blue (expected was to be on the beginning of the green span).

The question is, is it possible to control cursor position between the tags or not?

Update

1 - I need pure Javascript solution.
2 - It also behaves differently depending on browser. So, it needs a solution that only depends on Javascript, in other word, the question will be, "How it is possible to take control of cursor?"

Body:
Here is an approach with zero width non-joiner (&zwnj;) character is used. it solves the problem but adds an extra character which doesn't change the looks but has a problem when using arrows to move caret left and right, hope it helps.

<div contentEditable="true">
  <div> Hello
    <span style="color: red;">Foo </span>
    <span style="color: blue;">&zwnj;Bar
      <span style="color: green;">&zwnj;From Baz</span>
    </span>
  </div>
</div>

Edit

Here is another approach which doesn't have the problem above:

<div contentEditable="true">
  <div> Hello<span style="color: red;">
    Foo</span><span style="color: blue;">
    Bar<span style="color: green;">
    From Baz</span>
    </span>
  </div>
</div>

Edit 2

You could also do the following using Javascript:

function RemoveSpaces(myQuery, parentNodeName){
  var myElement = document.querySelector(myQuery);
  var iterator = document.createNodeIterator(myElement, NodeFilter.SHOW_TEXT, node => {
    if (node.parentElement.nodeName == parentNodeName) {
      return NodeFilter.FILTER_ACCEPT;
    }
    return NodeFilter.FILTER_REJECT;
  });

  var toBeRemoved = [];
  let next = iterator.nextNode();
  while(next) {
    toBeRemoved.push(next);
    next = iterator.nextNode();
  }

  toBeRemoved.forEach(n => RemoveFunction(n));
}

function RemoveFunction(c){
    if (!c.nodeValue.replace(/\s/g, '').length){
     c.remove();
    }
    else{
     c.nodeValue = "\n" + c.nodeValue.trim();
    }
}

RemoveSpaces('div[contenteditable="true"] div', 'DIV');
RemoveSpaces('div[contenteditable="true"] div', 'SPAN');

<div contentEditable="true">
  <div>Hello
    <span style="color: red;"> Foo </span>
    <span style="color: blue;">
      Bar
      <span style="color: green;">
        From Baz
      </span>
    </span>
  </div>
</div>

Edit 3

For the issue mentioned in the comments, we can combine the first approach (&zwnj;), with the third approach which was JS.
So the idea is to add &zwnj; after each child span, so we can use its weakness (which was adding an invisible space which needed an extra right arrow) as its strength, so when the user hits the right arrow at the end of the green span, he would go after the &zwnj; character which is in the parent (blue) span.

so the HTML which we are generating should look like this:

<div>
Hello<span style="color: red;">
Foo</span>&zwnj;<span style="color: blue;">
Bar<span style="color: green;">
From Baz</span>&zwnj;</span>&zwnj;</div>

And This is the complete code to achieve that:

function RemoveSpaces(myQuery, parentNodeName){
  var myElement = document.querySelector(myQuery);
  var iterator = document.createNodeIterator(myElement, NodeFilter.SHOW_TEXT, node => {
    if (node.parentElement.nodeName == parentNodeName) {
      return NodeFilter.FILTER_ACCEPT;
    }
    return NodeFilter.FILTER_REJECT;
  });

  var toBeRemoved = [];
  let next = iterator.nextNode();
  while(next) {
    toBeRemoved.push(next);
    next = iterator.nextNode();
  }

  toBeRemoved.forEach(n => RemoveFunction(n));
}
function RemoveFunction(c){
  if (!c.nodeValue.replace(/\s/g, '').length){
    c.remove();
  }
  else{
    c.nodeValue = "\n" + c.nodeValue.trim();
  }
}

RemoveSpaces('div[contenteditable="true"] div', 'DIV');
RemoveSpaces('div[contenteditable="true"] div', 'SPAN');

//Added Code

var childrenspans = document.querySelector("div[contenteditable='true']").getElementsByTagName("span");
var newNode = document.createTextNode('\u200c');
childrenspans[childrenspans.length-1].parentNode.insertBefore(newNode, childrenspans[childrenspans.length-1].nextSibling);

<div contentEditable="true">
  <div>Hello
    <span style="color: red;"> Foo </span>
    <span style="color: blue;">
      Bar
      <span style="color: green;">
        From Baz
      </span>
    </span>
  </div>
</div>

Note that we are using '\u200c' instead of '&zwnj;', it's because of the createTextNode, and we have to use it's Unicode which is u200c.

Edit 4

As mentioned in the comments, The Edit 3 code works but after adding text after the green span, it would have the same problem as before with the first approach
which means there is an extra &zwnj; in the middle of the texts.

We can track inputs every time user inputs something, and we can remove the &zwnj; character if it's beside a space character.

It doesn't completely fix it, but helps.
Here is the code:

function RemoveSpaces(myQuery, parentNodeName){
  var myElement = document.querySelector(myQuery);
  var iterator = document.createNodeIterator(myElement, NodeFilter.SHOW_TEXT, node => {
    if (node.parentElement.nodeName == parentNodeName) {
      return NodeFilter.FILTER_ACCEPT;
    }
    return NodeFilter.FILTER_REJECT;
  });

  var toBeRemoved = [];
  let next = iterator.nextNode();
  while(next) {
    toBeRemoved.push(next);
    next = iterator.nextNode();
  }

  toBeRemoved.forEach(n => RemoveFunction(n));
}
function RemoveFunction(c){
  if (!c.nodeValue.replace(/\s/g, '').length){
    c.remove();
  }
  else{
    c.nodeValue = "\n" + c.nodeValue.trim();
  }
}

RemoveSpaces('div[contenteditable="true"] div', 'DIV');
RemoveSpaces('div[contenteditable="true"] div', 'SPAN');

var childrenspans = document.querySelector("div[contenteditable='true']").getElementsByTagName("span");
var newNode = document.createTextNode('\u200c');
childrenspans[childrenspans.length-1].parentNode.insertBefore(newNode, childrenspans[childrenspans.length-1].nextSibling);

//Added Code

function saveCaretPosition(context){
    var selection = window.getSelection();
    var range = selection.getRangeAt(0);
    range.setStart(  context, 0 );
    var len = range.toString().length;

    return function restore(x){
        var pos = getTextNodeAtPosition(context, len);
        selection.removeAllRanges();
        var range = new Range();
        if(x)
          range.setStart(pos.node ,pos.position-1);
        else
          range.setStart(pos.node ,pos.position);
        selection.addRange(range);
    }
}
function getTextNodeAtPosition(root, index){
    var lastNode = null;
    var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT,function next(elem) {
        if(index >= elem.textContent.length){
            index -= elem.textContent.length;
            lastNode = elem;
            return NodeFilter.FILTER_REJECT
        }
        return NodeFilter.FILTER_ACCEPT;
    });
    var c = treeWalker.nextNode();
    return {
        node: c? c: root,
        position: c? index:  0
    };
}

function RemoveCharCodeIfBesideCharacter(str, charCode, besideCharacter){
  function SortNumber(a, b) {return a - b;}
  var indexesToRemove = [];
  for (var i = 0; i < str.length; i++) {
   var strchar = str.charCodeAt(i);
    if(strchar == charCode && i != 0 && i != str.length-1){
      if(str.charAt(i-1) == besideCharacter || str.charAt(i+1) == besideCharacter)
        indexesToRemove.push(i);
    }
  }
  indexesToRemove.sort(SortNumber);
  var removeCount = 0;
  for(var i=0; i < indexesToRemove.length; i++){
   str = str.slice(0, indexesToRemove[i]-removeCount) + str.slice(indexesToRemove[i]+1-removeCount);
    removeCount++;
  }
  return str;
}

document.querySelector("div[contenteditable='true']").addEventListener("input", function() {
    var restore = saveCaretPosition(this);
    var before = this.innerHTML;
    this.innerHTML = RemoveCharCodeIfBesideCharacter(this.innerHTML, "8204", " ");
    restore(before != this.innerHTML);
}, false);

<div contentEditable="true">
  <div>Hello
    <span style="color: red;"> Foo </span>
    <span style="color: blue;">
      Bar
      <span style="color: green;">
        From Baz
      </span>
    </span>
  </div>
</div>


问:
Reference Microsoft.VisualStudio.QualityTools.UnitTestFramework for CI build
I have created a C# test project in VS2015 RC. it builds locally but when i attempt to build on our CI build server (TeamCity) it fails with errors:

UnitTest1.cs(2,17): error CS0234: The type or namespace name
  'VisualStudio' does not exist in the namespace 'Microsoft' (are you
  missing an assembly reference?)
  [... .Tests.csproj]
  UnitTest1.cs(9,10): error CS0246: The type or namespace name
  'TestMethod' could not be found (are you missing a using directive or
  an assembly reference?)
  [... .Tests.csproj]

Clearly this is because the assembly containing these namespaces (Microsoft.VisualStudio.QualityTools.UnitTestFramework) is not on the build server; on my local machine it resides at C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll.

I could copy the assembly into my solution so that it becomes part of the codebase but manually moving files feels like a bit of an inelegant hack. I searched around on nuget and found http://www.nuget.org/packages/Microsoft.VisualStudio.QualityTools.UnitTestFramework/ which I figured would do the trick, but installing that package failed with:

Install-Package : Could not install package
  'Microsoft.VisualStudio.QualityTools.UnitTestFramework 11.0.50727.1'.
  You are trying to install this package into a project that targets
  '.NETFramework, Version=v4.5.2', but the  package does not contain any
  assembly references or content files that are compatible with that
  framework

What's my best option of solving this? I'm surprised that creating a test project in VS2015 does not automatically include all the dependencies that I need, though perhaps I'm being naive (I'm something of a fledgling dot netter).

答:
I was having this issue when trying to use MSBuild on our dev server via our CI/CD process after I was asked to uninstall VS2013 from our dev server by our IT team.

In my case in my build output there were a few lines with the word Considered. What this means is that the build is considering those folders for locations where the file may be located. One of those lines was as follows:

```<code>Considered "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll", but it didn't exist.
</code>```

I copied Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll from my local machine to that folder on the dev server and the error went away.

Body:
I was having this issue when trying to use MSBuild on our dev server via our CI/CD process after I was asked to uninstall VS2013 from our dev server by our IT team.

In my case in my build output there were a few lines with the word Considered. What this means is that the build is considering those folders for locations where the file may be located. One of those lines was as follows:

Considered "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll", but it didn't exist.

I copied Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll from my local machine to that folder on the dev server and the error went away.


问:
Issue with data population from XML
I am reading data from XML into a table. When I do select from the table, the table is empty.

```<code>SET @INPUTXML = CAST(@Attribute AS XML)
EXEC Sp_xml_preparedocument @TestDoc OUTPUT, @INPUTXML

SELECT Row_Number() OVER (ORDER BY Name) AS Row, *
INTO #tData
FROM OPENXML(@TestDoc, N'/DocumentElement/dtData')
WITH (
        ID VARCHAR(100) './ID'
        , Name VARCHAR(100) './Name'
        , Value VARCHAR(max) './Value'
        , Column VARCHAR(100) './Column'
)

EXEC Sp_xml_removedocument @TestDoc
</code>```

Below are my questions:

select * from #tData is empty table. Why is data not getting populated?

What does Sp_xml_preparedocument do? When I print @TestDoc, it gives me a number

What is Sp_xml_removedocument ?

答:
To answer your questions though.

#tData is empty because your SELECT statement returned no data. A SELECT...INTO statement will still create the table, even if the SELECT returns no rows. Why your SELECT is returning no data is impossible for us to say, because we have no sample data. If you remove the INTO clause you will see that no rows are returned, so you need to fix your SELECT, FROM, etc. but that brings on to my statement in a minute (about using XQUERY)

sp_xml_preparedocument (Transact-SQL) explains better than I could. Really though, you shouldn't be using it anymore, as it was used to read XML back in SQL Server 2000 (maybe 2005) and prior. Certainly SQL Server 2008 supported XQUERY, which you must be at least using if you are using SSMS  2014. To quote the opening statement of the documentation though:

Reads the XML text provided as input, parses the text by using the MSXML parser (Msxmlsql.dll), and provides the parsed document in a state ready for consumption. This parsed document is a tree representation of the various nodes in the XML document: elements, attributes, text, comments, and so on.

sp_xml_removedocument (Transact-SQL), but again, you should be using XQUERY.

Removes the internal representation of the XML document specified by the document handle and invalidates the document handle.

Title: Issue with data population from XML

Body:
I am reading data from XML into a table. When I do select from the table, the table is empty.

SET @INPUTXML = CAST(@Attribute AS XML)
EXEC Sp_xml_preparedocument @TestDoc OUTPUT, @INPUTXML

SELECT Row_Number() OVER (ORDER BY Name) AS Row, *
INTO #tData
FROM OPENXML(@TestDoc, N'/DocumentElement/dtData')
WITH (
        ID VARCHAR(100) './ID'
        , Name VARCHAR(100) './Name'
        , Value VARCHAR(max) './Value'
        , Column VARCHAR(100) './Column'
)

EXEC Sp_xml_removedocument @TestDoc

Below are my questions:

select * from #tData is empty table. Why is data not getting populated?

What does Sp_xml_preparedocument do? When I print @TestDoc, it gives me a number

What is Sp_xml_removedocument ?


问:
Best practices to parse and manipulate XML files, that are minimum of 1000 MBs or more in size

Possible Duplicates:

  PHP what is the best approach to using XML? Need to create and parse XML responses

  Parse big XML in PHP

Hello Community,

I am writing an application, that requires to parse XML files, that can minimum of 1000 MBs or more in size.

I have tried with few code that is available on internet. As file size is more, it's easy to understand that file will have lots and lots of XML tags. So, loop performance gets weak as time elapse.

So, I would need a parser:
-> Performance is considerably good as time passes, when doing execution / parsing
-> Doesn't load the whole XML file in memory

I know about following XML parsers, but not sure which to use and why?

XML Parser

SimpleXML

XMLReader

I am using PHP 5.3, so please help me guys and gals, to choose the parser.

You can even suggest me some other options, or classes.

Thanks.

EDIT

I even want to know about SAX (Simple API for XML) and StAX implementation of PHP

答:
Load your giant XML files into an XML database and perform your query and manipulations through their XQuery/XSLT interfaces.

http://www.xml.com/pub/a/2003/10/22/embed.html


问:
Typescript: Cannot find namespace
I have the following simple NodeJS code:

```<code>const express = require('express');

const server: express.Application = express();
</code>```

I'm adding Typescript to my project and am new to it so forgive me. With the above code I get the following issues/errors:

For the require:

```<code>var require: NodeRequire (id: string) => any (+1 overload)
'require' call may be converted to an import.
</code>```

For the express.Application usage:

```<code>Cannot find namespace 'express'.
</code>```

If I switch the 'require' to 'import' it fixes the namespace error but is no longer valid Node code so doesn't run (throws a new error about unexpected token for the import).

What's the correct way to write Node code like this with Typescript to avoid these errors?

My tsconfig.json looks like this:

```<code>{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "preserve",
    "lib": ["dom", "es2017"],
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "removeComments": true,
    "resolveJsonModule": true,
    "sourceMap": true,
    "strict": true,
    "target": "esnext",
  },
  "exclude": ["node_modules"],
}
</code>```

答:
After a lot of wasted time, it turns out this was due to the module setting in the tsconfig file which should be:

```<code>"module": "commonjs"
</code>```

This means Typescript will output common js modules instead of ES6 modules, meaning the code will run correctly as NodeJS code. I was therefore able to change require to import, since it compiles.

Title: Typescript: Cannot find namespace

Body:
I have the following simple NodeJS code:

const express = require('express');

const server: express.Application = express();

I'm adding Typescript to my project and am new to it so forgive me. With the above code I get the following issues/errors:

For the require:

var require: NodeRequire (id: string) => any (+1 overload)
'require' call may be converted to an import.

For the express.Application usage:

Cannot find namespace 'express'.

If I switch the 'require' to 'import' it fixes the namespace error but is no longer valid Node code so doesn't run (throws a new error about unexpected token for the import).

What's the correct way to write Node code like this with Typescript to avoid these errors?

My tsconfig.json looks like this:

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "preserve",
    "lib": ["dom", "es2017"],
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "removeComments": true,
    "resolveJsonModule": true,
    "sourceMap": true,
    "strict": true,
    "target": "esnext",
  },
  "exclude": ["node_modules"],
}

Body:
After a lot of wasted time, it turns out this was due to the module setting in the tsconfig file which should be:

"module": "commonjs"

This means Typescript will output common js modules instead of ES6 modules, meaning the code will run correctly as NodeJS code. I was therefore able to change require to import, since it compiles.


问:
Does @x ||= work like return @x if @x.present?
Is this:

```<code>def x?
  return @x if @x.present?

  @x = #boolean calculation
end
</code>```

Equivalent to this for boolean values of @x?

```<code>def x?
  @x ||= #boolean calculation
end
</code>```

答:
It depends.

@x ||= value
```

<p>is equivalent to</p>

<pre class="lang-rb prettyprint-override"><code>@x = @x || value
</code>```

which assigns value to @x only if @x is falsy. In Ruby, only false and nil are falsy.

Further, #present? is a concept from Rails (see doc).

Note though that depending on the value that you expect to store in @x, it might be equivalent. #present? is simply the negation of #blank? (also a Rails concept). #blank? is defined on Object as follows:

def blank?
  respond_to?(:empty?) ? !!empty? : !self
end
```

<p>Thus, the behavior of the two snippets you posted is guaranteed to be equivalent when <code>@x</code> contains a value that doesn't define its own <code>#present?</code>, <code>#blank?</code>, or <code>#empty?</code> methods.</p>

<p>Now, <code>FalseClass</code> and <code>NilClass</code> both define <code>#blank?</code>:</p>

<pre class="lang-rb prettyprint-override"><code>def blank?
  true
end
</code>```

TrueClass also defines #blank?:

def blank?
  false
end
```

But this is just an optimization as the default implementation from Object would result in the same values.

Therefore, false and nil will return false for #present? and true will return true for #present?.

From this we conclude that, in the specific case of storing boolean values in @x, the behavior of the two snippets is equivalent.

Body:
Is this:

def x?
  return @x if @x.present?

  @x = #boolean calculation
end

Equivalent to this for boolean values of @x?

def x?
  @x ||= #boolean calculation
end

Body:
It depends.

@x ||= value

is equivalent to

@x = @x || value

which assigns value to @x only if @x is falsy. In Ruby, only false and nil are falsy.

Further, #present? is a concept from Rails (see doc).

Note though that depending on the value that you expect to store in @x, it might be equivalent. #present? is simply the negation of #blank? (also a Rails concept). #blank? is defined on Object as follows:

def blank?
  respond_to?(:empty?) ? !!empty? : !self
end

Thus, the behavior of the two snippets you posted is guaranteed to be equivalent when @x contains a value that doesn't define its own #present?, #blank?, or #empty? methods.

Now, FalseClass and NilClass both define #blank?:

def blank?
  true
end

TrueClass also defines #blank?:

def blank?
  false
end

But this is just an optimization as the default implementation from Object would result in the same values.

Therefore, false and nil will return false for #present? and true will return true for #present?.

From this we conclude that, in the specific case of storing boolean values in @x, the behavior of the two snippets is equivalent.


问:
Textual geolocation
I need to geolocate a series of entries in a single-country development projects database. I have a brief synopsis for each project within which I would like to identify municipalities (or even larger political entities) to allow me to geolocate each project later on with the GoogleMaps API.

I am trying to extract the geographic information without using natural language processing. I am not keen to use NLP because the project are located in small villages, whose name I can obtain from other sources.

I was considering splitting the text on spaces, and trying to find matches using a Python vocabulary in which the value is the name of the village and the key is the name of the village split at spaces.

Example:

"Project X has been built in The Hague, The Netherlands".
Would give me: "The Hague"

答:
I would suggest to use NLP :-) or at least some algorithms related to NLP.
Here you can find list of cities/towns having more than 500 citizens with information about GPS coordinates, region(s), country and continent http://www.geonames.org/ or http://download.geonames.org/export/dump/readme.txt
I would use these data to build very light-weight Name Entity Recognition using https://pypi.org/project/pyahocorasick/ algorithms.
And after that you can have a nice and neat "tree"/hierarchy of village - small region - bigger region - country - continent (maybe even with GPS coordinates if I am not wrong).</p>

Title: Textual geolocation


问:
How to poll input from Linux /dev/input/eventX
I'm working on a project that requires me to get a touchscreen working on Scientific Linux 6.4 (Linux kernel 2.6.32). Although the kernel does not support the touchscreen fully, I am able to see multi-touch events being generated in the /dev/input/eventX location for the touchscreen when I touch the screen.

I'm trying to write a simple C++ program to read the data from the /dev/input/eventX file and parse it so I can manually deal with the multi-touch events, since that seems the only way I'll get this working.

So I wrote the following program:

std::ifstream input("/dev/input/event10");
if(input.is_open()) {
    while(input.good()) {
        int header;
        input >> header;

        cout << std::hex << header << " ";

        int data[16] = {};
        for(int i = 0; i < 16; i++) {
            input >> data[i];
            cout << std::hex << data[i] << " ";
        }

        cout << endl;
    }

    input.close();
} else cout << "Unable to open event handler for input polling..." << endl;
```

<p>Now, I don't exactly know if my method of reading and parsing the input itself is correct, but when I use the following command in bash:</p>

```sudo cat /dev/input/event10 | hexdump -C
```

I get the input data in the form of a number of lines beginning with an 8-digit hex value followed by 16 2-digit hex values (bytes).

The problem I'm having though is that I always get the message "Unable to open event handler for input polling..." suggesting an issue with opening the file. At first, I thought maybe that because nothing is in that file until an event is generated, it might not be able to be opened as an ifstream. I also tried running the program as sudo just in case it was a permissions issue and got the same message, so I believe it has to do with how I'm opening the file.

Does anyone know the proper way to open and read from these files?

EDIT: My question is regarding why the file is unable to be opened, not necessarily just how to parse the data. The suggested "duplicate" questions don't provide any helpful information in this regard.

答: Nevermind... there was a trailing space in my filename (which was detected rather than hard-coded). I added a trim function and now it opens just fine.</p>

Body:
I'm working on a project that requires me to get a touchscreen working on Scientific Linux 6.4 (Linux kernel 2.6.32). Although the kernel does not support the touchscreen fully, I am able to see multi-touch events being generated in the /dev/input/eventX location for the touchscreen when I touch the screen.

I'm trying to write a simple C++ program to read the data from the /dev/input/eventX file and parse it so I can manually deal with the multi-touch events, since that seems the only way I'll get this working.

So I wrote the following program:

std::ifstream input("/dev/input/event10");
if(input.is_open()) {
    while(input.good()) {
        int header;
        input >> header;

        cout << std::hex << header << " ";

        int data[16] = {};
        for(int i = 0; i < 16; i++) {
            input >> data[i];
            cout << std::hex << data[i] << " ";
        }

        cout << endl;
    }

    input.close();
} else cout << "Unable to open event handler for input polling..." << endl;

Now, I don't exactly know if my method of reading and parsing the input itself is correct, but when I use the following command in bash:

sudo cat /dev/input/event10 | hexdump -C

I get the input data in the form of a number of lines beginning with an 8-digit hex value followed by 16 2-digit hex values (bytes).

The problem I'm having though is that I always get the message "Unable to open event handler for input polling..." suggesting an issue with opening the file. At first, I thought maybe that because nothing is in that file until an event is generated, it might not be able to be opened as an ifstream. I also tried running the program as sudo just in case it was a permissions issue and got the same message, so I believe it has to do with how I'm opening the file.

Does anyone know the proper way to open and read from these files?

EDIT: My question is regarding why the file is unable to be opened, not necessarily just how to parse the data. The suggested "duplicate" questions don't provide any helpful information in this regard.


问:
Excel Template: Merging data and saving workbooks
I am on my first foray into Excel Interop and after a flying start have hit a wall.

I have an Excel template that contains one sheet which is an assessment form and another which contains guidance notes for how to carry out the assessment.

I also have an XML file with the details of the projects being assessed.

I need to merge the project title, application number and company name into the first sheet and then save the sheet with the filename [Application No] - [Project Title].xlsx.

The first part is working fine.  I have Loaded the XML and the code is putting the data into the form where it should be.

My problem is the saving part.  I found the .SaveAs method and it creates a couple of files... but they won't open.  I then get a HRESULT error 0x800A03EC - Searching the web has explained nothing about this.  Something is telling me that this.SaveAs() is referring to the worksheet rather than the work book but I am just guessing there.

I am hoping I have done something stupid and it is an easy fix.

For reference here is my code but like I say I am not sure how useful it is.

```<code>    private void MergeData()
    {
        doc.Load(@"C:\XML Data\source.xml");

        XmlNodeList forms = doc.SelectNodes("//form1");

        for (int i = 0; i < forms.Count; i++)
        {
            XmlNodeList nodes = forms[i].ChildNodes;

            string refNo = nodes[0].InnerText.ToString();
            string companyName = nodes[3].InnerText.ToString();
            string title = nodes[1].InnerText.ToString();

            this.Cells[9, 4] = title;
            this.Cells[11, 4] = refNo;
            this.Cells[14, 4] = companyName;

            this.SaveAs(@"C:\Assessment Forms\" + refNo + " - " + title + ".xlsx");
        }
    }
</code>```

Does anyone know how to save these files?

Thanks for reading

EDIT--

I have found this article

C# and Excel Interop issue, Saving the excel file not smooth

and changed the code to include its suggestion

```<code>Excel.Application app = this.Application;
Excel.Workbook wb = app.Workbooks.Add(missing);
wb.SaveAs(@"C:\Assessment Forms\" + refNo + " - " + title + ".xlsx");
</code>```

But it is doing the same.

I am on a deadline so think I am going to have to start copying, pasting and saving manually :(

答:
Not sure what object this is here, but if you are correct in assuming this is a worksheet, try this.Parent.SaveAs

Alternatively if this turns out to be a range, try this.Worksheet.Parent.SaveAs

Body:
I am on my first foray into Excel Interop and after a flying start have hit a wall.

I have an Excel template that contains one sheet which is an assessment form and another which contains guidance notes for how to carry out the assessment.

I also have an XML file with the details of the projects being assessed.

I need to merge the project title, application number and company name into the first sheet and then save the sheet with the filename [Application No] - [Project Title].xlsx.

The first part is working fine.  I have Loaded the XML and the code is putting the data into the form where it should be.

My problem is the saving part.  I found the .SaveAs method and it creates a couple of files... but they won't open.  I then get a HRESULT error 0x800A03EC - Searching the web has explained nothing about this.  Something is telling me that this.SaveAs() is referring to the worksheet rather than the work book but I am just guessing there.

I am hoping I have done something stupid and it is an easy fix.

For reference here is my code but like I say I am not sure how useful it is.

    private void MergeData()
    {
        doc.Load(@"C:\XML Data\source.xml");

        XmlNodeList forms = doc.SelectNodes("//form1");

        for (int i = 0; i < forms.Count; i++)
        {
            XmlNodeList nodes = forms[i].ChildNodes;

            string refNo = nodes[0].InnerText.ToString();
            string companyName = nodes[3].InnerText.ToString();
            string title = nodes[1].InnerText.ToString();

            this.Cells[9, 4] = title;
            this.Cells[11, 4] = refNo;
            this.Cells[14, 4] = companyName;

            this.SaveAs(@"C:\Assessment Forms\" + refNo + " - " + title + ".xlsx");
        }
    }

Does anyone know how to save these files?

Thanks for reading

EDIT--

I have found this article

C# and Excel Interop issue, Saving the excel file not smooth

and changed the code to include its suggestion

Excel.Application app = this.Application;
Excel.Workbook wb = app.Workbooks.Add(missing);
wb.SaveAs(@"C:\Assessment Forms\" + refNo + " - " + title + ".xlsx");

But it is doing the same.

I am on a deadline so think I am going to have to start copying, pasting and saving manually :(


答:
You should not use either option for memoizing boolean values as both will recalculate if @x is false.

present? is a special kind of rails check that equates to !blank? and false.blank? #=> true but even if this was not a boolean check present? and || are not equivalent. For objects that implement empty? blank defers to that so something that is empty? is also blank? and thus is not present?.

```<code>"".present? #=> false
"" || true #=> ""
[].present? #=> false
[] || true #=> []
false.present? #=> false
false || true #=> true
</code>```

@x ||= some_logic equates to @x = @x || some_logic where obviously if @x is false some_logic will fire.

If you just want to see if @x has already been determined to be a value (e.g. not nil) then you could replace this with

```<code>def x?
  return @x unless @x.nil?
  @x = some_logic
end
</code>```

Title: Does @x ||= work like return @x if @x.present?

Body:
You should not use either option for memoizing boolean values as both will recalculate if @x is false.

present? is a special kind of rails check that equates to !blank? and false.blank? #=> true but even if this was not a boolean check present? and || are not equivalent. For objects that implement empty? blank defers to that so something that is empty? is also blank? and thus is not present?.

"".present? #=> false
"" || true #=> ""
[].present? #=> false
[] || true #=> []
false.present? #=> false
false || true #=> true

@x ||= some_logic equates to @x = @x || some_logic where obviously if @x is false some_logic will fire.

If you just want to see if @x has already been determined to be a value (e.g. not nil) then you could replace this with

def x?
  return @x unless @x.nil?
  @x = some_logic
end


问:
Import of client scenarios
I import a file to update the client, but when I go to the AR303000 screen, an error appears.

please someone to tell me what is wrong, thanks to everyone.

答:
The error message implies that you are importing Customer ID that already exists in the database. It is a duplicate validation error. Customer ID is used as a key field and key fields must be unique in database.

If I were to import a customer with Customer ID ABARTENDE, I would expect this error because a customer with that ID already exists in the system:

EDIT:
Issue was duplicate ID in customization. Was confused with the import scenario.

Title: Import of client scenarios


问:
Dynamically setting state object by passing it as variable name : React
I have this scenario where I need to send a list of state object variables, and then dynamically set them inside the setState function by using the passed variable. Trying to achieve the same.
I am maintaining one setState functions, to which I will be passing state variables which are then set accordingly.

Am I going somewhere wrong?

Help would be appreciated.

Relevant snippet has been posted

```<code>constructor()
{
  super(props);
  this.state ={
      val1 : '',
      val2: '',
      val3: '',
  }
}

fetchValues = (stateVariable) =>{  // here the stateVariable ie val1,val2,val3 will be passed .

  //fetching a value that will be set to the state object variables
   this.set(stateVariable,value)
}

set = (val) => {
 this.setState(`${val}`: val
}
</code>```

答:
You can do that this way:

```<code>const set = val => {
  this.setState({ [val]: val });
};
</code>```

Plus you had issues like:

There's no => after (val).

The closing braces aren't right.

You're missing a const.

Fixed everything for you.

Quick demo for you.

var val = "Praveen";

console.log({ [val]: val });```

Body:
I have this scenario where I need to send a list of state object variables, and then dynamically set them inside the setState function by using the passed variable. Trying to achieve the same.
I am maintaining one setState functions, to which I will be passing state variables which are then set accordingly.

Am I going somewhere wrong?

Help would be appreciated.

Relevant snippet has been posted

constructor()
{
  super(props);
  this.state ={
      val1 : '',
      val2: '',
      val3: '',
  }
}

fetchValues = (stateVariable) =>{  // here the stateVariable ie val1,val2,val3 will be passed .

  //fetching a value that will be set to the state object variables
   this.set(stateVariable,value)
}

set = (val) => {
 this.setState(`${val}`: val
}

Body:
You can do that this way:

const set = val => {
  this.setState({ [val]: val });
};

Plus you had issues like:

There's no => after (val).

The closing braces aren't right.

You're missing a const.

Fixed everything for you.

Quick demo for you.

var val = "Praveen";

console.log({ [val]: val });


问:
Prevent DB query if relation was not loaded
I have 2 models, for example, Country and City with relations one-to-many.

When I run this code

```<code>$countries = Country::query()->with('cities')->get();

foreach ($countries as $country) {
    $cities = $country->cities;

    foreach ($cities as $city) {
        dump($city->country);
    }
}
</code>```

, on the each $city->country call I have a query to DB

```<code>select * from `countries` where `countries`.`id` = ? limit 1
</code>```

If relation (in my case cities.country) was not loaded with eager loading, is there a possibility to prevent making DB query on the each $city->county call?

I no need the $country variable. I need to get null if relation cities.country was not loaded in the main query.

答:
Thanks to

https://laracasts.com/discuss/channels/laravel/how-to-check-if-an-relationship-has-been-eager-loaded-or-not

In my case

```<code>//...
if ($city->relationLoaded('country')) {
    dump($city->country);
} else {
    dump(null);
}
//...

</code>```

Body:
I have 2 models, for example, Country and City with relations one-to-many.

When I run this code

$countries = Country::query()->with('cities')->get();

foreach ($countries as $country) {
    $cities = $country->cities;

    foreach ($cities as $city) {
        dump($city->country);
    }
}

, on the each $city->country call I have a query to DB

select * from `countries` where `countries`.`id` = ? limit 1

If relation (in my case cities.country) was not loaded with eager loading, is there a possibility to prevent making DB query on the each $city->county call?

I no need the $country variable. I need to get null if relation cities.country was not loaded in the main query.

Body:
Thanks to

https://laracasts.com/discuss/channels/laravel/how-to-check-if-an-relationship-has-been-eager-loaded-or-not

In my case

//...
if ($city->relationLoaded('country')) {
    dump($city->country);
} else {
    dump(null);
}
//...


问:
how to check if (c#) ControlCollection.Find() has returned a result
I am using ControlCollection.Find() method in C# to find some picture boxes present in my form.

I am storing the returned result in a Control[] array. How do I find out if the Find() was successful or not???

Code

```<code>Control[] temp = pictureBoxCollection.Find(TagNo, true);
if(temp.Length>0)
    UpdateRes = update_status(TagNo, Status);
</code>```

where TagNo is a string containing the Control's exact name.

Yes. I'm using the control's exact name. And I have used the Find() method successfully earlier (when the Control was surely present in the Collection). I am having a problem this time because the control may or may not be present in the Collection.

答:
Find() method will return an empty array (never null) if no controls were found. So you should simply do something like:</p>

```<code>Control[] controls = myForm.Find("picbox", true);
if (controls.Length > 0) {
   // Do logic when picture boxes are found
} else {
   // Do logic when there are no picture boxes
}
</code>```

Body:
I am using ControlCollection.Find() method in C# to find some picture boxes present in my form.

I am storing the returned result in a Control[] array. How do I find out if the Find() was successful or not???

Code

Control[] temp = pictureBoxCollection.Find(TagNo, true);
if(temp.Length>0)
    UpdateRes = update_status(TagNo, Status);

where TagNo is a string containing the Control's exact name.

Yes. I'm using the control's exact name. And I have used the Find() method successfully earlier (when the Control was surely present in the Collection). I am having a problem this time because the control may or may not be present in the Collection.

Body:
Find() method will return an empty array (never null) if no controls were found. So you should simply do something like:

Control[] controls = myForm.Find("picbox", true);
if (controls.Length > 0) {
   // Do logic when picture boxes are found
} else {
   // Do logic when there are no picture boxes
}


问:
PHP - go to Next or Previous file in directory
We're making a portfolio with pages in a directory like:

```<code>/portfolio/a-company-name.php
/portfolio/another-company-name.php
/portfolio/yet-another-company-name.php
</code>```

We want to build "next" and "previous" links on each page, where people can navigate to the next or previous page in the directory. Any ideas?

I would think the only little snag might occur on the first and last files in the directory. So I guess there'd have to be an "if statement" of some sort to only build next/previous link if there's actually a next/previous file in the directory. Or, even better, to where it would just endlessly loop....for example if you were on the last file in the directory, and the "next" link would simply go to the first file.

答:
Find all PHP files in the directory with the glob function and save them to an array.

Next, by the name of the current file, find its index in the file array and increase by 1 to get the name of the next file.

```<code>$page = dirname(__FILE__) . '/portfolio'.$_SERVER['REQUEST_URI'].'.php';

$files = glob(dirname(__FILE__) . '/portfolio/*.php');

$currentIdx = array_search($page, $files);

$nextIdx = $currentIdx + 1;

if (isset($files[$nextIdx]))
{
    $nextFile = $files[$nextIdx];
    $next = pathinfo($nextFile, PATHINFO_FILENAME);
    echo 'Next file: <a href="'.$next.'">'.$next.'</a>';
}
else
{
    echo "No next file";
}
</code>```

Previous similarly:

```<code>$page = dirname(__FILE__) . '/portfolio'.$_SERVER['REQUEST_URI'].'.php';
$files = glob(dirname(__FILE__) . '/portfolio/*.php');
$currentIdx = array_search($page, $files);
$prevIdx = $currentIdx - 1;
if (isset($files[$prevIdx])) {
    $prevFile = $files[$prevIdx];
    $prev = pathinfo($prevFile,PATHINFO_FILENAME);
    echo 'Previous file: <a href="'.$prev.'">'.$prev.'</a>';
} else {
    echo "No previous file";
}
</code>```

Body:
We're making a portfolio with pages in a directory like:

/portfolio/a-company-name.php
/portfolio/another-company-name.php
/portfolio/yet-another-company-name.php

We want to build "next" and "previous" links on each page, where people can navigate to the next or previous page in the directory. Any ideas?

I would think the only little snag might occur on the first and last files in the directory. So I guess there'd have to be an "if statement" of some sort to only build next/previous link if there's actually a next/previous file in the directory. Or, even better, to where it would just endlessly loop....for example if you were on the last file in the directory, and the "next" link would simply go to the first file.

Body:
Find all PHP files in the directory with the glob function and save them to an array.

Next, by the name of the current file, find its index in the file array and increase by 1 to get the name of the next file.

$page = dirname(__FILE__) . '/portfolio'.$_SERVER['REQUEST_URI'].'.php';

$files = glob(dirname(__FILE__) . '/portfolio/*.php');

$currentIdx = array_search($page, $files);

$nextIdx = $currentIdx + 1;

if (isset($files[$nextIdx]))
{
    $nextFile = $files[$nextIdx];
    $next = pathinfo($nextFile, PATHINFO_FILENAME);
    echo 'Next file: <a href="'.$next.'">'.$next.'</a>';
}
else
{
    echo "No next file";
}

Previous similarly:

$page = dirname(__FILE__) . '/portfolio'.$_SERVER['REQUEST_URI'].'.php';
$files = glob(dirname(__FILE__) . '/portfolio/*.php');
$currentIdx = array_search($page, $files);
$prevIdx = $currentIdx - 1;
if (isset($files[$prevIdx])) {
    $prevFile = $files[$prevIdx];
    $prev = pathinfo($prevFile,PATHINFO_FILENAME);
    echo 'Previous file: <a href="'.$prev.'">'.$prev.'</a>';
} else {
    echo "No previous file";
}


问:
how to pass variable from php to sed?
I'm have a raspbian running on a raspberry pi3, I'm making a system that requires the person to choose the hostname by typing it into a field. And to swap the hostname, I need to change two files inside the /etc/ folder.

I have already managed to make these changes by the sed command, however since I want the person to choose the hostname, I made a form for PHP and wanted to take this variable by POST and pass it on to the sed command.

```<code><link rel="stylesheet" type="text/css" href="css/style.css">

<form method="POST">

<input  type="text" name="hostname">
<input type="submit" name="Comentar" value=" Salvar">

</form>

<?php

if(isset($_POST['Comentar'])){
        echo "botão foi clicado"."<br/>";
        $SEU_HOSTNAME = $_POST["hostname"];
        echo  "hostname digitado: ".$SEU_HOSTNAME;

    shell_exec ('

        cd /etc/
        sudo sed -i "s/nome/${SEU_HOSTNAME}/" hosts
        sudo sed -i "s/nome/${SEU_HOSTNAME}/" hostname
    ');

    }

?>
</code>```

Only {} appears in the file that is modified. Would anyone know what I could change?

答:
You can only do the variable names in double quotes.</p>

```<code>shell_exec ('

    cd /etc/
    sudo sed -i "s/nome/'.$SEU_HOSTNAME.'/" hosts
    sudo sed -i "s/nome/'.$SEU_HOSTNAME.'/" hostname
');
</code>```

Title: how to pass variable from php to sed?

Body:
I'm have a raspbian running on a raspberry pi3, I'm making a system that requires the person to choose the hostname by typing it into a field. And to swap the hostname, I need to change two files inside the /etc/ folder.

I have already managed to make these changes by the sed command, however since I want the person to choose the hostname, I made a form for PHP and wanted to take this variable by POST and pass it on to the sed command.

<link rel="stylesheet" type="text/css" href="css/style.css">

<form method="POST">

<input  type="text" name="hostname">
<input type="submit" name="Comentar" value=" Salvar">

</form>

<?php

if(isset($_POST['Comentar'])){
        echo "botão foi clicado"."
";
        $SEU_HOSTNAME = $_POST["hostname"];
        echo  "hostname digitado: ".$SEU_HOSTNAME;

    shell_exec ('

        cd /etc/
        sudo sed -i "s/nome/${SEU_HOSTNAME}/" hosts
        sudo sed -i "s/nome/${SEU_HOSTNAME}/" hostname
    ');

    }

?>

Only {} appears in the file that is modified. Would anyone know what I could change?

Body:
You can only do the variable names in double quotes.

shell_exec ('

    cd /etc/
    sudo sed -i "s/nome/'.$SEU_HOSTNAME.'/" hosts
    sudo sed -i "s/nome/'.$SEU_HOSTNAME.'/" hostname
');