问:
Printing null pointers with %p is undefined behavior?
Is it undefined behavior to print null pointers with the %p conversion specifier?

```<code>#include <stdio.h>

int main(void) {
    void *p = NULL;

    printf("%p", p);

    return 0;
}
</code>```

The question applies to the C standard, and not to C implementations.

答:
This is one of those weird corner cases where we're subject to the limitations of the English language and inconsistent structure in the standard.  So at best, I can make a compelling counter-argument, as it's impossible to prove it :)1

The code in the question exhibits well-defined behaviour.

As [7.1.4] is the basis of the question, let's start there:

Each of the following statements applies unless explicitly stated otherwise in the detailed descriptions that follow: If an argument to a function has an invalid value (such as a value outside the domain of the function, or a pointer outside the address space of the program, or a null pointer, [... other examples ...]) [...] the behavior is undefined. [... other statements ...]

This is clumsy language.  One interpretation is that the items in the list are UB for all library functions, unless overridden by the individual descriptions.  But the list starts with "such as", indicating that it's illustrative, not exhaustive.  For example, it does not mention correct null-termination of strings (critical for the behaviour of e.g. strcpy).

Thus it's clear the intent/scope of 7.1.4 is simply that an "invalid value" leads to UB (unless stated otherwise).  We have to look to each function's description to determine what counts as an "invalid value".

Example 1 - strcpy

[7.21.2.3] says only this:

The strcpy function copies the string pointed to by s2 (including the terminating null character) into the array pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.

It makes no explicit mention of null pointers, yet it makes no mention of null terminators either.  Instead, one infers from "string pointed to by s2" that the only valid values are strings (i.e. pointers to null-terminated character arrays).

Indeed, this pattern can be seen throughout the individual descriptions. Some other examples:

[7.6.4.1 (fenv)] store the current floating-point environment in the object pointed to by envp

[7.12.6.4 (frexp)] store the integer in the int object pointed to by exp

[7.19.5.1 (fclose)] the stream pointed to by stream

Example 2 - printf

[7.19.6.1] says this about %p:

p - The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

Null is a valid pointer value, and this section makes no explicit mention that null is a special case, nor that the pointer has to point at an object.  Thus it is defined behaviour.

1. Unless a standards author comes forward, or unless we can find something similar to a rationale document that clarifies things.

Body:
Is it undefined behavior to print null pointers with the %p conversion specifier?

#include <stdio.h>

int main(void) {
    void *p = NULL;

    printf("%p", p);

    return 0;
}

The question applies to the C standard, and not to C implementations.


来源: stackexchange

问:
Dot notation vs. message notation for declared properties
We now have the "dot" notation for properties.  I've seen various back and forths about the merits of dot notation vs. message notation.  To keep the responses untainted I'm not going to respond either way in the question.

What is your thought about dot notation vs. message notation for property accessing?

Please try to keep it focused on Objective-C - my one bias I'll put forth is that Objective-C is Objective-C, so your preference that it be like Java or JavaScript aren't valid.

Valid commentary is to do with technical issues (operation ordering, cast precedence, performance, etc), clarity (structure vs. object nature, both pro and con!), succinctness, etc.

Note, I'm of the school of rigorous quality and readability in code having worked on huge projects where code convention and quality is paramount (the write once read a thousand times paradigm).

答:
OK, dot notation in Objective-C looks strange, indeed. But I still can't do the following without it:

```<code>int width = self.frame.size.width;
</code>```

Works fine, but:

```<code>int height = [[[self frame] size] height];
</code>```

Gives me "Cannot convert to a pointer type". I'd really like to keep my code looking consistent with message notation, though.

ContentLicense: CC BY-SA 3.0

Body:
OK, dot notation in Objective-C looks strange, indeed. But I still can't do the following without it:

int width = self.frame.size.width;

Works fine, but:

int height = [[[self frame] size] height];

Gives me "Cannot convert to a pointer type". I'd really like to keep my code looking consistent with message notation, though.

ContentLicense: CC BY-SA 2.5


问:
Regex exclude word from matches
Does anyone know what am I doing wrong?
I have this sentence:

```<code>hi [user=1234]John Jack[/user] take me home
</code>```

and I need regex which select only John Jack

My regex:

```<code>(\[user=\d\d\d\d](.+?)\[\/user\])(?!(\[user=\d\d\d\d\])|(\[\/user\]))
</code>```

I want exclude [user=1234] and [/user]

This (\[user=\d\d\d\d](.+?)\[\/user\]) selects [user=1234]John Jack[/user] but I want only John Jack

Full example:

hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha
  [\user] where you are [differentTag] hm?  [/differentTag]. Peter Im
  here with [user=1]Danny Di [\user]

答:
Try this:

```<code>String s = "hi [user=1234]John Jack[/user] take me home";
// assuming user id has always 4 decimals
Pattern p = Pattern.compile("(?<=\\[user=\\d{4}\\]).+(?=\\[/user\\])");
Matcher m = p.matcher(s);
m.find();
System.out.println(s.substring(m.start(), m.end()));
</code>```

Note, you can not use in "lookbehind" pattern of variable length like (?<=.+). So if you know, that user id has at max e.g. 11 places, then you can use:

```<code>Pattern.compile("(?<=\\[user=\\d{4,11}\\]).+(?=\\[/user\\])");
</code>```

For more details about regex see: Pattern javadoc

Title: Regex exclude word from matches

Body:
Does anyone know what am I doing wrong?
I have this sentence:

hi [user=1234]John Jack[/user] take me home

and I need regex which select only John Jack

My regex:

(\[user=\d\d\d\d](.+?)\[\/user\])(?!(\[user=\d\d\d\d\])|(\[\/user\]))

I want exclude [user=1234] and [/user]

This (\[user=\d\d\d\d](.+?)\[\/user\]) selects [user=1234]John Jack[/user] but I want only John Jack

Full example:

hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha
  [\user] where you are [differentTag] hm?  [/differentTag]. Peter Im
  here with [user=1]Danny Di [\user]

Body:
Try this:

String s = "hi [user=1234]John Jack[/user] take me home";
// assuming user id has always 4 decimals
Pattern p = Pattern.compile("(?<=\\[user=\\d{4}\\]).+(?=\\[/user\\])");
Matcher m = p.matcher(s);
m.find();
System.out.println(s.substring(m.start(), m.end()));

Note, you can not use in "lookbehind" pattern of variable length like (?<=.+). So if you know, that user id has at max e.g. 11 places, then you can use:

Pattern.compile("(?<=\\[user=\\d{4,11}\\]).+(?=\\[/user\\])");

For more details about regex see: Pattern javadoc


问:
How to check if a string contains an element from an array in Perl
I want to check if string $name ends with any of the elements from $end array_ref</p>

```<code>my $end=['.a[bc', '.de[f', '.xy]z'];
my $name="test.a[bc";

# But this is not working:
if(grep{$name=~m/\Q.+$_$/} @{$end}) { print "Yes\n"; } else {print "No\n"; } # prints "No"
</code>```

答:
In order to use grep() , you need to convert the $end variable to an array by using split(). Note that grep(/pattern/,@array) searches for /pattern/ in each element of @array. Since you are searching for last four characters in your pattern , we need to separate it first.

```<code>my $end="'.a[bc', '.de[f', '.xy]z'";
my @array = split(',',$end);
my $name="test.a[bc";
my $name_end = substr($name,-5);

if( grep( m/\Q$name_end/ , @array ) ) {
    print "Yes\n";
}
else {
    print "No\n";
} # prints "No";
</code>```

An alternative would be to to search in the $end for each array element by looping. The above solution works however. Let me know your feedback.

Body:
I want to check if string $name ends with any of the elements from $end array_ref

my $end=['.a[bc', '.de[f', '.xy]z'];
my $name="test.a[bc";

# But this is not working:
if(grep{$name=~m/\Q.+$_$/} @{$end}) { print "Yes\n"; } else {print "No\n"; } # prints "No"

Body:
In order to use grep() , you need to convert the $end variable to an array by using split(). Note that grep(/pattern/,@array) searches for /pattern/ in each element of @array. Since you are searching for last four characters in your pattern , we need to separate it first.

my $end="'.a[bc', '.de[f', '.xy]z'";
my @array = split(',',$end);
my $name="test.a[bc";
my $name_end = substr($name,-5);

if( grep( m/\Q$name_end/ , @array ) ) {
    print "Yes\n";
}
else {
    print "No\n";
} # prints "No";

An alternative would be to to search in the $end for each array element by looping. The above solution works however. Let me know your feedback.


问:
"Python has stopped Working" when training a convolution neural net in tensorflow gpu
This is a tensorflow code I wrote to test convolution neural net with only 1 convolution and pooling layer with only 1 fully connected layer of 512 neurons.

My dataset is of only 2 images: http://imgur.com/et1Sn1k and http://imgur.com/ZWxOGgO

When I train my network windows gives an pop up saying "Python has stoped" (ss: http://imgur.com/tc5jWlA )

This is my code:

```<code>from scipy.misc import imread
import matplotlib.pyplot as plt
import numpy as np
import PIL.Image as Image

base_image = imread("base_image.jpg")
subject_image = imread("subject_image.jpg")

base_image = np.resize(base_image, [1024, 768, 3])
subject_image = np.resize(subject_image, [1024, 768, 3])

images = []

images.append(base_image)
images.append(subject_image)

# hyper parameters

epochs = 10
batch_size = 2
learning_rate = 0.01
n_classes = 2
import tensorflow as tf

# Model

x = tf.placeholder('float', [2, 1024, 768, 3])
y = tf.placeholder('float', [2])

weights = {
            "conv": tf.random_normal([10, 10, 3, 32]),
            "fc": tf.random_normal([-1, 512]), #7*7*64
            "out": tf.Variable(tf.random_normal([512, n_classes]))
}

conv = tf.nn.conv2d(x, filter=weights['conv'], strides=[1, 1, 1, 1], padding="SAME")
conv = tf.nn.max_pool(value=conv, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME")

fc = tf.reshape(conv, shape=[2,-1])
fc = tf.nn.relu(tf.matmul(fc, weights['fc']))

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

loss = tf.reduce_mean((output - y)**2)

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

sess = tf.Session()

sess.run(tf.global_variables_initializer())

for i in range(epochs):
    sess.run(train, feed_dict={x: images, y: [0, 1]})
    print(i)
</code>```

Output:

```<code>2017-07-09 02:29:43.688699: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.689131: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.689504: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.689998: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.690380: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.690646: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.691117: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.691436: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:44.197766: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:940] Found device 0 with properties:
name: GeForce GTX 960M
major: 5 minor: 0 memoryClockRate (GHz) 1.176
pciBusID 0000:01:00.0
Total memory: 4.00GiB
Free memory: 3.35GiB
2017-07-09 02:29:44.198207: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:961] DMA: 0
2017-07-09 02:29:44.198391: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:971] 0:   Y
2017-07-09 02:29:44.198643: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:1030] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 960M, pci bus id: 0000:01:00.0)
2017-07-09 02:29:44.881448: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\framework\op_kernel.cc:1158] Invalid argument: Dimension -1 must be >= 0
2017-07-09 02:29:44.881875: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\framework\op_kernel.cc:1158] Invalid argument: Dimension -1 must be >= 0
     [[Node: random_normal_1/RandomStandardNormal = RandomStandardNormal[T=DT_INT32, dtype=DT_FLOAT, seed=0, seed2=0, _device="/job:localhost/replica:0/task:0/gpu:0"](random_normal_1/shape)]]
2017-07-09 02:29:44.882604: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\framework\op_kernel.cc:1158] Invalid argument: Dimension -1 must be >= 0
     [[Node: random_normal_1/RandomStandardNormal = RandomStandardNormal[T=DT_INT32, dtype=DT_FLOAT, seed=0, seed2=0, _device="/job:localhost/replica:0/task:0/gpu:0"](random_normal_1/shape)]]
2017-07-09 02:29:45.362917: E c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\stream_executor\cuda\cuda_dnn.cc:352] Loaded runtime CuDNN library: 6021 (compatibility version 6000) but source was compiled with 5105 (compatibility version 5100).  If using a binary install, upgrade your CuDNN library to match.  If building from sources, make sure the library loaded at runtime matches a compatible version specified during compile configuration.
2017-07-09 02:29:45.364154: F c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\kernels\conv_ops.cc:671] Check failed: stream->parent()->GetConvolveAlgorithms(&algorithms)
[Finished in 22.7s with exit code 3221226505]
[shell_cmd: python -u "E:\workspace_py\convolotion_neural_net.py"]
[dir: E:\workspace_py]
[path: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\libnvvp;E:\Program Files\Python 3.5\Scripts\;E:\Program Files\Python 3.5\;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Python27\Scripts;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;E:\Program Files\MATLAB\runtime\win64;E:\Program Files\MATLAB\bin;E:\Program Files\MATLAB\polyspace\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Python27\Scripts;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;E:\Program Files\MATLAB\runtime\win64;E:\Program Files\MATLAB\bin;E:\Program Files\MATLAB\polyspace\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Users\guita\AppData\Local\Microsoft\WindowsApps;E:\Program Files\Python27\Scipts;e:\Program Files (x86)\Microsoft VS Code\bin;C:\Users\guita\AppData\Local\atom\bin]
</code>```

My pc specs (Lenovo Y50):
Nvidia GTX 960m 4 GB memory,
Intel I7 4th gen,
8 GB RAM

Python 3.5 + Tensorflow with GPU

答: So I managed to fix it on my own. This happened because my cuDNN version was 6.0 but tensorflow works best 5.1. Also there's some minute errors in the code but that irrelevant :p </p>

Body:
This is a tensorflow code I wrote to test convolution neural net with only 1 convolution and pooling layer with only 1 fully connected layer of 512 neurons.

My dataset is of only 2 images: http://imgur.com/et1Sn1k and http://imgur.com/ZWxOGgO

When I train my network windows gives an pop up saying "Python has stoped" (ss: http://imgur.com/tc5jWlA )

This is my code:

from scipy.misc import imread
import matplotlib.pyplot as plt
import numpy as np
import PIL.Image as Image

base_image = imread("base_image.jpg")
subject_image = imread("subject_image.jpg")

base_image = np.resize(base_image, [1024, 768, 3])
subject_image = np.resize(subject_image, [1024, 768, 3])

images = []

images.append(base_image)
images.append(subject_image)

# hyper parameters

epochs = 10
batch_size = 2
learning_rate = 0.01
n_classes = 2
import tensorflow as tf

# Model

x = tf.placeholder('float', [2, 1024, 768, 3])
y = tf.placeholder('float', [2])

weights = {
            "conv": tf.random_normal([10, 10, 3, 32]),
            "fc": tf.random_normal([-1, 512]), #7*7*64
            "out": tf.Variable(tf.random_normal([512, n_classes]))
}

conv = tf.nn.conv2d(x, filter=weights['conv'], strides=[1, 1, 1, 1], padding="SAME")
conv = tf.nn.max_pool(value=conv, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME")

fc = tf.reshape(conv, shape=[2,-1])
fc = tf.nn.relu(tf.matmul(fc, weights['fc']))

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

loss = tf.reduce_mean((output - y)**2)

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

sess = tf.Session()

sess.run(tf.global_variables_initializer())

for i in range(epochs):
    sess.run(train, feed_dict={x: images, y: [0, 1]})
    print(i)

Output:

2017-07-09 02:29:43.688699: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.689131: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.689504: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.689998: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.690380: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.690646: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.691117: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.691436: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:44.197766: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:940] Found device 0 with properties:
name: GeForce GTX 960M
major: 5 minor: 0 memoryClockRate (GHz) 1.176
pciBusID 0000:01:00.0
Total memory: 4.00GiB
Free memory: 3.35GiB
2017-07-09 02:29:44.198207: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:961] DMA: 0
2017-07-09 02:29:44.198391: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:971] 0:   Y
2017-07-09 02:29:44.198643: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:1030] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 960M, pci bus id: 0000:01:00.0)
2017-07-09 02:29:44.881448: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\framework\op_kernel.cc:1158] Invalid argument: Dimension -1 must be >= 0
2017-07-09 02:29:44.881875: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\framework\op_kernel.cc:1158] Invalid argument: Dimension -1 must be >= 0
     [[Node: random_normal_1/RandomStandardNormal = RandomStandardNormal[T=DT_INT32, dtype=DT_FLOAT, seed=0, seed2=0, _device="/job:localhost/replica:0/task:0/gpu:0"](random_normal_1/shape)]]
2017-07-09 02:29:44.882604: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\framework\op_kernel.cc:1158] Invalid argument: Dimension -1 must be >= 0
     [[Node: random_normal_1/RandomStandardNormal = RandomStandardNormal[T=DT_INT32, dtype=DT_FLOAT, seed=0, seed2=0, _device="/job:localhost/replica:0/task:0/gpu:0"](random_normal_1/shape)]]
2017-07-09 02:29:45.362917: E c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\stream_executor\cuda\cuda_dnn.cc:352] Loaded runtime CuDNN library: 6021 (compatibility version 6000) but source was compiled with 5105 (compatibility version 5100).  If using a binary install, upgrade your CuDNN library to match.  If building from sources, make sure the library loaded at runtime matches a compatible version specified during compile configuration.
2017-07-09 02:29:45.364154: F c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\kernels\conv_ops.cc:671] Check failed: stream->parent()->GetConvolveAlgorithms(&algorithms)
[Finished in 22.7s with exit code 3221226505]
[shell_cmd: python -u "E:\workspace_py\convolotion_neural_net.py"]
[dir: E:\workspace_py]
[path: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\libnvvp;E:\Program Files\Python 3.5\Scripts\;E:\Program Files\Python 3.5\;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Python27\Scripts;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;E:\Program Files\MATLAB\runtime\win64;E:\Program Files\MATLAB\bin;E:\Program Files\MATLAB\polyspace\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Python27\Scripts;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;E:\Program Files\MATLAB\runtime\win64;E:\Program Files\MATLAB\bin;E:\Program Files\MATLAB\polyspace\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Users\guita\AppData\Local\Microsoft\WindowsApps;E:\Program Files\Python27\Scipts;e:\Program Files (x86)\Microsoft VS Code\bin;C:\Users\guita\AppData\Local\atom\bin]

My pc specs (Lenovo Y50):
Nvidia GTX 960m 4 GB memory,
Intel I7 4th gen,
8 GB RAM

Python 3.5 + Tensorflow with GPU


问:
Frame Switch to click on a Box (Python Selenium)
I have a problem trying to automate my browser with Selenium on Python. It's been several hours that I block, and since I'm a beginner .. :(

I explain my problem:
I have to reach click on a box of Recaptcha. To do this, my bot must click on a button on the site, which then displays the recaptcha that I have to validate.
Here are the source page screenshot:

The popup of the recaptcha, in which the checkbox is located

The location of the checkbox that I have to click

I try this code:

```<code>time.sleep(5)
browser.switch_to_frame(browser.find_element_by_tag_name("CaptchaPopup"))
browser.switch_to_frame(browser.find_element_by_tag_name("iframe"))
CheckBox = WebDriverWait(browser, 10).until(
        browser.find_element_by_id('recaptcha-anchor').click())

time.sleep(0.7)
CheckBox.click()
</code>```

But the latter returns me an error :(

```<code>selenium.common.exceptions.NoSuchFrameException: Message: no such frame
</code>```

I use Python 2.7.
Do you have a solution ?
Thank you very much in advance!

答:
Try to use below code to handle required check-box:</p>

```<code>from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC

wait(browser, 10).until(EC.frame_to_be_available_and_switch_to_it(browser.find_element_by_xpath('//iframe[contains(@src, "google.com/recaptcha")]')))
wait(browser, 10).until(EC.element_to_be_clickable((By.ID, 'recaptcha-anchor'))).click()
</code>```

Body:
I have a problem trying to automate my browser with Selenium on Python. It's been several hours that I block, and since I'm a beginner .. :(

I explain my problem:
I have to reach click on a box of Recaptcha. To do this, my bot must click on a button on the site, which then displays the recaptcha that I have to validate.
Here are the source page screenshot:

The popup of the recaptcha, in which the checkbox is located

The location of the checkbox that I have to click

I try this code:

time.sleep(5)
browser.switch_to_frame(browser.find_element_by_tag_name("CaptchaPopup"))
browser.switch_to_frame(browser.find_element_by_tag_name("iframe"))
CheckBox = WebDriverWait(browser, 10).until(
        browser.find_element_by_id('recaptcha-anchor').click())

time.sleep(0.7)
CheckBox.click()

But the latter returns me an error :(

selenium.common.exceptions.NoSuchFrameException: Message: no such frame

I use Python 2.7.
Do you have a solution ?
Thank you very much in advance!

Body:
Try to use below code to handle required check-box:

from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC

wait(browser, 10).until(EC.frame_to_be_available_and_switch_to_it(browser.find_element_by_xpath('//iframe[contains(@src, "google.com/recaptcha")]')))
wait(browser, 10).until(EC.element_to_be_clickable((By.ID, 'recaptcha-anchor'))).click()


问:
If cell is touched - move on the another VC [SWIFT]
If cell is touched - move on the another VC, how can i do it?
I tried to do it, but i didn't work.
Here is my code

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "transData" {
        let destination = segue.destination as! WinnerViewController

        let cell = sender as? UITableViewCell

        if cell == cell {
            let indexPath = tableView.indexPath(for: cell!)
            if indexPath == indexPath {
                let productName = users[(indexPath?.row)!]
                destination.winner = productName.name
            }
        }
    }
</code>```

When i touch each cell - it isn't moving.
Please help

答:
EDIT

The answer from @vadian is detailed and correct. The following are just other ways of navigating from a view controller to another.

If you use segue, and want to navigate to the WinnerViewController:

```<code>    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
        performSegue(withIdentifier: "YOUR_SEGUE_IDENTIFIER", sender: indexPath)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "YOUR_SEGUE_IDENTIFIER", let indexPath = sender as? IndexPath {
            let destinationVC = segue.destination as? WinnerViewController
            let productName = users[indexPath.row]
            destinationVC.winner = productName.name
        }
    }
</code>```

If you use Storyboard and pushViewController:

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let productName = users[indexPath.row]

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    guard let destinationVC = storyboard.instantiateViewController(withIdentifier: "YOUR_WINNER_VIEW_IDENTIFIER") as? WinnerViewController else { return}
    destinationVC.winner = productName.name
    navigationController?.pushViewController(destinationVC, animated: true)
}
</code>```

If you use Interface Builder and pushViewController:

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let productName = users[indexPath.row]
    let destinationVC = WinnerViewController(nibName: "YOUR_WINNER_VIEW_NAME", bundle: nil)
    destinationVC.winner = productName.name
    navigationController?.pushViewController(destinationVC, animated: true)
}
</code>```

Body:
If cell is touched - move on the another VC, how can i do it?
I tried to do it, but i didn't work.
Here is my code

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "transData" {
        let destination = segue.destination as! WinnerViewController

        let cell = sender as? UITableViewCell

        if cell == cell {
            let indexPath = tableView.indexPath(for: cell!)
            if indexPath == indexPath {
                let productName = users[(indexPath?.row)!]
                destination.winner = productName.name
            }
        }
    }

When i touch each cell - it isn't moving.
Please help

Body:
EDIT

The answer from @vadian is detailed and correct. The following are just other ways of navigating from a view controller to another.

If you use segue, and want to navigate to the WinnerViewController:

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
        performSegue(withIdentifier: "YOUR_SEGUE_IDENTIFIER", sender: indexPath)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "YOUR_SEGUE_IDENTIFIER", let indexPath = sender as? IndexPath {
            let destinationVC = segue.destination as? WinnerViewController
            let productName = users[indexPath.row]
            destinationVC.winner = productName.name
        }
    }

If you use Storyboard and pushViewController:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let productName = users[indexPath.row]

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    guard let destinationVC = storyboard.instantiateViewController(withIdentifier: "YOUR_WINNER_VIEW_IDENTIFIER") as? WinnerViewController else { return}
    destinationVC.winner = productName.name
    navigationController?.pushViewController(destinationVC, animated: true)
}

If you use Interface Builder and pushViewController:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let productName = users[indexPath.row]
    let destinationVC = WinnerViewController(nibName: "YOUR_WINNER_VIEW_NAME", bundle: nil)
    destinationVC.winner = productName.name
    navigationController?.pushViewController(destinationVC, animated: true)
}


问:
how to get value from other script? (in html)
I want to get value from other script.

(about socket.io) A script -> (about highchart) B script

this is A script

```<code><script>
var socket = io();

socket.on('currTemp', function(data){
    document.getElementById("temp").innerHTML = "Temperature : " + data;
                   ***// I WANT 'data'.***
}); </script>
</code>```

and this is B script

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

....
code
....

setInterval(function () {
var point,
    newVal,
    inc;

if (chartRpm) {
    point = chartRpm.series[0].points[0];
    inc = ------> ***I want 'inc = data '***
    newVal = inc;

    if (newVal < 0 || newVal > 1200) {
        newVal = point.y - inc;
    }

    point.update(newVal);
}}, 2000); </script>
</code>```

this code is in same file. how to do that ?

答:
You can assign a global variable in one script like this:

```<code>window.myVariable = "some_value";
</code>```

and then access it like you would any other variable in your other script;

Body:
I want to get value from other script.

(about socket.io) A script -> (about highchart) B script

this is A script

and this is B script

this code is in same file. how to do that ?

Body:
You can assign a global variable in one script like this:

window.myVariable = "some_value";

and then access it like you would any other variable in your other script;


问:
How does SAS identifies the End of Observation while reading data from csv?
My csv file sales.csv has 8 variables

Employee_ID ,First_Name ,Last_Name,  Gender, Salary ,Job_Title ,country and Emp_Hire_Date

my code is like this :

```<code>%let path = /folders/myfolders/ecprg193;
data work.sales1;
   infile "&path/sales.csv" dlm=',';
   input Employee_ID First_Name $
         Last_Name $ Gender $ Salary
         Job_Title $ Country $;
run;
</code>```

it is basically creation of dataset sales1 from the csv file.

In the code as u can see I hav specified till country variable.
My question is while creating data set work.sales1 how sas Skips the hiredate data in CSV ?

Let me know if any more information is required to answer this question.

答:
From your description your file has 8 fields per line and your program is only reading 7 variables per line.  So it skips the last field because you never read it.

By default SAS will expect variable length records that are separated by the normal end-of-line characters for your operating system. It looks like from your path you are running SAS on Unix so the default end-of-line will be just the linefeed character ('0A'x).  If you created the file on a PC then most likely it actually was created using carriage return and linefeed two byte sequence ('0D0A'x) as the end-of-line.  You can tell SAS which one to use by adding the TERMSTR= option to the INFILE statement.  So add termstr=CRLF if you are reading a PC/Windows file on Unix.

Body:
My csv file sales.csv has 8 variables

Employee_ID ,First_Name ,Last_Name,  Gender, Salary ,Job_Title ,country and Emp_Hire_Date

my code is like this :

%let path = /folders/myfolders/ecprg193;
data work.sales1;
   infile "&path/sales.csv" dlm=',';
   input Employee_ID First_Name $
         Last_Name $ Gender $ Salary
         Job_Title $ Country $;
run;

it is basically creation of dataset sales1 from the csv file.

In the code as u can see I hav specified till country variable.
My question is while creating data set work.sales1 how sas Skips the hiredate data in CSV ?

Let me know if any more information is required to answer this question.


问:
Create a custom Drawable and use it in XML
I am busy creating a less complicated version of NinePatchDrawable that tiles the inner panels instead of stretching them.

I can implement the actual logic to do the rendering and such.

However, I can't find documentation about how to use this Drawable in the XML files. Is this possible? That is, can I have a <tileable-nine-patch>, or some such, tag I can use to define resources?

答:
Starting Android API 24, custom Drawables classes can be used in XML only within your package.

Custom drawables classes may be used in XML in multiple ways:

Using the fully-qualified class name as the XML element name. For this method, the custom drawable class must be a public top-level class.

```<code><com.yourapp.MyCustomDrawable
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:color="#ffff0000"/>
</code>```

Using drawable as the XML element name and specifying the fully-qualified class name from the class attribute. This method may be used for both public top-level classes and public static inner classes.

```<code><drawable xmlns:android="http://schemas.android.com/apk/res/android"
 class="com.myapp.MyTopLevelClass$InnerCustomDrawable"
 android:color="#ffff0000" />
</code>```

Note: that is not supported by support library.

Body:
Starting Android API 24, custom Drawables classes can be used in XML only within your package.

Custom drawables classes may be used in XML in multiple ways:

Using the fully-qualified class name as the XML element name. For this method, the custom drawable class must be a public top-level class.

<com.yourapp.MyCustomDrawable
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:color="#ffff0000"/>

Using drawable as the XML element name and specifying the fully-qualified class name from the class attribute. This method may be used for both public top-level classes and public static inner classes.

<drawable xmlns:android="http://schemas.android.com/apk/res/android"
 class="com.myapp.MyTopLevelClass$InnerCustomDrawable"
 android:color="#ffff0000" />

Note: that is not supported by support library.


问:
PHP using regular expression to parse query string
How do I use preg_match to get a query string from a URL?

http://www.example.com/imgres?imgurl=http://www.example.com/images/blue-diamond-rings.jpg

How do I get 'imgurl' using preg_matches from the above URL?

答:
PHP has functions for parsing URLs and query strings, you don't need to use a regular expression.</p>

```<code>$parts = parse_url("http://www.mysite.com/imgres?imgurl=http://www.mysite.com/images/blue-diamond-rings.jpg");

$query_string = $parts['query'];

parse_str($query_string, $output);

echo $output['imgurl'];
</code>```

Body:
PHP has functions for parsing URLs and query strings, you don't need to use a regular expression.

$parts = parse_url("http://www.mysite.com/imgres?imgurl=http://www.mysite.com/images/blue-diamond-rings.jpg");

$query_string = $parts['query'];

parse_str($query_string, $output);

echo $output['imgurl'];


问:
Setup R shiny server in Azure Virtual Machine
Is it possible to setup R shiny server (open source version) on Azure virtual machine? </p>

答:
You can install Shiny Server normally, connecting through ssh to your R Server following this manual:

```<code>sudo su - \
-c "R -e \"install.packages('shiny', repos='https://cran.rstudio.com/')\""
sudo apt-get update
sudo apt-get install gdebi-core
wget https://download3.rstudio.org/ubuntu-12.04/x86_64/shiny-server-1.5.3.838-amd64.deb
sudo gdebi shiny-server-1.5.3.838-amd64.deb
</code>```

By default Rstudio Server 3838 port is not allowed, to alter this just

go to your Network Security groups

click security group associated with your virtual machine

go to Inbound security rules within selected security group

By default default-allow-ssh should be visible. Click Add+ and allow new name=allow-shiny with protocol=TCP protocol and port range=3838
And that's it.

Open your browser and go to http://your_public_ip:3838 - You should see RStudio login panel.

Same process can be repeated to install RStudio Server

If you have smaller instances some packages installation can be impossible due to memory insufficiency. You can resize your virtual machine just for a time of installation. After installation is done, resize back down

Enjoy!

Body:
You can install Shiny Server normally, connecting through ssh to your R Server following this manual:

sudo su - \
-c "R -e \"install.packages('shiny', repos='https://cran.rstudio.com/')\""
sudo apt-get update
sudo apt-get install gdebi-core
wget https://download3.rstudio.org/ubuntu-12.04/x86_64/shiny-server-1.5.3.838-amd64.deb
sudo gdebi shiny-server-1.5.3.838-amd64.deb

By default Rstudio Server 3838 port is not allowed, to alter this just

go to your Network Security groups

click security group associated with your virtual machine

go to Inbound security rules within selected security group

By default default-allow-ssh should be visible. Click Add+ and allow new name=allow-shiny with protocol=TCP protocol and port range=3838
And that's it.

Open your browser and go to http://your_public_ip:3838 - You should see RStudio login panel.

Same process can be repeated to install RStudio Server

If you have smaller instances some packages installation can be impossible due to memory insufficiency. You can resize your virtual machine just for a time of installation. After installation is done, resize back down

Enjoy!


问:
Rails 5: Bootstrap not styled properly
I am just starting to use bootstrap (I mostly work back-end) and I am a bit confused. I have configured it properly (followed every step of their guide for the bootstrap-gem setup) but when I copy the code for a navbar, from the examples at their site, it is not styled at all (other than positioning).

Please, tell me what code should I provide because I am really out of my league here.

Thank you

My application.js

```<code>//= require jquery3
//= require rails-ujs
//= require turbolinks
//= require popper
//= require bootstrap
//= require_tree .
</code>```

This is added to my Gemfile

```<code>gem 'bootstrap', git: 'https://github.com/twbs/bootstrap-rubygem'
gem 'jquery-rails'
gem 'sprockets-rails'
</code>```

in my application.html.erb

```<code><nav class="navbar navbar-default navbar-fixed-top">
  <div class="container">
    <%= link_to 'Home', movies_path %>
    <% if user_signed_in? %>
        Logged in as <strong><%= current_user.email %></strong>.
        <%= link_to 'Edit profile', edit_user_registration_path, :class => 'navbar-link' %> |
        <%= link_to "Logout", destroy_user_session_path, method: :delete, :class => 'navbar-link' %>
    <% else %>
        <%= link_to "Sign up", new_user_registration_path, :class => 'navbar-link' %> |
        <%= link_to "Login", new_user_session_path, :class => 'navbar-link' %>
    <% end %>
  </div>
</nav>
</code>```

and it's head is

```<code><%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</code>```

Finally in my application.scss

```<code>@import "bootstrap";
</code>```

答:
make sure in application.html.erb  tag you have responsive tag

```<code><meta name="viewport" content="width=device-width, initial-scale=1">
</code>```

below is sample of menu for twitter bootstrap with responsive menu (inside your application.html.erb) --> I custom the menu as your menu

```<code>  <div id="header" class="navbar navbar-fixed-top navbar-default" role="navigation">
    <div class="container-fluid">
      <!-- menu for mobile -->
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-megadropdown-tabs">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <%= link_to 'Home', movies_path %>
      </div>

      <!-- Collect the nav links, forms, and other content for toggling -->
      <div class="collapse navbar-collapse" id="bs-megadropdown-tabs">
        <ul class="nav navbar-nav navbar-right">
        <% if user_signed_in? %>
          <li class="dropdown">
            <a href="#" data-toggle="dropdown" class="dropdown-toggle">MENU <b class="caret"></b></a>
              <ul class="dropdown-menu">
                <li class="divider"></li>
                  <li><%= link_to 'Edit profile', edit_user_registration_path %></li>
                <li><%= link_to "Other menu",  %></li>
              </ul>
          </li>
          <li> <%= link_to "LOG OUT ( #{current_user.username} )", destroy_user_session_path, method: :delete %></li>
         <% else %>
          <li><%= link_to "Sign up", new_user_registration_path, :class => 'navbar-link' %></li>
          <li><%= link_to "Login", new_user_session_path, :class => 'navbar-link' %></li>
        <% end %>
        </ul> <!-- navbar-right  -->
      </div><!-- end navbar-collapse -->
    </div> <!-- end fluid -->
  </div> <!-- end navbar -->
</code>```

Ok for styled properly you have to import css that provided, below I gave you info

inside app/stylesheets/  edit your  application.scss
and add this lines below

```<code>// bootstrap
@import "bootstrap-sprockets";
@import "bootstrap";
</code>```

Title: Rails 5: Bootstrap not styled properly

Body:
I am just starting to use bootstrap (I mostly work back-end) and I am a bit confused. I have configured it properly (followed every step of their guide for the bootstrap-gem setup) but when I copy the code for a navbar, from the examples at their site, it is not styled at all (other than positioning).

Please, tell me what code should I provide because I am really out of my league here.

Thank you

My application.js

//= require jquery3
//= require rails-ujs
//= require turbolinks
//= require popper
//= require bootstrap
//= require_tree .

This is added to my Gemfile

gem 'bootstrap', git: 'https://github.com/twbs/bootstrap-rubygem'
gem 'jquery-rails'
gem 'sprockets-rails'

in my application.html.erb

    <%= link_to 'Home', movies_path %>
    <% if user_signed_in? %>
        Logged in as <%= current_user.email %>.
        <%= link_to 'Edit profile', edit_user_registration_path, :class => 'navbar-link' %> |
        <%= link_to "Logout", destroy_user_session_path, method: :delete, :class => 'navbar-link' %>
    <% else %>
        <%= link_to "Sign up", new_user_registration_path, :class => 'navbar-link' %> |
        <%= link_to "Login", new_user_session_path, :class => 'navbar-link' %>
    <% end %>

and it's head is

<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

Finally in my application.scss

@import "bootstrap";

Body:
make sure in application.html.erb  tag you have responsive tag

<meta name="viewport" content="width=device-width, initial-scale=1">

below is sample of menu for twitter bootstrap with responsive menu (inside your application.html.erb) --> I custom the menu as your menu

  <div id="header" class="navbar navbar-fixed-top navbar-default" role="navigation">
    <div class="container-fluid">
      <!-- menu for mobile -->
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-megadropdown-tabs">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <%= link_to 'Home', movies_path %>
      </div>

      <!-- Collect the nav links, forms, and other content for toggling -->
      <div class="collapse navbar-collapse" id="bs-megadropdown-tabs">
        <ul class="nav navbar-nav navbar-right">
        <% if user_signed_in? %>
          <li class="dropdown">
            <a href="#" data-toggle="dropdown" class="dropdown-toggle">MENU <b class="caret"></b></a>
              <ul class="dropdown-menu">
                <li class="divider"></li>
                  <li><%= link_to 'Edit profile', edit_user_registration_path %></li>
                <li><%= link_to "Other menu",  %></li>
              </ul>
          </li>
          <li> <%= link_to "LOG OUT ( #{current_user.username} )", destroy_user_session_path, method: :delete %></li>
         <% else %>
          <li><%= link_to "Sign up", new_user_registration_path, :class => 'navbar-link' %></li>
          <li><%= link_to "Login", new_user_session_path, :class => 'navbar-link' %></li>
        <% end %>
        </ul> <!-- navbar-right  -->
      </div><!-- end navbar-collapse -->
    </div> <!-- end fluid -->
  </div> <!-- end navbar -->

Ok for styled properly you have to import css that provided, below I gave you info

inside app/stylesheets/  edit your  application.scss
and add this lines below

// bootstrap
@import "bootstrap-sprockets";
@import "bootstrap";


问:
Activity not opens on notification clicked
I am new to android programming please help me out what I am missing.

I receive notification but my messageActivity is not opened

```<code>NotificationManager notificationManager = (NotificationManager)
                                    getSystemService(NOTIFICATION_SERVICE);
                            NotificationCompat.Builder mbuilder = new NotificationCompat.Builder(getApplicationContext())
                                    .setContentTitle("Message from " + name)
                                    .setContentText(message)
                                    .setAutoCancel(true)
                                    .setSmallIcon(R.mipmap.ic_launcher)
                                    .setSound(soundUri);
                            if (strVibratePreference)
                                mbuilder.setVibrate(new long[]{100, 100});
                            notificationManager.notify(110, mbuilder.build());
                            Intent intent=new Intent(MessageService.this,MessageActivity.class);
                            intent.putExtra("name",name);
                            intent.putExtra("phno",_from);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            PendingIntent pendingIntent = PendingIntent.getActivity(MessageService.this,0,intent,0);
                            mbuilder.setContentIntent(pendingIntent);
</code>```

答:
```<code>  Intent intent = new Intent(MessageService.this, MessageActivity.class);
                            intent.putExtra("name",name);
                            intent.putExtra("phno",_from);
                            PendingIntent pIntent = PendingIntent.getActivity(MessageService.this, (int) System.currentTimeMillis(), intent, 0);

                            // Build notification
                            // Actions are just fake
                            Notification noti = new Notification.Builder(MessageService.this)
                                    .setContentTitle("New mail from " + "test@gmail.com")
                                    .setContentText("Subject")
                                    .setContentIntent(pIntent)
                                    .setSmallIcon(R.mipmap.ic_launcher)
                                    .build();

                            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                            // hide the notification after its selected
                            noti.flags |= Notification.FLAG_AUTO_CANCEL;

                            notificationManager.notify(0, noti);
</code>```

Body:
I am new to android programming please help me out what I am missing.

I receive notification but my messageActivity is not opened

NotificationManager notificationManager = (NotificationManager)
                                    getSystemService(NOTIFICATION_SERVICE);
                            NotificationCompat.Builder mbuilder = new NotificationCompat.Builder(getApplicationContext())
                                    .setContentTitle("Message from " + name)
                                    .setContentText(message)
                                    .setAutoCancel(true)
                                    .setSmallIcon(R.mipmap.ic_launcher)
                                    .setSound(soundUri);
                            if (strVibratePreference)
                                mbuilder.setVibrate(new long[]{100, 100});
                            notificationManager.notify(110, mbuilder.build());
                            Intent intent=new Intent(MessageService.this,MessageActivity.class);
                            intent.putExtra("name",name);
                            intent.putExtra("phno",_from);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            PendingIntent pendingIntent = PendingIntent.getActivity(MessageService.this,0,intent,0);
                            mbuilder.setContentIntent(pendingIntent);


问:
kafka consumer API consumer.poll() doen't work with no wrong, no exception and just block
I am learning kafka following Apache kafka document. I started it with default configuration.

```<code>bin/zookeeper-server-start.sh config/zookeeper.properties
bin/kafka-server-start.sh config/server.properties &
</code>```

I ran the kafka-console-producer.sh and kafka-console-consumer.sh to produce and consume message, and it was successful. I wrote a java code using producer API to produce message, which is OK. This is verified by kafka-console-consumer.sh. The code is same as Apache Kafka guide:

```<code>Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer",    "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

Producer<String, String> producer = new KafkaProducer<>(props);
for(int i = 0; i < 100; i++)
  producer.send(new ProducerRecord<String, String>("my-topic", Integer.toString(i), Integer.toString(i)));

producer.close();
</code>```

Although producer code works, consumer code doesn't work. There's no Exception, but it just blocks at consumer.poll(100). The code is from Apache Kafka documentation:

```<code>Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "test");
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Arrays.asList("my-topic"));
while (true) {
    ConsumerRecords<String, String> records = consumer.poll(100);
    for (ConsumerRecord<String, String> record : records)
        System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
 }
</code>```

By the way, the example of kafka-console-consumer.sh in Apache Kafka document is successful in consuming message, which is produced to topic "test" by producer :

```<code>bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic test --from-beginning
</code>```

But if I don't connect to zookeeper, but connect to kafka broker directly, then also it doesn't work with no wrong and no exception, it just blocks.

```<code>bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning
</code>```

The kafka version and API version is 0.11.0.0

Why they can't consume messages?

答:
Using --zookeeper parameter means using the old consumer and it works well because you are specifying a Zookeeper server (localhost:2181).

When you want to specify a Kafka broker (so using the new consumer) you have to use the --bootstrap-server option: you are still using the --zookeeper but passing a valid Kafka broker address (localhost:9092).

So for the console consumer application your configuration needs to be --bootstrap-server localhost:9092 instead of --zookeeper localhost:9092.

Regarding your code, are you sure that the poll method is blocked? It should exit after 100 ms (the timeout you have specified) if there are no records but not blocking.

Then from your code I see that producer is sending to "my-topic", the consumer subscribes to "foo" and "bar"; finally the console consumer reads from "test". All are different topics!

ContentLicense: CC BY-SA 4.0

Body:
I am learning kafka following Apache kafka document. I started it with default configuration.

bin/zookeeper-server-start.sh config/zookeeper.properties
bin/kafka-server-start.sh config/server.properties &

I ran the kafka-console-producer.sh and kafka-console-consumer.sh to produce and consume message, and it was successful. I wrote a java code using producer API to produce message, which is OK. This is verified by kafka-console-consumer.sh. The code is same as Apache Kafka guide:

Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer",    "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

Producer<String, String> producer = new KafkaProducer<>(props);
for(int i = 0; i < 100; i++)
  producer.send(new ProducerRecord<String, String>("my-topic", Integer.toString(i), Integer.toString(i)));

producer.close();

Although producer code works, consumer code doesn't work. There's no Exception, but it just blocks at consumer.poll(100). The code is from Apache Kafka documentation:

Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "test");
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Arrays.asList("my-topic"));
while (true) {
    ConsumerRecords<String, String> records = consumer.poll(100);
    for (ConsumerRecord<String, String> record : records)
        System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
 }

By the way, the example of kafka-console-consumer.sh in Apache Kafka document is successful in consuming message, which is produced to topic "test" by producer :

bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic test --from-beginning

But if I don't connect to zookeeper, but connect to kafka broker directly, then also it doesn't work with no wrong and no exception, it just blocks.

bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning

The kafka version and API version is 0.11.0.0

Why they can't consume messages?


问:
Javascript center div on the page include scrolling
In javascript I need to show div content on the center of the browser window; Content of the window is high therefore it has a scroll.

How can I set up div element on the center of the screen independently of the scroll ?

Thanks!

答:
You can use this CSS (You don't need javascript for that):

```<code>#divID{
  width:500px;   /* adjust */
  height:500px;  /* adjust */
  top:50%;
  left:50%;
  margin-left: -250px;  /* half of the width */
  margin-top: -250px;  /* half of the height */
  position:fixed;
}
</code>```

You can check out the demo here including scrolling

You can make the div pretty with additional CSS.

Check out demo

Body:
You can use this CSS (You don't need javascript for that):

#divID{
  width:500px;   /* adjust */
  height:500px;  /* adjust */
  top:50%;
  left:50%;
  margin-left: -250px;  /* half of the width */
  margin-top: -250px;  /* half of the height */
  position:fixed;
}

You can check out the demo here including scrolling

You can make the div pretty with additional CSS.

Check out demo


问:
Trigger .onclick() on hover over another element
I'm trying to trigger an .onclick() event when I hover over another div.

The element that needs to trigger the .onclick() event has the ID #exp_des_p_trig.

.

The element that needs to be triggered has the href value #exp_des_p in an a tag.

.

I can understand the basics/read JS but I can't write it (yet), I'm thinking something like this:

```<code><script>
jQuery('#exp_des_p_trig').hover();
    jQuery('#exp_des_p').onclick();
</script>
</code>```

Can anyone help me correct this so that it works?

UPDATE:

I emailed Visual Composer support about this and this is the response I got:

Instead of triggering a click event you can try attaching vc_active class to the tour vc_tta-tab and vc_tta-panel via js. The vc_active class is responsible for opening a tour content for display.

Thank you for the answers below, it seems that this is a Visual Composer related issue which I will address elsewhere.

答:
As you only need the event for the mouse entering the element, you can use the mouseenter event, and then target the element with the given href and trigger a click

$('#exp_des_p_trig').on('mouseenter', function() {
    $('[href="#exp_des_p"]').trigger('click');
});

$('[href="#exp_des_p"]').on('click', function() {
    console.log('works fine !')
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="exp_des_p_trig">Hover me !</div>
</code>```

Note that triggering a click on an anchor doesn't redirect, it just triggers any event handlers attached.

Body:
I'm trying to trigger an .onclick() event when I hover over another div.

The element that needs to trigger the .onclick() event has the ID #exp_des_p_trig.

.

The element that needs to be triggered has the href value #exp_des_p in an a tag.

.

I can understand the basics/read JS but I can't write it (yet), I'm thinking something like this:

Can anyone help me correct this so that it works?

UPDATE:

I emailed Visual Composer support about this and this is the response I got:

Instead of triggering a click event you can try attaching vc_active class to the tour vc_tta-tab and vc_tta-panel via js. The vc_active class is responsible for opening a tour content for display.

Thank you for the answers below, it seems that this is a Visual Composer related issue which I will address elsewhere.

Body:
As you only need the event for the mouse entering the element, you can use the mouseenter event, and then target the element with the given href and trigger a click

$('#exp_des_p_trig').on('mouseenter', function() {
    $('[href="#exp_des_p"]').trigger('click');
});

$('[href="#exp_des_p"]').on('click', function() {
    console.log('works fine !')
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="exp_des_p_trig">Hover me !</div>
<a href="#exp_des_p"></a>

Note that triggering a click on an anchor doesn't redirect, it just triggers any event handlers attached.


答:
Declare a var globally simply with var data;
Both scripts should be able to access the variable.

Do check out https://www.w3schools.com/js/js_scope.asp.

Title: how to get value from other script? (in html)


问:
Symbolic link not working in chef recipe (vagrant/debian8)
I'm trying to write a Chef recipe to enable a site in nginx, and the symbolic link its creating doesn't seem to be working. The machine I'm provisioning is a Debian8 VM which I'm managing with vagrant.

This is my (very simplistic) recipe:

include_recipe 'apt'

package 'nginx' do
  action :install
  version '1.6.2-5+deb8u4'
end

service 'nginx' do
  action [ :enable, :start ]
end

cookbook_file '/etc/nginx/sites-available/corner-house.conf' do
    source 'corner-house.conf'
    mode '0644'
end

cookbook_file '/etc/nginx/nginx.conf' do
    source 'nginx.conf'
    mode '0644'
end

link '/etc/nginx/sites-enabled/corner-house.conf' do
    to 'etc/nginx/sites-available/corner-house.conf'
end

link '/etc/nginx/sites-enabled/default' do
  action :delete
end

file '/var/www/html/index.nginx-debian.html' do
    action :delete
end

service 'nginx' do
    action :restart
end
```

And if I ls /etc/nginx/sites-enabled after running vagrant provision I see that the symlink is orphaned. If I then delete it and create a new symlink with ln -s everything works perfectly.

Am I doing something horribly wrong here or is this an issue with the vagrant + chef + debian8 combination?

答:
This part contains a typo: the path lacks a leading /:

```<code>to 'etc/nginx/sites-available/corner-house.conf'
</code>```

So it must be

```<code>link '/etc/nginx/sites-enabled/corner-house.conf' do
    to '/etc/nginx/sites-available/corner-house.conf'
end
</code>```

Body:
I'm trying to write a Chef recipe to enable a site in nginx, and the symbolic link its creating doesn't seem to be working. The machine I'm provisioning is a Debian8 VM which I'm managing with vagrant.

This is my (very simplistic) recipe:

include_recipe 'apt'

package 'nginx' do
  action :install
  version '1.6.2-5+deb8u4'
end

service 'nginx' do
  action [ :enable, :start ]
end

cookbook_file '/etc/nginx/sites-available/corner-house.conf' do
    source 'corner-house.conf'
    mode '0644'
end

cookbook_file '/etc/nginx/nginx.conf' do
    source 'nginx.conf'
    mode '0644'
end

link '/etc/nginx/sites-enabled/corner-house.conf' do
    to 'etc/nginx/sites-available/corner-house.conf'
end

link '/etc/nginx/sites-enabled/default' do
  action :delete
end

file '/var/www/html/index.nginx-debian.html' do
    action :delete
end

service 'nginx' do
    action :restart
end

And if I ls /etc/nginx/sites-enabled after running vagrant provision I see that the symlink is orphaned. If I then delete it and create a new symlink with ln -s everything works perfectly.

Am I doing something horribly wrong here or is this an issue with the vagrant + chef + debian8 combination?

Body:
This part contains a typo: the path lacks a leading /:

to 'etc/nginx/sites-available/corner-house.conf'

So it must be

link '/etc/nginx/sites-enabled/corner-house.conf' do
    to '/etc/nginx/sites-available/corner-house.conf'
end


问:
change the image doesnt work
here is my javasript:

```<code>$(function() {
    $(".image2").click(function() {
        var image = $(this).attr("rel");
        $('#random_img').hide();
        $('#random_img').fadeIn('slow');
        $('#random_img').attr('src') == image;
        var image2 = $('#random_img').attr('src');
        $("#thumb2 a img").removeClass("open");
        $("#thumb2 a[rel='" + image2 + "'] img").addClass("open");
        return false;
    });
});
</code>```

here is my html:

```<code><div id="image2">
    <img id="random_img" src="/documents/templates/projedepo/banner/indigovision.jpg" height="420" width="964" />
</div>
<div id="thumb2">
    <a href="#" rel="/documents/templates/projedepo/banner/canon.jpg" class="image2">
        <img title="Canon" class="slider_thumb" src="/documents/templates/bilgiteknolojileri/images/t_flash/t1.png" border="0"/></a>
    <a href="#" rel="/documents/templates/projedepo/banner/indigovision.jpg" class="image2">
        <img title="IndigoVision" class="slider_thumb" src="/documents/templates/bilgiteknolojileri/images/t_flash/t2.png" border="0"/>
    </a>
</div>
</code>```

when i click on a thumbnail, the animation fadeIn and hide works, but the image is not changed...why?

答:
```<code>$('#random_img').attr('src') == image;
</code>```

should be

```<code>$('#random_img').attr('src') = image;
</code>```

Title: change the image doesnt work

Body:
here is my javasript:

$(function() {
    $(".image2").click(function() {
        var image = $(this).attr("rel");
        $('#random_img').hide();
        $('#random_img').fadeIn('slow');
        $('#random_img').attr('src') == image;
        var image2 = $('#random_img').attr('src');
        $("#thumb2 a img").removeClass("open");
        $("#thumb2 a[rel='" + image2 + "'] img").addClass("open");
        return false;
    });
});

here is my html:

when i click on a thumbnail, the animation fadeIn and hide works, but the image is not changed...why?

Body:
$('#random_img').attr('src') == image;

should be

$('#random_img').attr('src') = image;


问:
Accessing Entry widget created using for loop
An array of Entries was created using the following code

```<code>from tkinter import *
root = Tk()

height = 5
width = 5

delta=0

for i in range(height): #Rows
  for j in range(width): #Columns
    b = Entry(root, text="",width=8)
    b.grid(row=i, column=j)

mainloop()
</code>```

How do I access each Entry to update its value ( using StringVar - for example ) ?

答:
You could create a list of lists for your Entry widgets.

```<code>from tkinter import *
root = Tk()

height = 5
width = 5

delta=0

entries = []

for i in range(height): #Rows
  newrow = []
  for j in range(width): #Columns
    b = Entry(root, text="",width=8)
    b.grid(row=i, column=j)
    newrow.append(b)
  entries.append(newrow)

mainloop()
</code>```

You could then address individual entries as e.g. entries[2][4].

Edit: To edit the text of entry widget e, first use e.delete(0, END) to clear it, and then use e.insert(0, "new text") to insert new text.

Edit2: Alternatively, you could store the StringVars in a list of lists instead of the widgets...

Body:
An array of Entries was created using the following code

from tkinter import *
root = Tk()

height = 5
width = 5

delta=0

for i in range(height): #Rows
  for j in range(width): #Columns
    b = Entry(root, text="",width=8)
    b.grid(row=i, column=j)

mainloop()

How do I access each Entry to update its value ( using StringVar - for example ) ?

Body:
You could create a list of lists for your Entry widgets.

from tkinter import *
root = Tk()

height = 5
width = 5

delta=0

entries = []

for i in range(height): #Rows
  newrow = []
  for j in range(width): #Columns
    b = Entry(root, text="",width=8)
    b.grid(row=i, column=j)
    newrow.append(b)
  entries.append(newrow)

mainloop()

You could then address individual entries as e.g. entries[2][4].

Edit: To edit the text of entry widget e, first use e.delete(0, END) to clear it, and then use e.insert(0, "new text") to insert new text.

Edit2: Alternatively, you could store the StringVars in a list of lists instead of the widgets...


问:
composite key for the table using association annotation
I am new to hibernate and I am trying to implement a basic application that uses this schema (it does not follow the notation I just use it for clarity)

Here is the my classes

```<code>@Entity
@Table(name = "race")
public class Race {
    @Id
    @GeneratedValue
    private UUID id;
    private String name;
}

@Entity
@Table(name="np_character")
public class NPCharacter {
    @Id
    @GeneratedValue
    private UUID id;
    @OneToOne
    private Race race;
    private String name;
    private int age;
}

@Entity
@Table(name="main_female_character")
public class MainFemaleCharacter {
    @Id
    @GeneratedValue
    private UUID id;
    @OneToOne
    private Race race;
    private String name;
    private int age;
}

@Entity
@Table(name="copulation_registry")
public class CopulationRegistry {
    // ??
    private NPCharacter npCharacter;
    // ??
    private MainFemaleCharacter femCharacter;
    private int times;
}
</code>```

But I ran into the problem with copulation_registry class. I used everywhere OneToOne annotation, instead of using references to keys. But what I should do here? Pairs of id_femPlayer and id_npCharacter are unique.

Should I use EmbeddedId annotation or is it possible somehow to use association annotations to represent the same relation?

答:
```<code>You can annotate class CopulationRegistry with @IdClass

@Entity
@IdClass(CopulationRegistryKey.class)
@Table(name="copulation_registry")
public class CopulationRegistry {
    @Id
    private NPCharacter npCharacter;
    @Id
    private MainFemaleCharacter femCharacter;
    private int times;
}

public class CopulationRegistryKey{
    private NPCharacter npCharacter;
    private MainFemaleCharacter femCharacter;
}
</code>```

Body:
I am new to hibernate and I am trying to implement a basic application that uses this schema (it does not follow the notation I just use it for clarity)

Here is the my classes

@Entity
@Table(name = "race")
public class Race {
    @Id
    @GeneratedValue
    private UUID id;
    private String name;
}

@Entity
@Table(name="np_character")
public class NPCharacter {
    @Id
    @GeneratedValue
    private UUID id;
    @OneToOne
    private Race race;
    private String name;
    private int age;
}

@Entity
@Table(name="main_female_character")
public class MainFemaleCharacter {
    @Id
    @GeneratedValue
    private UUID id;
    @OneToOne
    private Race race;
    private String name;
    private int age;
}

@Entity
@Table(name="copulation_registry")
public class CopulationRegistry {
    // ??
    private NPCharacter npCharacter;
    // ??
    private MainFemaleCharacter femCharacter;
    private int times;
}

But I ran into the problem with copulation_registry class. I used everywhere OneToOne annotation, instead of using references to keys. But what I should do here? Pairs of id_femPlayer and id_npCharacter are unique.

Should I use EmbeddedId annotation or is it possible somehow to use association annotations to represent the same relation?


问:
Oracle SQL: Replace all non-numeric values, such as NULL, blank or empty strings
I have a column that is formatted as number but seems to contain some other values as well that are causing trouble with my other functions (Rtrim, Xmlagg, Xmlelement, Extract), leading the whole query to fail (which works well if I take this column out).

Can someone tell me the best way to replace anything in a column that is not a valid number by 0 (or alternatively a placeholder number like 99999) ?

I tried the following but guess this only covers NULL values, not empty strings or blank strings which I think I have to replace first.

```<code>TO_CHAR(NVL(a.mycolumn, 0))
</code>```

Many thanks in advance,

Mike

答:
In Oracle, you should be able to use TRIM():

```<code>NVL(TRIM(a.mycolumn), '0')
</code>```

Oracle (by default) treats empty strings as NULL.

Do note that this will trim the result, even if it is not NULL.  If that is not desirable, use CASE:

```<code>(CASE WHEN TRIM(a.mycolumn) IS NULL THEN '0' ELSE a.myolumn END)
</code>```

Body:
I have a column that is formatted as number but seems to contain some other values as well that are causing trouble with my other functions (Rtrim, Xmlagg, Xmlelement, Extract), leading the whole query to fail (which works well if I take this column out).

Can someone tell me the best way to replace anything in a column that is not a valid number by 0 (or alternatively a placeholder number like 99999) ?

I tried the following but guess this only covers NULL values, not empty strings or blank strings which I think I have to replace first.

TO_CHAR(NVL(a.mycolumn, 0))

Many thanks in advance,

Mike

Body:
In Oracle, you should be able to use TRIM():

NVL(TRIM(a.mycolumn), '0')

Oracle (by default) treats empty strings as NULL.

Do note that this will trim the result, even if it is not NULL.  If that is not desirable, use CASE:

(CASE WHEN TRIM(a.mycolumn) IS NULL THEN '0' ELSE a.myolumn END)


问:
Constructing a png file out of multiple images and labels
I have a few UIImageViews and UILabels that you can drag around the screen in an editor.
The images are png's with a very high resolution (>2400px ) but on screen they might appear smaller.

I would like to produce a png file out of that screen ( which includes labels and images at certain positions), which will hold the actual sizes of these images (>2400px) .

If I just capture the screen programmatically (render), he will produce an image in the size of the screen, and it will not be transparent.

How can I construct the png file by my self by placing images and texts in whatever sizes and positions I want?

This for example :

```<code>if let image = UIImage(named: "example.png") {
    if let data = UIImagePNGRepresentation(image) {
        let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
        try? data.write(to: filename)
    }
}
</code>```

will not let you specify locations or add multiple images and texts to the file

答:
Found a pretty simple and sweet way to do so, first you save in a dictionary all your screen elements, then you can simply add them to a file with :</p>

```<code>let font = UIFont.boldSystemFont(ofSize: 160)
let showText:NSString = "hello world"
// setting attr: font name, color...etc.
let attr = [NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.blue]
// getting size
let sizeOfText = showText.size(attributes: attr)

let image = UIImage(named: "image.png")
let rect = CGRect(x: 0, y: 0, width: image!.size.width,height: image!.size.height)

UIGraphicsBeginImageContextWithOptions(CGSize(width: rect.size.width, height: rect.size.height), false, 0)

// drawing our image to the graphics context
image?.draw(in: rect)
// drawing text
showText.draw(in: CGRect(x: rect.size.width/2.0, y: rect.size.height/2.0, width: rect.size.width, height: rect.size.height), withAttributes: attr)

// getting an image from it
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()
</code>```

Body:
I have a few UIImageViews and UILabels that you can drag around the screen in an editor.
The images are png's with a very high resolution (>2400px ) but on screen they might appear smaller.

I would like to produce a png file out of that screen ( which includes labels and images at certain positions), which will hold the actual sizes of these images (>2400px) .

If I just capture the screen programmatically (render), he will produce an image in the size of the screen, and it will not be transparent.

How can I construct the png file by my self by placing images and texts in whatever sizes and positions I want?

This for example :

if let image = UIImage(named: "example.png") {
    if let data = UIImagePNGRepresentation(image) {
        let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
        try? data.write(to: filename)
    }
}

will not let you specify locations or add multiple images and texts to the file

Body:
Found a pretty simple and sweet way to do so, first you save in a dictionary all your screen elements, then you can simply add them to a file with :

let font = UIFont.boldSystemFont(ofSize: 160)
let showText:NSString = "hello world"
// setting attr: font name, color...etc.
let attr = [NSFontAttributeName: font, NSForegroundColorAttributeName:UIColor.blue]
// getting size
let sizeOfText = showText.size(attributes: attr)

let image = UIImage(named: "image.png")
let rect = CGRect(x: 0, y: 0, width: image!.size.width,height: image!.size.height)

UIGraphicsBeginImageContextWithOptions(CGSize(width: rect.size.width, height: rect.size.height), false, 0)

// drawing our image to the graphics context
image?.draw(in: rect)
// drawing text
showText.draw(in: CGRect(x: rect.size.width/2.0, y: rect.size.height/2.0, width: rect.size.width, height: rect.size.height), withAttributes: attr)

// getting an image from it
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()


问:
Choosing an OpenID Connect Provider
I need to implement SSO in my JAVA Web App with OpenID Connect. I already have experience in SSO with SAML 2.0 with WSO2 as Identity Provider.

I am clear on the client part, and planning to implement the same with Spring Security.

My question is, does it make sense to build my own Identity provider for OpenID Connect? For some reasons, I do not want to use any third party IDP (like WSO2).

If yes, is there any library that can help? If no, what are the best IDP I can use for OpenIDConnect? Ofcourse, WSO2 is on top of my list because I have already implemented SAML SSO with WSO2 and it also supports OpenID connect.

Any experience or suggestion is most welcome.

答:
An answer for this question is not that straightforward. But I will try to summarise some key points which will be helpful in making a decision.

Implementing in-house identity provider

Cost and effort

You will have to develop and maintain everything by yourself. This means implementing the specification (OpenID Connect) adhering to RFC6749. Adding to that you need to register clients, issue tokens, validate tokens and maintain token state (ex- issued refresh token). Indeed some libraries like Nimbus would come in handy.

If you are dealing with third parties you are bound to strictly follow specifications. And it could be a higher development cost and effort depending on the talent pool

Maintenance and support

Any internal development will come with support and maintenance. Bug fixes, issues and new feature requirements will be costly over time and could involve valuable developer time

Performance and reliability

As you have mentioned, implementing your own identity provider and making it to perform as any existing product is challenging. Besides, identity provider should be reliable. It must be secure enough to sustain security attacks (specially if you are exposing it to internet). And implementation should be done with security in mind from ground up (ex:- Secure certificates for token signing, access token and refresh token entropy)

Using a third party product

Cost and effort

Depending on the provider, it could be free and open source or paid tool. And if it is an established product there will be less implementation effort

Maintenance and support

Now this depends on the service agreement. You might have to pay for support. But you get rid of maintenance. A product might lack some features you expect it to have (ex- RFC7662 - token introspection endpoint). For example MS Azure AD lacks an introspection endpoint.

Performance and reliability

Given that it's a product you purchase or available openly and used by many, commercial products tend to have optimum performance. And indeed they are developed by domain experts (ex:- A dedicated team who have gone through all the specs) and could include higher reliability.

P.S -

Regardless of all of these considerations, there could be a requirement to develop and maintain an internal identity provider. If that's the case you have to implement it according to related specifications and make it secure. Hope this helped with your decision.

Title: Choosing an OpenID Connect Provider


问:
Mysql subselect extremely slow (doesn't seem to be using indexes)
This query doesn't complete in a reasonable amount of time:

```<code>mysql> select * from prices where symbol='GOOG' and date in
(select max(date) from prices where symbol='GOOG' and yearweek(date) > 201001
 group by yearweek(date));
</code>```

'prices' is keyed off id, and has a secondary unique index of (symbol, date):

```<code>mysql> show index from prices;
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| Table  | Non_unique | Key_name        | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| prices |          0 | PRIMARY         |            1 | id          | A         |      468915 |     NULL | NULL   |      | BTREE      |         |
| prices |          0 | SECONDARY_INDEX |            1 | date        | A         |       10905 |     NULL | NULL   | YES  | BTREE      |         |
| prices |          0 | SECONDARY_INDEX |            2 | symbol      | A          |      468915 |     NULL | NULL   | YES  | BTREE      |         |
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
3 rows in set (0.00 sec)
</code>```

From looking at the EXPLAIN output, it seems as though MySql is not using the index on (date, symbol).  Does the combination of WHERE symbol='GOOG' and date IN (...)) require a full table scan and not use the secondary unique index?

```<code>mysql> EXPLAIN select * from prices where symbol='GOOG' and date in (select max(date) from prices where symbol='GOOG' and yearweek(date) > 201001 group by yearweek(date));
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
| id | select_type        | table  | type  | possible_keys | key             | key_len | ref  | rows   | Extra                                                     |
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
|  1 | PRIMARY            | prices | ALL   | NULL          | NULL            | NULL    | NULL | 468915 | Using where                                               |
|  2 | DEPENDENT SUBQUERY | prices | index | NULL          | SECONDARY_INDEX | 17      | NULL | 468915 | Using where; Using index; Using temporary; Using filesort |
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
2 rows in set (0.00 sec)
</code>```

答:
Try a JOIN:

```<code>SELECT
    prices.*
FROM
    prices
        JOIN
            (SELECT MAX(date) AS maxdate FROM prices WHERE symbol='GOOG' AND yearweek(date) > 201001 GROUP BY yearweek(date))
        AS sub ON prices.date = sub.maxdate
WHERE
    symbol='GOOG' ;
</code>```

But the yearweek() will still be a problem, MySQL can't use an index on this one. Precalculate this value (using a trigger) , store it in an extra column and index this column, might help.

Body:
This query doesn't complete in a reasonable amount of time:

mysql> select * from prices where symbol='GOOG' and date in
(select max(date) from prices where symbol='GOOG' and yearweek(date) > 201001
 group by yearweek(date));

'prices' is keyed off id, and has a secondary unique index of (symbol, date):

mysql> show index from prices;
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| Table  | Non_unique | Key_name        | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| prices |          0 | PRIMARY         |            1 | id          | A         |      468915 |     NULL | NULL   |      | BTREE      |         |
| prices |          0 | SECONDARY_INDEX |            1 | date        | A         |       10905 |     NULL | NULL   | YES  | BTREE      |         |
| prices |          0 | SECONDARY_INDEX |            2 | symbol      | A          |      468915 |     NULL | NULL   | YES  | BTREE      |         |
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
3 rows in set (0.00 sec)

From looking at the EXPLAIN output, it seems as though MySql is not using the index on (date, symbol).  Does the combination of WHERE symbol='GOOG' and date IN (...)) require a full table scan and not use the secondary unique index?

mysql> EXPLAIN select * from prices where symbol='GOOG' and date in (select max(date) from prices where symbol='GOOG' and yearweek(date) > 201001 group by yearweek(date));
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
| id | select_type        | table  | type  | possible_keys | key             | key_len | ref  | rows   | Extra                                                     |
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
|  1 | PRIMARY            | prices | ALL   | NULL          | NULL            | NULL    | NULL | 468915 | Using where                                               |
|  2 | DEPENDENT SUBQUERY | prices | index | NULL          | SECONDARY_INDEX | 17      | NULL | 468915 | Using where; Using index; Using temporary; Using filesort |
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
2 rows in set (0.00 sec)

Body:
Try a JOIN:

SELECT
    prices.*
FROM
    prices
        JOIN
            (SELECT MAX(date) AS maxdate FROM prices WHERE symbol='GOOG' AND yearweek(date) > 201001 GROUP BY yearweek(date))
        AS sub ON prices.date = sub.maxdate
WHERE
    symbol='GOOG' ;

But the yearweek() will still be a problem, MySQL can't use an index on this one. Precalculate this value (using a trigger) , store it in an extra column and index this column, might help.