text:
Q: Filter dictionary for values which are not in another dictionary The two dictionaries mydict1 and mydict2 are given. Key-value-pairs in mydict2 should be removed if the values are already contained in mydict1, regardless of the key and regardless of the order of the values.
The code below delivers the correct output mydict2 = {'key6': [2,1,4], 'key4': [2]}. However, it will be used as part of a larger code. Is there is a better, i.e. more phytonic, way to write it in order to make it more compact and effective without the need of functions?
mydict1 = {'key1':[1],'key2':[1,2],'key3':[1,2,3]}
mydict2 = {'key4':[2],'key5':[2,1],'key6':[2,1,4]}
mydict3 = {}

for md2 in mydict2:
    isindict = False
    for md1 in mydict1:
        isindict = isindict|(sorted(mydict1[md1])==sorted(mydict2[md2]))
    if not isindict:
        mydict3[md2] = mydict2[md2]
mydict2 = mydict3

The solutions for removing items from a list, comparison of dictionaries and conditional filtering of a dictionary are not transferable in a straightforward way.

A: Use a list comprehension and dict comprehension to sort all the values of mydict2 then check if the sorted value of mydict1 is in there:
mydict1 = {'key1':[1],'key2':[1,2],'key3':[1,2,3]}
mydict2 = {'key4':[2],'key5':[2,1],'key6':[2,1,4]}

vals = [tuple(sorted(x)) for x in mydict1.values()]
mydict2 = {k:v for (k,v) in mydict2.items() if tuple(sorted(v)) not in vals}

print(mydict2)

Or, in one line:
mydict1 = {'key1':[1],'key2':[1,2],'key3':[1,2,3]}
mydict2 = {'key4':[2],'key5':[2,1],'key6':[2,1,4]}

mydict2 = {k:v for (k,v) in mydict2.items()
        if tuple(sorted(v)) not in [tuple(sorted(x)) for x in mydict1.values()]}

print(mydict2)

A: You can use dict comprehension :
mydict1 = {'key1':[1],'key2':[1,2],'key3':[1,2,3]}
mydict2 = {'key4':[2],'key5':[2,1],'key6':[2,1,4]}

results = {key : value for (key,value) in mydict2.items()
           if set(value) not in [ set(val) for val in mydict1.values()]}
print(results)

{'key4': [2], 'key6': [2, 1, 4]}

Edit1
Doesn't work wiht duplicate like this :
mydict1 = {'key1':[1],'key2':[1,2],'key3':[1,2,3], 'key4' : [1, 1, 2]}
mydict2 = {'key4':[2],'key5':[2,1],'key6':[2,1,4], 'key7' : [2, 2, 1]}

Edit 2
Following @Ruzihm awsers and @Peter Wood comments :
mydict3 = {k:v for (k,v) in mydict1.items()
        if tuple(sorted(v)) not in set(tuple(sorted(x)) for x in mydict2.values())}

This awser the OP question and avoid creating multiple time the same tuple of value as mentioned by @Peter Wood.

A: i think this will work:
mydict1 = {'key1':[1],'key2':[1,2],'key3':[1,2,3]}
mydict2 = {'key3':[2],'key5':[2,1],'key6':[2,1,4]}

def merge_two_dicts(x, y):
    z = x.copy()
    z.update(y)
    return z

result = merge_two_dicts(mydict1, mydict2)
print(result)


text:
Q: use the result of function as a new function's parameter, but why exception occurred? i wrote a lite RPC framework and use kryo serialize object.
but exception occurred when i wrote like this
RpcResponse rpcResponse = new RpcResponse(input.readInt(), kryo.readClassAndObject(input), input.readBoolean());

so i use another way to init my RpcResponse object.
int id = input.readInt();
boolean isInvokeSuccess = input.readBoolean();
Object resultOrThrowable = kryo.readClassAndObject(input);

RpcResponse rpcResponse = new RpcResponse(id, resultOrThrowable, isInvokeSuccess);

and it works.
so my question is: is there any difference between these two way that i used?
the exception is
io.netty.handler.codec.DecoderException: com.esotericsoftware.kryo.KryoException: Unable to find class: abc123123
at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:459)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1434)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:965)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:647)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:582)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:499)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:461)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:884)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.esotericsoftware.kryo.KryoException: Unable to find class: abc123123
at com.esotericsoftware.kryo.util.DefaultClassResolver.readName(DefaultClassResolver.java:156)
at com.esotericsoftware.kryo.util.DefaultClassResolver.readClass(DefaultClassResolver.java:133)
at com.esotericsoftware.kryo.Kryo.readClass(Kryo.java:670)
at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:781)
at org.develcarl.rpc.serializer.RpcResponseSerializer.read(RpcResponseSerializer.java:30)
at org.develcarl.rpc.serializer.RpcResponseSerializer.read(RpcResponseSerializer.java:14)
at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:790)
at org.develcarl.rpc.serializer.KryoSerializer.deserialize(KryoSerializer.java:56)
at org.develcarl.rpc.netty.NettyKryoDecoder.decode(NettyKryoDecoder.java:28)
at io.netty.handler.codec.LengthFieldBasedFrameDecoder.decode(LengthFieldBasedFrameDecoder.java:343)
at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489)
at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428)
... 16 more
Caused by: java.lang.ClassNotFoundException: abc123123
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at com.esotericsoftware.kryo.util.DefaultClassResolver.readName(DefaultClassResolver.java:154)
... 27 more

A: Yes. The second one works. The order of operations matters, you have int, boolean, Object. In your first example you read int, Object, boolean. You could do,
int id = input.readInt();
boolean isInvokeSuccess = input.readBoolean();
RpcResponse rpcResponse = new RpcResponse(id,
        kryo.readClassAndObject(input), isInvokeSuccess);

Regardless, you have to read the fields in the order they're written.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Kubectl keeps restarting container when ran I'm currently trying to move our company's squid server to a dockerized version and I'm struggling to get it working with Kubernetes.
I have built a Docker image that works perfectly fine when run with "docker run".
The complete Docker Run command is:
sudo docker run -d -i -t --privileged --volume=/proc/sys/net/ipv4/ip_nonlocal_bind:/var/proc/sys/net/ipv4/ip_nonlocal_bind --net=host --cap-add=SYS_MODULE --cap-add=NET_ADMIN --cap-add=NET_RAW -v /dev:/dev -v /lib/modules:/lib/modules -p80:80 -p8080:8080 -p53:53/udp -p5353:5353/udp -p5666:5666/udp -p4500:4500/udp -p500:500/udp -p3306:3306 --name=edge crossense/edge:latest /bin/bash
When I try to run the Image with Kubernetes, with the something like:
kubectl run --image=crossense/edge:latest --port=80 --port=8080 --port=53 --port=5353 --port=5666 --port=4500 --port=500 --port=3306 edge
seems like Kubernetes tries to get the container up and running, but without any success...
$kubectl get po
NAME         READY     REASON    RESTARTS   AGE
edge-sz7wp   0/1       Running   10         15m

And the $kubectl describe pod edge command gives me lots of these:
Thu, 09 Nov 2017 17:13:05 +0000 Thu, 09 Nov 2017 17:13:05 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id abcc2ff25a624a998871e02bcb62d42d6f39e9db0a39f601efa4d357dd8334aa
Thu, 09 Nov 2017 17:13:15 +0000 Thu, 09 Nov 2017 17:13:15 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 878778836bd3cc25bdf1e3b9cc2f2f6fa22b75b938a481172f08a6ec50571582
Thu, 09 Nov 2017 17:13:15 +0000 Thu, 09 Nov 2017 17:13:15 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 878778836bd3cc25bdf1e3b9cc2f2f6fa22b75b938a481172f08a6ec50571582
Thu, 09 Nov 2017 17:13:25 +0000 Thu, 09 Nov 2017 17:13:25 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id aa51e94536216b905ff9ba07951fedbc0007476b55dfdb2e5106418fb6aee05c
Thu, 09 Nov 2017 17:13:25 +0000 Thu, 09 Nov 2017 17:13:25 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id aa51e94536216b905ff9ba07951fedbc0007476b55dfdb2e5106418fb6aee05c
Thu, 09 Nov 2017 17:13:35 +0000 Thu, 09 Nov 2017 17:13:35 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id f4661e5ea33471cd1ba30816b40c8ba2d204fa22509b973da4af6eedb64c592e
Thu, 09 Nov 2017 17:13:35 +0000 Thu, 09 Nov 2017 17:13:35 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id f4661e5ea33471cd1ba30816b40c8ba2d204fa22509b973da4af6eedb64c592e
Thu, 09 Nov 2017 17:13:45 +0000 Thu, 09 Nov 2017 17:13:45 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 75f83dcb9b4f8af5134d6fd2edcd9342ecf56111e132a45f4e9787e83466e28b
Thu, 09 Nov 2017 17:13:45 +0000 Thu, 09 Nov 2017 17:13:45 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 75f83dcb9b4f8af5134d6fd2edcd9342ecf56111e132a45f4e9787e83466e28b
Thu, 09 Nov 2017 17:13:55 +0000 Thu, 09 Nov 2017 17:13:55 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id c9d0535b3962ec9da29c068dbb0a6b64426a5ac3e52f72e79bcbaf03c9f3d403
Thu, 09 Nov 2017 17:13:55 +0000 Thu, 09 Nov 2017 17:13:55 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id c9d0535b3962ec9da29c068dbb0a6b64426a5ac3e52f72e79bcbaf03c9f3d403
Thu, 09 Nov 2017 17:14:05 +0000 Thu, 09 Nov 2017 17:14:05 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 579f4428e9804404bd746cceee88bb6c73066a33263202bb5f1eb15f6ff26d7b
Thu, 09 Nov 2017 17:14:05 +0000 Thu, 09 Nov 2017 17:14:05 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 579f4428e9804404bd746cceee88bb6c73066a33263202bb5f1eb15f6ff26d7b
Thu, 09 Nov 2017 17:14:15 +0000 Thu, 09 Nov 2017 17:14:15 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id d36b2c9ddf0b1a05d86b43d2a92eb3c00ae92d00e155d5a1be1da8e2682f901b
Thu, 09 Nov 2017 17:14:15 +0000 Thu, 09 Nov 2017 17:14:15 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id d36b2c9ddf0b1a05d86b43d2a92eb3c00ae92d00e155d5a1be1da8e2682f901b
Thu, 09 Nov 2017 17:14:25 +0000 Thu, 09 Nov 2017 17:14:25 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 2d7b24537414f5e6f2981bf5f01596b19ea1abdb0eb4b81508fc7f44e8c34609
Thu, 09 Nov 2017 17:14:25 +0000 Thu, 09 Nov 2017 17:14:25 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 2d7b24537414f5e6f2981bf5f01596b19ea1abdb0eb4b81508fc7f44e8c34609
Thu, 09 Nov 2017 17:14:35 +0000 Thu, 09 Nov 2017 17:14:35 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id fdae44c599b77d44839e4897b750203c183001a6053c926432ef5a3c7f4deb38
Thu, 09 Nov 2017 17:14:35 +0000 Thu, 09 Nov 2017 17:14:35 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id fdae44c599b77d44839e4897b750203c183001a6053c926432ef5a3c7f4deb38
Thu, 09 Nov 2017 17:14:45 +0000 Thu, 09 Nov 2017 17:14:45 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 544351dda838d698e3bc125840edb6ad71cd0165a970cce46825df03b826eb38
Thu, 09 Nov 2017 17:14:45 +0000 Thu, 09 Nov 2017 17:14:45 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 544351dda838d698e3bc125840edb6ad71cd0165a970cce46825df03b826eb38
Thu, 09 Nov 2017 17:14:55 +0000 Thu, 09 Nov 2017 17:14:55 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 00fe4c286c1cc9b905c9c0927f82b39d45d41295a9dd0852131bba087bb19610
Thu, 09 Nov 2017 17:14:55 +0000 Thu, 09 Nov 2017 17:14:55 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 00fe4c286c1cc9b905c9c0927f82b39d45d41295a9dd0852131bba087bb19610

Any help would be much appreciated!

A: While I can't say this conclusively without the ability to re-produce and lack of logs, one of the differences which can be noticed easily is the privileges you have provided in docker command for example NET_ADMIN or NET_RAW etc. which are missing in Kubernetes run command.
Kubernetes also provides the ability to assign such privileges to a pod with capabilities within the securityContext in a pod declaration.
I am not sure if you can do this with Kubectl, but if you use the YAML declaration for the pod, the specs look roughly like:
apiVersion: v1
kind: Pod
metadata:
 name: mypod
spec:
 containers:
   - name: myshell
     image: "ubuntu:14.04"
     command:
       - /bin/sleep
       - "300"
     securityContext:
       capabilities:
         add:
           - NET_ADMIN
For more reference, I would suggest a quick look at:

*

*This post on Weave blog which lists all capabilities and an example which I have borrowed above as well

*Official Kubernetes documentation which provides all details needed around security context

A: For all the poor souls out there, who couldn't find out the answer,
the reason for the pod to keep restarting is that the command executed by it has exited with code 0 (meaning successfully).
In my case, I was running /bin/bash as the entrypoint command, as specified in my pod configuration .yaml file:
apiVersion: v1
kind: Pod
metadata:
 name: edge
spec:
 containers:
   - name: edge
     image: "crossense/edge:production"
     command:
       - /bin/bash
     securityContext:
       capabilities:
         add:
           - NET_ADMIN
           - SYS_MODULE
           - NET_RAW
     volumeMounts:
       - name: ip-nonlocal-bind
         mountPath: /host/proc/sys/net/ipv4
       - name: dev
         mountPath: /host/dev
       - name: modules
         mountPath: /host/lib/modules

....

The solution was simply adding a non exiting command to the
entrypoint. This can be any process run on foreground or simply a
/bin/sleep

For the sake of example and future learning, my final pod configuration file looked like this:
apiVersion: v1
kind: Pod
metadata:
 name: edge
spec:
 hostNetwork: true
 containers:
   - name: edge
     image: "crossense/edge:production"
     command: ["/bin/bash", "-c"]
     args: ["service rsyslog restart; service proxysql start; service mongodb start; service pdns-recursor start; service supervisor start; service danted start; touch /var/run/squid.pid; chown proxy /var/run/squid.pid; service squid restart; service ipsec start; /sbin/iptables-restore < /etc/iptables/rules.v4; sleep infinity"]
     securityContext:
       privileged: true
       capabilities:
         add:
           - NET_ADMIN
           - SYS_MODULE
           - NET_RAW
     volumeMounts:
       - mountPath: /dev/shm
         name: dshm
       - name: ip-nonlocal-bind
         mountPath: /host/proc/sys/net/ipv4
       - name: dev
         mountPath: /dev
       - name: modules
         mountPath: /lib/modules
     ports:
       - containerPort: 80
       - containerPort: 8080
       - containerPort: 53
         protocol: UDP
       - containerPort: 5353
         protocol: UDP
       - containerPort: 5666
       - containerPort: 4500
       - containerPort: 500
       - containerPort: 3306
 volumes:
   - name: dshm
     emptyDir:
       medium: Memory
   - name: ip-nonlocal-bind
     hostPath:
       path: /proc/sys/net/ipv4
   - name: dev
     hostPath:
       path: /dev
       type: Directory
   - name: modules
     hostPath:
       path: /lib/modules
       type: Directory

For any questions, feel free to comment of this thread, or ask me at max.vlashchuk@gmail.com :)


text:
Q: Trying to display a hidden div based on a select (dropdown) element I have a select field for the country and I want to display a checkbox that is in a hidden div. This is the code I have on the site. Any reason why this wouldn't work?
<select id="country" name="field-010" required="" data-name="field-010" class="w-select" onchange="showDiv()">
  <option value="United States of America">United States of America</option>
  <option value="Canada">Canada</option>
  <option value="Australia">Australia</option>
  <option value="United Kingdom">United Kingdom</option>
  <option value="Belgium">Belgium</option>
</select>

  <input type="checkbox" id="field-011" name="field-011" data-name="field-011" style="opacity:0;position:absolute;z-index:-1" data-di-id="#field-011">TEXT HERE

A: Correction:

if(country.value=="United Kingdom")

Not:

if(country.value==United Kingdom)

Use VSCode with a linter it helps

https://code.visualstudio.com/

A: Just one correction: United Kingdom should be in quotes

function showDiv() {
  if (country.value === "United Kingdom") {
    document.getElementById('gdpr').style.display = "block";
  } else {
    document.getElementById('gdpr').style.display = "none";
  }
}
<select id="country" name="field-010" required="" data-name="field-010" class="w-select" onchange="showDiv()">
  <option value="United States of America">United States of America</option>
  <option value="Canada">Canada</option>
  <option value="Australia">Australia</option>
  <option value="United Kingdom">United Kingdom</option>
  <option value="Belgium">Belgium</option>
</select>

    <input type="checkbox" id="field-011" name="field-011" data-name="field-011" style="opacity:0;position:absolute;z-index:-1" data-di-id="#field-011">TEXT HERE

A: Change your  control to be a
, or add a
 around the  and toggle the display style on that. You can't have the
 inside the  element.


text:
Q: Cannot load model in keras from Model.get_config() when the model has Attention layer I'm loading a model in keras from a config dict created by some function. I've tried this scheme with many other models without issues, but this is the first one were i'm using tensorflow.keras.layers.Attention and i'm getting an Unknown Layer exception when reading from the config.
I know there is an API to serialize and load custom layers using JSON/YAML, but this is a keras layer, am I doing something wrong?
by the way this is using Tensorflow 1.14.0
from tensorflow.keras import layers, models, utils

def my_model(max_len, vocab_size, embedding_dims):
    sequence = layers.Input(shape=(max_len,), name='sequence')
    feature = layers.Input(shape=(1,), name='another_feature')

    x = layers.Embedding(input_dim=vocab_size,
                         output_dim=embedding_dims,
                         input_length=max_len)(sequence)
    out, sh, sc = layers.LSTM(64, return_state=True)(x)
    att = layers.Attention()([out, sh])
    x = layers.concatenate([att, feature])
    model = models.Model(inputs=[sequence, feature], outputs=[x])
    model.summary()
    return model.get_config()

title_max_len = 50
vocab_size = 35000
embedding_dims = 30

config = my_model(
    title_max_len,
    vocab_size,
    embedding_dims
)
model = models.Model.from_config(config)  # Unknown layer: Attention
utils.plot_model(
    model,
    show_shapes=True,
    show_layer_names=True,
    to_file='model.png'
)

A: It looks like the problem exists for Tensorflow 1.14 but it works without any problems in 1.15. If you're able to upgrade then that may be the easiest solution.


text:
Q: One-off creation with the Factory Pattern I'm putting together a game whilst trying to conform to various design patterns, the factory design pattern is one of them.
There are certain game elements that get created constantly e.g. enemies, bullets. Then there are elements that only get instantiated one time, like background element for instance.
In cases when you're only doing one-off creations of objects, is there any point in using the factory design pattern? or would it be more appropriate to have a mixture of directly created objects and factory created ones?

A: Yes, using factory method, still makes sense for single instance objects.
The most basic reason is that you will end up with a more testable code.


text:
Q: Image mime type and extension is correct but get failed upload i have image with extension .jpeg and mime type is image/jpeg.. and this is the var_dump() from the uploaded image using file upload (input type="file")
array (size=5)
 'name' => string 'WhatsApp Image 2023-02-01 at 17.07.41.jpeg' (length=42)
 'type' => string 'image/jpeg' (length=10)
 'tmp_name' => string 'D:\xampp\tmp\phpDAF2.tmp' (length=24)
 'error' => int 0
 'size' => int 140484

other references said that maybe the mimes.php (oh and yes i am using codeigniter 3) and this is the mimes.php for jpeg extension, here's the mimes.php line on jpeg
'gif'   =>  'image/gif',
'jpeg'  =>  array('image/jpeg', 'image/pjpeg'),
'jpg'   =>  array('image/jpeg', 'image/pjpeg'),

i'm confused while i do this upload attached the code
$config['upload_path'] = './uploads/patient_img/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['file_name'] = strtolower($patient->get_name());
$config['overwrite'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['image_library'] = 'gd2';

$this->load->library('upload', $config);

$this->upload->initialize($config);

$error = [];
$listing_filename = [];
foreach ($list_image as $row) {
    if ($_FILES['image_' . $row]['name'] != '' && is_null($this->input->post('existing_image_' . $row))) {
        if (!$this->upload->do_upload('image_' . $row)) {
            $error[] = $this->upload->display_errors();
            print_r($this->upload->display_errors());
            die();
            break;
        } else {
            $listing_filename[] = $this->upload->data('file_name');
        }
    }
}

and i get the CI Upload error "The filetype you are attempting to upload is not allowed."
anybody knows what is going on? because i can't find the answer.. thanks a lot

A: i found the solution!
turns out that i have using combination of string for the filename, when i double check it the name contain "." (dot) that makes the uploaded image already has "."
let's say i input "this is. a name" and the uploaded image filename will be "this_is._a_name" that cause extension isn't valid
so the solution is simply replace the "." using regex


text:
Q: Spivak Calculus Chapter 1 Question 19(a) I need to prove Schwarz inequality from : $(\lambda y_1-x_1)^2+(\lambda y_2-x_2)^2>0$, such that $\lambda y_1≠x_1$ and $\lambda y_2≠x_2$
This is fairly simple by using question's 18 fact: If $x^2+bx+c>0$ for all $x$, then $b^2-4c<0$.
Using these two I arrived at $x_1y_1+x_2y_2< \sqrt{x_1^2+x_2^2}\sqrt{y_1^2+y_2^2}$, but the Schwarz inequality presented in the book is:
$$x_1y_1+x_2y_2\le \sqrt{x_1^2+x_2^2}\sqrt{y_1^2+y_2^2}$$
I'm not sure how the operator $\le$ replaces my $<$ here.

A: *

*If you have proven $a < b$, then you've also proven $a \le b$. So that would answer your question.

*However, you must've made some mistake because you actually can't always have strict inequality. Consider $$x_1 = x_2 = y_1 = y_2 = 1.$$

EDIT: The question now mentions that $\lambda y_1 \neq x_1$ and $\lambda y_2 \neq x_2$.
What I suspect Spivak really means is that the following equality:
$$(x_1, x_2) = \lambda (y_1, y_2)$$
does not hold for any $\lambda \in \Bbb R$.
In this case, you would indeed the first strict inequality that you write in your question. (Note that you only need one of $\lambda_iy_i - x_i$ to be nonzero.)
That leads you to
$$\lambda(y_1^2 + y_2^2) - 2\lambda(x_1x_2 + y_1y_2) + (x_1^2 + x_2^2) > 0.$$
Now, I know that you would proceed to write $b^2 < 4ac$ but you cannot do that for the leading coefficient in the above need not be nonzero. (That is, the above need not be a quadratic and you can't use that.)
However, that is possible only in the case $y_1 = y_2 = 0$ and that in the case, equality does indeed hold.
For example, take $$x_1 = x_2 = 1, \; y_1 = y_2 = 0$$
to see that you still need to allow equality.


text:
Q: Failed building wheel PyYAML I'm trying to install flask-ask using pip
pip3 install flask_ask

and I'm getting a very long error that's in short saying
Building wheel for PyYAML (setup.py): finished with status 'error'

I'm running python3.7.4_1 on MacOS 10.14.5. I've tried python 3.6 and 3.7 along with different versions of pip to no avail.

Below is the error message (let me know if you need more):
Links are broken as of Feb 2023:

*

*Error Pt 1

*Error Pt 2

*Error Pt 3


text:
Q: Run WPF application through URL directly in Google-Chrome I have WPF application(.exe), which was hosted in my remote web server.
Now I want to access WPF application from my web page by clicking respective link.
Response.Redirect(WPFLaunchUrl);

By using this, I am able lunch application in IE. But whenever I am using Google-Chrome then application downloading into my local system instead of running application from Hosted URL.
Could you please suggest me on this.


text:
Q: mongodb pull element from multidimensional array Hi i have the following array and i want to pull the array with productId 100343
Array(
    [_id] => MongoId Object
        (
            [$id] => 5388a02c8ead0ebf048b4569
        )

    [cartId] => 14ce496ac194d5d8ee8d0cd11bd3ef5a
    [products] => Array
        (
            [100343] => Array
                (
                    [productId] => 100343
                    [quantity] => 13
                    [name] => a
                )

            [100344] => Array
                (
                    [productId] => 100344
                    [quantity] => 3
                    [name] => ab
                )

            [100345] => Array
                (
                [productId] => 100345
                    [quantity] => 1
                    [name] => abc
                )

        )

)

I've tried like this but it doesn't work
$c->update(
    $aQuery,
    array(
        '$pull' => array('products'=>array('productId'=>'100343'))
    )
);

A: That is not an array. Arrays in MongoDB are different in concept to what PHP calls an array, so the structure you have there is the same as this JSON representation:
{
    "products": {
        "100343": {
            "productId": 100343,
            "quantity": 13,
            "name": "a"
        },
        "100344": {
            "productId": 100344,
            "quantity": 3,
            "name": "ab"
        },
        "100345": {
            "productId": 100345,
            "quantity": 1,
            "name": "abc"
        }
    }
}

That sort of structure is just a use of sub-documents and is not an array in the sense as used by MongoDB. To remove the entry as you want with this structure you use the $unset operator.
$c->update(
    $aQuery,
    array(
        '$unset' => array('products.productId.100343' => "")
    )
);

But really you need to change your data, so to serialize a proper array for MongoDB you need to structure code like this:
$data = array(
    "products" => array(
         array(
             "productId" => 100343,
             "quantity" => 13,
             "name" => "a"
         ),
         array(
             "productId" => 100344,
             "quantity" => 3,
             "name" => "ab"
         ),
         array(
             "productId" => 100345,
             "quantity" => 1,
             "name" => "abc"
         )
     )
 );

That produces a JSON structure that looks like this:
{
    "products":[
        {
            "productId":100343,
            "quantity":13,
            "name":"a"
        },
        {
            "productId":100344,
            "quantity":3,
            "name":"ab"
        },
        {
            "productId":100345,
            "quantity":1,
            "name":"abc"
        }
    ]
}

That is what MongoDB calls an array, so now you can use the $pull operator correctly:
$c->update(
    $aQuery,
    array(
        '$pull' => array( 'products.productId' => 100343 )
    )
);


text:
Q: How to Combine groups of duplicate and repeating values and preserving order? Matlab I am having trouble combining repeated elements of my Matlab "data" variable. I can easily combine the values using unique and sort.
[sorted,idx] = sort(data);
[~,ij] = unique(sorted,'first');
Indx = (sort(idx(ij)));

However, by doing this I am combining ALL repeated values. What I really want to do is combine only groups of repeating elements. For example take this:
data = [1;1;1;2;2;2;3;3;3;4;4;4;4;4;3;3;2;2;2;2;1;1;1;1;4;4;4;4;]

Combine duplicate groups of elements:
data = [1;2;3;4;3;2;1;4;]

I need to combine the groups of repeating elements wile still preserving the order. It would also be helpful to return the index because I need to average data in another variable based on the index of combination.
For example:
data  = [1;1;1;2;2;2;3;3;3;4;4;4;4;4;3;3;2;2;2;2;1;1;1;1;4;4;4;4;]
data2 = [7;2;4;5;3;4;6;8;5;3;5;7;4;2;4;6;8;4;3;6;7;8;4;2;9;3;2;0;]

dataCombined = [1;     2;  3;    4;   3;  2;     1;     4;   ]
data2average = [4.33;  4;  6.33  4.2  5;  5.25;  5.25;  3.5; ]

Can anyone give suggestions?

SOLUTION:
Thank you all for your answers. MZimmerman6's solution worked well for me. I wanted to show what I did in order to average the values in "data2" array.
data = [1;1;1;2;2;2;3;3;3;4;4;4;4;4;3;3;2;2;2;2;1;1;1;1;4;4;4;4;];
data2 = [7;2;4;5;3;4;6;8;5;3;5;7;4;2;4;6;8;4;3;6;7;8;4;2;9;3;2;0;];
change = diff(data)~=0;
indices = [1,find(change)'+1];
compressed = data(indices)';

numberOfRepeatingGroups = size(indices);

for i=1:numberOfRepeatingGroups(1,2)

  if(i == 1)

      dataToAverage = data2(indices(1,1):(indices(1,2)-1));

  elseif (i == numberOfRepeatingGroups(1,2))

       dataToAverage = data2(indices(1,i):end);

  else

       dataToAverage = data2(indices(1,i):(indices(1,(i+1))-1));

  end

       data2Averaged(1,i) = mean(dataToAverage(:));

end

data2Averaged =

4.3333    4.0000    6.3333    4.2000    5.0000    5.2500    5.2500    3.5000

A: You can use a derivative to find fluctuations in your data arrays, which would indicate a change in grouping. Anywhere where the derivative is not 0, there is a change, either positive or negative. Find where these changes occur, and then grab the corresponding indices. Something like below.
data = [1;1;1;2;2;2;3;3;3;4;4;4;4;4;3;3;2;2;2;2;1;1;1;1;4;4;4;4;];
change = diff(data)~=0;
indices = [1,find(change)'+1];
compressed = data(indices)';

and the result will be
compressed =
     1     2     3     4     3     2     1     4

And of course you can use the indices variable for whatever you need as well.
Note
On the third line, we add index 1 because technically the start of the array is a change, and then we add 1 to the find command because we are using find on the derivative, so the returned change array will be 1 shorter than the original.

A: I will never stop recommending this run-length encoding/deconding utility from the File Exchange: rude().
% Run-length encode preserving order
[len,val] = rude(data);
len =
     3     3     3     5     2     4     4     4
val =
     1     2     3     4     3     2     1     4

Now, to calculate the mean, first re-label each subsequence with rude(), then use accumarray()
% Decode and re-label each subsequence
subs = rude(len,1:numel(len))';

% Take average on each re-labelled subsequence
accumarray(subs,data2,[],@mean)
ans =
    4.3333
    4.0000
    6.3333
    4.2000
    5.0000
    5.2500
    5.2500
    3.5000


text:
Q: Express item.parentElement.remove() in a way that is supported by IE From what I understand, the
remove()

function is not supported in IE. I have a JS function that creates a div and appends it to an existing list.The div contains another div styled as a button (this is the 'item' in the title, that's what I called it when I got it from HTML), which, on click, removes its parentNode (and consequently itself) from the DOM (by means of remove()), though it still 'exists' in that JavaScript can read it's data and stuff. I need a way to remove it from the DOM, as well as all of it's child elements. Setting it's innerHTML equal to nothing will not work, nor will setting it's display to none. Any idea how to do this in a way compatible with IE?
Any help appreciated, please no jQuery or other frameworks.

A: Anytime you would use .remove(), you can always just use .removeChild() instead with slightly different code around it.
So, if you wanted to do to remove the parent of a given node:
item.parentElement.remove();

Then, you can instead do this:
var p = item.parentNode;
p.parentNode.removeChild(p);

If you want to put this in a utility function, you can do this:
function removeNode(node) {
    node.parentNode.removechild(node);
}

And, in your case, instead of item.parentElement.remove() you would call it like this:
removeNode(item.parentNode);

Note, I'm using parentNode instead of parentElement since you appear to want IE compatibility with older versions of IE.  parentNode and parentElement are not exactly the same, but it's very rare where parentNode would be different than parentElement (in fact, I can't think of a case in a normal DOM where it wouldn't be appropriate to use parentNode).  See Difference between DOM parentNode and parentElement for a discussion of the differences.


text:
Q: If something doesn't exist in a database I am currently making profile pages for my new website, but the only thing I can't figure out is, how do I check if the user DOESN'T exist in the database, so if the user doesn't exist, I can echo out something saying that "User not found: lol123"

A: Simple.  Just query the database for a user of that name.  If no records are returned then they don't exist.


text:
Q: html response time java servlet is very high I have a servlet which needs to handle high volumes of simple http requests. I sometimes have to return it as an json response and the other times as html.
The code of the entire servlet is the same however at the end I have an if-statement:
 if(json) {
      request.setContentType("application/JSON");
      String json_response = String.format("some string %s", some_other_string);
      out.print(json_response);
 } else {
      request.setContentType("text/html");
      String html_response = String.format("some text %s", some_other_string);
      out.print(html_response);
 }

My connection pooling settings are:
<Resource name="jdbc/testdb"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/table?autoReconnect=true"
username="user"
password="pass"
maxActive="250"
maxIdle="60"
minIdle="30"
maxWait="10000"
/>

I run it on a dedicated server. quad-core with 12gb ram and a ssd. Tomcat 8 and Sun jdk 8
When I send requests for json responses the server has no problem handeling 200 requests per second.
But when I send requests for html responses the response time is around 80 ms when the load is less then 10 requests per second, but when it goes over this the response time goes on average to 3000 - 4000 ms.
I timed the servlet execution and it is executed in 1ms. Also with the html response at high load, so the 3000 ms should come from somewhere else.
I tried putting the html into a jsp file but this did not change anything.
I was not able to get visualVM running to check the performance of the servlet but since it executes in 1ms I think the problem should be somewhere in the Tomcat config.
Does anybody have an idea on an approach to fixing this problem?
Thanks


text:
Q: Iframe content is a text not html code I have a problem with iframe. I added HTML code (string - I get that code from DB) in the <body> of iframe but I can't see that code as HTML, its just a string.
document.getElementById("iframe_with_content").ready(function() {
        (document.getElementById("iframe_with_content").contentWindow.document).write("<%= post.text %>");
        (document.getElementById("iframe_with_content").contentWindow.document).close();
});

A: Include jQuery to your page, and
var data = $('<textarea />').html("<%= post.text %>").text();
document.getElementById("iframe_with_content").ready(function() {
        (document.getElementById("iframe_with_content").contentWindow.document).write(data);
        (document.getElementById("iframe_with_content").contentWindow.document).close();
});

Explanation: your data provided by <%= post.text %> was actually html-entity-encoded. So actually you've got something like sadasds<i>dasd....

A: This can occur because of html escaping done by ejs try and check to see whether this works:
<%- post.text %>

Refer : How to escape HTML in node.js EJS view?
WARNING: Be careful using these functions please check XSS attacks


text:
Q: Python Django Cannot go the wanted link within another page I am currently working on a website and I have a navigation bar in it. When I click the "about" button I need website to open localhost:8000/about/ link. But when I'm in a different page like localhost:8000/chapter/3/ It directs me to localhost:8000/chapter/3/about/ (The website is about a web novel thats why there is chapters) How can I make it so that wherever I click that "about" button from I want it to direct me to localhost:8000/about/. How can I make it happen?
Urls:
urlpatterns = [
    path('', views.home, name="home"),
    path('chapter/<int:cid>/', views.view, name="chapter"),
    path('chapter/<int:cid>', views.view, name="chapter"),
    path('about/', views.about, name="about_us")
]

Views:
def home(request):
    chapter_list = Chapter.objects.all()
    last = chapter_list.last()
    return render(request, 'main.html',
                  {'chapter_list': chapter_list,
                  'last': last})

def view(request, cid: int):
    chapter_info = Chapter.objects.get(chapter_id=cid)
    chapter_info.chapter_text = chapter_info.chapter_text.replace('background-color:#ffffff', '')
    chapter_info.chapter_text = chapter_info.chapter_text.replace('color:#757575', 'color:#EEEEE')
    chapter_info.chapter_footnotes = chapter_info.chapter_footnotes.replace('background-color:#ffffff', '')
    chapter_info.chapter_footnotes = chapter_info.chapter_footnotes.replace('color:#757575', 'color:#EEEEE')
    return render(request, 'chapters.html', {'chapter_info': chapter_info})

def about(request):
    return render(request, 'about.html', {})

Note:
I tried using ../ but didn't work for me

A: Try this where ever you are it will got the about link. Try reading absolute and relative path.
about


text:
Q: Spring with jsp Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sat Sep 26 12:30:38 IST 2020
There was an unexpected error (type=Not Found, status=404).
HomeController.java
package com.JspPRo.Jspdemo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Controller
public class HomeController {

  @RequestMapping("/")
  public String homepage()
  {
    return "index.jsp";
  }

}

Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.JspPro</groupId>
<artifactId>JspProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>JspProject</name>
<description>Demo project for Spring Boot</description>
<properties>
    <java.version>11</java.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!--
 https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper
-->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.38</version>
</dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</project>

index.jsp
 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
 <body>
 hi welcome java
</body>
</html>

I dont know why its happen. plese help me to solve this i cant run jsp page.i am using spring version 4.8.0.RELEASE

A: This problem is related to your project setup, where have you placed the index.jsp file? Spring cannot find the file in the directory, so you have most likely placed it in the wrong folder.


text:
Q: Setting to DataContext not reflecting in Listbox I have a ViewModel and i am setting an instance of it to DataContext.In xaml i have binded the Listbox itemsource to an observable collection in ViewModel.But when i run the program nothing appears in listbox.What may be the Reason.
My ViewModel class:
public class ViewModel
    {
        public ObservableCollection<Data> _collectionData = new ObservableCollection<Data>();
        -----
        -----
     }

Xaml:
ListBox Name="myListBox" Margin="8,113,8,8" ItemsSource="{Binding _collectionData}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal"   >
                            <Border BorderThickness="3" BorderBrush="#A5FFFFFF" Width="80" Margin="0,20,0,20" Height="60">
                                <Image Source="{Binding ImageUrl, Mode=OneWay}"  VerticalAlignment="Stretch" Margin="0,0,0,0" Width="80" Height="60" Stretch="Fill" />
                            </Border>
                            <TextBlock TextWrapping="Wrap" Text="{Binding Title}" FontSize="40" FontWeight="Normal" VerticalAlignment="Center" Margin="30,0,0,0" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
              </ListBox>

Constructor of main page:
ViewModel vm = new ViewModel();
this.DataContext = vm;

But when i give myListBox.ItemsSource = vm._collectionSplashData; it works .what may be the reason?

A: Make property instead of field
see Binding Sources Overview

A: Applying both ItemsSource and Datacontext not needed.


text:
Q: multiple key detection for KeyListener (java) How would one implement KeyListener so that I can create a two-player system where one person uses '.' and '/' to control a character, and the other person can use the arrow keys without them interrupting each other? The way I have it now is that when one person holds down the arrow key, their character moves, but the instant you use the other player's controls, the first person's character stops.

A: Create a HashMap<Int,Boolean> that marks which keys are currently pressed/depressed.
Then in your game loop, you can move your objects depending on if the keys are depressed in this map.
For example:
if (keyMap.get(VK_COLON) == Boolean.TRUE) //True indicates pressed
   playerAXPos+= 10;

A: From the sounds of things you're listening to a keyPressed event.  Basically, you need to maintain stateful information about what keys are currently "down" and only stop the appropriate action when the keyReleased event occurs.
This will require to have two seperate lines action handler, one for when the key is pressed and one when the key is released.
One of the other things you might need to do is maintain some kind of cache of the active keys...which just got mentioned by Ethan as I was typing :P


text:
Q: Adding Image and background to NatTable rows I have read the documentation at: https://eclipse.org/nattable/documentation.php?page=styling
I am curious if there is any easy way to add background row colors and images using separate configurations.  I do not wish to combine them into 1 configuration like the CellPainterWrapper example because I want to separate the logic between the two.  My current code works for either the image or the background color, but I cannot do both (the top-most configuration overrides the bottom-most one).  Below is my snippet:
    void run(){
           addBackgroundRowColors();
           addImageToColumn();
    }

    void addImageToColumn() {
        getNatTable().addConfiguration(new AbstractRegistryConfiguration() {
            @Override
            public void configureRegistry(IConfigRegistry configRegistry) {
                final Style cellStyleOne = new Style();
                cellStyleOne.setAttributeValue(CellStyleAttributes.IMAGE,
                   myIcon);
                configRegistry.registerConfigAttribute(
                   CellConfigAttributes.CELL_STYLE, cellStyleOne,
                   DisplayMode.NORMAL, myIconLabel);

                final Style cellStyleTwo = new Style();
                cellStyleTwo.setAttributeValue(CellStyleAttributes.IMAGE,
                   myIcon2);
                configRegistry.registerConfigAttribute(
                   CellConfigAttributes.CELL_STYLE, cellStyleTwo,
                   DisplayMode.NORMAL, myIconLabel2);

                configRegistry.registerConfigAttribute(
                   CellConfigAttributes.CELL_PAINTER,
                   new CellPainterDecorator(new TextPainter(),
                   CellEdgeEnum.LEFT, 10, new ImagePainter()),
                   DisplayMode.NORMAL);
            }
        });
        DataLayer dl = getGlazedListsGridLayer().getBodyDataLayer();
        IConfigLabelAccumulator cellLabelAccumulator = (configLabels,
          columnPosition, rowPosition) -> {
               // Label code here...
        };

        dl.setConfigLabelAccumulator(cellLabelAccumulator);
    }

    void addBackgroundRowColors() {
        getNatTable().addConfiguration(new AbstractRegistryConfiguration() {
            @Override
            public void configureRegistry(IConfigRegistry configRegistry) {
                Style cellStyleOne = new Style();
                cellStyleOne.setAttributeValue(
                  CellStyleAttributes.BACKGROUND_COLOR, myColorOne);
                configRegistry.registerConfigAttribute(
                  CellConfigAttributes.CELL_STYLE, cellStyleOne,
                  DisplayMode.NORMAL, myColorLabel1);

                Style cellStyleTwo = new Style();
                cellStyleTwo.setAttributeValue(
                  CellStyleAttributes.BACKGROUND_COLOR, cellStyleTwo);
                configRegistry.registerConfigAttribute(
                  CellConfigAttributes.CELL_STYLE, cellStyleTwo,
                  DisplayMode.NORMAL, myColorLabel2);
            }
        });
        DataLayer dl = getGlazedListsGridLayer().getBodyDataLayer();
        IConfigLabelAccumulator cellLabelAccumulator = (configLabels,
          columnPosition, rowPosition) -> {
               // Label code here...
        };

       dl.setConfigLabelAccumulator(cellLabelAccumulator);
    }

Update
I ended up doing something similar to the following to make it work:
  AggregateConfigLabelAccumulator aggregate =
    new AggregateConfigLabelAccumulator();
  aggregate.add(addImageToColumn());
  aggregate.add(addBackgroundRowColors());

  getGlazedListsGridLayer().getBodyDataLayer().
    setConfigLabelAccumulator(aggregate);

A: From the comments the real question is about how to support separated IConfigLabelAccumulator. As you can only register one IConfigLabelAccumulator per layer, there are two ways to achieve this:

*

*register the different IConfigLabelAccumulator on different layers

*Use an AggregateConfigLabelAccumulator where you can combine multiple IConfigLabelAccumulator
This is also explained in the Getting Started Tutorial:
http://www.vogella.com/tutorials/NatTable/article.html


text:
Q: "datetime-local" control: Which events are triggered when the control closed? How can I track/catch with JQuery when a datetime-local control has been closed for what ever reasons:

*

*Datetime has been selected.

*Cancel button clicked.

*Reset button clicked.

This is the very simple HTML tag:
<input type="datetime-local" name="myDateTime">

A: I am not sure it will trigger for close but below code will must work when do you changed/select the date.
Below code work for me.
<input type="datetime-local" name="myDateTime" id="myDateTime">

$("#myDateTime").bind("input", function (evt) {
                    console.log(evt, evt.target.value);
                });


text:
Q: Why is the text overlapping in an infinite scroll animation on the X axis? I'm trying to set up an infinite animation effect but the seems to overlap every time I add another row (green banner) and if the div is rotated at an angle. It looks fine if there is only one green banner and if it's straight but I'm not sure why it overlaps when there are multiple. Any help would be appreciated. Image is attached for reference.

section {
  position: relative;
  width: 100%;
  height: 42%;
  overflow: hidden;
}

section .scroll {
  display: flex;
  background-color: #99e836;
  transform: rotate(-5deg);
  margin: 8rem 0;
  width: 100vw;
  border: 2px solid white;
}

section .scroll div {
  color: white;
  font-size: 4em;
  white-space: nowrap;
  font-weight: 800;
  animation: animate 40s linear infinite;
}

section .scroll div:nth-child(2) {
  animation: animate2 40s linear infinite;
  animation-delay: -20s;
}

section .scroll div span {
  margin: 0 2rem;
}

.transparent {
  color: transparent;
  -webkit-text-stroke-width: 1.3px;
  -webkit-text-stroke-color: blue;
  font-weight: 600;
  &-no {
    color: black;
    font-weight: 500;
  }
}

@keyframes animate {
  0% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(-100%);
  }
}

@keyframes animate2 {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-200%);
  }
}

section .scroll2 {
  display: flex;
  background-color: #99e836;
  transform: rotate(8deg);
  width: 100vw;
  border: 2px solid white;
  position: absolute;
  top: 7.5rem;
}

section .scroll2 div {
  color: $primary-light;
  font-size: 4em;
  white-space: nowrap;
  font-weight: 800;
  animation: animate 40s linear infinite;
}

section .scroll2 div:nth-child(2) {
  animation: animate2 40s linear infinite;
  animation-delay: -20s;
}

section .scroll2 div span {
  margin: 0 2rem;
}

section .scroll.text1 {
  box-shadow: 0 5px 15px rgba(255, 255, 255, 0.3);
}

section .scroll2.text2 {
  box-shadow: 0 5px 15px rgba(255, 255, 255, 0.3);
}

       Available for Hire
       Available for Hire
       Available for Hire
       Available for Hire

       Available for Hire
       Available for Hire
       Available for Hire
       Available for Hire

       Available for Hire
       Available for Hire
       Available for Hire
       Available for Hire

       Available for Hire
       Available for Hire
       Available for Hire
       Available for Hire

overlapping image


text:
Q: What subset of errors can be expected from a call to Stripe.card.createToken()? When making a call to Stripe.card.createToken() (Stripe.js) it seems that only a subset of the errors described in the api docs could be returned. Some errors, like card_error/card_declined, could only (?) be returned from a server side call to charge a card.
What error types and codes can be expected when making a client side call to Stripe.card.createToken()?
https://stripe.com/docs/testing#cards-responses

A: Unlike Checkout, Stripe.js only does a basic set of validations on a card such as a Luhn check and whether the expiration is with the valid universe.
You will see a card_error if, for example, the expiration or card properties are invalid, invalid_request_error should you attempt to send invalid parameters to the API, a connection error if there were a time out between your client and Stripe.
But your understanding is correct here, you would never see a decline as (unlike Checkout) an authorization is not attempted until the time at which you add the card to a Customer or create a Charge on your backend.


text:
Q: Trouble installing Particle js I've tried several different methods in trying to install Particle JS but can't seem to get them to work. When the page loads, the div that's supposed to contain the animated effect is there and in the right place, but there are no particles. I'm not the savviest with JavaScript, as I'm starting to get into web design more.
My source code is at https://github.com/nickhom3/UC-2.0 (https://nickhom3.github.io/UC-2.0/).
I've tried the setup guides here:

*

*https://github.com/VincentGarreau/particles.js

*https://redstapler.co/particles-js-tutorial/

*https://alligator.io/js/background-effects-particlesjs/
I can't figure out if I just didn't set things up right and hopefully somebody can help me fix this.


text:
Q: Считывание qr кодов у меня проблема, есть ссылка с изображением qr кода, нужно считать этот qr код(там находятся числа) и вывести данные полученные из qr кода
Спасибо
Если нужно кину код
На вход подаётся ссылка, там расположен qr код, нужно обработать его и вывести информацию

A: Я знаю как можно сделать такую штуку при помощи opencv-python в режиме реального времени(с веб камеры)
from cv2 import cv2
from pyzbar.pyzbar import decode

cap = cv2.VideoCapture(0)

cap.set(3, 360)
cap.set(4, 360)

while True:
    _, frame = cap.read()

    for code in decode(frame):
        data  = code.data.decode('utf-8')
        print(data)

    cv2.imshow('QrLinkDetection', frame)
    cv2.waitKey(1)

При запуске данного кода у вас появиться окно транслирующие изображение вашей веб камеры, если вы покажете в веб камеру QrCode то в консоль вывудиться куда он ведёт(ссылку). Думаю это можно реализовать и с картинкой подобным образом...


text:
Q: Is there any reason to clone an empty array in android? This may seems weird, but I am currently maintaining some Android code, which uses clone of an existing EMPTY ArrayList, to create a new ArrayList instead of just using new to allocate an ArrayList
The code does the same when creating new LinkedHashMap(Cloning them from an empty LinkedHashMap), so it looks like something the previous developer thought about, but what do i know.
First I thought it might be a prototype/factory thing, but he cast the cloned object back to ArrayList, so I don't think it's a way to change the allocation type later.

A: An ArrayList can be created with a initial capacity which is cloned as well, LinkedHashMap has similar parameters but this would be a weak reason.
Maybe the developer anticipated that in future versions of the code the "template" wouldn't be empty anymore.


text:
Q: php - datetimezone I'm using functions with the datetime object that require a datetimezone object as an argument. I see a list of timezones here:
http://www.php.net/manual/en/class.datetimezone.php
but there's not things like 'est'. How could I create a 'datetimezone' object from EST?

A: $tz = new DateTimeZone('EST');

A: In http://www.php.net/manual/en/timezones.php you can find in the OTHER section the EST there.
To create one use date_default_timezone_set('EST');
To make sure you have it do echo date_default_timezone_get();

A: A very verbose loop.  The construct function for the DateTime class isn't working properly for me but this works.

$date = "2011/03/20";
$date = explode("/", $date);

$time = "07:16:17";
$time = explode(":", $time);

$tz_string = "America/Los_Angeles"; // Use one from list of TZ names http://us2.php.net/manual/en/timezones.php
$tz_object = new DateTimeZone($tz_string);

$datetime = new DateTime();
$datetime->setTimezone($tz_object);
$datetime->setDate($date[0], $date[1], $date[2]);
$datetime->setTime($time[0], $time[1], $time[2]);

print $datetime->format('Y/m/d H:i:s');

?>

A: Be aware of that some TimeZone abbreviations like EST are not unique. See http://www.timeanddate.com/library/abbreviations/timezones/.
The usage of EST is not recommended, see
 http://www.php.net/manual/en/timezones.others.php.
Use for example America/New_York instead.


text:
Q: Ruby retry statement I am following this tutorial and read until loops. From the tutorial, I expected to get:

Value of local variable is 1
Value of local variable is 2
Value of local variable is 1
Value of local variable is 2
Value of local variable is 1
Value of local variable is 2
............................

but I get this instead
Value of local variable is 0
Value of local variable is 1
Value of local variable is 2

This is the code I use, which exactly same with the tutorial
#!/usr/bin/ruby

for i in 0..5
  retry if i > 2
  puts "Value of local variable is #{i}"
end

Did I miss anything?

A: As others have stated, retry is limited to rescue blocks now.  If you want to re-produce your example, you'll have to wrap it in a begin...rescue:
begin
  for i in 0..5
    raise "too big" if i > 2
    puts "Value of local variable is #{i}"
  end
rescue
  retry
end

A: You missed this: from The Ruby Programming Language, (a book from 2008, co-authored by Matz, which covers Ruby 1.8 and 1.9):"(...) In Ruby 1.8 however, retry has another use: it starts an iterator based iteration (or any method invocation) from the beginning. This use of the retry statement is extremely rare, and has been removed from the language in Ruby 1.9. It should, therefor, be considered a deprecated language feature and should not be used in new code."(page 152).
Running OP's code results in a syntax error, at least since Ruby 2.3.
Invalid retry (SyntaxError)


text:
Q: Incremental Data loading and Querying in Pyspark without restarting Spark JOB Hi All I want to do incremental data query.
  df = spark .read.csv('csvFile', header=True)  #1000 Rows
  df.persist() #Assume it takes 5 min
  df.registerTempTable('data_table') #or createOrReplaceTempView
  result = spark.sql('select * from data_table where column1 > 10') #100 rows
  df_incremental  = spark.read.csv('incremental.csv') #200 Rows
  df_combined = df.unionAll(df_incremental)
  df_combined.persist() #It will take morethan 5 mins, I want to avoid this, because other queries might be running at this time
  df_combined.registerTempTable("data_table")
  result = spark.sql('select * from data_table where column1 > 10') # 105 Rows.

*

*read a csv/mysql Table data into spark dataframe.

*Persist that dataframe in memory Only(reason: I need performance & My dataset can fit to memory)

*Register as temp table and run spark sql queries. #Till this my spark job is UP and RUNNING.

*Next day i will receive a incremental Dataset(in a temp_mysql_table or a csv file). Now I want to run same query on a Total set i:e persisted_prevData + recent_read_IncrementalData.  i will call it mixedDataset.
*** there is no certainty that when incremental data comes to system, it can come 30 times a day.

*Till here also I don't want the spark-Application to be down,. It should always be Up. And I need performance of querying mixedDataset with same time measure as if it is persisted.
My Concerns :

*

*In P4,  Do i need to unpersist the prev_data and again persist the union-Dataframe of prev&Incremantal data?

*And my most important concern is i don't want to restart the Spark-JOB to load/start with Updated Data(Only if server went down, i have to restart of course).

So, on a high level, i need to query (faster performance) dataset + Incremnatal_data_if_any dynamically.
Currently i am doing this exercise by creating a folder for all the data, and incremental file also placed in the same directory. Every 2-3 hrs, i am restarting the server and my sparkApp starts with reading all the csv files present in that system. Then queries running on them.
And trying to explore hive persistentTable and Spark Streaming, will update here if found any result.
Please suggest me a way/architecture to achieve this.
Please comment, if anything is not clear on Question, without downvoting it :)
Thanks.

A: Try streaming instead it will be much faster since the session is already running and it will be triggered everytime you place something in the folder:

df_incremental = spark \
    .readStream \
    .option("sep", ",") \
    .schema(input_schema) \
    .csv(input_path)

df_incremental.where("column1 > 10") \
    .writeStream \
    .queryName("data_table") \
    .format("memory") \
    .start()

spark.sql("SELECT * FROM data_table).show()


text:
Q: sata timeout on webserver I have a web server. About 100-150 virtual hosts. Just small websites. My first post is here: SATA hdd errors , but now I have new error on other disk.
1. I have problem with sata disk as described in the link.
2. I have put in other disk and... no luck, mkfs.ext3 - and on a new disk the same issue a lot of errors while mkfs is running.
3. Next step was to replace sata cable and this helped. after that I was able to format disk and have started file transfer from backup. So it is now 4 days since cable and disk change.. and now I see the following message in dmesg:
ata2.00: exception Emask 0x0 SAct 0x1 SErr 0x0 action 0x6 frozen
ata2.00: cmd 60/08:00:3f:25:db/00:00:01:00:00/40 tag 0 ncq 4096 in
         res 40/00:00:00:4f:c2/00:00:00:00:00/00 Emask 0x4 (timeout)
ata2.00: status: { DRDY }
ata2: hard resetting link
ata2: SATA link up 3.0 Gbps (SStatus 123 SControl 300)
ata2.00: configured for UDMA/133
ata2: EH complete
SCSI device sdb: 490350672 512-byte hdwr sectors (251060 MB)
sdb: Write Protect is off
sdb: Mode Sense: 00 3a 00 00
SCSI device sdb: drive cache: write back

In smart:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
  1 Raw_Read_Error_Rate     0x002f   200   200   051    Pre-fail  Always       -       89
  3 Spin_Up_Time            0x0027   200   200   021    Pre-fail  Always       -       991
  4 Start_Stop_Count        0x0032   100   100   000    Old_age   Always       -       16
  5 Reallocated_Sector_Ct   0x0033   200   200   140    Pre-fail  Always       -       0
  7 Seek_Error_Rate         0x002e   200   200   000    Old_age   Always       -       0
  9 Power_On_Hours          0x0032   099   099   000    Old_age   Always       -       1090
 10 Spin_Retry_Count        0x0032   100   253   000    Old_age   Always       -       0
 11 Calibration_Retry_Count 0x0032   100   253   000    Old_age   Always       -       0
 12 Power_Cycle_Count       0x0032   100   100   000    Old_age   Always       -       15
192 Power-Off_Retract_Count 0x0032   200   200   000    Old_age   Always       -       8
193 Load_Cycle_Count        0x0032   200   200   000    Old_age   Always       -       7
194 Temperature_Celsius     0x0022   118   100   000    Old_age   Always       -       25
196 Reallocated_Event_Count 0x0032   200   200   000    Old_age   Always       -       0
197 Current_Pending_Sector  0x0032   200   200   000    Old_age   Always       -       0
198 Offline_Uncorrectable   0x0030   200   200   000    Old_age   Offline      -       0
199 UDMA_CRC_Error_Count    0x0032   200   200   000    Old_age   Always       -       0
200 Multi_Zone_Error_Rate   0x0008   200   200   000    Old_age   Offline      -       0

SMART Error Log Version: 1
No Errors Logged

SMART Self-test log structure revision number 1
Num  Test_Description    Status                  Remaining  LifeTime(hours)  LBA_of_first_error
# 1  Short offline       Completed without error       00%      1024         -
# 2  Conveyance offline  Completed without error       00%       978         -
# 3  Extended captive    Interrupted (host reset)      90%       977         -
# 4  Extended captive    Interrupted (host reset)      90%       977         -
# 5  Extended offline    Completed without error       00%       977         -
# 6  Short offline       Completed without error       00%       974         -

Question 1: What does it mean, and what can be the problem? (I found in Google that 99% it is cable problem)
Question 2: Raw_Read_Error_Rate increases by 20-30 every day. Is it Ok? On disk sda value is 7000 and no errors.

A: Your hardware is defunctive, fix it.

A: I didn't read (and think about) your problem thoroughly so I may be wrong about this, but you might want to rethink the IOPS limitation of the drive. I read it somewhere (forgot the link) that on average the current consumer SATA drives only have about 75-100 IOPS while the enterprise SATA drives could double the number (and then the SAS drives which could double the number again). IIRC it was an article about SSD where it is possible to have IOPS over 9000!
EDIT0 Add related Wikipedia article: http://en.wikipedia.org/wiki/IOPS


text:
Q: How to get the current screen resolution on windows via command line? I'm trying get the current screen resolution on windows via command line.
Based on most of the answers I've found, I should use:
wmic desktopmonitor get screenheight, screenweight

But this returns the max supported resolution of the display device, not the current one, which is what I need.
Example:
I'm using a 4k monitor, but currently set to display only at 1920x1080. When I run the command above, I get:
ScreenHeight  ScreenWidth
2160          3840

How do I get the current screen resolution on windows via command line?

A: Dealing with high DPI made this somewhat challenging because most Windows API functions return a scaled version of the resolution for compatibility unless the application declares high DPI awareness. Inspired by this Stack Overflow answer I wrote this PowerShell script:
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class PInvoke {
    [DllImport("user32.dll")] public static extern IntPtr GetDC(IntPtr hwnd);
    [DllImport("gdi32.dll")] public static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
}
"@
$hdc = [PInvoke]::GetDC([IntPtr]::Zero)
[PInvoke]::GetDeviceCaps($hdc, 118) # width
[PInvoke]::GetDeviceCaps($hdc, 117) # height

It outputs two lines: first the horizontal resolution, then the vertical resolution.
To run it, save it to a file (e.g. screenres.ps1) and launch it with PowerShell:
powershell -ExecutionPolicy Bypass .\screenres.ps1

A: I had a similar problem.
Try this:
wmic PATH Win32_VideoController GET CurrentVerticalResolution,CurrentHorizontalResolution


text:
Q: uploading csv file on website and get result Dear friends
I have a console application in which i want to first  sign in and then I press button which directs me to  file upload form .In file upload form I want to upload a csv file and then redirect to next form after clicking submit button then i want to get response of that form .
can any one help me to do this from C# console application?
thanks.

A: if you want to upload a file on a website from a console application,
then you should have information about FTP credentials.

A: If you want to do a real http-transfer you need to create a http request, I looked around a little bit and found this: Upload files with HTTPWebrequest (multipart/form-data), seems to be right. I'm doing something similar in python currently.


text:
Q: show two different list as a matrix table I have two lists (item and obj) for which I will have input field that will look like this:
       item1           item2
obj1   input_field1   input_field2

obj2    input_field3  input_field4

Based on the input field data if filled up I will create obj1 record related to item1 record
How will I achieve this in aura?

A:

        <aura:iteration items="{!v.lists1}" var="list1">

                {!list1.Name}
                <aura:iteration items="{!v.lists2}" var="list2">
                    <input id="{!list2.Name+'-'+list1.Name}" value="{!list1.Name}"></input>
                </aura:iteration>

        </aura:iteration>


text:
Q: SQL: count all tasks that belong to a user inside each project I need to get the number of tasks that belong to a user inside each project on the system. The tables are:
Projects:
ID, Name
Tasks:
ID, ProjectID, Assignee(the user)
Right now I'm doing this query:
SELECT Projects.ID, Projects.Name, COUNT(*)
FROM Tasks JOIN Projects ON Tasks.ProjectID = Projects.ID
WHERE Assignee=1 GROUP BY Projects.ID;

Which only works partially. IT returns the number of tasks but only for the projects which have tasks assigned to the user. I'd like the query to return all projects in the system, even if no task has been assigned.
How can I do this?
Thanks!

A: use LEFT JOIN instead.
LEFT JOIN operates different from INNER JOIN. What it does is it returns all records from the lefthand side table which is Projects whether it has a match or none on the righthand side table which is Tasks.
SELECT  Projects.ID, Projects.Name, COUNT(Tasks.ProjectID)
FROM    Projects
        LEFT JOIN Tasks
            ON Tasks.ProjectID = Projects.ID AND
                Assignee=1
GROUP   BY Projects.ID;

To further gain more knowledge about joins, kindly visit the link below:

*

*Visual Representation of SQL Joins

A: If you need all the projects you need RIGHT OUTER JOIN instead of JOIN:
SELECT Projects.ID, Projects.Name, COUNT(Projects.ID)
FROM Tasks RIGHT OUTER JOIN Projects
ON Tasks.ProjectID = Projects.ID
AND Assignee=1 GROUP BY Projects.ID;

A: Try this
SELECT Projects.ID, Projects.Name, COUNT(*)
FROM Projects JOIN Tasks ON Tasks.ProjectID = Projects.ID
WHERE Assignee=1 GROUP BY Projects.ID;


text:
Q: React JS, load json data then manipulate it Started to play around with react, just learning the small syntax stuff at the moment, im stuck on AJAX requests with data displaying.
The console gives me an error saying the local version of test.json cannot be found. It is in the same directory as the header.js file
//header.js
import React from 'react';
import $ from 'jquery';

var theData = [];

var Header = React.createClass({
    getInitialState: function() {
        return {
        data: null
        };
    },
    componentDidMount: function() {
        $.ajax({
            dataType: 'json',
            url:  "./test.json",
            success: function(data) {
            theData.push(data);
            console.log(theData);
            }
        });
    },
    render: function() {
        return (

              {theData.someValue}

        );
    }
});

A: test.json might be in the same directory as header.js, but your code is running client-side and the client (browser) has no idea of what test.json is.
Instead, you should define an endpoint in your server-side logic to read the contents of test.json and return it back to the client as a JSON object. In your client-side logic, the URL property in your current XHR should be replaced with the URI to the endpoint.
Side note: your component as-is won't display any data after the XHR is complete. theData will be properly mutated but it won't trigger a component rerender. You should instead associate your XHR response JSON with component state (which you initialized properly in getInitialState), and React will rerender accordingly when its value is modified.
Update with a code example, assuming your server is Express.
On the server:
const fs = require('fs');
const app = ...

app.get('/name-this-endpoint-appropriately', (req, res) => {
    const json = fs.readFileSync('test.json', 'utf8');
    res.send(json);
});

On the client (with fixes as mentioned in the side note above):
import React from 'react';
import $ from 'jquery';

var Header = React.createClass({
    getInitialState: function() {
        return {
            data: []
        };
    },
    componentDidMount: function() {
        $.ajax({
            dataType: 'json',
            url:  "/name-this-endpoint-appropriately",
            success: (data) => this.setState({data})
        });
    },
    render: function() {
        return (

              {this.state.data.someValue}

        );
    }
});


text:
Q: Why do I need to name my connection string as "DefaultConnection" to create database MDF file? I wonder what's going on: if my connection string name is something other than DefaultConnection, then the .mdf file will not be created in the App_data folder, and the database will be created with the name efaultConnection as it appear when I go to SQL Server.
If I rename the connection string to DefaultConnection, then the .mdf file will be created in the App_data folder and I will not see the database in SQL Server using SQL Server Management Studio.
By the way, the database will be created once I try to create new user using Identity Framework.
<connectionStrings>
    <add name="DefaultConnection"
         connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\JobsWebsiteDB.mdf;Integrated Security=True;User Instance=True"
         providerName="System.Data.SqlClient"/>
</connectionStrings>

A: You don't, at least I didn't. When you create your DB context, you will need to pass the name of your connection string. For example, my connection string is named "LonelyCacheIdentity":
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, long, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    public ApplicationDbContext() : base("LonelyCacheIdentity")
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Properties<DateTime>().Configure(property => property.HasColumnType("datetime2"));
    }
}

Then, in my web.config, I have the following connection strings defined:
<connectionStrings>
    <add name="LonelyCacheConnection" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=lonelycacheproject;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="LonelyCacheIdentity" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=lonelycacheproject;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

For production, I transform the connection strings to work on the production server.


text:
Q: Elasticsearch analyzers not working on queries So I am running Elasticsearch and Kibana locally on ports 9200 and 5601 respectively. I am attempting to process a JSONL file into Elasticsearch documents and apply an analyzer to some of the fields.
This is the body:
body = {
  "mappings": {
    "testdoc": {
      "properties": {
        "title": {
          "type": "text",
          "analyzer": "stop"
        }
        "content": {
          "type": "text",
          "analyzer": "stop"
        }
      }
    }
  }
}

I then create a new index (and I am deleting the index between tests so I know it's not that)
es.indices.create("testindex", body=body)

I then parse my JSONL object into documents and upload them to elasticsearch using
helpers.bulk(es, documents, index="textindex", doc_type="testdoc"

Finally I query like this
q = {"query": { "match-all": {}}}
print(es.search(index="testindex", body="query")

My result, for a sample sentence like "The quick brown fox" is unchanged when I'd expect it to be 'quick brown fox'.
When I run the same query in Kibana I also see it not working
GET /testindex/_search
{
  "query": {
    "match-all": {}
  }
}

Response:
{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 10,
    "max_score" : 4.128039,
    "hits" : [
      {
        "_index" : "testindex",
        "_type" : "textdocument",
        "_id" : "6bfkb4EBWF89_POuykkO",
        "_score" : 4.128039,
        "_source" : {
          "title" : "The fastest fox",
          "body" : "The fastest fox is also the brownest fox. They jump over lazy dogs."
        }
      }
    ]
  }
}

Now I do this query:
POST /testindex/_analyze
{
  "field": "title",
  "text": "The quick brown fox"
}

I get this response:
{
  "tokens" : [
    {
      "token" : "quick",
      "start_offset" : 4,
      "end_offset" : 9,
      "type" : "word",
      "position" : 1
    },
    {
      "token" : "brown",
      "start_offset" : 10,
      "end_offset" : 15,
      "type" : "word",
      "position" : 2
    },
    {
      "token" : "fox",
      "start_offset" : 16,
      "end_offset" : 19,
      "type" : "word",
      "position" : 3
    }
  ]
}

Which is what I would expect.
But conversely if I do
POST testindex/testdoc
{
  "title":"The fastest fox",
  "content":"Test the a an migglybiggly",
  "published":"2015-09-15T10:17:53Z"

}

and then search for 'migglybiggly', the content field of the returned document has not dropped its stop words.
I am really at a loss as to what I am doing wrong here. I'm fairly new to elasticsearch and this is really dragging me down.
Thanks in advance!
Edit:
If I run
GET /testindex/_mapping

I see
{
  "textindex" : {
    "mappings" : {
      "testdoc" : {
        "properties" : {
          "title" : {
            "type" : "text",
            "analyzer" : "stop"
          },
          "content" : {
            "type" : "text",
            "analyzer" : "stop"
          }
        }
      }
    }
  }
}

So, to me, it looks like the mapping is getting uploaded correctly, so I don't think it's that?

A: This is expected behavior because when you execute queries and get a response then it is your original content (_source) you receive and not analyzed field.
The analyzer is used for, how the Elasticsearch Index field into inverted index and it is not for changing your actual content. Same analyzer will be applied at query time as well, so when you pass the query, it will use stop analyzer and remove stopwords and search your query in inverted index.
This POST /testindex/_analyze API will show how your original content is analyzed / tokenized and store to inverted index. It will not change your original document.
So when you search match_all query, it will just get all the documents from Elasticsearch with _source which have original document content and give you as a response.
You can use match query for matching on specific field insted of match_all as match_all will give you all the document from index (by default 10).
{
  "query": {
    "match": {
      "title": "The quick brown fox"
    }
  }
}

Here, you can try query like quick brown fox or The quick etc.
Hope I have clear your understandings..


text:
Q: How to create dynamic array in java depending up on input? At start ,I am initiating 20 size array fields for taking input (i.e. std_id, name,...etc) .
I wants to create  a dynamic array for these fields instead intializing length at start.
The dynamic array should be assigned its length as per the input entered by the user.
Please help in the below code.
public class Input {
    private int[] std_id = new int[20];// initiating 20 size
    private String[] name = new String[20];
    private int[] age = new int[20];
    private String[] email = new String[20];;

    Scanner in = new Scanner(System.in);

    private final List<Student> Students = new ArrayList<Student>();

    public Input()
    {
        initInput();
    }

    public void initInput()
    {
         int rec;
         System.out.println("How  many records do u want to enter:");
         rec = in.nextInt();

        for(int i=0 ; i <= rec; i++)
        {
            std_id[i] = in.nextInt();
            name[i] = in.next();
            age[i] = in.nextInt();
            email[i] = in.next();
        }

        for(int i=0; i <= rec ; i++)
        {
            Students.add(new Student(std_id[i],name[i], age[i], email[i]));
        }
    }
}

A: Use following lines just after reading the value of rec from user:
std_id = new int[rec];
name = new String[rec];
age = new int[rec];
email = new String[rec];

Following is fully corrected code:
public class Input {
    private int[] std_id;// initiating 20 size
    private String[] name;
    private int[] age;
    private String[] email;

    Scanner in = new Scanner(System.in);

    private final List<Student> Students = new ArrayList<Student>();

    public Input()
    {
        initInput();
    }

    public void initInput()
    {
         int rec;
         System.out.println("How  many records do u want to enter:");
         rec = in.nextInt();

        std_id = new int[rec];
        name = new String[rec];
        age = new int[rec];
        email = new String[rec];

        for(int i=0 ; i < rec; i++)
        {
            std_id[i] = in.nextInt();
            name[i] = in.next();
            age[i] = in.nextInt();
            email[i] = in.next();
        }

        for(int i=0; i < rec ; i++)
        {
            Students.add(new Student(std_id[i],name[i], age[i], email[i]));
        }
    }
}

Note: While using loop, don't use i <= rec because you are using wrong index and you will get ArrayIndexOutOfBoundsException. Use i < rec instead.

A: Initialize the arrays after you know the value of rec:
int rec;
System.out.println("How  many records do u want to enter:");
rec = in.nextInt();

std_id = new int[rec];
age = new int[rec];
etc.

And remove the initialization from the class variables at the top:
public class Input {
    private int[] std_id;
    private String[] name;
    etc.

A: Get rid of the arrays. You don't need them.
Also, if you want rec number of records, don't loop from 0 to <= rec, because that would be rec + 1 records, so I changed loop to use < rec, which is the common way to do it.
Java naming convention is for field names to start with lowercase letter, so I renamed Students to students.
public class Input {
    Scanner in = new Scanner(System.in);

    private final List<Student> students = new ArrayList<Student>();

    public Input()
    {
        initInput();
    }

    public void initInput()
    {
        System.out.println("How  many records do u want to enter:");
        int rec = in.nextInt();

        for (int i = 0; i < rec; i++)
        {
            int std_id = in.nextInt();
            String name = in.next();
            int age = in.nextInt();
            String email = in.next();
            students.add(new Student(std_id, name, age, email));
        }
    }
}

A: One more solution:
class Input {
    private Scanner in = new Scanner(System.in);
    private List<Student> list = new ArrayList<>();

    public Input() {
        initInput();
    }

    public void initInput() {
        int rec;
        System.out.println("How  many records do u want to enter:");
        rec = in.nextInt();

        for (int i = 0; i < rec; i++) {
            Student student = new Student();
            student.setId(in.nextInt());
            student.setName(in.next());
            student.setAge(in.nextInt());
            student.setEmail(in.next());
            list.add(student);
        }
        // this line to stop entering data
        in.close();
        // this one just to show the result
        list.forEach(s -> System.out.println("Student ID " + s.getId() + ", name: " + s.getName()));
    }
}

Comments:

*

*Don't need to use array, take List instead!

*In your for loop you need to use '<' not '<=' to prevent extra iteration

*It's quite enough to use one for loop to do everything


text:
Q: Authentication Servlet Filter I created java ee application with this tutorial: http://prideafrica.blogspot.com/2007/04/simple-authentication-servlet-filter.html
but I do not know what libraries are needed. These lines give me the "cannot find symbol" errors:
User user = UserFacade.findByUsername(username);
UserToken tok = Authentication.authenticateUser(user, username, password);
ServletContext context = filterConfig.getServletContext();

and another question. What do I need to add to these files that are in this tutorial?
Thanks. Sorry for bad english.

A: You will need to add a Servlet API library into your project. If you use maven to manage dependency, here is the dependency setting:
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
</dependency>

You may need to change the version of servlet api depending on what version you want to use and whether your servlet container support it. Since you are creating a Java EE web application, I guess your servlet container should support version 3.0. Normally, Netbeans should already add this library to your classpath when you create a web application project.
If you are using Netbeans and already add servlet api to your classpath, you should be able to use Netbeans to fix what should be imported, Right click in your code editor and then clikc "Fix import". Whatever that cannot be fixed is what you need to take care of it yourself.
You will need to have a better understanding of web authentication, at least how the basic authentication work.
I recommend you to have a look at Spring-Security, it can deal with almost all of authentication problems. However, for a beginner, this can be a little difficult.


text:
Q: J8583 LLLLBIN and LLLLVAR produces the different length padding result LLLLVAR and LLLLBIN produces different length produced from the same input.
Tried to pass in the value "6832" into the same IsoMessage object,  however, LLLLVAR returns "00046382", while LLLLBIN returns "000836333832".
Sample of the source code as below:
msg.setValue(60, "6832".toByteArray(Charsets.US_ASCII), IsoType.LLLLBIN, 10)//encodes to 000836333832
msg.setValue(60, "6832", IsoType.LLLLVAR, 10) //encodes to 00046382

I though both should return 0004, why are both results different?

A: When you encode ISO messages as text, the LxBIN fields encode their data in hex, and so the size is double what you'd expect. However, the decoder decodes the hex data and gives you a byte array when parsing.
LxVAR and LxBIN fields only have the same length when the whole message is encoded using binary formatting.


text:
Q: What is the difference between a trivial ctor (or dtor) and a user defined empty ctor (or dtor) The C++ standard defines some very specific behaviors when a class has a trivial constructor and/or a trivial destructor.
As an example, as per §3.8/1 of the standard:

The lifetime of an object of type T ends when:
— if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or
— the storage which the object occupies is reused or released.

So,

*

*if an object is not trivialy destructible, any attempt to access members of the object after the destructor is called is UB.

*if an object is trivialy destructible, attempt to access members of the object after the destructor is called is safe and not UB.

Although this example may not be the best one, it shows that the difference in behavior maybe crucial (UB/non-UB) whether an object is trivialy destructible or not.
§12.4/3 of the Standard states that (to sumerize) a destructor of a class T is trivial if it is implicitely defined, not virtual, and if all base classes and members of class T are trivially destructible.
In my (modest) experience, I never saw any difference, in terms of code generated by the compiler, between :

*

*a class with a trivial default ctor and/or a trivial dtor, and

*a class with a user defined empty ctor and/or a non-virtual user defined empty dtor (as long as the class, its base classes and members classes also have non-virtual dtor user defined empty or trivial)

So, my questions are:

*

*In what way a user defined empty ctor/dtor can or cannot be considered as a trivial-like ctor/dtor regarding compiler code generation, optimizations, trade-offs, ...

*Same question with user defined non-empty ctor/dtor; what rules should follow a code implemented in ctor/dtor to consider them as trivial-like.

My question is not related to standard (please, do not answer the standard states what is a trivial ctor/dtor, so user defined ctor/dtor is not) but to the way compilers deal with user defined ctor/dtor and in what way the behavior of a compiled code may change (or not) compared to trivial ctor/dtor.

A: You know the standards better than I, but going on the information you've provided, the standard defines a trivial destructor, but it doesn't define an empty destructor, which would make this question kind of misleading.  A trivial destructor is then a special case that compilers can optimize to, and while an  empty constructor makes sense to us, it's not something compiler writers have to consider.
Browsing a few SO links:

*

*Why Does Default user defined destructors in C++ increases execution time? shows a case where a compiler does act differently for trivial vs. empty destructors.  The answer there implies one difference is in exception handling.  It doesn't look for an empty constructor because it's not required to, and so handles exceptions as if there was valid code inside the dtor.

*Will an 'empty' constructor or destructor do the same thing as the generated one? seems to be such a close match to your question that it might be a duplicate.  It's better to read it on your own instead of relying on my interpretation, but it makes mention of Microsoft compilers not being able to inline empty destructors, and all compilers wanting a working base class destructor (and it being a very bad programming practice for the base dtor not to be virtual).

To answer your second question, as soon as your ctor is non-empty, it isn't trivial.  The closest you get to trivial is an empty ctor/dtor, and your careful reading of the standard already tells you that that's not defined to be trivial.
TL;DR: The standard defines a trivial dtor, but not an empty one.  Smart compilers can choose to notice that it's user-defined empty and treat it as trivial, but the standard doesn't require any such consideration.

A:
In what way a user defined empty ctor/dtor can or cannot be considered as a trivial-like ctor/dtor regarding compiler code generation, optimizations, trade-offs, ...

If the constructor/destructor are not inlined, then the compiler may (depending on link-time optimizations) have to issue a call to them, even though they're no-ops.
For example, the following code:
struct Struct {
  Struct();
  ~Struct();
};

int main() {
  Struct s;
}

Is compiled to (with optimizations turned on):
main:
        subq    $24, %rsp
        leaq    15(%rsp), %rdi
        call    Struct::Struct()
        leaq    15(%rsp), %rdi
        call    Struct::~Struct()
        xorl    %eax, %eax
        addq    $24, %rsp
        ret

Notice that there is still a call to the constructor and destructor, even though in a separate file I could have defined them to just be empty functions.
If, however, you've inlined the definitions:
struct Struct {
  Struct() {}
  ~Struct() {}
};

Struct foo() {
  return Struct{};
}

Then the compiler can (and will if it doesn't totally suck) treat them just like trivial constructors/destructors:
foo():
        movq    %rdi, %rax
        ret

In that sample, any constructor/destructor calls are completely optimized away, and the generated code is the same as if Struct's definition were simple struct Struct {};.

Same question with user defined non-empty ctor/dtor; what rules should follow a code implemented in ctor/dtor to consider them as trivial-like.

This kind of depends. Again, if the constructor/destructor are not inlined, then the compiler might still have to issue calls to them, in which case they're not at all trivial-like.
However, inline non-empty constructors/destructors might still be "trivial-like" if the optimizer can completely optimize them away (for example, if they only contain for (int x = 0; x < 1000; ++x);, then that is useless code that can be optimized away) to the point that they're effectively empty.
But if they do useful work that can't just be optimized away, then they won't be trivial-like at all. They'll be run. They have to.


text:
Q: PHP - Access-Control-Allow-Origin not working I own a site that we'll call www.example.com. The main chunk of my site is in two files; header.php and index.php. The top half of the website code is in header.php while the bottom half is in index.php. My problem is, I can't get the Access-Control-Allow-Origin attribute to show up in the response header from example.com

My code:
The following is a simplified version of header.php:
<?php
header("Access-Control-Allow-Origin:*", false);
...
additional code here
...
?>
<!DOCTYPE html>

        <title>My Site</title>

        ....
        top half of site code
        ....

The following is a simplified version of index.php:
<?php
header("Access-Control-Allow-Origin:*", false);
include ("header.php");
?>
        ....
        bottom half of site code
        ....

Here is my request to retrieve the images:
$.ajax({
            type: "GET",
            url : folder,
            success: function (data) {
                if($(".img").length){
                    $(".img").remove();
                }

                $(data).find("a").attr("href", function (i, val) {
                    if( val.match(/\.(jpe?g|png|gif)$/) ) {
                        $("#img-lib").append( "" );
                    }
                });
            },
            error: function () {
                $("#er").remove();
                $("#img-lib").append("
There was an error retrieving the images
");
            }
});

My error: This is what I get when I try to access www.example.com/Section/images/ : http://i.stack.imgur.com/29t8n.jpg

What I have already tried:
(The following code snippets are the first line of php code)

*

*header("Access-Control-Allow-Origin:*"); in header.php ONLY.

*header("Access-Control-Allow-Origin:www.example.com"); in header.php ONLY.

*header("Access-Control-Allow-Origin:*"); in header.php and index.php

*header("Access-Control-Allow-Origin:*", false); in header.php and index.php

It Might be worth mentioning that the site I am currently building is going to be used to edit my existing site (www.example.com).

A: Probably your static files, like images, aren't accessed via index.php (you are referring to their physical location). In this case, CORS headers can be set at the level of HTTP server. If it handles .htaccess files, you can simply create .htaccess file containing following content:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

in the main or specified directory.


text:
Q: Layout responsivo con css Buen dia!
Estoy aprendiendo css y quiero hacer el layout de un dashboard que contenga un sidebar, un nav en la parte de arriba y el contenido en el centro.
Lo estoy haciendo utilizando grid, pero no estoy seguro de si esta es la mejor manera de hacerlo, ya que quiero que en dispositivos moviles el sidebar siempre este oculto y se muestre al pulsar un boton un "hambuger button".
Oculto el sidebar reconstruyendo mi grid-templates-areas. Pero me gustaria que en dispositivos moviles ocupara toda la pantalla y apareciera con una sencilla animacion al presionar el "hamburger button", es por eso que no estoy seguro de que usar grid para hacer esto sea la mejor opcion
el codigo que tengo hasta ahora es el siguiente:
https://codepen.io/JohnatanDeLeon/pen/jOqVKjZ

A: Te recomiendo usar flexbox en lugar de grid, es hay mas posibilidades con flexbox:
Por el alto en móbil no te preocupes ya que el contenido se encargará de ello.
Yo lo haría de la siguiente forma, solo restaría crear la funcionalidad del botón para que muestre nuevamente el contenidor que se oculta.
Puede probar esto, visualizalo en pantalla completa para que veas como queda.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.content-wrapper {
    display: flex;
    height: 100vh;
}

.nav{
    background: #f00;
}

.nav li, .aside li {list-style-type: none;}

.contentDiv {
    width: 75%;
    order: 1;
}
.aside{
    width: 25%;
    background: #0f0;
}

.content{
    background: #fff;
}

@media screen and (max-width: 768px){
    .content-wrapper {display: block;}
    .contentDiv, .aside {
          width: 100%;
    }
    .aside {display: none}
}

                    item1
                    item2
                    item3

                item1
                item2
                item3