Q: Bash loop, print current iteration? Say you have a simple loop
while read line
do
  printf "${line#*//}\n"
done < text.txt

Is there an elegant way of printing the current iteration with the output? Something like

0 The
1 quick
2 brown
3 fox

I am hoping to avoid setting a variable and incrementing it on each loop.

A: To do this, you would need to increment a counter on each iteration (like you are trying to avoid).
count=0
while read -r line; do
   printf '%d %s\n' "$count" "${line*//}"
   (( count++ ))
done < test.txt

EDIT: After some more thought, you can do it without a counter if you have bash version 4 or higher:
mapfile -t arr < test.txt
for i in "${!arr[@]}"; do
   printf '%d %s' "$i" "${arr[i]}"
done

The mapfile builtin reads the entire contents of the file into the array. You can then iterate over the indices of the array, which will be the line numbers and access that element.

A: You can use a range to go through, it can be an array, a string, a input line or a list.
In this example, i use a list of numbers [0..10] is used with an increment of 2, as well.
#!/bin/bash
for i in {0..10..2}; do
   echo " $i times"
done

The output is:
 0 times
 2 times
 4 times
 6 times
 8 times
 10 times

To print the index regardless of the loop range, you have to use a variable "COUNTER=0" and increase it in each iteration "COUNTER+1".
my solution prints each iteration, the FOR traverses an inputline and increments by one each iteration, also shows each of words in the inputline:
#!/bin/bash

COUNTER=0
line="this is a sample input line"

for word in $line; do
    echo "This i a word number $COUNTER: $word"
    COUNTER=$((COUNTER+1))
done

The output is:
This i a word number 0: this
This i a word number 1: is
This i a word number 2: a
This i a word number 3: sample
This i a word number 4: input
This i a word number 5: line

to see more about loops: enter link description here
to test your scripts: enter link description here

A: n=0
cat test.txt | while read line; do
  printf "%7s %s\n" "$n" "${line#*//}"
  n=$((n+1))
done

This will work in Bourne shell as well, of course.
If you really want to avoid incrementing a variable, you can pipe the output through grep or awk:
cat test.txt | while read line; do
  printf " %s\n" "${line#*//}"
done | grep -n .

or
awk '{sub(/.*\/\//, ""); print NR,$0}' test.txt

A: You don't often see it, but you can have multiple commands in the condition clause of a while loop. The following still requires an explicit counter variable, but the arrangement may be more suitable or appealing for some uses.
while ((i++)); read -r line
do
    echo "$i $line"
done < inputfile

The while condition is satisfied by whatever the last command returns (read in this case).
Some people prefer to include the do on the same line. This is what that would look like:
while ((i++)); read -r line; do
    echo "$i $line"
done < inputfile

A: Update:  Other answers posted here are better, especially those of @Graham and @DennisWilliamson.
Something very like this should suit:
tr -s ' ' '\n' <test.txt | nl -ba

You can add a -v0 flag to the nl command if you want indexing from 0.


Q: Kubernetes Ingress Nginx Controller is Not Found Ingress Nginx controller is returning 404 Not Found for the React application. I narrowed it down to the React app because if I try to hit posts.com/posts, it actually returns the JSON list of existing posts, but for the frontend app it keeps showing
GET http://posts.com/ 404 (Not Found)
I looked to some other stackoverflow questions, to no avail unfortunately.
ingress-srv.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress-srv
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: "use"
spec:
  rules:
    - host: posts.com
      http:
        paths:
          - path: /posts/create
            pathType: Prefix
            backend:
              service:
                name: posts-clusterip-srv
                port:
                  number: 4000
          - path: /posts
            pathType: Prefix
            backend:
              service:
                name: query-srv
                port:
                  number: 4002
          - path: /posts/?(.*)/comments
            pathType: Prefix
            backend:
              service:
                name: comments-srv
                port:
                  number: 4001
          - path: /?(.*)
            pathType: Prefix
            backend:
              service:
                name: client-srv
                port:
                  number: 3000

client-depl.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: client-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: client
  template:
    metadata:
      labels:
        app: client
    spec:
      containers:
        - name: client
          image: brachikaa/client
          imagePullPolicy: Always
---
apiVersion: v1
kind: Service
metadata:
  name: client-srv
spec:
  selector:
    app: client
  ports:
    - name: client
      protocol: TCP
      port: 3000
      targetPort: 3000

frontend Dockerfile
FROM node:alpine

ENV CI=true

WORKDIR /app
COPY package.json ./
RUN npm install
COPY ./ ./

CMD ["npm", "start"]

Logging the pod:
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  11m   default-scheduler  Successfully assigned default/client-depl-f7cf996cf-cvh6m to minikube
  Normal  Pulling    11m   kubelet            Pulling image "brachikaa/client"
  Normal  Pulled     11m   kubelet            Successfully pulled image "brachikaa/client" in 42.832431635s
  Normal  Created    11m   kubelet            Created container client
  Normal  Started    11m   kubelet            Started container client

If you need any other logs, I will gladly provide them. Thanks.

A: In your yamls, there is a path "/?..." for handling the query parameters but this path will not receive traffic from "/" path as there is no prefix match. So you have to create a path "/" with type prefix to solve the issue. Then you can ignore current "/?..." path as it will match prefix with "/" path.
Please try this:
ingress-srv.yaml
__________________
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress-srv
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: "use"
spec:
  rules:
    - host: posts.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: client-srv
                port:
                  number: 3000
          - path: /posts/create
            pathType: Prefix
            backend:
              service:
                name: posts-clusterip-srv
                port:
                  number: 4000
          - path: /posts
            pathType: Prefix
            backend:
              service:
                name: query-srv
                port:
                  number: 4002
          - path: /posts/?(.*)/comments
            pathType: Prefix
            backend:
              service:
                name: comments-srv
                port:
                  number: 4001
          - path: /?(.*)
            pathType: Prefix
            backend:
              service:
                name: client-srv
                port:
                  number: 3000

A: so the issue was a really dumb one - I actually set nginx.ingress.kubernetes.io/use-regex: "use" instead of nginx.ingress.kubernetes.io/use-regex: "true"... After three days of checking through the documentation, I finally found it. If anyone encounters a similar problem - there you have it.

A: You have to add following rules in your spec
          - path: /
            pathType: Prefix
            backend:
              service:
                name: client-srv
                port:
                  number: 3000

This matches all paths.
Reference - https://kubernetes.io/docs/concepts/services-networking/ingress/#examples


Q: Why do we even attempt to predict random numbers when they are by definition, "random"? I've been given the task of writing an algorithm to predict the next value of the Mackey glass time series, given 4 past values using neural networks, so I want to understand how that makes sense.
I know random number generators are pseudo random. But the Mackey glass time series and this answer on StackOverflow made me curious.
I know there are ways to predict data based on the variation of related variables. That's sensible. But why do people try to predict a future value of something that's obviously random, using previous values which were obviously random? The way I see it, on a 2D graph, there's a 50% chance that the value would go up or down. So half of the time you might get a correct prediction, even if you didn't use the previous data. I wouldn't even call it a prediction. It seems so dumb to pretend to predict something like this. Yet, there are people who try to actually theorize it. Why?

A: There are many versions of random.  We all agree that random numbers should be equally distributed over some range unless you ask for some other distribution.  That doesn't preclude correlations between successive numbers from a generator.  I might create a generator that produces randoms in the range $[0,1)$ by $a_{n+1}=a_n+\pi \pmod 1$.  Over the long run they will be nicely distributed.  They would fail a test for the correlation of two successive numbers.  The question implies that using the last four values you can predict the next value better than chance.  You are being asked to demonstrate this.

A: If you can reduce the uncertainty by a factor of 8, you can predict the first three bits of the next number.  So someone sending speech over the net doesn't have to send those first three bits.  That reduces the bandwidth needed.


Q: Unable to connect to micro service through ZUUL api gateway in docker I've following services and working fine when they are deployed in localhost (through eclipse). But unable to invoke the rest service when deployed as separate docker containers.
I'm new docker and attended the tutorials to have knowledge on how this works.
Following services are running in separate docker containers and configured as follows (local environment)
Eureka
Docker IP : 172.17.0.3
Docker port mapping : 8761:8761

spring.application.name=naming-server
server.port=8761

Zuul API gate way
Docker IP : 172.17.0.4
Docker port mapping : 8765:8765

spring.application.name=gateway-server
server.port=8765

User service
Docker IP : 172.17.0.5
Docker port mapping : 8101:8101

spring.application.name=user-service
server.port=8101

Registered services info in Eureka
Application         AMIs    Availability Zones  Status
USER-SERVICE        n/a (1) (1)                 UP (1) - de4396a354ea:user-service:8101
API-GATEWAY         n/a (1) (1)                 UP (1) - e5dd509065cd:api-gateway:8765
When tried to invoke the service in "User service" through gateway, it's throwing exception
    com.netflix.zuul.exception.ZuulException: Forwarding error
        at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.handleException(RibbonRoutingFilter.java:198) ~[spring-cloud-netflix-zuul-2.2.0.RELEASE.jar!/:2.2.0.RELEASE]
        at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.forward(RibbonRoutingFilter.java:173) ~[spring-cloud-netflix-zuul-2.2.0.RELEASE.jar!/:2.2.0.RELEASE]

    Caused by: java.net.UnknownHostException: de4396a354ea: Name or service not known
        at java.base/java.net.Inet4AddressImpl.lookupAllHostAddr(Native Method) ~[na:na]
        at java.base/java.net.InetAddress$PlatformNameService.lookupAllHostAddr(InetAddress.java:929) ~[na:na]
        at java.base/java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1515) ~[na:na]

Note: "de4396a354ea" is the container id for "User service"
Please guide on how to resolve this issue and also provide any links where I can get more info regarding deploying microservices in docker containers.

A: Able to resolve this by adding "eureka.instance.hostname=" property.


Q: GEE do not import data into array I am having problems importing data from Google Earth Engine to a local array using Python API.
A simplified version of my code:
import ee
ee.Initialize()

#Load a collection
TERRA = ee.ImageCollection("MODIS/006/MOD09A1").select(['sur_refl_b02', 'sur_refl_b07',"StateQA"])
TERRA = TERRA.filterDate('2003-01-01', '2019-12-31')

#Extract an image
TERRA_list = TERRA.toList(TERRA.size())
Terra_img = ee.Image(TERRA_list.get(1))

#Load as array
Terra_img = Terra.get('sur_refl_b02')
np_arr_b2 = np.array(Terra_img.getInfo())

But np_arr_b2 seems to be empty
Does anybody know what am I doing wrong?
Thanks!

A: You are not far from the goal, at least to a certain extent. There's a limit to how many pixels can be transferred over such a request, namely 262144. Your image, when taken over the whole globe (like you are doing), has 3732480000 - over 10000x too many. Still, you can sample a small area and put in the numpy:
import ee
import numpy as np
import matplotlib.pyplot as plt

ee.Initialize()

#Load a collection
TERRA = ee.ImageCollection("MODIS/006/MOD09A1").select(['sur_refl_b02', 'sur_refl_b07',"StateQA"])
TERRA = TERRA.filterDate('2003-01-01', '2019-12-31')

#Extract an image
TERRA_list = TERRA.toList(TERRA.size())
Terra_img = ee.Image(TERRA_list.get(1))
img = Terra_img.select('sur_refl_b02')

sample = img.sampleRectangle()
numpy_array = np.array(sample.get('sur_refl_b02').getInfo())

It's an area over Wroclaw, Poland, and looks like this when passed to matplotlib via imshow:

What if you really need the whole image? That's where Export.image.toDrive comes into play. Here's how you'd download the image to the Google Drive:
bbox = img.getInfo()['properties']['system:footprint']['coordinates']
task = ee.batch.Export.image.toDrive(img,
    scale=10000,
    description='MOD09A1',
    fileFormat='GeoTIFF',
    region=bbox)
task.start()

After the task is completed (which you can monitor also from Python), you can download your image from Drive and access it like any other GeoTIFF (see this GIS Stack Exchange post).

A: It seems like you want to download data from earth engine to then use them with numpy. You are doing two things wrong here:

*

*You are treating Google Earth Engine as a download service. This is not the purpose of Earth Engine. If you want to download big amounts of data (like in your case a year of Terra Surface Reflectance) you should download them directly from the service providers. The only thing you should download from Earth Engine are the end-results of your analysis which you conducted within Earth Engine.

*.getInfo does not get you the satellite data, it will only get you the metadata of your ImageCollection in the form of a JSON Object. If you want to the actual raster data you would have to export it (which, as said in 1, you shouldn't do for this amount of data).


Q: Samba Share Over OpenVPN, Split Tunneling? I would like my PC to connect to a server running OpenVPN + Samba + file management software. How would I setup so that the PC only connects to the server without tunneling all the internet traffic to the VPN? I would like to keep the Samba Share connection encrypted.

A: You shouldn't push the default route from your OpenVPN server - you push only routes to the network you want to access. For example I have OpenVPN running on internal network, so in OpenVPN server.conf I have this:
push "route 10.10.2.0 255.255.255.0"
push "route 172.16.2.0 255.255.255.0"

This will cause Windows OpenVPN client to add only routes for these 2 networks after connect, so it won't affect the default route and internet traffic.
One caveat is that at least Windows 7 recognizes different networks by their gateways. If the network doesn't have a gateway, Windows is unable to recognize the network and you are unable to choose if is it Home/Work/Public network (which would deny samba access if using Windows Firewall).
The workaround I use is to add a default gateway route with big metric (999), so that it is never used for routing by Windows. I have this in the clients config file, but probably it can be put also to the server's config.
# dummy default gateway because of win7 network identity
route 0.0.0.0 0.0.0.0 vpn_gateway 999


Q: memcached dead but subsys locked service memcached restart yields:
stopping memcached:      [failed]
starting memcached:      [  ok  ]
service memcached status yields:
memcached dead but subsys locked
ls inside /var/lock/subsys/ shows a file named memcached
ls inside /var/run/ shows no pid file named memcached
there is another folder named memcached in here but there is nothing in that folder.
rm /var/lock/subsys/memcached gets rid of the memcached lock file
service restart memcached yeilds:
stopping memcached:      [failed]
starting memcached:      [  ok  ]
service memcached status yields:
memcached dead but subsys locked
what am I doing wrong?
EDIT: I'd like to add that I've searched for this before posting and I'm either already doing the steps listed in said post or that post is years old.

A: Is there another process binding to TCP/11211?
Perhaps you tried to start the memcached service as a non-privileged user and it failed with:
$ service memcached start
Starting memcached:                                        [  OK  ]
touch: cannot touch ‘/var/lock/subsys/memcached’: Permission denied

After that, service memcached status will falsely report that memcached is not running:
$ service memcached status
memcached dead but subsys locked

But it is, and it is binding to port 11211, in order to check for this you can use:
$ fuser -n tcp 11211
11211/tcp:            4439

Or:
$ pgrep -l memcached
4439 memcached

Memcached will fail to start because it cannot bind to 11211, as the running instance is already bound to it. Unfortunately there are some systems (I'm looking at you, CENTOS) where it may not leave any useful hint at /var/log/messages or /var/log/syslog. That is why many of the previous answers to this question that fiddle with the binding address will look like they solved the problem.
How do you fix it?
Since service stop memcached will not work, you have to kill it:
$ pkill memcached

Or this (where 4439 is the pid you found in the previous step):
$ kill 4439

Then you can do it right, using sudo:
$ sudo service memcached start
Starting memcached:                                        [  OK  ]
$ service memcached status
memcached (pid 6643) is running...

A: Solved this problem by typing the following commands in terminal:
1) su (becoming root).
2) killall -9 memcached (killing memcached).
3) /etc/init.d/memcached start (starting memcached by hands).
Alternatively: 3) service memcached start.

A: check /etc/sysconfig/memcached
make sure the OPTIONS="-l 127.0.0.1" is correct

A: Remove -l from OPTION.
e.g., Instead of
    OPTION="-l 2.2.2.2"
try using
    OPTION="2.2.2.2"
This worked for me.

A: To resolve this problem, run the following script as root
rm /var/run/memcached/memcached.pid
rm /var/lock/subsys/memcached
service memcached start

A: Removing and reinstalling memcached is what worked for me:
[acool@acool super-confidential-dir]$ sudo yum remove memcached
...
[acool@acool super-confidential-dir]$ sudo yum install memcached

After the above commands and starting it I got:
[acool@acool super-confidential-dir]$ sudo service memcached status
memcached dead but pid file exists

At that point I killed it and removed the pid file:
[acool@acool super-confidential-dir]$ sudo killall -s 9 memcached
...
[acool@acool super-confidential-dir]$ sudo rm /var/run/memcached/memcached.pid

And finally started it and checked its status:
[acool@acool super-confidential-dir]$ sudo service memcached start
...
[acool@acool super-confidential-dir]$ sudo service memcached status
memcached (pid  13804) is running...

And then I was happy again.
Good luck.

A: In my case I wanted to use memcache through the socket with
OPTIONS="-t 8 -s /run/memcached/memcached.sock -a 0777 -U 0"

copied from another OS, and get the same problem.
Then I realized that I just forgot, that in my OS /run/ doesn't exist. That's it. Just check your path, hah


Q: Replace Space (%20) with dashes in url using .htacess I am facing an issue in url re-writing in .htaccess. My url data coming from Database which include some spaces as well. I want to omit spaces from my url's and want to replace it with dashes.
currently what i am getting with my current .htacess ..
http://www.xyz.com/detail-10-Event%20Tickets.html
I want it to be replaced with
http://www.xyz.com/detail-43-61-Event-Tickets.html (This is what i want.)
Please find the code for .htaccess and suggest what changes should i made to solve this issue.
Options +FollowSymLinks
<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteRule uploadPRODUCT-(.*)-(.*)-(.*).html$ uploadPRODUCT.php?cid=$1&aid=$2&tid=$3

    RewriteRule ab-(.*)-(.*).html$ products.php?cid=$1&cname=$2
    RewriteRule detail-(.*)-(.*)-(.*).html$ productDETAILS.php?cid=$1&aid=$2&pname=$3

    RewriteRule (.*)-(.*).html$ cms.php?name=$1&cmsid=$2

    errorDocument 404 http://www.xyz.com/notfound.php
    errorDocument 500 http://www.xyz.com/500error.html

    RewriteCond %{http_host} ^xyz.com.com [NC]

    RewriteRule ^(.*)$ http://www.xyz.com/$1 [R=301,L]

</IfModule>

A: Since you create the URLs from database entries, I would replace the spaces at URL creation time. You can use str_replace for this
$url = str_replace(' ', '-', $db_column);


Q: Integral of a function which equals division of its values at integral boundaries I am doing some derivations and stuck at some point.
Given a $C^0$ function $f(x): \mathbb{R} \to \mathbb{R}$ where $f(x) > 0$ $\forall x$, is it possible to define an integral over an interval $[a,b]$ such that
$$
\int_a^b g[f(x)]\,dx = \frac{f(b)}{f(a)}
$$
where $g$ is a functional of $f$?
If so, what is $g$?
If it makes it easier, the condition could also be
$$
\int_a^b g[f(x)]\,dx = h\left(\frac{f(b)}{f(a)}\right)
$$
where $h$ is an invertible function.

A: Such a well defined and bounded function independent from $f(x)$ and the bounds of integral $a,b$ does not exist because otherwise we should have $$\int_a^ag[f(x)]dx=0$$and while $\int_a^ag[f(x)]dx={f(a)\over f(x)}=1$ we must have $$0=1$$ which is a contradiction. Therefore such $g$ doesn't exist.


Q: How much room is there for original mathematics research? Should more universities and colleges offer degrees in mathematical research?
I am in the process of incorporating a non-profit college and I am considering offering a degree in mathematical research. However, it would have to be original research, e.g. a new proof or a new formula of some kind.
Is original research in mathematics something that can be done by anyone with some education and talent in mathematics, or is it something far too difficult for your average mathematician?
EDIT
The target student for this university would not be a young person wanting to learn mathematics, they should go to a traditional university. The target student is people like you guys on math.stackexchange. Anyone who already has good knowledge of math and who wants to expand this knowledge through researching something that will (1) be guaranteed to be published by a university affiliated journal, (2) get a degree, up to a Ph.D., by doing something in their own time that they both enjoy and adds to the world's knowledge-base.

A: Firstly, a bit of an aside, which nevertheless seems relevant: many of "the people like you guys" on Math.SE are either mathematical Ph.D.s, or Ph.D. students.  Several of them are academic staff at universities or similar institutions.
Secondly, regarding the initial question on whether more universities should offer degrees in mathematical research: this is what the Ph.D. is.   Experience shows that it is difficult to engage in successful mathematical research without a strong undergraduate background in mathematics, and without mentoring by faculty who are themselves successful mathematical researchers.  This is why the Ph.D. is a graduate degree, and why universities compete for strong researchers to make up their faculty.
I think the question "Is original research in mathematics something that can be done by anyone with some education and talent in mathematics, or is it something far too difficult for your average mathematician?" sets up a false dichotomy.  I don't think that original research is something that can easily be done by anyone with some education and talent in mathematics; a good academic environment and good advising is essential.  On the other hand, it is not far too difficult for your average mathematician: most university mathematicians are engaging in original research.  But they are not students!  They were students in a Ph.D. program, and most of them did find original research very difficult at that time --- but they developed their talent for it over their years of study, got their Ph.D., and (in most or at least many cases) continued to mature as a researcher as their career progressed.  (For example, it is pretty unusual for very recent Ph.D.'s to advise Ph.D. students, because they are too new at the research game themselves; the wherewithal to successfully advise students is something that develops as one's own ability as a researcher matures.)
In conclusion, I don't really understand what you are envisioning/asking about that is different from the traditional Ph.D. program.

A: Well, new discoveries can always happen even with basic arithmetic I'm sure there's something out there we may not know about.
Think Isaac Newton, his knowledge of math back then wasn't better than the average high school student today. He basically knew algebra and created the calculus out of need. If one of those students is extremely curious and reaches a question to which there is no answer, this may lead him to new maths and discoveries.


Q: what is the difference between GNU,GCC and MinGW.. arent they same? I was informed that Gcc is the not only the compiler for c but also for many languages is it true? if it is then how it is done

A: GNU is not a compiler. It is an Operating System and a collection of free software made to be "Unix like" without using Unix.
(GNU stands for "GNU's not Unix!")
GCC stands for "GNU Compiler Collection" and is a piece of GNU software that includes a compiler with frontends for multiple languages:

The standard compiler releases since 4.6 include front ends for C
(gcc), C++ (g++), Objective-C, Objective-C++, Fortran (gfortran), Java
(gcj), Ada (GNAT), and Go (gccgo).

MinGW stands for "Minimalist GNU for Windows" It is essentially a tool set that includes some GNU software, including a port of GCC.
In summary, MinGW contains GCC which is in the collection of GNU free software.
Further Reading Below:
GNU - https://en.wikipedia.org/wiki/GNU
GCC - https://en.wikipedia.org/wiki/GNU_Compiler_Collection#cite_note-39
MinGW - http://www.mingw.org/


Q: Data distribute in large cluster with many indices (Elasticsearch) I have  a cluster with 30 nodes and a lot  of indices with small number of primary shards . Let's say 800 indices . most indices only have 1 or 2 primary shards.
I want to know how elasticsearch cluster distribute data across the cluster such a lot of small indices?
Does all nodes in cluster receive data evenly ? or near evenly ?
Thanks,
Sun Chanras

A:
The cluster reorganizes itself to spread the data evenly.

You can read it here
For your specific case you cane use kopf, A greate plugin that visualize the location of all  shards in each node.
I think that there are more similar plugins but this is the only one that i worked with.


Q: Get documents using find() method in couchdb-nano Since CouchDB doesn't have any collections, I added a custom typeproperty to my entitys. Now I want to filter all entitys on that property, e.g. get all users by {type:'user'}. In the couchdb-doc I found a method called 'find()', which is also implemented in the nano typings, but have a lack of documentation in couchdb-nano. According to the definition, I wrote the follwing code:
class UserModel {
    type: string = 'User';
    name: string = '';
    mail: string = '';
}
let db = <nano.DocumentScope<UserModel>>nano("http://localhost:5984/testdb");
let query: nano.MangoQuery = { selector: { type: "User" } };
db.find(query, (cb:nano.Callback<nano.MangoResponse<UserModel>>) => {
    // How to get the results here? cb is a callback, but this doesn't make sense
});

It doesn't make sense to me that I get a callback. How can I get the results?
Tried using some kind of callback:
db.find(query, (users: nano.MangoResponse<UserModel>) => {
    console.log(users);
});

But users is undefined, altough the filter { selector: { type: "User" } } works well in Project Fauxton.

A: As mentioned in the nano documentation:

In nano the callback function receives always three arguments:

*

*err - The error, if any.

*body - The HTTP response body from CouchDB, if no error. JSON parsed body, binary for non JSON responses.

*header - The HTTP response header from CouchDB, if no error.

Therefore, in the case of db.find you will have:
db.find(query, (err, body, header) => {
    if (err) {
        console.log('Error thrown: ', err.message);
        return;
    }
    console.log('HTTP header received: ', header)
    console.log('HTTP body received: ', body)
});

I didn't work with typescript, however I think you can do the same with typescript.


Q: how to show results of data augmentation before and after keras.preprocessing.image.ImageDataGenerator
i am currently training a CNN with the ASL dataset https://www.kaggle.com/datamunge/sign-language-mnist. To optimize my accuracy I used the ImageDataGenerator from Keras. I wanted to print out the results of the Data Augmentation (image before and after the Data Augmentation). But I don't understand how to plot the results from datagen. This is my code:
datagen = keras.preprocessing.image.ImageDataGenerator(
        featurewise_center=False, samplewise_center=False,
        featurewise_std_normalization=False,
        samplewise_std_normalization=False,
        zca_whitening=False, rotation_range=10,
        zoom_range=0.1, width_shift_range=0.1,
        height_shift_range=0.1, horizontal_flip=False,
        vertical_flip=False)
datagen.fit(train_data)
result_data = datagen.flow(train_data, train_label, batch_size=128)
print(result_data)

train_data is a numpy array of shape (20, 28, 28, 1) and train_label(20, 1) as they are 20 images with 28*28 pixels and the third dimension for the usage in a CNN. I would like to plot it with matploit lib but also happy with anything else (np array of the pixels).If someone could also tell me how I can print the amount of data the datagen generated would be awesome. Thank you in advance for your help.

A: First, you can create default DataGenerator to plot original images easily
datagenOrj = keras.preprocessing.image.ImageDataGenerator()

You can flow a small sample like the first five images into your 'datagen'. This generator gets images randomly. To making a proper comparison, small and certain sampling can be good for large dataset.
result_data     = datagen.flow(train_data[0:5], train_label[0:5], batch_size=128)
result_data_orj = datagenOrj.flow(train_data[0:5], train_label[0:5], batch_size=128)

When you call the next() function, your data generator loads your first batch. The result should contain both train data and train label. You can access them by index.
def getSamplesFromDataGen(resultData):
    x = resultData.next() #fetch the first batch
    a = x[0] # train data
    b = x[1] # train label
    for i in range(0,5):
        plt.imshow(a[i])
        plt.title(b[i])
        plt.show()

Be carefull about plotting. You may need to rescale your data. If your data type is float, you need to scale it between 0 and 1 and if your data type integer, you should scale it between 0 and 255. To do it you can use rescale property.
datagenOrj = keras.preprocessing.image.ImageDataGenerator(rescale=1.0/255.0)

I tried on my own dataset and it is working.
Best


Q: Correct Way for Threads in Java I am beginning to learn threads in Java and I am a bit confused now.
I hope this is the right place to ask.
I made a little program  for testing:
public class GetInfo implements Runnable {
    //private static boolean stopPointerInfo = false;
    private static  Thread tn;

    public static void StartPointerInfo() {
        //stopPointerInfo = false;
        tn = new Thread(new GetInfo());
        tn.start();
        System.out.println("After start1");
    }

    public static void StopPointerInfo() {
        //stopPointerInfo = true;
        tn.interrupt();
    }

    @Override
    public void run() {
        //  while (stopPointerInfo == false) {

        while (! tn.isInterrupted() ) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                tn.interrupt();
            }
            .
            .
            doSomething
        }
    }
}

Because the run() method must know which thread is interrupted I must use the global definition of thread tn?
Should I use the interrupt() method like I did or should I use the boolean variable like in the comments?
With this Method I can't use the interrupt and I must use the boolean version because Runnable r doesn't know the thread here?
public class GetInfo {
    private static boolean stopPointerInfo = false;

    public static void StartPointerInfo() {
        stopPointerInfo = false;
        getPointerInfo();
    }

    public static void StopPointerInfo() {
        stopPointerInfo = true;
    }

    public static void getPointerInfo() {
        Runnable r = new Runnable() {

            @Override
            public void run() {
            while (stopPointerInfo == false) {

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) { }
                    .
                    .
                    doSomething
                }
            }
        };
        new Thread(r).start();
    }
}

A: The boolean flag solution is fragile as it is not guaranteed that updates will be visible across different threads. To fix this problem you may declare it as volatile, but if you set the boolean flag you don't interrupt the sleep call like in first version. Thus using interrupts is preferred.
I see no reason to declare Thread tn as static. You may use:
public class GetInfo implements Runnable {
    private final Thread tn;

    private GetInfo() {
        this.tn = new Thread(this);
        this.tn.start();
    }

    public static GetInfo StartPointerInfo() {
        GetInfo info = new GetInfo();
        System.out.println("After start1");
        return info;
    }

    public void StopPointerInfo() {
        tn.interrupt();
    }
    ...
}

And use it like this:
GetInfo infoWorker = GetInfo.StartPointerInfo();
...
infoWorker.StopPointerInfo();

A: You don't need to use a static Thread.
Within the run() method, you need to test whether the current thread has been interrupted.  You don't need access to tn for that. You can do this like this:
    Thread.currentThread().isInterrupted();

or
    Thread.interrupted();

(Note that the behavior of these two are different.  One clears the interrupt flag and the other doesn't.)
Alternatively, you could just change the static field to an instance field, and make all of the GetInfo methods instance methods.  That means you can instantiate multiple instances of GetInfo which each create their own Thread and hold the reference in the instance field.

Two more points:

*

*The way that you are creating and then disposing of threads is rather inefficient.  (Starting a thread is expensive.)  A better way is to restructure the code so that it can use a thread pool.

*Calling your methods StartPointerInfo and StopPointerInfo is BAD STYLE.  Java method names should always start with a lowercase letter.


Q: How can I filter instances of a model in django, with a queryset value of filter field? I am creating an application in django, and I have the next question:
I want to filet objects of modelA, by the field att1, and I have a queryset of values of the field att1. I mean, my models are:
class modelA(models.Model):
    att1 = models.ForeignKey(modelB)
    ...

class modelB(models.Model):
    ...

I got a queryset ot objects of modelB, and I want to get all objects of modelA which has as value of att1, any of the values of the queryset of modelB.
How can I do it?
Thank you so much!

A: Nothing magic
ModelA.objects.filter(att1=queryset of modelB)

A: say you have object B with fields att2 and att3
class modelA(models.Model):
    att1 = models.ForeignKey(modelB)

class modelB(models.Model):
   att2 = models.CharField(max_length=255)
   att3 = models.CharField(max_length=255)

then you filter by doing:
    results = modelA.objects.filter(att1__att2='foo')
hope this helps


Q: Как реализовать междоменную авторизацию на Laravel? Есть около 100 доменов, ссылающихся на 1 проект на laravel
Возможно ли реализовать автоматическую авторизацию на всех доменах сразу (При авторизации на 1 сайте, автоматически авторизируешся на всех 100)

A: Как я решил на данный момент
В таблицу users добавил два новых столбика - auth_token(для токена), auth_date(для даты получения токена)
Добавил новый Middleware - Cors.php он нужен, чтобы мы могли принимать запросы с любых доменов
Содержание - Cors.php:
<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET');
    }
}

Добавил два маршрута:
Route::group(['middleware' => 'cors'], function () {
    Route::get('/auth/user', 'HomeController@authUser');//Для данного маршрута применяем middleware - cors(по данному адресу можно получить доступ с любого сайт)
});
Route::post('/api/auth/user/get', 'HomeController@authUserGet');

HomeController:
    public function authUser() { // В данной функции проверяем авторизирован ли пользователь на основном сайте и если он авторизирован, мы генерируем токен и записываем его в таблицу и выводим токен
        if(Auth::user()) {
            $user = User::where('id', Auth::user()->id)->first();
            if($user) {
                $token = sha1(time());
                $date = date('Y-m-d h:i:s');
                User::where('id', Auth::user()->id)->update([
                    'auth_token' => $token,
                    'auth_date' => $date
                ]);
                echo $_GET['callback']."({token:'$token'});";
            }
        } else {
            echo $_GET['callback']."({token:''});";
        }
    }
    public function authUserGet(Request $request) { // В этой функции мы получаем сгенерированный токен и по нему ищем пользователя в таблице, если находим, то проверяем, чтобы дата выпуска не превышала 60 секунд и авторизируем
        $token = $request->input('token');
        $rez['rez'] = 0;
        if($token) {
            $user = User::where('auth_token', $token)->first();
            if($user) {
                if($user->auth_date) {
                    $date = date('Y-m-d H:i:s');
                    $time_one_min = strtotime($date) + 60;
                    $time_one_min_minus = strtotime($date) - 60;
                    $time_token = strtotime($user->auth_date);
                    if($time_one_min_minus <= $time_token and $time_token <= $time_one_min) {
                        Auth::login($user);
                        $rez['rez'] = 1;
                        $user->auth_token = NULL;
                        $user->auth_date = NULL;
                        $user->save();
                    } else {
                        $rez['rez'] = 'Время токена истекло';
                    }
                } else {
                    $rez['rez'] = 'Не верный токе #3';
                }
            } else {
                $rez['rez'] = 'Не верный токе #2';
            }
        } else {
            $rez['rez'] = 'Не верный токе';
        }
        return $rez;
    }

И в самый низ шаблона добавляем сам скрипт отправки запросов
@guest
    <script>
        $(document).ready(function() {
            $.ajax({
                url: 'https://site.ru/auth/user', // Отправляем запрос на основной сайт, для проверки авторизирован на нем или нет
                dataType: 'JSONP',
                type: 'GET',
                success: function (data) {
                    if(data.token) { // Если авторизирован, берем токен
                        axios({
                            method: 'post',
                            url: '/api/auth/user/get',
                            params: { token: data.token }
                        }).then((response) => {
                            if(response.data.rez == 1) {
                                location.reload();
                            } else {
                                console.log(response.data.rez);
                            }
                        });
                    }
                }
            });
        });
    </script>
@endguest

В чем минусы данного способа -

*

*По данному адресу может обратится любой сайт - https://site.ru/auth/user

*Может так получится, что будут сгенерированы одинаковые токены и все сломается

*И самая главная проблема, что для данного метода, должен быть 1 главный сайт, то есть если Вы авторизированы на главном сайте, то при заходе на любой другой, авторизация происходит автоматический


Q: Нарисовать линию пути Есть массив точек ( объявляются в настройках скрипта ), по которым движется объект ( 3d )
Вопрос: каким образом можно провести линию между этими точками, что бы ее было видно при старте игры ( интересует не сам алгоритм, а скорее что использовать в качестве линии: игровые объекты, какие-то графические элементы )

A: Все зависит от формы кривой. Проще всего воспользоваться готовыми объектами в Unity вроде LineRenderer (http://docs.unity3d.com/ru/current/Manual/class-LineRenderer.html_), вот только при если точки лежат не в плоскости, толщина линии может искажаться, поэтому в своих проектах я генерировал линии при помощи скрипта.
Видел в других проектах как делали линии из цилиндров от точки до точки а в самих точках вставляли сферы чтобы сгладить переход. Все зависит от характера кривой, и какую линию вы хотите рисовать. При помощи GL можно рисовать линии в один пиксель, а если надо больше, то лучше делать это уже через Mesh.


Q: window.location.reload(); is losing viewstate in IE8 On Click of a button, I need to make sure window control changes to new new element(tab). Therefore, I am using something like this in html:
<input id="back" type="button" value="Back to Form" onclick="backTo();">

and the corresponding JS code is:-
function backTo(){
    window.location.href='#fragment-1';
    window.location.reload();
}

On executing above in Firefox, control is going back to the element(fragment-1) with fields having text-data entered prev. While the same in IE8 control is going back to fragment-1 element but all text-data entered prev is lost.
Further, I have added Cache-control paremeter set to public and tried seeing whether this would help the viewstate to be loaded from cache whenever control goest back to given div/element.
Anything missing?

A: well.. it depends upon how a particular browser saves the state of the page..
also try using history.go() method http://www.w3schools.com/jsref/met_his_go.asp and see if the problem is solved.

A: how about resubmitting the form instead of reloading:
document.forms[0].submit();//assumed there is only one form in you page

UPDATE: This should do it:
Assuming that div below is the element you like to transfer the control to, use the scrollIntoView function:
<div id="fragment-1" name="fragment-1">
....
</div>

document.getElementById('fragment-1').scrollIntoView();


Q: git commit fix to project owner I forked binux/pyspider and made some change.Today I found a bug and want to commit a fix to the owner.
I have 4 commit for now, the last commit contain two files(one file to fix bug, one file my edit).
And I found the most easy understanding way by John Naegle.
But I got error here:
mithril@KASIM /E/Project/pyspider (master)
$ git checkout pullrequest
Switched to branch 'pullrequest'

mithril@KASIM /E/Project/pyspider (pullrequest)
$ git pull https://github.com/binux/pyspider.git
From https://github.com/binux/pyspider
 * branch            HEAD       -> FETCH_HEAD
Already up-to-date.

mithril@KASIM /E/Project/pyspider (pullrequest)
$ git branch
  master
* pullrequest
$ git cherry-pick 6b8fc09133b11ff8f243cdcf90fa559ee9cf4f26
error: could not apply 6b8fc09... fix pymongo dump error
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'

mithril@KASIM /E/Project/pyspider (pullrequest|CHERRY-PICKING)
$ git diff
diff --cc pyspider/scheduler/scheduler.py
index 48a7888,a2f5aaf..0000000
--- a/pyspider/scheduler/scheduler.py
+++ b/pyspider/scheduler/scheduler.py

I run the command under my pyspider clone folder, is it wrong?
Does that means I have to revert changes of scheduler.py and add them back after I switch to master branch?
Could I just add pyspider/webui/result.py to the pullrequest branch without influence to mater brach?
Should I go to a new folder to create and get this new branch?
I am not very familiar with git, I fear I would do something wrong..

A: Now I know Git is very powerful:
1. create a new branch and make change, would not affect other branches.
2. I can create branch with a SHA key (every commit has a unique key)
I have made my first the pullrequest, it's feel good.


Q: OpenMP reduction into array of C++ template-specified size causes undefined behaviour I'm new to OpenMP, but am trying to use it to accelerate some operations on entries of a 2D array with a large number of rows and a small number of columns. At the same time, I am using a reduction to calculate the sum of all the array values in each column. The code looks something like this (I will explain the weird bits in a moment):
template <unsigned int NColumns>
void Function(int n_rows, double** X, double* Y)
{
    #pragma omp parallel for reduction(+:Y[:NColumns])
    for (int r = 0; r < n_rows; ++r)
    {
        for (int c = 0; c < NColumns; ++c)
        {
            X[r][c] = some_complicated_stuff(X[r], X[r][c]);
            Y[c] += X[r][c];
        }
    }
}

To clarify, X is a n_rows x NColumns-sized 2D array allocated on the heap, and Y is a NColumns-sized 1D array. some_complicated_stuff isn't actually implemented as a separate function, but what I do to X[r][c] in that line only depends on X[r][c] and other values in the 1D array X[r].
The reason that NColumns is passed in as a template parameter rather than as a regular argument (like n_rows) is that when NColumns is known at compile-time, the compiler can more aggressively optimise the inner loop in the above function. I know that NColumns is going to be one of a small number of values when the program runs, so later on I have something like this code:
cin >> n_cols;
double** X;
double Y[n_cols];

// initialise X and Y, etc. . .

for (int i = 0; i < n_iterations; ++i)
{
    switch (n_cols)
    {
        case  2: Function< 2>(X, Y); break;
        case 10: Function<10>(X, Y); break;
        case 60: Function<60>(X, Y); break;
        default: throw "Unsupported n_cols."; break;
    }
    // . . .
    Report(i, Y); // see GDB output below
}

Through testing, I have found that having this NColumns "argument" to Update as a template parameter rather than a normal function parameter actually makes for an appreciable performance increase. However, I have also found that, once in a blue moon (say, about every 10^7 calls to Function), the program hangs—and even worse, that its behaviour sometimes changes from one run of the program to the next. This happens rarely enough that I have been having a lot of trouble isolating the bug, but I'm now wondering whether it's because I am using this NColumns template parameter in my OpenMP reduction.
I note that a similar StackOverflow question asks about using template types in reductions, which apparently causes unspecified behaviour - the OpenMP 3.0 spec says

If a variable referenced in a data-sharing attribute clause has a type
  derived from a template, and there are no other references to that
  variable in the program, then any behavior related to that variable is
  unspecified.

In this case, it's not a template type per se that is being used, but I'm sort of in the same ballpark. Have I messed up here, or is the bug more likely to be in some other part of the code?
I am using GCC 6.3.0.
If it is more helpful, here's the real code from inside Function. X is actually a flattened 2D array; ww and min_x are defined elsewhere:
#pragma omp parallel for reduction(+:Y[:NColumns])
for (int i = 0; i < NColumns * n_rows; i += NColumns)
{
    double total = 0;
    for (int c = 0; c < NColumns; ++c)
        if (X[i + c] > 0)
            total += X[i + c] *= ww[c];

    if (total > 0)
        for (int c = 0; c < NColumns; ++c)
            if (X[i + c] > 0)
                Y[c] += X[i + c] = (X[i + c] < min_x * total ? 0 : X[i + c] / total);
}

Just to thicken the plot a bit, I attached gdb to a running process of the program which hanged, and here's what the backtrace shows me:
#0  0x00007fff8f62a136 in __psynch_cvwait () from /usr/lib/system/libsystem_kernel.dylib
#1  0x00007fff8e65b560 in _pthread_cond_wait () from /usr/lib/system/libsystem_pthread.dylib
#2  0x000000010a4caafb in omp_get_num_procs () from /opt/local/lib/libgcc/libgomp.1.dylib
#3  0x000000010a4cad05 in omp_get_num_procs () from /opt/local/lib/libgcc/libgomp.1.dylib
#4  0x000000010a4ca2a7 in omp_in_final () from /opt/local/lib/libgcc/libgomp.1.dylib
#5  0x000000010a31b4e9 in Report(int, double*) ()
#6  0x3030303030323100 in ?? ()
[snipped traces 7-129, which are all ?? ()]
#130 0x0000000000000000 in ?? ()

Report() is a function that gets called inside the program's main loop but not within Function() (I've added it to the middle code snippet above), and Report() does not contain any OpenMP pragmas. Does this illuminate what's happening at all?
Note that the executable changed between when the process started running and when I attached GDB to it, which required referring to the new (changed) executable. So that could mean that the symbol table is messed up.

A: I have managed to partly work this out.
One of the problems was with the program behaving nondeterministically. This is just because (1) OpenMP performs reductions in thread-completion order, which is non-deterministic, and (2) floating-point addition is non-associative. I assumed that the reductions would be performed in thread-number order, but this is not the case. So any OpenMP for construct that reduces using floating-point operations will be potentially non-deterministic even if the number of threads is the same from one run to the next, so long as the number of threads is greater than 2. Some relevant StackOverflow questions on this matter are here and here.
The other problem was that the program occasionally hangs. I have not been able to resolve this issue. Running gdb on the hung process always yields __psynch_cvwait () at the top of the stack trace. It hangs around every 10^8 executions of the parallelised for loop.
Hope this helps a little.


Q: getting an extra 0.001 in my calculation When i enter 0.2 as the volume i should get 2260.00 but im getting 2260.001 and i cant understand why. Even after adjusting how many decimals i want there is always 0.1 at the end...
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int option;
    float volume;
    float density = 11300;
    float mass;

    while (option != 3)
    {
        printf("1: Calculate Mass\n");
        printf("2: Calculate Volume\n");
        printf("3: Exit\n");
        printf("Input here: ");
        scanf("%d", &option);

        if (option == 1)
        {
            printf("Input Volume: ");
            scanf("%f", &volume);

            mass = volume*density;
            printf("%.2f", mass);
        }

    }

   return 0;
}


Q: Changing Mysql Column Names I want to change various column names using:
ALTER TABLE tablename CHANGE COLUMN oldname newname datatype(length);

This is easy except for the last part: datatype(length). It seems silly to need to specify that since I don't want to change the column type or length, only its name, but from what I've read, specifying that is mandatory. I need automated code, NOT a  command that merely displays the table from which datatype(length) is displayed on a screen; I want to put those values into PHP variable(s) so they can be manipulated by other PHP code. Thus I'd appreciate code that gives me $datatype and $length, if the latter is applicable.

A: You can select that information from the INFORMATION_SCHEMA.COLUMNS table.
select
  DATA_TYPE,
  CHARACTER_MAXIMUM_LENGTH,
  IS_NULLABLE,
  NUMERIC_SCALE,
  NUMERIC_PRECISION
  -- And many other properties
from
  INFORMATION_SCHEMA.COLUMNS
where
  TABLE_NAME = 'tablename' and
  COLUMN_NAME = 'yourcolumn'


Q: Is calling not thread-safe method properly possible? I need to parallelize this code in C#. listTipoGraficos is a ListView object (I'm locking its access) but the method this.claseChartPadre.CargarGrafico is not thread-safe. It only modifies the input graficos[i] but it has very much local variables, so modify it is an horror... Can I do anything without adapting it?
System.Collections.Concurrent.ConcurrentDictionary<int, Grafico> graficos = new System.Collections.Concurrent.ConcurrentDictionary<int,Grafico>();
for (int i = 0; i < listTipoGraficos.CheckedItems.Count; i++)
   graficos[i] = (Grafico)listTipoGraficos.CheckedItems[i].Tag;
System.Threading.Tasks.Parallel.For(0,listTipoGraficos.CheckedItems.Count, i =>
{
   //Controlamos que no lo tenemos ya cargado
   if (graficos[i].EstaPintado == false || graficos[i].TipoFecha != fechaSelecionada || graficos[i].FechaIni != fechaIniSelec || graficos[i].FechaFin != fechaFinSelec)
   {
       graficos[i].TipoFecha = fechaSelecionada;
       graficos[i].FechaIni = fechaIniSelec;
       graficos[i].FechaFin = fechaFinSelec;
       //Resetea el contenido del grafico
       graficos[i].reiniciarContenido();
       this.claseChartPadre.CargarGrafico(graficos[i]); // A lot of local variables inside
    }
});

I can't post very much code because it isn't mine.
    public bool CargarGrafico(Grafico gf)
    {
        bool leido_ok = true;
        // Reding from DB
        ClaseComandoSql comando = new ClaseComandoSql();
        comando.NombreComando = this.procedimiento;
        comando.TipoComando = System.Data.CommandType.StoredProcedure;
        comando.AñadirParametro("@CodGrafico", gf.CodGrafico);
        comando.AñadirParametro("@Codigo", this.codigoObjeto);
        comando.AñadirParametro("@CodOpcion", gf.TipoFecha);
        comando.AñadirParametro("@FecInicial", gf.FechaIni);
        comando.AñadirParametro("@FecFinal", gf.FechaFin);
        System.Data.DataSet lector = comando.EjecutarLector(); // This is the operation I need to parallelize

        bool primeraPasada = true;
        bool codigoNulo = false;

        int totalLeyendas = 0;
        int totalAgrupaciones = 0;
        String LeyendaAnterior = "";
        int i = 0;
        // Calculus and formatting
    }

Basically the code create an sql command, executes it and formats a graph to draw it.
EDIT: I took this approach and seems that works well, but I think it's ugly. sync is an instance variable inside the class.
    public bool CargarGrafico(Grafico gf)
    {
        lock (sync)
        {
        bool leido_ok = true;
        // Reding from DB
        ClaseComandoSql comando = new ClaseComandoSql();
        comando.NombreComando = this.procedimiento;
        comando.TipoComando = System.Data.CommandType.StoredProcedure;
        comando.AñadirParametro("@CodGrafico", gf.CodGrafico);
        comando.AñadirParametro("@Codigo", this.codigoObjeto);
        comando.AñadirParametro("@CodOpcion", gf.TipoFecha);
        comando.AñadirParametro("@FecInicial", gf.FechaIni);
        comando.AñadirParametro("@FecFinal", gf.FechaFin);
        }
        System.Data.DataSet lector = comando.EjecutarLector(); // This is the operation I need to parallelize

        lock(sync)
        {
        bool primeraPasada = true;
        bool codigoNulo = false;

        int totalLeyendas = 0;
        int totalAgrupaciones = 0;
        String LeyendaAnterior = "";
        int i = 0;
        // Calculus and formatting
    }


Q: Actualizar componente en Vuejs Estoy teniendo un problema, tengo desarrollado una app donde tiene un login. Una vez logueado te lleva al perfil de usuario, pero siempre me aparece la información del usuario anterior logueado, solamente se actualiza cunado realizo cambio en el script y luego refresca de forma automática el servidor de Vuejs y ahí recién aparece con la información del usuario logueado en ese momento. También cuando recién inicio la app no me reconoce el usuario logueado en ese momento, recién cuando actualizo la pagina lo reconoce.
1) Alguien sabe como actualizar un div cada cierto tiempo con VueJS
2) Como hago para que me reconozca el usuario al inicio de la template perfil cuando el usuario es logueado y redirigido al template.
Perfil.vue
<template>

  Navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home (current)

        Link

          Dropdown

          Action
          Another action

          Something else here

        Disabled

    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>

Logout
DATOS

Registra gratis

              <form @submit.prevent="registrarVariable">

                       <input type="text" id="Variablenom"  class="form-control" placeholder="Nombre de la Variable" v-model="Variable.Variablenom">

                        Nacimiento

                          <input class="form-control" type="date" value=""  v-model="Variable.Variable_nacimiento" name="Variable_nacimiento" id="Variable_nacimiento">

                       <input type="text" class="form-control" placeholder="sexo" v-model="Variable.sexo">

                <button type="submit" class="btn btn-primary">Registrar</button>

              </form>

    Por favor corrige los siguientes errores :

{{ er }}

    Mis Variables

     {{m.Variablenom}}

        Place sticky footer content here.

Modal Heading

          <button type="button" class="close" data-dismiss="modal">×</button>

          Modal body..

          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

</template>

A: El tema de actualizar un div cada cierto tiempo es tapar un problema que puede estar detrás y que te va a traer problemas a la larga. En cualquier caso al utilizar vue.js puedes usar forceUpdate.
Sería algo así:
mounted() {
this.$forceUpdate();
  }

Si quisieras ejecutarlo cada X segundos puedes usar setInterval o si quieres ejecutarlo al cabo de X segundos setTimeout
Ejemplo:
setTimeout(this.$forceUpdate(), 5000)

Aquí tienes el orden en que se ejecutan las intancias de vue para que sepas donde ponerlo: https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram te adjunto también el enlace a la documentación oficial de forceUpdate: https://v2.vuejs.org/v2/api/#vm-forceUpdate
Ahora bien, si quieres tratar de arreglarlo, en tu función onAuthStateChanged tienes pasados dos valores user y request, deberías modificarlo para que quede así:
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // El usuario está logeado y muestro sus datos o lo que sea
  } else {
    // El usuario no está logeado y borro todo rastro del anterior
  }
});

A: 1.- No uses forze update, es una mala practica y te hará garras tu propio proyecto.
2.- Como usas tu autentificación? En base a un Token de logged in? -> esto es lo más común, asi que te explicare en base a esto.
Tienes 2 maneras de hacerlo, manejar el header si está loggined or not (v-if) si en tu token respondes con la información del usuario, puedes decodificarlo y mostrar sus datos en base a su token. Si quieres que se siga guardando el usuario cuando entre a tú página, solo guarda el token en el localStorage, y al momento de que entre, las variables de VueJs que pusiste en tu header, van a tomar el token existente y mostrará de nuevo la información del token.

A: Tiene que ver con la manera que se interpreta la reactividad en el contexto de tu aplicacion.
El navegador no sabe cuando actualizas los datos, otra forma de hacer que un componente se vuelva a renderizar (ademas de las ya mencionadas, y menos invasiva), es usar una key, en este caso tampoco necesitas actualizar cada x tiempo, por que en el momento que el valor de la key se actualice el componente se volvera a renderizar.
por ejemplo:
<tu-componente :key="user.id"/>

con eso deberia ser suficiente para que ese componente se actualice cada ver que user.id cambie.


Q: Is that we can send the multipart/form-data till 2GB by using rest api in apex Is that multipart message is available in RestAPI in Apex 2021 to send the large files(till 2GB) from source org to target org??

A: Apex can't handle data this large. You will need some kind of external ETL (Extract, Transform, Load) tool, or custom software, in order to migrate files of this size. By the way, you're looking for "chunked" upload, not "multipart message." The former is an HTTP header that allows for resuming uploads, the latter is used for posting forms with binary content.


Q: Getting the exit code within a __del__ function I'd like to do a clean shutdown of a class that does one task when exiting normally, and not under something like exit(1).  How can I determine the current exit code.  Example:
import sys
import atexit

def myexit():
    print("atexit")
atexit.register(myexit)

class Test(object):
    def __init(self):
        pass
    def __del__(self):
        print("here")
        # print(sys.exit_code) # How do I get this???

x = Test()
exit(1)

which produces:
atexit
here

But in neither of those places do I know how to get the exit code passed to sys.exit().
There was other
answer
but it doesn't seem wise to implement a forced wrapper from another
reusable module.


Q: How to add column values from one Data Frame to the other column in second Data Frame based on conditions in Python?
df1 = pd.DataFrame(zip(l1), columns =['l1'])
df1.l2.value_counts()

df2 = pd.DataFrame(zip(l2), columns =['l2'])
df2.l2.value_counts()

I want to add the column values from l2 to l1 depending on the value count in df1. For example

*

*if value count of 'bb_#2' < value count of 'bb_#1' in df1 then all of 'bb_#3' in df2 should be added in 'bb_#2' in df1 also changing their name to 'bb_#2' as well and

*same logic as described above for 'aa_#3'

*'cc_#2' & 'cc_#3' in df2 should be combined and added into 'cc_#1' in df1.

conditions should be checked in df1 and if a condition is met then values from l2 in df2 should be added to the l1 column of df1
output
is given here as well
l1=['aa_#1', 'bb_#1', 'bb_#2', 'aa_#1', 'aa_#1', 'aa_#1', 'bb_#1','aa_#2','bb_#2','aa_#2','bb_#1','bb_#1','bb_#1','bb_#2','bb_#2','cc_#1','bb_#2','bb_#2', 'bb_#2','aa_#2','aa_#2','aa_#2', 'cc_#1','cc_#1','cc_#1','cc_#1']

Please let me know if there is a way to do this in Python. I have 10,000 rows like this to add from l2 to l1 and I don't know how to even begin with it. I am really new to Python.

A: This is a method that doesn't use pandas. The .count() method returns the value count of an item in a list. The .extend() method appends another to the end of an existing list. Lastly, multiplying a list by an integer duplicates and concats it that many times. ['a'] * 3 == ['a', 'a', 'a']
def extend_list(l1, l2, prefixes, final_prefixes, suffix_1, suffix_2, suffix_3):
    for prefix in prefixes:
        if l1.count(f'{prefix}_{suffix_2}') < l1.count(f'{prefix}_{suffix_1}'):
            l1.extend([f'{prefix}_{suffix_2}'] * l2.count(f'{prefix}_{suffix_3}'))
    for final_prefix in final_prefixes:
        l1.extend([f'{final_prefix}_{suffix_1}'] *
        (l2.count(f'{final_prefix}_{suffix_2)') + l2.count(f'{final_prefix}_{suffix_3}')))

l1 = ['aa_#1','bb_#1','bb_#2','aa_#1','aa_#1','aa_#1','bb_#1','aa_#2','bb_#2','aa_#2','bb_#1','bb_#1','bb_#1','bb_#2','bb_#2','cc_#1']
l2 = ['aa_#3','aa_#3','aa_#3','bb_#3','bb_#3','bb_#3','cc_#2','cc_#2','cc_#3','cc_#3']

l1 = extend_list(l1, l2, ["aa", "bb"], ["cc", "dd"], "#1", "#2", "#3")


Q: Hibernate criteria of Projection I have 2 classes with a relation @OneToOne: User and Player.
User contain a player:
@Entity
@Table(name = "user")
public class User {
    @Column(name = "nickname")
    private String nickname;

    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "id_player")
    private Player player;

   //getters and setters...
}

I want to query user with only nickname and player, and with player I don't want all attributes, I only want 2.
This is what I have now:
    //Projections for the class User
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.property("id"), "id");
    projectionList.add(Projections.property("nickname"), "nickname");
    projectionList.add(Projections.property("player"), "player");

    Criteria criteria = session.createCriteria(User.class);
    criteria.setFirstResult(player.getPvpRank() - 5);
    criteria.setMaxResults(11);
    criteria.createAlias("player", "p");
    criteria.addOrder(Order.asc("p.pvpRank"));
    criteria.setProjection(projectionList);
    criteria.setResultTransformer(Transformers.aliasToBean(User.class));

I am getting only nickname, id and the player, but how can I set projections to the player to only get player.level and not all the attributes?

A: Its think it is exactly as you suggest:
projectionList.add(Projections.property("player.level"), "player.level");

A: First create alias for the JoinColumn table Player in User & then refer it in your projectionList.
Criteria criteria = session.createCriteria(User.class);
criteria.createAlias("player", "p");
projectionList.add(Projections.property("p.level"), "player");
...
criteria.setProjection(projectionList);
criteria.setResultTransformer(Transformers.aliasToBean(User.class));

I hope this helps you.


Q: Apostrophe replacement in mysql query I have in a column names(notes) as
Notes:

John's Table

Smith's Window

Column contains an apostrophe in it. I am trying to run 2 queries.

*

*Select query to get the column entries that have apostrophe.

*Update those with apostrophe with empty string ie.John's Table replace to John Table

select notes from table1 where notes like ' '% ';

I get a syntax error , any help will be great.

A: Escape the apostrophe with a backslash;
select notes from table1 where notes like '%\'%';

And to update, use REPLACE()
UPDATE table1 SET notes = REPLACE(notes, '\'', '');

A: Did you try:
select notes from table1 where notes like "'%";


Q: How to change elements in a navbar in html I made a navigation bar in HTML and trying that the elements of the navigation bar are on the right site. However, the elements are on the right side but in the wrong direction. The direction of the elements is, Kontakt, Über uns, Klimawandel and Home. The direction I will is the reverse of this.
This is the HTML I wrote for the navigation bar:

nav {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #96CB49;
}

li {
  float: right;
  border-right: 1px solid black;
}

.active {
  background-color: #254a01;
}

li:last-child {
  border-right: none;
}

li a:hover:not(.active) {
  background-color: #254a01;
}

li a,
.dropbtn {
  display: inline-block;
  color: #F9FCEA;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
.dropdown:hover .dropbtn {
  background-color: #254a01;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #96CB49;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: #F9FCEA;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #254a01;
}

.dropdown:hover .dropdown-content {
  display: block;
}

Home

    Klimawandel

      Der Klimawandel
      Die Ursachen des Klimawandels
      Die Auswirkungen des Klimawandels

Über uns

Kontakt

Logo

A: The way to approach this is to make the container float right, and the items inside of it to float left, if you want to use floats for this purpose.
And since you are using float which will cause the element width to depend on its content, you will need to add a wrapper to your  element, that will have the same background color, so that you achieve full width background visually. In my example below, I wrapped the list elements in the
, and made  be the top level container to add the background.

nav {
  background-color: #96CB49;
  overflow: hidden;
}
ul {
  float: right;
  list-style-type: none;
  margin: 0;
  padding: 0;
}

li {
  float: left;
  border-right: 1px solid black;
}

.active {
  background-color: #254a01;
}

li:last-child {
  border-right: none;
}

li a:hover:not(.active) {
  background-color: #254a01;
}

li a,
.dropbtn {
  display: inline-block;
  color: #F9FCEA;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
.dropdown:hover .dropbtn {
  background-color: #254a01;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #96CB49;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: #F9FCEA;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #254a01;
}

.dropdown:hover .dropdown-content {
  display: block;
}

Home

    Klimawandel

      Der Klimawandel
      Die Ursachen des Klimawandels
      Die Auswirkungen des Klimawandels

Über uns

Kontakt

Logo

However, today there are more effective approaches to doing layout in CSS, such as flex-box which would make your task very easy:

ul {
  background: green;
  display: flex;
  list-style: none;
  justify-content: end;
}

One

Two

Three


Q: AngularJS - Disable ng-click if element has specific class I have a list of li items with functions attached to them. I also have an event listener which attaches a class of "current" to whichever li item is being clicked.
HTML

5 km

10 km

25 km

50 km

100 km

Is there a way to disable the ng-click event if that specific li item has a class of "current" or is there a better way to go about this?

A: You cannot disable a list cause its not a interactive element can use ngClass to apply a specific class when disabled to make it appear disabled:

item

You can use ng-if to remove those items completely from the list:

item

item

A: If you use button tag as trigger instead of li, you can use ng-disabled directive to permit click by a condition. For example:

<button ng-click="getRadius(5)" ng-disabled="current!=5">5 km</button>

<button ng-click="getRadius(10)" ng-disabled="current!=10">10 km</button>

<button ng-click="getRadius(25)" ng-disabled="current!=25">25 km</button>

<button ng-click="getRadius(50)" ng-disabled="current!=50">50 km</button>

<button ng-click="getRadius(100)" ng-disabled="current!=100">100 km</button>

If you want, you can customize button style and you can show it like a standart text element.
.cf button {
  border: none;
  background: none;
}

A: // template

5 km

10 km

25 km

50 km

100 km

// controller
function MyController($scope) {
    $scope.clickLi = {
        5: true
    };

    $scope.getRadius = function(li_id) {
        $scope.clickLi[li_id] = true;
        console.log(li_id);
    };
}

A demo on JSFiddle.

A: Possible workaround:
If you need a single selection you can add variable into the scope specifying which row is selected and generate your list with the ng-repeat, then you can add lazy checking on ng-click if current $index is equal to selected index, you can use the same condition to apply current class with ng-class.
For example:
app.js
$scope.selected = 0;
$scope.distances = [5, 10, 25, 50, 100];

app.html

{{distance}} km


Q: bash shell append to variable frustration So I have a relatively simple bash script:
#!/bin/bash

declare ALL="";
while IFS="" read -r line || [ -n "$line" ]
do
   if [[ $line == 'ENV ms'* ]]; then
      words=( $line )
      if [[ ${#ALL} > 0 ]]; then
         ALL="$ALL;${words[1]}=${words[2]}"
      else
         ALL="${words[1]}=${words[2]}"
      fi

      if [[ ${#ALL} > 0 ]]; then
        printf '%s\n' "$ALL"
        echo "${#ALL}"
      fi

   fi
done < Dockerfile

echo "$ALL"
echo "${#ALL}"

parsing a Dockerfile that looks like this:
#
# Configuration Stage
#
FROM maven:3.6.1-jdk-12 AS build

ENV HOME=/usr/local/ms-cards

RUN mkdir -p $HOME

WORKDIR $HOME

COPY maven-settings.xml /root/.m2/settings.xml
COPY pom.xml $HOME

RUN mvn -Dmaven.test.skip=true clean verify --fail-never

COPY . $HOME

RUN mvn -Dmaven.test.skip=true clean package

#
# Package stage
#
FROM openjdk:12
COPY --from=build /usr/local/ms-cards/target/ms-cards-1.0-exec.jar /usr/local/lib/ms-cards.jar
ENV ms_oauth_ip ms-oauth
ENV ms_oauth_port 48001
ENV ms_cards_client_id clientapp
ENV ms_cards_client_secret 123456
ENV ms_cards_port 48002
ENV ms_connection_port 48003
ENV ms_connection_ip ms-connection
EXPOSE 48002
ENTRYPOINT ["java","-jar","/usr/local/lib/ms-cards.jar"]

and it gives me this output:
ms_oauth_ip=ms-oauth
21
;ms_oauth_port=48001
42
;ms_cards_client_id=clientapp
72
;ms_cards_client_secret=123456
103
;ms_cards_port=48002ret=123456
124
;ms_connection_port=4800323456
150
;ms_connection_ip=ms-connection
182
;ms_connection_ip=ms-connection
182

So I can see that my ALL variable is growing in length...but when printf'ing it never seems to be growing...Anyone know what I'm doing wrong?

A: The Dockerfile has Windows \r\n line endings. Each \r that is printed causes the cursor to jump back to the beginning of the line and overwrite the previous setting.
Debugging tip: Use declare -p var to see exactly what's in a variable.


Q: How can i change Mysql character_set_system UTF8 to utf8bin When i dump mysql data out , some data has changed because of the character_set_system which is UTF8.Server , client and connection character sete are utf8mb4.
I guess the problem is system character set and server character set differences.
I am trying to change system caharacter set from UTF8 to utf8mb4 with this
Change MySQL default character set to UTF-8 in my.cnf?
But i can not

A: The title is incorrectly phrased.
"utf8" is a "character set"
"utf8_bin" is a "collation" for the character set utf8.
You cannot change character_set... to collation.  You may be able to set some of the collation_% entries to utf8_bin.
But none of that a valid solution for the problem you proceed to discuss.
Probably you can find more tips here:  Trouble with UTF-8 characters; what I see is not what I stored
To help you further, we need to see the symptoms that got you started down this wrong path.


Q: Never ending while() loop I need to add a while loop for my script. It's a while $points < 17 ( draw_cards)
Maybe you can guess, it's a cards game. I wish it was as simple as that because it won't work. It gets stuck in an endless while loop.
if(FORM_stand("Stand")){
   while ($total_dealer < 17){
     list_dealer_hand();
     draw_dealer_card();
   }
}

If i run my script it goes on forever. Showing me for example 7, 7, 3, 7, 3, 9, 7, 3, 9, 2, 7, 3, 9, 2, 6, 7, 3, 9, 2, 6, 10, 7, 3, 9, 2, 6, 10, Ace, 7, 3, 9, 2, 6, 10, Ace, 5, 7, 3, 9, 2, 6, 10, Ace, 5, Queen, 7, 3, 9, 2, 6, 10, Ace, 5, Queen, Jack, 7, 3, 9, 2, 6, 10, Ace, 5, Queen, Jack, King, 7, 3, 9, 2, 6, 10, Ace, 5, Queen, Jack, King, 4, 7, 3, 9, 2, 6, 10, Ace, 5, Queen, Jack, King, 4, 8,
before eventually repeating
Notice: Undefined index
But i if i were to use:
if(FORM_stand("Stand")){
   list_dealer_hand();
      if ($total_dealer < 17){
         draw_dealer_card();
      }
}

I need to press Stand manually a couple of times because it's an if but this way it will keep drawing cards untill his points are 17 or higher, meaning the If works but the While never ends.
I don't know if you need any more information, in case you do, please ask away. Since i've been stuck on this while loop for 2 days now. And no one seems to be able to help me.
Thanks in advance!
PS: If i run the while loop and press control + f5 after all the errors are shown, it shows me this: 3, 10, 7, 9, 6, King, 8, Queen, Jack, 4, 2, Ace, 5, , and in the point section: 85
Busted!
I know all points together are 95, but since i used a case for my Ace that if points are > 11 it will count as a 1 instead of an 11. Mabye this bit will help you!
list_dealer_hand()
function list_dealer_hand() {
foreach($_SESSION["dealer_hand"] as $dealer_card=>$points) {
    echo $dealer_card;
    echo ', ';
}
}

and draw_dealer_card()
function draw_dealer_card() {
    $dealer_card = array_rand($_SESSION["dealer_pile"]);
    $_SESSION["dealer_hand"][$dealer_card] = $_SESSION["dealer_pile"][$dealer_card];
    unset($_SESSION["dealer_pile"][$dealer_card]);

}
My case system for points looks as follows:
$total_dealer = 0;
$text_dealer = '';
foreach($_SESSION["dealer_hand"] as $dealer_card=>$dealer_points) {
switch($dealer_card)
{
    case "King":
    case "Queen":
    case "Jack":
    case "10":
    $total_dealer += 10;
    break;
    case "Ace":
    if($total_dealer >= 11)
        {
        $total_dealer += 1;
        }else{
            $total_dealer += 11;
        }
        break;
    case "9":
        $total_dealer += 9;
        break;
    case "8":
        $total_dealer += 8;
        break;
    case "7":
        $total_dealer += 7;
        break;
    case "6":
        $total_dealer += 6;
        break;
    case "5":
        $total_dealer += 5;
        break;
    case "4":
        $total_dealer += 4;
        break;
    case "3":
        $total_dealer += 3;
        break;
    case "2":
        $total_dealer += 2;
        break;
}
}

EDIT: Session dealer_pile
if(!isset($_SESSION["dealer_pile"])) $_SESSION["dealer_pile"] = array(
2           =>  2,
3           =>  3,
4           =>  4,
5           =>  5,
6           =>  6,
7           =>  7,
8           =>  8,
9           =>  9,
10          =>  10,
'Jack'      =>  10,
'Queen'     =>  10,
'King'      =>  10,
'Ace'       =>  11 );

A: draw_dealer_card() needs to increase $total_dealer; otherwise the loop will go an forever.
A more elaborate answer
You only calculate the total once and never again in the while loop, that is why the dealers total will never increase and therefore will never be greater than 17.
Put the code that converts a card to its value in its own function, so you can use it anywhere
<?php
/**
 * return the value of the card for the current total
 * @param string $card the card to convert to count
 * @param int $current_total the current total of the player/dealer
 * @return int the value of $card
 */
function get_card_value($card, $current_total) {
    switch($card) {
        case "King":
        case "Queen":
        case "Jack":
            return 10;

        case "Ace":
           return ($current_total > 10) ? 1 : 11;

        case "10":
        case "9":
        case "8":
        case "7":
        case "6":
        case "5":
        case "4":
        case "3":
        case "2":
            return (int) $card;
    }
    return 0; // this should not happen probably abort here
}

From here it is easy, edit your while loop like this:
<?php
while ($total_dealer < 17){
    list_dealer_hand();
    draw_dealer_card();
    /* this is bad code using end(),
     * which might not always get the last drawn card.
     * Also calculation of total is wrong this way:
     *   What happens if dealer draws Ace, Ace, Ace, King?
     *   Should be 1+1+1+10 = 13 but will result in 11+1+1+10=23
     */
    $total_dealer += get_card_value(end($_SESSION['dealer_hand']), $total_dealer);
}

Correct calculation of total
To make your code more robust add a function calc_total(array $cards) which calculates the total of an array of cards and use it instead in the while loop to recalculate the dealers total. A function like this could look like this
<?php
function calc_total(array $cards) {
    //this is a little tricky since aces must be counted last
    $total = 0;
    $aces = array();
    foreach($cards as $card) {
        if($card === 'Ace') {
            $aces[] = $card;
            continue; // next $card
        }
        $total += get_card_value($card, $total);
    }
    // add aces values
    if (($total + 10 + count($aces)) > 21) {
        //all aces must count 1 or 21 will be exceeded
        return $total + count($aces);
    }
    foreach($aces as $card) {
        $total += get_card_value($card, $total);
    }
    return $total;
}

Now your while loop could lool like this
<?php
while ($total_dealer < 17){
    list_dealer_hand();
    draw_dealer_card();
    // recalculate the dealers total
    $total_dealer = calc_total($_SESSION['dealer_hand']);
}

Setting up the pile
Mixing of number and string keys is perfectly valid php, but also most of the time misleading. In your pile you  only need the cards, the values are not imoprtant, you can get a cards value at all time by calling get_card_value($card, 0). So set up the pile like this:
<?php
if(!isset($_SESSION["dealer_pile"])) $_SESSION["dealer_pile"] = array(
    'Jack', 'Queen', 'King', 'Ace', '10', '9', '8', '7', '6', '5', '4', '3', '2'
);

Also change the draw_dealer_card function
<?php
function draw_dealer_card() {
    //get a key
    $key = array_rand($_SESSION["dealer_pile"]);
    // add the card to the hand
    $_SESSION["dealer_hand"][] = $_SESSION["dealer_pile"][$key];
    /*
     * why are you removing it from pile, the pile might
     * contain multiple cards of each type
     */
    // unset($_SESSION["dealer_pile"][$dealer_card]);
}

Notice how the $_SESSION['dealer_hand'] is no longer associative. Take this into account whenever you are adding cards to it, just use, $_SESSION["dealer_hand"][] = $the_new_card

A: Your current code gets static value of $total_dealer and checks in while loop without incrementing, which results in infinite loop.So try putting foreach{} loop inside while loop, which will allow $total_dealer to increment value after each selection.
if(FORM_stand("Stand")){
$total_dealer = 0;
   while ($total_dealer < 17){
     list_dealer_hand();
     draw_dealer_card();

$text_dealer = '';
foreach($_SESSION["dealer_hand"] as $dealer_card=>$dealer_points) {
switch($dealer_card)
{
    case "King":
    case "Queen":
    case "Jack":
    case "10":
    $total_dealer += 10;
    break;
    case "Ace":
    if($total_dealer >= 11)
        {
        $total_dealer += 1;
        }else{
            $total_dealer += 11;
        }
        break;
    case "9":
        $total_dealer += 9;
        break;
    case "8":
        $total_dealer += 8;
        break;
    case "7":
        $total_dealer += 7;
        break;
    case "6":
        $total_dealer += 6;
        break;
    case "5":
        $total_dealer += 5;
        break;
    case "4":
        $total_dealer += 4;
        break;
    case "3":
        $total_dealer += 3;
        break;
    case "2":
        $total_dealer += 2;
        break;
}
}
   }
}

A: try this
$total_dealer=0;
    if(FORM_stand("Stand")){
       while ($total_dealer < 17){
         list_dealer_hand();
         draw_dealer_card();
         $total_dealer =$total_dealer+1;
       }
    }


Q: Why did the folder not clone too So I have Visual Studio 2019 and Azure Devops as my repository.
I went to VS to clone the repo. Everything came with it except one folder. It was an authorization filter folder to filter authorization of a policy based authorization.
Why did that not get cloned?

A: Visual Studio is just calling git clone command to clone the repo.
Suggest you could directly use Git Command, such as follow
git clone https://dev.azure.com/fabrikam/DefaultCollection/_git/Fabrikam C:\Repos\FabrikamFiber

If you still get the same result. Afraid these files .xxx are all ignored in Git by default. You need to check .gitingore file.
Either manually add them or override this for particular folders in your .gitignore file.


Q: How do I match zero or more brackets in python regex I want a python regex to capture either a bracket or an empty string. Trying the usual approach is not working. I need to escape something somewhere but I've tried everything I know.
one = "this is the first string [with brackets]"
two = "this is the second string without brackets"

# This captures the bracket on the first but throws
# an exception on the second because no group(1) was captured
re.search('(\[)', one).group(1)
re.search('(\[)', two).group(1)

# Adding a "?" for match zero or one occurrence ends up capturing an
# empty string on both
re.search('(\[?)', one).group(1)
re.search('(\[?)', two).group(1)

# Also tried this but same behavior
re.search('([[])', one).group(1)
re.search('([[])', two).group(1)

# This one replicates the first solution's behavior
re.search("(\[+?)", one).group(1) # captures the bracket
re.search("(\[+?)", two).group(1) # throws exception

Is the only solution for me to check that the search returned None?

A: The answer is simple! :
(\[+|$)

Because the only empty string you need to capture is the last of the string.

A: Here's a different approach.
import re

def ismatch(match):
  return '' if match is None else match.group()

one = 'this is the first string [with brackets]'
two = 'this is the second string without brackets'

ismatch(re.search('\[', one)) # Returns the bracket '['
ismatch(re.search('\[', two)) # Returns empty string  ''

A: Ultimately, the thing I wanted to do is to take a string and, if I find any square or curly brackets, remove the brackets and their contents from the string.
I was trying to isolate the strings that needed fixing first by finding a match and the fixing the resulting list in a second step when all I needed to do was do both at the same time as follows:
re.sub ("\[.*\]|\{.*\}", "", one)


Q: Not transfer/received voice (Twilio VOIP) after cellular call ended iOS
If I am on a Twilio video call (VOIP) and at the same time I received a cellular call on my device, I accept the call, speak with the person and end the call, I resume on Twilio video call everything is working apart from my voice is not getting transfer to the other end, also other end’s voice is not received at my end.
iOS is using 'TwilioVideo', '~> 1.2.1' SDK's
Android
In Android, we are having a different issue, Audio is not getting transferred to a cellular call if the user is already on a Twilio VOIP call.
Android is using build.gradle dependencies - compile 'com.twilio:video-android:1.2.0'
So basically what I want to do is, even if I am on a Twilio VOIP call, I want the user to be able to successfully do a cellular call from the application in both the platform, Android, and iOS.


Q: How to find out what caused a power mode change VB.NET has an event that fires when a computer's power mode is changed (SystemEvents.PowerModeChanged).
I need my program to find out what caused the power mode change, specifically, if there was a power button pressed, or some other reason.
How can I program this in VB.NET?


Q: Android: Result of TextView.setText() overridden by fragment I'm a bit new to using fragments, and am having an issue with setting the text of a TextView within a fragment.
Right now, I have a single Activity with a common set of six buttons, along with two fragments which are displayed in a LinearLayout. I am able to use the buttons to replace the fragment in the LinearLayout successfully. However, I'm noticing some strange behavior related to changing a TextView in those two fragments.
I have a method in the fragments' class, called setTimer(), which attempts to change the text in the TextView. The strange thing is, the method works successfully. However, a split second later, the text reverts back to the default text in the TextView contained in the fragment's layout .xml file (which is a blank string).
I've tried calling the setTimer() method both before and after I replace the fragment in the LinearLayout, and the results are the same either way. How can I change this TextView's contents without having them overridden moments later? Thank you!
MainActivity.java's onCreate() method:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {
        FocusFragment initialFragment = new FocusFragment();
        initialFragment.setFragmentType( Constants.FRAGMENT_WORK );
        initialFragment.setTimer( 25 );
        getFragmentManager().beginTransaction()
                .add( R.id.linearLayout_fragmentHolder, initialFragment, "fragment_work" )
                .commit();
    }
}

FocusFragment.java:
public class FocusFragment extends Fragment {

    int fragment_type;
    static TextView timer;

    final String TAG = "FocusFragment";

    public FocusFragment() {

    }

    public void setFragmentType( int fragment_type ) {
        this.fragment_type = fragment_type;
    }

    public int getFragmentType() {
        return this.fragment_type;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        View rootView;
        if ( getFragmentType() == Constants.FRAGMENT_WORK ) {
            rootView = inflater.inflate( R.layout.fragment_work, container, false );
        } else {
            rootView = inflater.inflate( R.layout.fragment_break, container, false );
        }
        timer = ( TextView ) rootView.findViewById( R.id.textView_timer );
        return rootView;
    }

    public boolean setTimer( int timerValue ) {
        if ( timer != null ) {
            if ( timerValue < 10 ) {
                timer.setText( "0" + timerValue + ":00" );
            } else {
                timer.setText( timerValue + ":00" );
            }
            Log.d( TAG, "Timer text set successfully." );
            return true;
        }
        Log.w( TAG, "WARNING: setTimer() couldn't find the timer TextView!" );
        return false;
    }
}

Finally, the changeFragment() method, which is called when the buttons are pressed:
public void changeFragment( String fragmentName, int timerValue ){
    FocusFragment fragment = new FocusFragment();
    if ( fragmentName == "fragment_work" ) {
        fragment.setFragmentType( Constants.FRAGMENT_WORK );
    } else {
        fragment.setFragmentType( Constants.FRAGMENT_BREAK );
    }
    fragment.setTimer( timerValue );
    getFragmentManager().beginTransaction()
            .replace( R.id.linearLayout_fragmentHolder, fragment, fragmentName )
            .commit();
}

A: The problem is that the OnCreateView() method of the fragment is called after the setTimer() is called.
An easy way to solve this is to first call fragment.setTimerValue(value) when you create the fragment.
void setTimerValue(int value){
    this.timerValue = value;
}

Then at the end of OnCreateView() method do:
OnCreateView(){
    ...
    setTimer(timerValue);
    return rootView;
}


Q: Passing Angular form data I'm attempting to pass the data of an angular form to external service, however, the base form is returning a null object and prevents any further processing. Haven't been able to identify the issue. I was able to accomplish an insert form almost identical to this.
Thanks in advance for any suggestions.
My form

    <form #currentItem="ngForm" (ngSubmit)="updateItem(currentItem.value)" autocomplete="off" novalidate>

        *
        Item name:
        <input [formControl]="name" (ngModel)="currentItem.name" name="name" required id="name" type="text" class="form-control" placeholder="name" />

          *
          Item Description:
          <input [formControl]="description" (ngModel)="currentItem.description" name="description" required id="description" type="text" class="form-control" placeholder="description" />

          *
          Item Price:
          <input [formControl]="price" (ngModel)="currentItem.price" name="price" required id="price" type="text" class="form-control" placeholder="price" />

          *
          Item Inventory:
          <input [formControl]="inventory" (ngModel)="currentItem.inventory" name="inventory" required id="inventory" type="text" class="form-control" placeholder="inventory" />

          *
          Item Category:
          <input [formControl]="category" (ngModel)="currentItem.category" name="category" required id="category" type="text" class="form-control" placeholder="category" />

        *
        Image:
        <input [formControl]="image_url" (ngModel)="currentItem.image_url" name="image_url" required pattern=".*\/.*.(png|jpg)" id="image_url" type="text" class="form-control" placeholder="preview.png" />
        Must be a png or jpg url

        <button type="submit" class="btn btn-primary">Update</button>
        <button type="button" [disabled]="currentItem.invalid" class="btn btn-default" (click)="cancel()">Cancel</button>

    </form>

Component
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router,  Params } from '@angular/router';
import { IItem } from './../../models/index';
import { ItemsService } from './../../services/index';
import { FormControl } from '@angular/forms';
import { JsonPipe } from '@angular/common';

@Component({
  selector: 'app-update-item',
  templateUrl: './update-item.component.html',
  styleUrls: ['./update-item.component.scss']
})
export class UpdateItemComponent implements OnInit {
  existingObject:any;
  currentItem: IItem;
  isDirty:boolean = true
  // Form Controls
  name = new FormControl('name');
  description = new FormControl('description');
  price = new FormControl('price');
  inventory = new FormControl('inventory');
  category = new FormControl('category');
  image_url = new FormControl('image_url');

  constructor(private itemsService: ItemsService, private route:ActivatedRoute, private router: Router) { }

  updateItem(formValues) {
    console.log(formValues); // temporary
    console.log(this.currentItem); // temporary
    this.itemsService.updateItem(formValues).subscribe(() => {
      this.router.navigate(['/items'])
    });
  }

  cancel() {
    this.router.navigate(['/items'])
  }

  ngOnInit() {
    this.route.params.forEach((params: Params) => {
      this.itemsService.getItem(+params['id']).subscribe((res: any) => {
        this.existingObject = res;
        this.name.setValue(this.existingObject.name);
        this.description.setValue(this.existingObject.description);
        this.price.setValue(this.existingObject.price);
        this.inventory.setValue(this.existingObject.inventory);
        this.category.setValue(this.existingObject.category);
        this.image_url.setValue(this.existingObject.image_url);
      })
    });
  }

}

Service
  updateItem(item) {
    let options = { headers: new HttpHeaders({'Content-Type': 'application/json'})};
    return this.http.post<IItem>(this.server_url + '/backend/items/update.php', item, options);
  }

A: You should put all your formcontrols in a formGroup
myFormGroup: FormGroup = this.fb.group({
  name: new FormControl('name'),
  description: new FormControl('description'),
  price: new FormControl('price'),
  inventory: new FormControl('inventory'),
  category: new FormControl('category'),
  image_url: new FormControl('image_url'),
});

In order to do so, you need to be able to make a formGroup, thus have the FormBuilder dependency injected.
constructor(..., private fb: FormBuilder) {}

The above code of grouping formcontrols can be done easier like this:
myFormGroup: FormGroup = this.fb.group({
  name: [''],
  description: [''],
  price: [''],
  inventory: ['']),
  category: [''],
  image_url: [''],
});

You will need to add the formGroup to your HTML template aswell
<form [formGroup]="myFormGroup" (ngSubmit)="updateItem()" autocomplete="off" novalidate>
   ...
</form>

Lastly, you can print the values in your submit function by adding likes this
updateItem() {
   if (this.myFormGroup.valid) //Not necessary since you don't use validators
       console.log(this.myFormGroup.value)
}

All this information and more can be found on the Reactive Forms Documentation of Angular


Q: Operational Transformation in Meteor.js? Does Meteor.js support Operational Transformation yet?
I'm working on a project which is some what related to Etherpad for which I thought of using Meteor.js(which I think is very much suited for this kind of project). Operational transformation is very important for my project if I think of making it scalable.  My current knowledge suggest that meteor does't support operational transformation out of box (correct me if I am wrong here).
So basically my question is how to implement operational transformation in meteor.js?
I tried using this library google-diff-match-patch, by Neil Fraser, but had problems while applying patches(though it worked outside meteor.js quite easily).
So any suggestions?

A: After seeing several Meteor projects make use of OT (i.e. http://cocodojo.meteor.com/), I decided to go for a proper integration.
I've created a smart package to integrate ShareJS into meteor. Please come check it out and add your pull requests: https://github.com/mizzao/meteor-sharejs
Demo App: http://documents.meteor.com

A: An in-browser collaborative text editor has two major components: the text area itself, which must behave well in coordinating the user's typing with other edits that are received from the server; and the data model for sending, receiving, and combining these edits.
Meteor today doesn't provide special help for either of these things specifically, but it does provide real-time data transport, and a way to move data automatically between the client and server.
If I were to implement EtherPad on Meteor, I've always imagined I would use a collection as an "operation log".  User changes would be sent to the server, where they would be appended to the official log of operations (basically diffs) which would automatically stream to all clients.  The client would have the work of applying diffs that come in and reconciling them with typing that hasn't been acknowledged by the server yet.
It's a tough implementation challenge.  Good luck!