text:
Q: Deriving Cauchy's inequality with Fubini's theorem The exercise is the following:

Let $f,g: X \to \mathbb K$ be two measurable functions such that $|f|^2, |g|^2 \in \mathcal L^1$. Making use of Fubini's theorem and by considering the function $$(x,y) \mapsto |f(x)g(x) f(y) g(y)|$$
  derive Cauchy's inequality:
  $$\left(\int_X |fg|\, d\mu \right)^2 \le \left(\int_X |f|^2 \, d\mu \right)\left(\int_X |g|^2\, d\mu\right)$$

I can prove that $\int_{X\times X} |f(x)g(x)f(y)g(y)| \, d(\mu\otimes \mu)= \left(\int_X |fg|\, d\mu\right)^2$ by an application of Fubini with $A = \{f\ne 0\}\cup \{g\ne 0\}$, which is $\sigma$-finite, since it can be written as a union $$A = \bigcup_{n = 1}^\infty (\{|f|^2>1/n\}\cup\{|g|^2\ge 1/n\})$$
where all sets on the RHS have to have finite measure, since $f,g \in L^2$. So
$$
\begin{align*}
\int_{X\times X} |f(x)g(x)f(y)g(y)| \, d(\mu\otimes \mu) &= \int_{A\times A} |f(x)g(x)f(y)g(y)| \, d(\mu\otimes \mu) \\
&= \left(\int_A |fg|\, d\mu\right)^2 \\
&= \left(\int_X |fg|\, d\mu\right)^2
\end{align*}
$$
But I don't really see how to prove $$\int_{X\times X} |f(x)g(x)f(y)g(y)| \, d(\mu\otimes \mu)\le \left(\int_X |f|^2 \, d\mu\right)\left( \int_X |g|^2\, d\mu\right)$$
without making use of Young's inequality (or AM-GM). I think one should be able to see this last inequality directly somehow.
Why I don't want to use AM-GM: The derivation in this exercise should probably be an alternative to the usual one, where one integrates $$\frac{|fg|}{\Vert f\Vert_2 \Vert g\Vert_2} \le \frac12 \left(\frac{|f|^2}{\Vert f\Vert_2^2}+\frac{|g|^2}{\Vert g \Vert_2^2}\right)$$
Some help would be very much appreciated, thanks! =)

A: We can write
\begin{align*}
0&\leq \int_{X^2}|f(x)g(y)-f(y)g(x)|^2d\mu\otimes \mu(x,y)
\\\
&=\int_{X^2}|f(x)|^2\cdot |g(y)|^2d\mu\otimes \mu(x,y)-2\int_{X^2}|f(x)|\cdot |f(y)|\cdot |g(x)|\cdot |g(y)|d\mu\otimes \mu(x,y)\\\
&+\int_{X^2}|f(y)|^2\cdot |g(x)|^2d\mu\otimes \mu(x,y)\\\
&=2\left(\int_X |f|^2d\mu\right)\left(\int_X |g|^2d\mu\right)-2\bigg(\int_X|fg|d\mu \bigg)^2,
\end{align*}
where Fubini's theorem was used to go from the second/third line to the forth.


text:
Q: Smart HTTP git backend with apache2 I'm trying to use the smart HTTP functionality of git on my Ubuntu Server. I've read the documentation for both smart HTTP and git-http-backend, as well as the documentation for apache; but for the life of me, I can't figure out why this isn't working. I have a functionning Sonar server that's proxied through apache, which is working fine, but I can't get this to work. Namely, I keep getting a 403 error.
/etc/apache2/sites-available/git.conf
SetEnv GIT_PROJECT_ROOT /opt/git
SetEnv GIT_HTTP_EXPORT_ALL
ScriptAlias /git/ /usr/lib/git-core/git-http-backend/

<Directory "/opt/git">
    Order allow,deny
    Allow from all
    Require all granted
</Directory>

<LocationMatch "^/git/.*/git-receive-pack$">
    AuthType Basic
    AuthName "Git Access"
    Order allow,deny
    Allow from all
    AuthUserFile /opt/git/.htpasswd
    Require valid-user
</LocationMatch>

I thought that maybe it was a permission issue, as www-data didn't have access to the /opt/git folder, so I created a new group, git-access and added both myself and www-data to that group, and changed the permissions of the /opt/git so that www-data was the group, with rw permission for the group and owner.
zymus@ubuntu:/etc/apache2/sites-available$ groups www-data
www-data : www-data git-access

zymus@ubuntu:/etc/apache2/sites-available$ ls -la /opt/git
total 56
drwxrwxr-x 13 git  git-access 4096 Mar  4 19:37 .
drwxr-xr-x  5 root root       4096 Jan 23 15:44 ..
-rw-rw-r--  1 git  git-access   50 Jan 26 13:34 .htpasswd
drwxrwxr--  7 git  git-access 4096 Mar  4 19:40 pokemod-game-api.git
drwxrwxr--  7 git  git-access 4096 Nov 25 23:18 pokenet-cms.git
drwxrwxr--  7 git  git-access 4096 Nov 25 23:20 pokenet-file-server.git
drwxrwxr--  3 git  git-access 4096 Jan 11 01:05 pokenet-game-client.git
drwxrwxr--  7 git  git-access 4096 Jan 16 21:57 pokenet-game-core.git
drwxrwxr--  7 git  git-access 4096 Nov 22 19:25 pokenet-game-server.git
drwxrwxr--  7 git  git-access 4096 Nov 25 23:26 pokenet-launcher.git
drwxrwxr--  7 git  git-access 4096 Dec 26 17:44 pokenet-login-client.git
drwxrwxr--  7 git  git-access 4096 Nov 22 19:24 pokenet-login-server.git
drwxrwxr--  7 git  git-access 4096 Dec  4 15:24 pokenet-login-token.git
drwxrwxr--  7 git  git-access 4096 Nov 23 00:03 zephyrion-core.git

zymus@ubuntu:/etc/apache2/sites-available$ groups zymus
zymus : zymus adm cdrom sudo dip plugdev lpadmin sambashare git git-access

zymus@ubuntu:/etc/apache2/sites-available$ groups www-data
www-data : www-data git-access

zymus@ubuntu:/etc/apache2/sites-available$ groups git
git : git git-access

zymus@ubuntu:/etc/apache2/sites-available$ cat /opt/git/.htpasswd
zymus:Git Access:*

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple domains to single document root I am currently working on a distributed CMS that is built on a traditional LAMP stack. Customers can access their backend (and front end) using a subdomain of their username, for example:
benm.mycms.com
However, now we want to be able to add support custom domains, so that the user can decide to point any domain to their account, for example:
benscms.com
The site should be accessible from both URLs still, but we need multiple domains to point to the same document root on the server. I know that this can be achieved using Name-based virtual hosts in Apache, but we want an entirely automated process (so that when the customer fills in the form, it just happens). Is there a way around it without modifying the main Apache conf files?
Essentially what we're trying to achieve is that many domains access the same PHP system, but we detect the customer based on the domain used (or the subdomain, if that's their preferred route).

A: You would need to have a single Apache virtual host without any domain name, and have that as the default virtual host on the server.
Then, in your PHP application you read the $_SERVER['HTTP_HOST'] variable, which contains the Host: HTTP header.


text:
Q: Evaluating the limit ${\lim_\limits{x\to0^+}\frac{e^x-\cos(\lambda \sqrt x)}{\sqrt {1+\sin(\lambda x)}-1}}$
Evaluate $$\lim_\limits{x\to0^+}\frac{e^x-\cos(\lambda \sqrt x)}{\sqrt {1+\sin(\lambda x)}-1}=(*)$$

My attempt:
I have used Taylor expansion of $e^x, \ \cos x, \ \sin x:$
$$(*)=\lim_\limits{x\to0^+}\frac{1+x-1+\frac{\lambda^2 x}2+ o(x)}{\sqrt {1+\lambda x+o(x)}-1}=\lim_\limits{x\to0^+}\frac{(x+\frac{\lambda^2 x}2)(\sqrt{1+\lambda x+o(x)}+1)}{\lambda x}=\\ =\left(\frac1{\lambda}+\frac{\lambda}2\right)\lim_\limits{x\to0^+}\frac{\sqrt{1+\lambda x}+1}{\lambda x}$$
$\left(\dfrac1{\lambda}+\dfrac{\lambda}2\right)$ is the result written on my textbook, but there seems to be a typo.
Thanks in advance
P.S. the exercise comes from Calculus Problems, $8.20$ page $144$
EDIT: Actually the last step should have been:
$$\left(\frac1{\lambda}+\frac{\lambda}2\right)\lim_\limits{x\to0^+}\sqrt{1+\lambda x}+1=\frac2{\lambda}+\lambda$$

A: You are on the right track. At the first step, the $\lambda$ at the numerator    should be squared,
$$\begin{align}
\lim_\limits{x\to0^+}\frac{1+x-1+\frac{\lambda^2 x}2+ o(x)}{\sqrt {1+\lambda x+o(x)}-1}&=\lim_\limits{x\to0^+}\frac{x+\frac{\lambda^2 x}2+ o(x)}{ \lambda x}\cdot \left(\sqrt{1+\lambda x+o(x)}+1\right)\\
&=\left(\frac{1}{\lambda}+\frac{\lambda }2\right)\lim_\limits{x\to0^+}(\sqrt{1+\lambda x+o(x)}+1)=\frac{2}{\lambda}+\lambda
\end{align}$$
which is different from your expected result (probably a typo in your textbook).

A: By standard limits
$$\frac{e^x-\cos(\lambda \sqrt x)}{\sqrt {1+\sin(\lambda x)}-1}=x\frac{\frac{e^x-1}{x}+\frac{1-\cos(\lambda \sqrt x)}{x}}{\sqrt {1+\sin(\lambda x)}-1}\frac{\sqrt {1+\sin(\lambda x)}+1}{\sqrt {1+\sin(\lambda x)}+1}=\left(\sqrt {1+\sin(\lambda x)}+1\right)\left(\frac{e^x-1}{x}+\lambda^2\frac{1-\cos(\lambda \sqrt x)}{\lambda^2x}\right)\frac{\lambda x}{\sin \lambda x}\frac1{\lambda}\\\to2\left(1+\frac12\lambda^2\right)\frac1{\lambda}=\frac2{\lambda}+\lambda$$

A: After expansion and simplification, the dominant terms of the numerator are (the units cancel out)
$$x+\frac{\lambda^2\sqrt x^2}2$$ and that of the denominator (linearize the sine, then the square root, the units also cancel out)
$$\frac{\lambda x}2.$$
Hence the ratio tends to
$$\frac2\lambda+\lambda.$$


text:
Q: Latest localstack does not start Dynamodb properly in Linux I have below versions of
python --> 3.6.10
pip --> pip 19.3.1 from python2
localstack --> 0.11.1
Docker --> 18.09.9-ce

but when I tried to start the localstack -->localstack start
it throws me below error:

LocalStack version: 0.11.1.1
Starting local dev environment. CTRL-C to quit.
docker run -it -e DEFAULT_REGION="us-east-1" -e TEST_AWS_ACCOUNT_ID="000000000000" -e HOSTNAME="10-20-134-45" -e LOCALSTACK_HOSTNAME="10-20-134-45" --rm --privileged --name localstack_main -p 8080-8081:8080-8081 -p 4567-4620:4567-4620 -p 10000:10000  -v "/tmp/localstack:/tmp/localstack" -v "/var/run/docker.sock:/var/run/docker.sock" -e DOCKER_HOST="unix:///var/run/docker.sock" -e HOST_TMP_FOLDER="/tmp/localstack" "localstack/localstack"
Unable to find image 'localstack/localstack:latest' locally
latest: Pulling from localstack/localstack
5a20acb0595b: Pull complete
Digest: sha256:78e3bce5360fc42890d3e1cc16fac660b32a4a29d0c7f0068ff52d18458dbb19
Status: Downloaded newer image for localstack/localstack:latest
Waiting for all LocalStack services to be ready
2020-05-18 16:55:22,958 CRIT Supervisor is running as root.  Privileges were not dropped because no user is specified in the config file.  If you intend to run as root, you can set user=root in the config file to avoid this message.
2020-05-18 16:55:22,961 INFO supervisord started with pid 13
2020-05-18 16:55:23,963 INFO spawned: 'dashboard' with pid 19
2020-05-18 16:55:23,965 INFO spawned: 'infra' with pid 20
2020-05-18 16:55:23,971 INFO success: dashboard entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
(. .venv/bin/activate; bin/localstack web)
LocalStack version: 0.11.1
(. .venv/bin/activate; exec bin/localstack start --host)
LocalStack version: 0.11.1
Starting local dev environment. CTRL-C to quit.
2020-05-18 16:55:25,555 INFO success: infra entered RUNNING state, process has stayed up for > than 1 seconds (startsecs)
Waiting for all LocalStack services to be ready
Starting edge router (https port 4566)...
Starting mock API Gateway service in http ports 4566 (recommended) and 4567 (deprecated)...
2020-05-18T16:55:30:INFO:localstack.multiserver: Starting multi API server process on port 51492
Starting mock CloudFormation service in http ports 4566 (recommended) and 4581 (deprecated)...
Starting mock CloudWatch service in http ports 4566 (recommended) and 4582 (deprecated)...
Starting mock DynamoDB service in http ports 4566 (recommended) and 4569 (deprecated)...
Starting mock DynamoDB Streams service in http ports 4566 (recommended) and 4570 (deprecated)...
Starting mock EC2 service in http ports 4566 (recommended) and 4597 (deprecated)...
Starting mock ES service in http ports 4566 (recommended) and 4578 (deprecated)...
Starting mock Firehose service in http ports 4566 (recommended) and 4573 (deprecated)...
Starting mock IAM service in http ports 4566 (recommended) and 4593 (deprecated)...
Starting mock STS service in http ports 4566 (recommended) and 4592 (deprecated)...
Starting mock Kinesis service in http ports 4566 (recommended) and 4568 (deprecated)...
Starting mock KMS service in http ports 4566 (recommended) and 4599 (deprecated)...
Starting mock Lambda service in http ports 4566 (recommended) and 4574 (deprecated)...
Starting mock CloudWatch Logs service in http ports 4566 (recommended) and 4586 (deprecated)...
Starting mock Redshift service in http ports 4566 (recommended) and 4577 (deprecated)...
Starting mock Route53 service in http ports 4566 (recommended) and 4580 (deprecated)...
Starting mock S3 service in http ports 4566 (recommended) and 4572 (deprecated)...
Starting mock Secrets Manager service in http ports 4566 (recommended) and 4584 (deprecated)...
Starting mock SES service in http ports 4566 (recommended) and 4579 (deprecated)...
Starting mock SNS service in http ports 4566 (recommended) and 4575 (deprecated)...
Starting mock SQS service in http ports 4566 (recommended) and 4576 (deprecated)...
Starting mock SSM service in http ports 4566 (recommended) and 4583 (deprecated)...
Starting mock Cloudwatch Events service in http ports 4566 (recommended) and 4587 (deprecated)...
Starting mock StepFunctions service in http ports 4566 (recommended) and 4585 (deprecated)...
Waiting for all LocalStack services to be ready
Waiting for all LocalStack services to be ready
Waiting for all LocalStack services to be ready
Waiting for all LocalStack services to be ready
Waiting for all LocalStack services to be ready
Waiting for all LocalStack services to be ready
Waiting for all LocalStack services to be ready
2020-05-18T16:56:24:WARNING:localstack.services.plugins: Service "dynamodb" not yet available, retrying...
Waiting for all LocalStack services to be ready

I tried below  possibilities , but still not able to start all the services.
python -m pip uninstall localstack
python -m pip install --no-cache --upgrade localstack
sudo chown -R $USER /usr/local/lib/python3.6/site-packages

can anyone help me or point me to start the service without any problem.


text:
Q: How to turn off autocomplete while keep using datalist element in html I have a input field which shows a list using html5 <datalist> element. The problem is that with <datalist> the browser autocomplete also shows the history list (which is the list of previously typed values, that are not included in the <datalist>). So I just want to get rid of the history-list not the <datalist>.
If I use the autocomplete = "off" feature, this also blocks the <datalist>.
In short, I just want the <datalist> not the history one.

A: I use a code like this:
<input name="anrede" list="anrede" onmousedown="value = '';" />
<datalist id="anrede">
    <option value="Herr"></option>
    <option value="Frau"></option>
</datalist>

good: The datalist shown for selection is complete
bad : The input field is empty,
      therefore the old value is not documented,
      if needed to be remembered by the user

A: you can use autocomplete="new-password". autocomplete = "off" didn't worked in my case.
<input name="q" type="text" autocomplete="new-password"/>

A: Is it possible for you to use the input field without an id or name attribute?  Without that, the browser doesn't really have any way to associate a history with that element.
In my real quick testing on Firefox, this seemed to do the trick:
<form>

  With id: <input id="myInputId" list="myList" />

  With name: <input name="myInputName" list="myList" />

  No id, name, class: <input list="myList" />

  With class: <input class="myInputClass" list="myList" />

  <datalist id="myList">
    <option value="Option 1"></option>
    <option value="Option 2"></option>
  </datalist>

  <input type="submit" />
</form>

In the code above, the inputs with an id or name would remember past values, but the input without anything and the input with just a class would not remember anything.
Unfortunately, this does make using the input slightly more difficult if you need it to have a name or id.  In that case, I'd try having an id'ed input which is also display: none'ed and then use some JavaScript to keep it in sync with an input that won't remember past values.

A: Try using the HTML attribute autocomplete
<input name="q" type="text" autocomplete="off"/>

source Turn Off Autocomplete for Input

A: Try this, I hope it works.
<input id="datalisttestinput" list="stuff" autocomplete="off"></input>
<datalist id="stuff">
     <option id="1" value="Amy">
     <option id="2" value="Kristal">
     <option id="3" value="Collin">
     <option id="4" value="Carl">
</datalist>

A: try this:
<datalist id="datalist_id">

js:
dataList = $("#datalist_id")
dataList.empty()

This will clear the datalist's history. This worked for me on chrome.
Then if you want to add options to the list, try:
dataList.append("<option>Some Option</option>")

Cheers !!!


text:
Q: Importing only a few columns of a csv as a python pandas dataframe? I would like to only import a subset of a csv as a dataframe as it is too large to import the whole thing. Is there a way to do this natively in pandas without having to set up a database like structure?
I have tried only importing a chunk and then concatenating and this is still too large and causes memory error. I have hundreds of columns so manually specifying dtypes could help, but would likely be a major time commitment.
df_chunk = pd.read_csv("filename.csv", chunksize=1e7)
df = pd.concat(df_chunk,ignore_index=True)

A: You may use the skiprows and nrows arguments in the read_csv function to load only a subset of rows from your original dataframe.
For instance:
 import pandas as pd
 df = pd.read_csv("test.csv", skiprows = 4, nrows=10)


text:
Q: Activity indicator for 5seconds? All
I am trying to run UIActivityIndicator for a 5 seconds on viewdidappear method .But how do i give a time limit for activity indicator(5 seconds)  ?
This is the code for UIActivityIndicator
 UIActivityIndicatorView *activityView=[[UIActivityIndicatorView alloc]     initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

    activityView.center=self.view.center;

    [activityView startAnimating];

    [self.view addSubview:activityView];

A: With one line and no additional dependencies & conditions:
[activityView performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:5.0];

A: Set activity view to hide automatically when stopped
activityView.hidesWhenStopped = YES;

And hide it after 5s like this:
[activityView performSelector:@selector(stopAnimating) withObject:nil afterDelay:5.0];

This will allow you to start animation again by just calling startAnimating if you need so in the future and keep pointer to the UIActivityIndicatorView
If you just need to show activity indicator once and will not use it anymore, Alexanders answer will suit best to your needs

A: Use NSTimer for 5 sec.
In the call back method of timer stop the animation

A: try this code,
  -(void)viewDidAppear:(BOOL)animated
{
        UIActivityIndicatorView *activityView=[[UIActivityIndicatorView alloc]     initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        activityView.center=self.view.center;
        [self.view addSubview:activityView];
        [activityView startAnimating];
        activityView.tag=1111;
        [activityView release];
}

    [activityView performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:5.0];

    -(void)removeFromSuperview
    {
            UIActivityIndicatorView *activityView=(UIActivityIndicatorView*)[self.viewviewWithTag:1111];
            [activityView stopAnimating];
[activityView removeFromSuperview];
        }


text:
Q: Alt-Gr key is not working in Ubuntu 13.10 I installed Ubuntu with mostly default configuration; the keyboard seems not to detect the Alt Gr key so that I can not type international characters.
How can I enable Alt Gr key?

A: In order to set up the Alt-Gr  key you must go to (setting -> keyboard -> layout settings -> keyboard settings -> then go to the typing tab -> press and hold the Alternative Keyboard Key setting -> move you mouse down to select the key you want to assign Alt-Gr to.

A: This answer has screenshots for Gnome-Shell (Ubuntu Gnome 13.10). I suppose it will be similar for standard Unity, but if not, please chime in.
First of all (and this is the most common problem), to have AltGr working you need a keyboard layout which uses it. For example, this is my keyboard layout (Settings -> Region and Language):

*

*English (US, international with dead keys) has AltGr.

*English (US) has NO AltGr.

*English (international AltGr dead keys) has AltGr.

(My preferred layout is the third one, really).
If the layout does not map AltGr+Key to anything, like for example the default "English (US)", AltGr will not work even if it's activated in the Keyboard -> Shortcuts panel.
This is normally sufficient. To change the position of the AltGr you go to Settings -> Keyboard and set the "Alternative Characters Key":

For example, my keyboard has no physical AltGr key, so I mapped it to the Right Alt key.
Now with the third layout, pressing AltGr and n together gives ñ.
Compose (the option before) is a very different beast. If you enable it, then you will have a set of characters available with three (or more) keystrokes. For example, pressing Compose, o, e  gives œ. That's three sequential keystrokes, not together.
Take into account that there is a bug related to the layout switching in 13.10 which is being worked on, so check it if you have problems changing layout.

A: AltGr sounds like a lot of trouble for only a few symbols.  A better choice might be the United States Alternative International keyboard.  This one gives a choice of dozens of letters with diacritical marks .  The k'bd is just like the standard k'bd except that the `~ ^' and the " are --dead-- keys  ( delayed action ) until the next key is pressed.
These are the accent grave, tilde, circumflex and the accent agut.  Just these 5 added to all the vowels and many consonants gives dozens of extra characters .  If you want to type the apostrophe by it self just hit the space bar.  ( Or the quote sign )  I have Ubuntu 12.10 and it works OK.  I used the instructions for Ubuntu 14.04 so I had to do some guessing but I finally got it to work.
http://www.wikihow.com/Change-Keyboard-Layout-in-Ubuntu
  ã â ś Ḱ ç ŕ ï ḿ ĝ  ĥ â ŝ ó õ------samples

the 'and the v  =   ǘ  this u with 2 marks above it ,,, wonder where it is used ?


text:
Q: Using R as a game simulator I am trying to simulate a simple game where you spin a spinner, labeled 1-5, and then progress on until you pass the finish line (spot 50). I am a bit new to R and have been working on this for a while searching for answers. When I run the code below, it doesn't add the numbers in sequence, it returns a list of my 50 random spins and their value. How do I get this to add the spins on top of each other, then stop once => 50?
SpacesOnSpinner<-(seq(1,5,by=1))
N<-50
L1<-integer(N)

for (i in 1:N){
takeaspin<-sample(SpacesOnSpinner,1,replace=TRUE)
L1[i]<-L1[i]+takeaspin
}

A: This is a good use-case for replicate. I'm not sure if you have to use a for loop, but you could do this instead (replicate is a loop too):
SpacesOnSpinner<-(seq(1,5,by=1))
N<-10
cumsum( replicate( N , sample(SpacesOnSpinner,1,replace=TRUE) ) )
#[1]  5 10 14 19 22 25 27 29 30 33

However, since you have a condition which you want to break on, perhaps the other answer with a while condition is exactly what you need in this case (people will tell you they are bad in R, but they have their uses). Using this method, you can see how many spins it took you to get past 50 by a simple subset afterwards (but you will not know in advance how many spins it will take, but at most it will be 50!):
N<-50
x <- cumsum( replicate( N , sample(5,1) ) )

# Value of accumulator at each round until <= 50
x[ x < 50 ]
#[1]  5  6  7  8 12 16 21 24 25 29 33 34 36 38 39 41 42 44 45 49

# Number of spins before total <= 50
length(x[x < 50])
[1] 20

A: Here is another interesting way to simulate your game, using a recursive function.
spin <- function(outcomes = 1:5, start = 0L, end = 50L)
   if (start <= end)
      c(got <- sample(outcomes, 1), Recall(outcomes, start + got, end))

spin()
# [1] 5 4 4 5 1 5 3 2 3 4 4 1 5 4 3

Although elegant, it won't be as fast as an improved version of @Simon's solution that makes a single call to sample, as suggested by @Viktor:
spin <- function(outcomes = 1:5, end = 50L) {
   max.spins <- ceiling(end / min(outcomes))
   x <- sample(outcomes, max.spins, replace = TRUE)
   head(x, match(TRUE, cumsum(x) >= end))
}

spin()
# [1] 3 5 2 3 5 2 2 5 1 2 1 5 5 5 2 4

For your ultimate goal (find the probability of one person being in the lead for the entire game), it is debatable whether while will be more efficient or not: a while loop is certainly slower, but you may benefit from the possibility of exiting early as the lead switches from one player to the other. Both approaches are worth testing.

A: You can use a while statement and a variable total for keeping track of the sum:
total <- 0
while(total <= 50){
   takeaspin<-sample(SpacesOnSpinner,1,replace=TRUE)
   total <- takeaspin + total
}

print (total)


text:
Q: How to schedule a wall post with php and cUrl I managed to post a status to my wall with a custom app, but what I want to do, is schedule the status, to be posted on a given datetime.
The problem was, when I close my app, the script is aborted.
Right now it works, I'm using ignore_user_abort(true) and sleep().
I'm also using set_time_limit(1), once the given datetime has passed, so the script stops.
I feel like this is crappy coding and want to know if there's a better way to do this?
Here's the code I'm using right now:
<?php
 ignore_user_abort(true);
 $token=$_GET["access_token"];
 $attachment =  array(
    'access_token' => "$token",
    'message' => "deze post moet om 14.14 online komen",
    'name' => "testpost",
    'link' => "http://myurl.be/",
    'description' => "Write here your description",
    'picture'=> "http://myurl/assets/images/layout/logo.png");

date_default_timezone_set('Europe/Belgrade');
$time= date('d/m/Y H:i');
if ("10/01/2012 14:14" < $time ){
set_time_limit(1);
$result = $facebook->api('/me/feed/','post',$attachment);
}else{
sleep(60);
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, "https://www.myurl.com/tests/facebooklogin/post.php?access_token=".$token);
curl_exec ($curl);
curl_close ($curl);
}
print $result;
?>

A: You could store all the information needed for your post (text, link, description and so on) in a database (like MySQL), setup a PHP script that get's called periodically by cron and fetches all posts from the database that need to be posted by the time the script get's executed.
But be aware that access tokens expire after a few hours/a day or when the user changes his password. Unless you don't have a "offline_access" permission, then the token never expires.


text:
Q: "Search" no longer finds any results I don't know how I don't know when, but at any moment my search engine of my application has stopped working, or rather, it no longer finds any results.
Controller
$request->validate([
    'search' => 'required',
]);

if($request->has('search')) {
    $key = $request->input('search');
    $searchResults = Items::whereHas('category', function ($query) {
        $query->where('status', 1);
    })
    ->search($key)
    ->where('status', 1)
    ->orderByDesc('id')
    ->paginate(15);
}

Items.php Models
use App\Traits\FullTextSearch;
use FullTextSearch;

/**
 * The columns of the full text index
 */
protected $searchable = [
    'title',
    'description'
];

Whatever the word to search for, it does not find any results, even simply searching for "the" or "is", it does not find any results despite the fact that each post contains it both in the description and in the title.

A: What is wrong of using where for search?

$query->where($request->column, 'LIKE', "%{$request->search}%");


text:
Q: Simple download/install script (OS X) that could be better I'm new to shell scripting (OS X) and decided to try my hand at a basic script that downloads and installs Chrome.
#!/bin/bash -x

cd ~/Downloads
curl -O https://dl.google.com/chrome/mac/stable/CHFA/googlechrome.dmg
open ~/Downloads/googlechrome.dmg && sleep 10
cp -R /Volumes/Google\ Chrome/Google\ Chrome.app /Applications && open
/Applications/Google\ Chrome.app
diskutil eject Google\ Chrome

The script technically works but only because of the sleep 10 I put in there, and only because the dmg happens to launch within 10 seconds (which won't always be the case in the real world).
I've tried to link open and cp together with &&, but that doesn't work, and I get the error that /Volumes/Google\ Chrome/Google\ Chrome.app doesn't exist (because the previous command hasn't completed fully yet).
I don't think this script will have a lot of useful applications; again, I'm just trying to learn, but I'm just wondering if there is a better way to go about this.
Thanks!

A: This could be revised to use an "are we there yet?" sanity check rather than sleeping for a sixth of a minute:
#!/bin/bash -x

cd ~/Downloads
curl -O https://dl.google.com/chrome/mac/stable/CHFA/googlechrome.dmg
open ~/Downloads/googlechrome.dmg
while ! [[ -d /Volumes/Google\ Chrome/ ]]; do
   sleep 1
done
cp -R /Volumes/Google\ Chrome/Google\ Chrome.app /Applications && open
/Applications/Google\ Chrome.app
diskutil eject Google\ Chrome

However, in the event that the .dmg fails to mount or for some reason mounts into another location, this will spin its wheels until the end of time.
Slightly better than handing this off to open though (which just asks Finder to pretend we double-clicked on the file), let's mount it ourselves:
#!/bin/bash -x
cd ~/Downloads
curl -O https://dl.google.com/chrome/mac/stable/CHFA/googlechrome.dmg
set -o pipefail
if mountpoint=$(hdiutil attach googlechrome.dmg | awk 'END { print $1 }'; then
   cp -R /Volumes/Google\ Chrome/Google\ Chrome.app /Applications && open
   /Applications/Google\ Chrome.app
   hdiutil detach "$mountpoint"
fi


text:
Q: Is there another way to concatenate instead of using the CONCATENATE keyword? Is there another way to concatenate in ABAP instead of using the CONCATENATE keyword?
An example using CONCATENATE:
DATA:
  foo    TYPE string,
  bar    TYPE string,
  foobar TYPE string.

  foo = 'foo'.
  bar = 'bar'.

  CONCATENATE foo 'and' bar INTO foobar SEPARATED BY space.

A: Besides the String Expressions mentioned by Eduardo Copat, it is sometimes sensible to use the MESSAGE ... INTO ... statement - especially if the text is supposed to be translated. In some translations, the positions of variables relative to each other have to be swapped, and it is generally much easier to translate the text You cannont combine &1 with &2. than the separate parts You cannot combine and with.

A: You can (starting with ABAP 7.02) use && to concatenate two strings.
Data:
foo    TYPE string,
bar    TYPE string,
foobar TYPE string.

foo = 'foo'.
bar = 'bar'.

foobar = foo && bar.

This also works with character literals:
foobar = 'foo' && 'bar'.

For preserving spaces, use this kind of character literal named "text string literal" which is defined with two grave accents (U+0060):
foobar = foo && ` and ` && bar

A: You can use && or |{}{}| notations.
You don't need to type and between the objects, if you give space it will take it as space or any other.
"no space:
foobar = |{ foo }{ bar }|.
"1 space:
foobar = |{ foo } { bar }|.

etc.

A: Yes, you can use String Templates, which were introduced in ABAP 7.02.
An example following:
DATA:
  foo    TYPE string,
  bar    TYPE string,
  foobar TYPE string.

  foo = 'foo'.
  bar = 'bar'.

  foobar = |{ foo } and { bar }|.

A: DATA: v_line TYPE string.

CONCATENATE 'LINE1' 'LINE2' 'using cl_abap_char_utilities=>NEWLINE' INTO v_line SEPARATED BY cl_abap_char_utilities=>NEWLINE.

CALL FUNCTION 'LXE_COMMON_POPUP_STRING'
  EXPORTING
    text          = v_line
          .

CLEAR: v_line.

CONCATENATE 'LINE3' 'LINE4'  'cl_abap_char_utilities=>HORIZONTAL_TAB' INTO v_line SEPARATED BY cl_abap_char_utilities=>HORIZONTAL_TAB.

CALL FUNCTION 'LXE_COMMON_POPUP_STRING'
  EXPORTING
    text          = v_line
          .

CLEAR: v_line.

CONCATENATE 'LINE5' 'LINE6'  'cl_abap_char_utilities=>VERTICAL_TAB' INTO v_line SEPARATED BY cl_abap_char_utilities=>VERTICAL_TAB.

CALL FUNCTION 'LXE_COMMON_POPUP_STRING'
  EXPORTING
    text          = v_line
          .

CLEAR: v_line.

CONCATENATE 'LINE7' 'LINE8'  'cl_abap_char_utilities=>CR_LF' INTO v_line SEPARATED BY cl_abap_char_utilities=>CR_LF.

CALL FUNCTION 'LXE_COMMON_POPUP_STRING'
  EXPORTING
    text          = v_line
          .


text:
Q: C free(): invalid pointer I am teaching myself C. My goal is to make a C function that just walks a query string and splits on the ampersand and the equals sign. I am getting stuck on this error from Valgrind.
==5411== Invalid free() / delete / delete[] / realloc()
==5411==    at 0x402AC38: free (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==5411==    by 0x804857C: main (leak.c:28)
==5411==  Address 0x420a02a is 2 bytes inside a block of size 8 free'd
==5411==    at 0x402AC38: free (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==5411==    by 0x804857C: main (leak.c:28)
==5411==
==5411==
==5411== HEAP SUMMARY:
==5411==     in use at exit: 0 bytes in 0 blocks
==5411==   total heap usage: 1 allocs, 2 frees, 8 bytes allocated
==5411==
==5411== All heap blocks were freed -- no leaks are possible
==5411==
==5411== For counts of detected and suppressed errors, rerun with: -v
==5411== ERROR SUMMARY: 20 errors from 9 contexts (suppressed: 0 from 0)

and the backtrace :
*** Error in `./leak': free(): invalid pointer: 0x08c1d00a ***
======= Backtrace: =========
/lib/i386-linux-gnu/libc.so.6(+0x767c2)[0xb75f17c2]
/lib/i386-linux-gnu/libc.so.6(+0x77510)[0xb75f2510]
./leak[0x804857d]
/lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xf5)[0xb7594905]
./leak[0x8048421]
======= Memory map: ========
08048000-08049000 r-xp 00000000 08:05 262764     /home/danny/dev/c-qs-parser/leak
08049000-0804a000 r--p 00000000 08:05 262764     /home/danny/dev/c-qs-parser/leak
0804a000-0804b000 rw-p 00001000 08:05 262764     /home/danny/dev/c-qs-parser/leak
08c1d000-08c3e000 rw-p 00000000 00:00 0          [heap]
b757a000-b757b000 rw-p 00000000 00:00 0
b757b000-b7729000 r-xp 00000000 08:05 1312132    /lib/i386-linux-gnu/libc-2.17.so
b7729000-b772b000 r--p 001ae000 08:05 1312132    /lib/i386-linux-gnu/libc-2.17.so
b772b000-b772c000 rw-p 001b0000 08:05 1312132    /lib/i386-linux-gnu/libc-2.17.so
b772c000-b772f000 rw-p 00000000 00:00 0
b772f000-b774a000 r-xp 00000000 08:05 1312589    /lib/i386-linux-gnu/libgcc_s.so.1
b774a000-b774b000 r--p 0001a000 08:05 1312589    /lib/i386-linux-gnu/libgcc_s.so.1
b774b000-b774c000 rw-p 0001b000 08:05 1312589    /lib/i386-linux-gnu/libgcc_s.so.1
b774c000-b7750000 rw-p 00000000 00:00 0
b7750000-b7751000 r-xp 00000000 00:00 0          [vdso]
b7751000-b7771000 r-xp 00000000 08:05 1312116    /lib/i386-linux-gnu/ld-2.17.so
b7771000-b7772000 r--p 0001f000 08:05 1312116    /lib/i386-linux-gnu/ld-2.17.so
b7772000-b7773000 rw-p 00020000 08:05 1312116    /lib/i386-linux-gnu/ld-2.17.so
bfe93000-bfeb4000 rw-p 00000000 00:00 0          [stack]
Aborted (core dumped)

finally here is the code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {

    //char p[] = "t=quote&k=id&v=10";
    char p[] = "t=quote";

    char* token;
    char* tk;
    char* s;
    unsigned short int found;

    s = strdup(p);

    if (s != NULL) {
        while ((token = strsep(&s, "&")) != NULL) {

            found = 0;

            printf("TOKEN: %s\n\n", token);

            while ((tk = strsep(&token, "=")) != NULL) {

                printf("TK: %s\n\n", tk);

                free(tk);
            }

            free(token);
        }
    }

    free(s);

    return 0;
}

Thanks

A: You're attempting to free something that isn't a pointer to a "freeable" memory address. Just because something is an address doesn't mean that you need to or should free it.
There are two main types of memory you seem to be confusing - stack memory and heap memory.

*

*Stack memory lives in the live span of the function. It's temporary space for things that shouldn't grow too big. When you call the function main, it sets aside some memory for your variables you've declared (p,token, and so on).

*Heap memory lives from when you malloc it to when you free it. You can use much more heap memory than you can stack memory. You also need to keep track of it - it's not easy like stack memory!
You have a few errors:

*

*You're trying to free memory that's not heap memory. Don't do that.

*You're trying to free the inside of a block of memory. When you have in fact allocated a block of memory, you can only free it from the pointer returned by malloc. That is to say, only from the beginning of the block. You can't free a portion of the block from the inside.
For your bit of code here, you probably want to find a way to copy relevant portion of memory to somewhere else...say another block of memory you've set aside. Or you can modify the original string if you want (hint: char value 0 is the null terminator and tells functions like printf to stop reading the string).
EDIT: The malloc function does allocate heap memory*.
"9.9.1 The malloc and free Functions
The C standard library provides an explicit allocator known as the malloc package. Programs allocate blocks from the heap by calling the malloc function."
~Computer Systems : A Programmer's Perspective, 2nd Edition, Bryant & O'Hallaron, 2011
EDIT 2: * The C standard does not, in fact, specify anything about the heap or the stack. However, for anyone learning on a relevant desktop/laptop machine, the distinction is probably unnecessary and confusing if anything, especially if you're learning about how your program is stored and executed. When you find yourself working on something like an AVR microcontroller as H2CO3 has, it is definitely worthwhile to note all the differences, which from my own experience with embedded systems, extend well past memory allocation.

A: You can't call free on the pointers returned from strsep. Those are not individually allocated strings, but just pointers into the string s  that you've already allocated. When you're done with s altogether, you should free it, but you do not have to do that with the return values of strsep.

A: From where did you get the idea that you need to free(token) and free(tk)? You don't. strsep() doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc() (or similar), so free()ing them is undefined behavior. You only need to free(s) when you are done with the entire string.
Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup() and free() altogether by simply writing char *s = p;.


text:
Q: C++11 member initializer list vs in-class initializer? What difference between these ways of initializing object member variables in C++11 ? Is there another way ?  which way is better (performance) ?:
class any {
  public:
    obj s = obj("value");
    any(){}
};

Or
class any {
  public:
    obj s;
    any(): s("value"){}
};

Thanks.

A: Both examples are equivalent.
Though only if the type is copyable or movable (check it for yourself) and NRVO is actually done (any halfway decent compiler will do it as a matter of course).
Though if you had many constructors and constructor-chaining were inappropriate, the first method would allow you not to repeat yourself.
Also, you can use that method to define aggregates with defaults different from aggregate-initialization for (some) members since C++14.

A: No, these are not the same.
The difference between them is the same that applies for direct-initialization vs. copy-initialization, which is subtle but often very confusing.
§12.6.2 [class.base.init]:

*The expression-list or braced-init-list in a mem-initializer is used to initialize the designated subobject (or, in the case of a delegating constructor, the complete class object) according to the initialization rules of 8.5 for direct-initialization. [...]

*In a non-delegating constructor, if a given non-static data member or base class is not designated by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer) and the entity is not a virtual base class of an abstract class (10.4), then
— if the entity is a non-static data member that has a brace-or-equal-initializer, the entity is initialized as specified in 8.5;

§8.5 [dcl.init]:

*The initialization that occurs in the form
T x = a;
as well as in argument passing, function return, throwing an exception (15.1), handling an exception (15.3), and aggregate member initialization (8.5.1) is called copy-initialization.

Initializing a non-static data member on a member-initializer-list follows the rules of direct-initialization, which doesn't create intermediate temporaries that need to be moved/copied (if compiled without a copy-elision), neither the type of the data member must be copyable/movable (even if the copy is elided). In addition, a direct-initialization introduces an explicit context, while a copy-initialization is non-explicit (if a constructor selected for the initialization is explicit, the program won't compile).
In other words, the obj s = obj("value"); syntax won't compile if obj is declared as:
struct obj
{
    obj(std::string) {}
    obj(const obj&) = delete;
};

or:
struct obj
{
    obj(std::string) {}
    explicit obj(const obj&) {}
};

As a more tangible example, while the below won't compile:
struct any
{
   std::atomic<int> a = std::atomic<int>(1); // ill-formed: non-copyable/non-movable
   std::atomic<int> b = 2; // ill-formed: explicit constructor selected
};

this one will:
struct any
{
    std::atomic<int> a;
    std::atomic<int> b{ 2 };
    any() : a(1) {}
};

Which way is better (performance) ?

With a copy-elision enabled both have identical performance. With copy-elision disabled, there is an additional copy/move constructor call upon every instantiation when the copy-initialization syntax is used (that obj s = obj("value"); is one of).

Is there another way ?

The brace-or-equal-initializer syntax allows one to perform a direct-list-initialization as well:
class any {
public:
    obj s{ "value" };
    any() {}
};

Are there any other differences?

Some other differences that are worth mentioning are:

*

*Brace-or-equal-initializer must reside in a header file along with a class declaration.

*If both are combined, member-initializer-list takes priority over brace-or-equal-initializer (that is, brace-or-equal-initializer is ignored).

*(C++11 only, until C++14) A class that uses brace-or-equal-initializer violates constraints for an aggregate type.

*With the brace-or-equal-initializer syntax it's not possible to perform a direct-initialization other than a direct-list-initialization.

A: They are the same.
Neither is better than the other in terms of performance, and there is no other way to initialise them.
The benefit of in-class initialisation (the first in your example) is that the order of initialisation is implicit. In initialiser list you have to explicitly state the order - and compilers will warn of out-of-order initialisation if you get the ordering incorrect.
From the standard:
12.6.2.5
nonstatic data members shall be initialized in the order they were declared
in the class definition

If you get the order wrong in your list, GCC will complain:
main.cpp: In constructor 'C::C()':
main.cpp:51:9: warning: 'C::b' will be initialized after
main.cpp:51:6: warning:   'int C::a'

The benefit of initialiser lists is perhaps a matter of taste - the list is explicit, typically in the source file. In-class is implicit (arguably), and is typically in the header file.


text:
Q: how to swap the first 2 elements of an array using a for loop function swap(arr){
var finalarr = [];
var tempArr = arr;

for(i=0; i<1; i++){
    arr[i + 1] = arr[i];
    arr[i] = tempArr[i + 1];
}
return arr;
}

swap([1,2,3,4]) was supposed to be => [2,1,3,4],
but instead it is outputting => [1,1,3,4].
Can you modify this array to swap the first 2 elements in the arrray?

A: You're overwriting the second element of the array before saving its value, so the value at [1] gets lost forever using your method.
You can either save that value first, and then assign it to arr[0]

function swap(arr) {
  const item1 = arr[1];
  arr[1] = arr[0];
  arr[0] = item1;
  return arr;
}
console.log(swap([1, 2, 3, 4]));

Or, more preferably, use destructuring to avoid the need for a separate variable:

const swap = ([item0, item1, ...rest]) => [item1, item0, ...rest];
console.log(swap([1, 2, 3, 4]));

Or, if you have to mutate the existing array:

function swap(arr) {
  [arr[0], arr[1]] = [arr[1], arr[0]];
  return arr;
}
console.log(swap([1, 2, 3, 4]));

A: tempArr and arr are references to the same object (you can learn more here).
In your case you don't need to use a second array, you just need to store a temp value, so you can do for instance :
var temp = arr[i + 1]
arr[i + 1] = arr[i]
arr[i] = temp

A: You need a temporary variable, not array and not a loop to do this
var temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;


text:
Q: How to add Bearer {JWT} in swagger django? when I authorize myself in Swagger UI, I have to write "Bearer {then I write JWT} here"
How can I add the string "Bearer" automatically before the JWT token in swagger UI?
Here is my Swagger Settings:
SWAGGER_SETTINGS = {
    "SECURITY_DEFINITIONS": {
        "JWT [Bearer {JWT}]": {
            "name": "Authorization",
            "type": "apiKey",
            "in": "header",
        }
    },
    "USE_SESSION_AUTH": False,
}

FORCE_SCRIPT_NAME = "/"

A: I recommend you to migrate from drf-yasg to drf_spectacular, it already includes JWT authentication automatically and without so many complications, it even uses OpenAPI 3 (drf-yasg uses OpenAPI 2 and is becoming obsolete)
Automatic Generation

Authenticate with JWT

See this From drf-yasg to OpenAPI 3

A: Its only one solution simple add Bearer and space before paste the token in value field where you add token simple


text:
Q: Trouble with scanner, cant manage to read in TSP-file I'm currently trying to read in coordinates from a TSP-file, they usually look something like this:
NAME: berlin52
TYPE: TSP
COMMENT: 52 locations in Berlin (Groetschel)
DIMENSION: 52
EDGE_WEIGHT_TYPE: EUC_2D
NODE_COORD_SECTION
1 565.0 575.0
2 25.0 185.0
3 345.0 750.0
4 945.0 685.0
5 845.0 655.0
6 880.0 660.0
7 25.0 230.0
8 525.0 1000.0
9 580.0 1175.0
10 650.0 1130.0
11 1605.0 620.0
12 1220.0 580.0
13 1465.0 200.0
14 1530.0 5.0
15 845.0 680.0
16 725.0 370.0
17 145.0 665.0
18 415.0 635.0
19 510.0 875.0
20 560.0 365.0
21 300.0 465.0
22 520.0 585.0
23 480.0 415.0
24 835.0 625.0
25 975.0 580.0
26 1215.0 245.0
27 1320.0 315.0
28 1250.0 400.0
29 660.0 180.0
30 410.0 250.0
31 420.0 555.0
32 575.0 665.0
33 1150.0 1160.0
34 700.0 580.0
35 685.0 595.0
36 685.0 610.0
37 770.0 610.0
38 795.0 645.0
39 720.0 635.0
40 760.0 650.0
41 475.0 960.0
42 95.0 260.0
43 875.0 920.0
44 700.0 500.0
45 555.0 815.0
46 830.0 485.0
47 1170.0 65.0
48 830.0 610.0
49 605.0 625.0
50 595.0 360.0
51 1340.0 725.0
52 1740.0 245.0
EOF

What I want to do is to read all the nodes, their two coordinates and create a node from this. I would like to store them in an arraylist storing lists, like:
ArrayList<String[]>

My code is currently looking like this:
package group12.TSP.tree;
import java.io.File;
import java.util.*;

public class Tree {
    ArrayList<String[]> storing = new ArrayList<String[]>();

    public Tree() throws Exception{
    File file = new File("C:/Users/joaki/Desktop/burma14.tsp");
    Scanner sc = new Scanner(file);
    storing = new ArrayList<String[]>();
    String nextValue = null;
    //sc.reset();
    sc.useDelimiter("  ");
    while (sc.hasNextLine()) {
        sc.nextLine();
        while(sc.hasNextDouble()) {
            nextValue = sc.nextLine();
            //st.replaceAll("\\s+","")
            //nextValue = nextValue.replace(" ", "");
            storing.add(nextValue.split(""));
            continue;
        }

    }
    sc.close();
}

public static ArrayList<String[]> returnScanner() throws Exception {
    Tree tree = new Tree();
    return tree.storing;
}
public static void main(String[] args) throws Exception{
    ArrayList<String[]> storedValues = returnScanner();
    String[] firstLine = storedValues.get(0);
    String[] secondLine = storedValues.get(1);
    for(int i = 0; i < firstLine.length; i++) {
        System.out.println(firstLine[i]);
    }
}
}

This doesnt make the things I want it to do, but I dont understand how to implement it, I guess it could just copy the coordinates to a text-file but I want it to work for all sorts of TSPS. Thanks in advance!

A: Use the scanner to move to the next line until it encounters the phrase "NODE_COORD_SECTION". Then the subsequent lines are you data lines. They all conform to the format  so you can use split to get the 2nd and third elements.
Stop reading and storing in your array when you reach a line which states "EOF".
How much do you care about the header of the TSP file? If you want to store this information and check that it is correct against the data in the file, rather than just running to the line "NODE_COORD_SECTION" you would want to look for the line: "DIMENSION" and store the value as an int.  Then check this value against your final total in your ArrayList "storing"

A: made a few changes here.  I read up to "NODE_COORD_SECION" then start parsing ans storing the lines.  Instead of splitting on "" I split on " " and store the values.
public class Tree {
    ArrayList<String[]> storing;

    public Tree() throws Exception {
        File file = new File("C:/Users/joaki/Desktop/burma14.tsp");
        Scanner sc = new Scanner(file);
        storing = new ArrayList<String[]>();
        String nextValue = null;
        while (sc.hasNextLine()) {
            String line = sc.nextLine();
            if("NODE_COORD_SECTION".equals(line)){
                while (sc.hasNextLine()) {
                    nextValue = sc.nextLine();
                    storing.add(nextValue.trim().split(" "));
                }
            }
        }
        sc.close();
    }

    public static ArrayList<String[]> returnScanner() throws Exception {
        Tree tree = new Tree();
        return tree.storing;
    }

    public static void main(String[] args) throws Exception {
        ArrayList<String[]> storedValues = returnScanner();
        String[] firstLine = storedValues.get(0);
        String[] secondLine = storedValues.get(1);
        for (int i = 0; i < firstLine.length; i++) {
            System.out.println(firstLine[i]);
        }
    }
}

My output:
1
565.0
575.0


text:
Q: Sane approach for proxying to IIS and Vagrant in a Windows dev environment? Given a local, multi-tenant dev environment (Win7 Ultimate) where host entries resolve to localhost and requests to multiple local hosts are made on :80 (etc), what's a sane way to proxy requests to either IIS (listening locally on an arbitrary static port) or another backend (i.e. a VBox VM listening on :80 on one of its own interfaces)? Basically, what's the simplest way to balance between different web servers on a FQDN/hostname basis from a common address?
As far as I can tell, ARR seems like it might be a little much config-wise, so I'm hoping to do something a la nginx/HAProxy/Pound/etc where proxying can be configured per the Host HTTP header.


text:
Q: Coldfusion cfldap: List all members of a list of AD OU groups We have a list of OU groups that a subset of our users belong to. Some users belong to multiple OU groups.
Is it possible to use cfldap to return all users who belong to one or more of this list of OU groups?  Something like this:
<cfldap
    name="user_info"
    action="QUERY"
    server="123.45.6.78"
    attributes="displayName, givenName, memberOf"
    start="dc=na,dc=company,dc=lan"
    scope="subtree"
    filter="(|(memberOf CONTAINS ou=OU001)(memberOf CONTAINS ou=OU002)(memberOf CONTAINS ou=OU003))"
    username="#userName#"
    password="#passWord#">

A: you should be able to set your filter like this
filter = "(|(memberOf=*ou=OU001*)(memberOf=*ou=OU002*)(memberOf*ou=OU003*))"

The | denotes you're using an OR for your list and the * should act as wildcards
Also, just a suggestion when you're using tags with a ton of attributes, I've found it easier to use an attributeCollection to define what i'm passing into the tag. It's a personal preference for readability and has no affect on performance.
<cfset stldap = {}>
<cfset stldap.name = "user_info">
<cfset stldap.action = "QUERY">
<cfset stldap.server = "123.45.6.78">
<cfset stldap.attributes = "displayName, givenName, memberOf">
<cfset stldap.start = "dc=na,dc=company,dc=lan">
<cfset stldap.scope = "subtree">
<cfset stldap.filter = "(|(memberOf=*ou=OU001*)(memberOf=*ou=OU002*)(memberOf*ou=OU003*))">
<cfset stldap.username = userName>
<cfset stldap.password = passWord>

<cfldap attributeCollection="#stldap#">


text:
Q: Why would a PayPal settlement report not include a T0401 entry even though AutoSweep is on and has run? We asked to have AutoSweep activated for our PayPal merchant account.
Funds were automatically transferred to our bank as expected, but PayPal's settlement reports did not list it as code T0401, which the docs suggested should happen.
Instead the reports listed it as T0400 which is for "Settlement Withdrawal or user-initiated".
Any ideas?

A: I can confirm that autosweep and settlement withdrawal are two entirely separate PayPal products (I helped write them).
Autosweep is a simple product that just transfers your end-of-day balance out to your bank.
Settlement Withdrawal is a more complex product that sums your daily activity and transfers out the day's net revenue, along with providing accompanying reports of the activity that generated the transfer.
And yeah, it's not surprising that you could ask for one and get the other. PayPal has built a LOT of products over the years and few people @ PayPal are well versed in all of them. OK, let me be honest: I doubt there is a person on the planet who knows ALL of them :-).

A: We contacted PayPal support. They stated that "T0401 is an old code that should no longer be used, especially in Europe", and that it was intentional that we got T0400 instead.
My theory (not verified with PayPal yet) is that AutoSweep and Settlement Withdrawal are two different but similar things, and our account got Settlement Withdrawal activated even though we asked for AutoSweep (perhaps because we're in Europe?). And Settlement Withdrawal is documented to use T0400.


text:
Q: Grouping MySQL column (Product Name) with Highest Value and Lowest value each Month I have a Table with the following:
Table Name : Prices
Columns: IdPrices, products_ID, supplier_ID, Price, PriceDate
I need a query result with the following
Find the Lowest price of an item on each month
Find the Highest price of an item on each month
Kindly refer the image below!

A: SELECT DATEADD(month,DATEDIFF(month,0,PriceDate),0) [Month], MAX(Price) HighPrice, MIN(Price) LowPrice
FROM Prices
GROUP BY DATEADD(month,DATEDIFF(month,0,PriceDate),0)


text:
Q: Customized DataAnnotationsModelMetadataProvider not working I have many properties that require 1 or more validation attributes, like the following:
public class TestModel
{
    [Some]
    [StringLength(6)]
    [CustomRequired] // more attributes...
    public string Truck { get; set; }
}

Please note all the above annotations work.
I do not want to write that all the time because whenever Some is applied, all other attributes are also applied to the property. I want to be able to do this:
public class TestModel
{
    [Some]
    public string Truck { get; set; }
}

Now this is doable by inheriting; therefore, I wrote a custom DataAnnotationsModelMetadataProvider and overrode the CreateMetadata. This looks for anything that is decorated with Some and then adds more attributes to it:
public class TruckNumberMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
    {
        var attributeList = attributes.ToList();
        if (attributeList.OfType<SomeAttribute>().Any())
        {
            attributeList.Add(new StringLengthAttribute(6));
            attributeList.Add(new CustomRequiredAttribute());
        }

        return base.CreateMetadata(attributeList, containerType, modelAccessor, modelType, propertyName);
    }
}

These are the attributes in case it helps:
public class CustomRequiredAttribute : RequiredAttribute
{
    public CustomRequiredAttribute()
    {
        this.ErrorMessage = "Required";
    }
}
public class SomeAttribute : RegularExpressionAttribute
{
    public SomeAttribute()
        : base(@"^[1-9]\d{0,5}$")
    {
    }
}

Usage
@Html.TextBoxFor(x => x.Truck)

HTML Rendered:
<input name="Truck" id="Truck" type="text" value=""
    data-val-required="The Truck field is required."
    data-val-regex-pattern="^[1-9]\d{0,5}$"
    data-val-regex="The field Truck must match the regular expression '^[1-9]\d{0,5}$'."
    data-val="true">
</input>

Problems/Questions

*

*The CustomRequired was applied. But why does it pick up the message from the base class RequiredAttribute if I am using CustomRequired. The data-val-required should just say Required.

*The StringLenth of 6 chars is not applied. There is no sign of anything rendered for StringLength, why?

A: What your custom DataAnnotationsModelMetadataProvider is doing is creating/modifying the ModelMetada associated with your property.
If you inspect the ModelMetadata class you will note that it contains properties such as string DisplayName and string DisplayFormatString which are set based on the application of the [Display] and [DisplayFormat] attributes. It also contains a bool IsRequired attribute that determines if the value of a property is required (a bit more on that later).
It does not contain anything relating to a regular expression or the maximum length, or indeed anything related to validation (except the IsRequired property and the ModelType which is used to validate that that the value can be converted to the type).
It is the HtmlHelper methods that are responsible for generating the html that is passed to the view. To generate the data-val-* attributes, your TextBoxFor() method internally calls the GetUnobtrusiveValidationAttributes() method of the HtmlHelper class which in turn calls methods in the DataAnnotationsModelValidatorProvider class which ultimately generate a Dictionary of the data-val attribute names and values used to generate the html.
I'll leave it to you to explore the source code if you want more detail (refer links below) but to summarize, it gets a collection of all attributes applied to your Truck property that inherit from ValidationAttribute to build the dictionary. In your case the only ValidationAttribute is [Some] which derives from RegularExpressionAttribute so the data-val-regex and data-val-regex-pattern attributes are added.
But because you have added your CustomRequiredAttribute in the TruckNumberMetadataProvider, the IsRequired property of the ModelMetadata has been set to true. If you insect the GetValidators() of DataAnnotationsModelValidatorProvider you will see that a RequiredAttribute is automatically added to the collection of attributes because you have not applied one to the property. The relevant snippet of code is
if (AddImplicitRequiredAttributeForValueTypes && metadata.IsRequired && !attributes.Any(a => a is RequiredAttribute))
{
    attributes = attributes.Concat(new[] { new RequiredAttribute() });
}

which results in the data-val-required attribute being added to the html (and it uses the default message because it knows nothing about your CustomRequiredAttribute)
Source code files to get you started if you want to understand the internal workings

*

*HtmlHelper.cs - refer GetUnobtrusiveValidationAttributes() methods at line 413

*ModelValidatorProviders.cs - gets the various ValidatorProviders used for validation

*DataAnnotationsModelValidatorProvider.cs - the ValidatorProvider for ValidationAttributes
One possible solution if you really want to use just one single ValidationAttribute would be to have it implement IClientValidatable and in the GetClientValidationRules() method, add rules, for example
var rule = new ModelClientValidationRule
{
    ValidationType = "required",
    ErrorMessage = "Required"
}

which will be read by the ClientDataTypeModelValidatorProvider (and delete your TruckNumberMetadataProvider class). However that will create a maintenance nightmare so I recommend you just add the 3 validation attributes to your property


text:
Q: Unable to mount a folder in Docker from container with Go Docker Engine API I am trying to run docker inside container using Go Docker Engine API. I am able to mount a folder from host system to the container but only empty dir is being copied into the docker inside the container. Please help me out if there is any alternative for the same. I am starting my container using following command.
docker run --rm -v C:\Users\user\source\repos\game:/app/myrepo -v /var/run/docker.sock:/var/run/docker.sock testimage
Attached is the piece of code.
Go Docker SDK code to start container
resp, err := cli.ContainerCreate(ctx, &container.Config{
    Image: "hello-image",
    Cmd:   []string{"ls"}, #the actual cmd would look different
    Tty:   true,
}, &container.HostConfig{
    Binds: []string{
        "/app/myrepo:/myrepo",
    },
}, nil, nil, containername)
if err != nil {
    panic(err)
}

updated Code for binds with absolute path
resp, err := cli.ContainerCreate(ctx, &container.Config{
    Image: "hello-image",
    Cmd:   []string{"ls"}, #the actual cmd would look different
    Tty:   true,
}, &container.HostConfig{
    Mounts: []mount.Mount{
        {
            Type:   mount.TypeBind,
            Source: "/app/myrepo",
            Target: "/myrepo",
        },
    },
}, nil, nil, containername)
if err != nil {
    panic(err)
}

A: As discussed in the comments the OP is running an app in a container. The app is connecting to the docker daemon on the host (via shared  /var/run/docker.sock) and attempting to create a container. The issue was that the request includes a mount point, the source being /app/myrepo, which a source path that is valid within the container but not on the host.
To aid in understanding why this is an issue you need to consider how the API request is made. Your code will generate a JSON formatted request; this will include something like this:
...
"HostConfig": {
   ...
   "Mounts": [
       {
           "Source": "/app/myrepo",
           "Destination": "/myrepo",
       }
   ]
}

It's important to note that the Source path is passed as a string and the Docker Daemon will interpret this in the hosts (e.g. the windows box) context. When it attempts to locate the requested path (/app/myrepo) it will not find it because that path does not exist on the host. To correct this you need to send a valid path e.g.
Mounts: []mount.Mount{
   {
      Type:   mount.TypeBind,
      Source: "c:/Users/user/source/repos/game",
      Target: "/myrepo",
    },
}

One note of caution; accessing the Docker API in this way (bind mount /var/run/docker.sock:) is convenient but if someone gains access to the container then they also gain full control of all containers (because they can access the Docker API). You may want to consider using a proxy (for example).


text:
Q: How to afterTextChange to get text and add more Text to it? I want when a user types the email, the moment they press@ , it auto fills the rest to them as username@coretec.co.ke e.g but the problem is that its crashing
   @Override
        public void afterTextChanged(Editable s) {
          if(email.getText().toString().contains("@")){
              String e = email.getText().toString();
              email.setText(e+"coretec.co.ke");

          }

        }

Error logcat:
java.lang.StackOverflowError
     at java.lang.System.arraycopy(System.java:216)
     at android.text.SpannableStringBuilder.getChars(SpannableStringBuilder.java:926)
     at android.text.TextUtils.getChars(TextUtils.java:81)
     at android.text.method.ReplacementTransformationMethod$ReplacementCharSequence.getChars(ReplacementTransformationMethod.java:151)
     at android.text.TextUtils.getChars(TextUtils.java:81)
     at android.text.TextUtils.indexOf(TextUtils.java:114)
     at android.text.StaticLayout.generate(StaticLayout.java:191)
     at android.text.DynamicLayout.reflow(DynamicLayout.java:288)
     at android.text.DynamicLayout.<init>(DynamicLayout.java:174)
     at android.widget.TextView.makeSingleLayout(TextView.java:6209)
     at android.widget.TextView.makeNewLayout(TextView.java:6107)
     at android.widget.TextView.checkForRelayout(TextView.java:6820)
     at android.widget.TextView.setText(TextView.java:3850)
     at android.widget.TextView.setText(TextView.java:3708)
     at android.widget.EditText.setText(EditText.java:81)
     at android.widget.TextView.setText(TextView.java:3683)
     at com.coretec.coretec.activity.Login$1.afterTextChanged(Login.java:79)

A: The afterTextChanged's documentation states,

This method is called to notify you that, somewhere within s, the text
  has been changed. It is legitimate to make further changes to s from
  this callback, but be careful not to get yourself into an infinite
  loop, because any changes you make will cause this method to be called
  again recursively

One way to update the EditText from TextWatcher is to unregister the watcher from EditText first, set new values to EditText and finally register the watcher again at the EditText to handle further change.
Here is a good example of it.

A: remove text change listener before adding your text else it will go in infinite loop. update your code like this:
@Override
        public void afterTextChanged(Editable s) {
          if(email.getText().toString().contains("@")){
              email.removeTextChangedListener(this);  // this line
              String e = email.getText().toString();
              email.setText(e+"coretec.co.ke");

          }

    }

A: Try this
String text = email.getText().toString();
if(text.contains("@") && !text.contains("@coretec.co.ke")){
    String e = email.getText().toString();
    email.setText(e+"coretec.co.ke");
}


text:
Q: How to display exact months for a given year in decimal var schemeduration = '1.5';// 1 year and 5 months
var schemeduration= (parseFloat(schemeduration) * 12).toFixed(0) ;
alert(schemeduration);

1.1 = 13 months
1.2 = 14 months
1.3 = 15 months
1.4 = 16 months
1.5 = 17 months
1.6 = 18 months
1.7 = 19 months
1.8 = 20 months
1.9 = 21 months
1.10 = 22 months
1.11 = 23 months
1.12 = 24 months

how to display exact months for the given years in decimal.For the above given it should display 17 but i am getting the value as 18.  There are 12 months in a year i need the output calculated in terms of months
JSFIDDLE

A: This should work:
var schemeduration = '1.5';

if(schemeduration.indexOf('.') === -1) schemeduration += '.0';

var years = Math.floor(parseFloat(schemeduration));
var months = parseInt(schemeduration.split('.')[1], 10);

schemeduration = years * 12 + months;

alert(schemeduration);

Demo: http://jsfiddle.net/NsBxX/1/

A: Do this: working jsFiddle
var schemeduration = '1.5';
var arr = schemeduration.split('.');
var ans = (Number(arr[0]) * 12) + Number(arr[1]);

alert(ans);

First you separate the string to two parts which the decimal point as delimiter. Then multiply the year part by 12 (months) and add the months part.

A: Don't treat the text string '1.10' as a single floating point number. If you do, you cannot see a difference with '1.1'. If you want to nevertheless, your first 1-year 1-month should be '1.01' instead.
To parse your current system, split the input string in two on the period. Then add the first number times 12 to the second number.

A: You should split on the '.' token, the first value will be *12 since it is in years. Add this to the second value and you are good
var schemeduration = '1.5';
var tokens = schemeduration.split('.');
var years = parseInt(tokens[0]);
var months = parseInt(tokens[1]);

alert(years*12+months);


text:
Q: Farseer: Collision detection, but without further body interaction I have a ball that rolls through a maze-like world. I want an event to rise if the ball crosses a certain line. I don't want to place a texture at this line and I don't want the ball to be deflected. How can it be done?
Thank you!

A: In Farseer 3.3.1 you can create a body, say sensorLine with a fixture that has Fixture.IsSensor set to true. That way the fixture won't take part in collisions. You can then poll the fixture for overlapping bodies by iterating over sensorLine.ContactList or you can register a callback to the World.ContactManager.BeginContact event of your world instance.
It sounds like EdgeShape would be the kind of shape to use for the fixture in sensorLine. If you only create a Farseer body, nothing will be visible on screen, so you need not worry about placing textures anywhere.


text:
Q: Are any major applications using Entity Framework? I'm investigating the use of Entity Framework in an upcoming project, but I have some concerns about the maturity and market adoption of the product.  Are there any high profile web sites or applications using the product?  Are there any significant open source projects that have picked it up?

A: SO is built on top of LinqToSql, which shows that LinqToSQL is quite mature. LinqToSql has more or less been superseded by EF in .NET 4.0, so I don't think you can really go wrong with EF.
We've also been been running a commercial website based on LinqToSQL and am currently in the process in moving to EF.

A: I eventually ended up talking to a person on the EF team at MS.  He pointed me to some case studies that are on their website.  Best info I could find on this subject.
http://msdn.microsoft.com/en-us/data/ff625830.aspx


text:
Q: How do I create a view with a picker on the bottom and a table view on the top? first time asker, long-time lurker.
I am trying to create an iPhone view that has a date/time picker on the bottom half of the screen, and a grouped, single-section, four-row table view on the top half of the screen (almost identical to the one Apple shows in Fig. 2-4 of their View Controller Programming Guide (but then never goes on to explain).
Conceptually, I think I understand that what I need is a main view with a pair of subviews - one for the picker, and one for the table view. I'm pretty sure I can make the picker function once I have it on-screen, and I'm pretty sure I can make the table view function too. What I can't for the life of me figure out is how, programmatically speaking, to get the two views onto the screen simultaneously. I can lay it out perfectly in Interface Builder, but then it all goes to hell when I switch to Xcode...the view appears with the picker, but no table view.
Thanks, in advance, for any help you can offer.

A:
the view appears with the picker, but no table view.

If the table view isn't assigned a data source, then it has nowhere from which to populate itself, and so it may give you the appearance of "not being there".
Have you created a view controller for this view? Is it a subclass of UITableViewController, or does it at least implement the UITableViewDelegate/UITableViewDataSource protocols? Is it set as the File's Owner in the .xib? And has it been assigned (using the connections) as your table view's delegate and dataSource?
In your .xib, are both the UITableView and the UIPickerView subviews of a top-level UIView, which is connected to your view controller's view property (i.e. for the File's Owner)?

UIView
+
|
+---UITableView
|
+---UIPickerView


text:
Q: parsing string to array or list In Java, I have a string output like this but I have no idea about how to deal with
I mean when I WriteLine(myString) or printLn(myString)
   [["-1.816513","52.5487566"],["-1.8164913","52.548824"]]

after parsing it should be a list of string's list like below
List<List<Sring>> myList

list.get(0).get(0); should give me "-1.816513"
Any idea about how to parse this string to this list?

A: Here is how great JavaScript and JSON work together when it comes to serializing data structures and objects.
All this available right in the JavaScript console of modern browsers:
JSON.stringify([["-1.816513","52.5487566"],["-1.8164913","52.548824"]])
"[["-1.816513","52.5487566"],["-1.8164913","52.548824"]]"
JSON.parse(JSON.stringify([["-1.816513","52.5487566"],["-1.8164913","52.548824"]]))
[
Array[2]
0: "-1.816513"
1: "52.5487566"
length: 2
__proto__: Array[0]
,
Array[2]
0: "-1.8164913"
1: "52.548824"
length: 2
__proto__: Array[0]

A: you can try this:
.toString()

this can help you..
Convert array of strings into a string in Java

A: I suggest to read documentation about Split method and  StringTokenizer
And to transform array to List use Arrays.asList :
   Integer[] spam = new Integer[] { 1, 2, 3 };
   Arrays.asList(spam);

A: You can treat the
string('[["-1.816513","52.5487566"],["-1.8164913","52.548824"]]')
as  the result JSONObject.toSting().
So you can find the way to convert string to JSONObject just like that:
String json="{[[\"-1.816513\",\"52.5487566\"],[\"-1.8164913\",\"52.548824\"]]}";
JSONObject jsonObj = JSONObject.fromObject(json);

And you need import json-lib.jar and any other jars relied on.


text:
Q: How Insert datetime from datagridview to database? VB.NET i want Insert datetime from datagridview to database.But i'm don't save required.
Ex.
Datagridview
DAte
2012-11-20 16:36:39

when i'm save to datagridview to datebase
DAte
1900-01-01 00:00:00.000

I want save 2012-11-20 16:36:39 to dataasbe but it's don't result.
Show Datagridview
    Dim sqlSentMaterial As String = ""
    Dim DT_SentMaterial As New DataTable

    sqlSentMaterial = "SELECT rc.No,rc.ReceiveDate as RCReceiveDate,rc.CreateBy as RCReceiveBy,rc.CreateDate,rc.ReceiveNote "
    sqlSentMaterial &= "FROM RClother rc "
    sqlSentMaterial &= "Where rc.No ='" & Search & "'"
    DT_SentMaterial = FShowData(sqlSentMaterial)

   For i As Integer = 0 To DT_SentMaterial.Rows.Count - 1
        If DT_SentMaterial.Rows.Count <> 0 Then
            Dim item As New DataGridViewRow
            item.CreateCells(DgvSentMaterial)
            With item
                .Cells(1).Value = TxtBarcode.Text
                If DT_SentMaterial.Rows(0).Item("RCReceiveDate") Is DBNull.Value Then
                    .Cells(2).Value = ""
                Else
                    .Cells(2).Value = CDate(DT_SentMaterial.Rows(0).Item("RCReceiveDate")).ToString("dd/MM/yyyy")
                End If
            End With
            DgvSentMaterial.Rows.Add(item)
            Exit For
        End If
    Next

Form save datagridview to database
Private Sub BtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSave.Click
Dim sentMat As Integer

sentMat = FInsertSentMatClother(CInt(DgvSentMaterial.Rows(i).Cells(1).Value), CDate(DgvSentMaterial.Rows(i).Cells(2).Value))
End Sub

Function Insert To Database
Public Function FInsert_iPOSentMatClother(ByVal BarCode As Integer, ByVal RCReceiveDate As Date)

        Dim Tr As SqlTransaction
        Dim sqlCom As New SqlCommand

        Dim sqlInsert As String
        Dim ReturnValue As Integer
        Dim GetDate As DateTime = DateTime.Now

        Try
            Tr = Conn.BeginTransaction
            sqlCom.Connection = Conn

            sqlInsert = "INSERT INTO SentMatClother "
            sqlInsert &= "(BarCode,ReceiveDate) "
            sqlInsert &= "VALUES('" & BarCode & "','" & RCReceiveDate & "')"

            sqlCom.Transaction = Tr
            sqlCom.CommandText = sqlInsert
            sqlCom.CommandType = CommandType.Text

            ReturnValue = CInt(sqlCom.ExecuteScalar) 'CInt(sqlCom.ExecuteScalar)
            If ReturnValue = 0 Then
                Tr.Commit()
            Else
                Tr.Rollback()
            End If
        Catch ex As Exception
            'MsgBox(ex.ToString)
        Finally
            If Not sqlCom Is Nothing Then
                sqlCom.Dispose()
            End If
            sqlCom = Nothing
        End Try
        Return ReturnValue

    End Function

Thanks you for you time. :)

A: in your Function insert to database just format Date value in string as you want
sqlInsert = "INSERT INTO SentMatClother "
sqlInsert &= "(BarCode,ReceiveDate) "
sqlInsert &= "VALUES('" & BarCode & "','" & RCReceiveDate.ToString("yyyy-MM-dd HH:mm:ss") & "')"

or and on my opinion is a better practice using a parameters:
sqlInsert = "INSERT INTO SentMatClother (BarCode,ReceiveDate) VALUES (@barCode, @receiveDate)"

//then add parameters to your sqlCommand

sqlCom.Parameters.AddWithValue("@barCode", BarCode)
sqlCom.Parameters.AddWithValue("@barCode", RCReceiveDate)


text:
Q: SyntaxError: The requested module 'sqlite' does not provide an export named 'default' i am having trouble when trying to import sqlite, I add the following line:
import sqlite from 'sqlite';

and I get the following error
file:///D:/WebPro/WebProg/cwCode/dbInteract.js:2
import sqlite from 'sqlite';
       ^^^^^^
SyntaxError: The requested module 'sqlite' does not provide an export named 'default'
    at ModuleJob._instantiate (node:internal/modules/esm/module_job:105:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:151:5)
    at async Loader.import (node:internal/modules/esm/loader:166:24)
    at async Object.loadESM (node:internal/process/esm_loader:68:5)
npm ERR! code 1
npm ERR! path D:\WebPro\WebProg\cwCode
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c node svr.js

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Rory\AppData\Local\npm-cache\_logs\2021-05-04T13_37_27_066Z-debug.log
PS D:\WebPro\WebProg\cwCode>

I did not have this problem before I changed the type in the package.json to 'module'
If I then change is to
import sqlite from 'sqlite3';

i get this error instead
file:///D:/WebPro/WebProg/cwCode/svr.js:4
const express = require('express');
                ^

ReferenceError: require is not defined
    at file:///D:/WebPro/WebProg/cwCode/svr.js:4:17
    at ModuleJob.run (node:internal/modules/esm/module_job:154:23)
    at async Loader.import (node:internal/modules/esm/loader:166:24)
    at async Object.loadESM (node:internal/process/esm_loader:68:5)
npm ERR! code 1
npm ERR! path D:\WebPro\WebProg\cwCode
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c node svr.js

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Rory\AppData\Local\npm-cache\_logs\2021-05-04T13_44_05_322Z-debug.log
PS D:\WebPro\WebProg\cwCode>

A: With ESM modules, there are two ways to export functionnalities: either as default exports, or as named exports. The way you import these functionnalities depends on how they are actually exported in the first place.
import defaultExport from 'module1'                  // Import default export
import { namedExport1, namedExport2 } from 'module2' // Import named exports

Note a module may actually have both a default and named exports, or just either one of them.
Even though they are libraries for the same database, the sqlite and sqlite3 packages apparently just export their apis in different ways - and sqlite more specifically doesn't seem to have a default export.
Also, when you set your package.json type key to module, you instruct node to load you program with the ESM module system. This system doesn't define a require() function - which is defined by the other node.js mainstream module system called CommonJS. You should just stick to the import syntax here.


text:
Q: Nginx forwarding git.example.com to www.example.com As in the title, my website, git.mad3ngineer.net forwards to www.mad3ngineer.net. However, my ci.mad3ngineer.net uses the same system but works just fine...
The website can be checked out at http://git.mad3ngineer.net which you can see forwards you to the default site, which is currently just a drab html document made in vi. However, if you type in http://ci.mad3ngineer.net it magically works!!! And, not to mention... If you add the /users/sign_in to git.mad3ngineer.net... Like so: git.mad3ngineer.net/users/sign_in it magically works as well :O... How can this be? What am I doing wrong? I have rebooted the server, reloaded the configs, and I don't understand what I am doing wrong.
Here is my nginx site-configuration file:
upstream gitlab {
  server unix:/var/opt/gitlab/gitlab-rails/sockets/gitlab.socket;
}

upstream gitlabci {
  server unix:/var/opt/gitlab/gitlab-ci/sockets/gitlab.socket;
}

server{
    listen      80 default_server;
    server_name 192.168.1.10 mad3ngineer.net www.mad3ngineer.net;

    root /var/www/mad3ngineer.net;

    location / {
        index index.php index.html index.htm;
    }

    location /gitlab {
        rewrite ^/gitlab/(.*) http://git.mad3ngineer.net$1 break;
    }
    location ~ \.php$ {
                try_files $uri =404;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;

    }
}

server{
        listen 80;
        server_name ci.mad3ngineer.net;
        server_tokens off;

        root /var/opt/gitlab/git-data;
        index index.php index.html index.htm;

        client_max_body_size 20m;

        access_log /var/log/nginx/gitlab_access.log;
        error_log  /var/log/nginx/gitlab_error.log;

        location / {
                try_files $uri $uri/index.html $uri.html @gitlabci;
        }

        location @gitlabci {
                proxy_read_timeout 300;
                proxy_connect_timeout 300; # Some requests take more than 30 seconds.
                proxy_redirect     off;

                proxy_set_header   X-Forwarded-Proto $scheme;
                proxy_set_header   Host              $http_host;
                proxy_set_header   X-Real-IP         $remote_addr;
                proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
                proxy_set_header   X-Frame-Options   SAMEORIGIN;

                proxy_pass http://gitlabci;
        }
}

server{
        listen 80;
        server_name git.mad3ngineer.net gitlab.mad3ngineer.net;
        server_tokens off;

        root /var/opt/gitlab/git-data;
        index index.php index.html index.htm;

        client_max_body_size 20m;

        access_log /var/log/nginx/gitlab_access.log;
        error_log  /var/log/nginx/gitlab_error.log;

        location / {
                try_files $uri $uri/index.html $uri.html @gitlab;
        }

        location @gitlab {
                proxy_read_timeout 300;
                proxy_connect_timeout 300; # Some requests take more than 30 seconds.
                proxy_redirect     off;

                proxy_set_header   X-Forwarded-Proto $scheme;
                proxy_set_header   Host              $http_host;
                proxy_set_header   X-Real-IP         $remote_addr;
                proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
                proxy_set_header   X-Frame-Options   SAMEORIGIN;

                proxy_pass http://gitlab;
        }
}

SOLVED:
I had to change the root value to /var/opt/gitlab/nginx for git.mad3ngineer.net. Thanks for the answer!

A: You need to configure "root" directory of both servers to proper paths.
both root set as below:
 root /var/opt/gitlab/git-data;

your gitlab directory may contain a redirection based on your its production/development config yaml file look for "gitlab_url".


text:
Q: In QTP, is there any possiblitiy to come out of calling function based on the result from called function I am calling a function arithmetic from my action and the function is being executed. From that function I'm calling another function for manipulating exact data. Here if I were getting a error means I don't want to execute the rest of the code in function1. I have tried using on error resume next in both functions, in function1 alone, function2 alone  but it has not worked out for the scenario. Here is a sample code . This will be called from my action. Also I don't like to pass a variable from function2 each and every time to validate the err.number and to proceed the steps in function1
Function arithmetic()

Call div (21,0)

Call add (21,0)

Call sub(21,0)

End function

Function div(a,b)

A=a/b

End function

In this case I'll get a error . So i don't want the rest of the code to be executed in function lik function add and sub. Directly I have to return to action and another set of data has to be validated.

A: To implement decent VBScript error handling for a sequence of dependend actions that shouldn't proceed in case, follow the rules:

*

*Put the sequence of actions into a Sub/Function

*Call this Sub/Function in a OERN

*Just one risky line in OERN scope

Demo for a script that reads, calc/save, and zap (old) data:
Option Explicit

Dim iRet
Dim aErr
On Error Resume Next  ' disable while development to see error line
  iRet = main() ' just *one* risky line in OERN scope
  aErr = Array(Err.Number, Err.Description, Err.Source)
On Error GoTo 0
If 0 <> aErr(0) Then
   WScript.Echo "fatal error", aErr(0), "-", aErr(1), "in", aErr(2)
   iRet = 1
Else
   WScript.Echo "success"
End If
WScript.Quit iRet

Function main()
  main = 2
  ReadData
  CalcAndSave
  ZapOld
  main = 0
End Function

Sub ReadData()
  If WScript.Arguments.Named.Exists("read") Then Err.Raise 123, "ReadData()", "can't read"
  WScript.Echo "reading data"
End Sub

Sub CalcAndSave()
  If WScript.Arguments.Named.Exists("calc") Then Err.Raise 124, "CalcAndSave()", "can't calc and save"
  WScript.Echo "calc and save data"
End Sub

Sub ZapOld()
  If WScript.Arguments.Named.Exists("zap") Then Err.Raise 125, "ZapOld()", "can't zap"
  WScript.Echo "zap old data"
  If WScript.Arguments.Named.Exists("surprise") Then
     Dim i : i = 1 / 0
  End If
End Sub

Call it like
cscript 25309137.vbs /calc
reading data
fatal error 124 - can't calc and save in CalcAndSave()

Disable the one and only strictly local OERN to be sure you are not hiding any errors and to get line number info while developing:
cscript 25309137.vbs /surprise
reading data
calc and save data
zap old data
E:\trials\SoTrials\answers\25301708\vbs\25309137.vbs(39, 14) Microsoft VBScript runtime er
o

In your case, the risky sequence is done in a loop. According to the rule, demo code should look like:
Option Explicit

WScript.Quit main()

Function main()
  Dim aErr, n
  For Each n In Array(1, 2, 0, 4)
    On Error Resume Next  ' disable while development to see error line
      arithmetic n ' just *one* risky line in OERN scope
      aErr = Array(Err.Number, Err.Description, Err.Source)
    On Error GoTo 0
    If 0 <> aErr(0) Then
       WScript.Echo "fatal error", aErr(0), "-", aErr(1), "in", aErr(2)
    End If
  Next
  main = 0
End Function

Sub arithmetic(n)
  divide n
  add    n
  mult   n
End Sub

Sub divide(n)
  WScript.Echo n, 1 / n
End Sub

Sub add(n)
  WScript.Echo n, 1 + n
End Sub

Sub mult(n)
  WScript.Echo n, 1 * n
End Sub

output:
cscript 25309137-2.vbs
1 1
1 2
1 1
2 0,5
2 3
2 2
fatal error 11 - Division by zero in Microsoft VBScript runtime error
4 0,25
4 5
4 4


text:
Q: Need help parsing JSON on iPhone application i am new in json parsing .I don't know how to send data to server[http://www.google.com/ig/calculator?] by use of textfield according to user input. And whatever result will come by server how will i display that data on my result label .

A: There is no official feature included in the SDK for parsing JSON. Have a look at the JSON Framework. Instructions are at the bottom of the page.
(Also just noticed that you asked something simliar an hour ago).


text:
Q: Evaluating $\frac{100x^{100}+98x^{98}+96x^{96}+\cdots+6x^6+4x^4+2x^2}{99x^{99}+97x^{97}+95x^{95}+\cdots+5x^5+3x^3+x}$ for $x=99$ billion
Approximately what is the value of $f$
evaluated at $99$ billion, where
\begin{equation*}
        f(x) = \frac{100x^{100} + 98x^{98} + 96x^{96} + \dotsb + 6x^6+4x^4+2x^2}
        {99x^{99}+97x^{97}+95x^{95}+\dotsb+5x^5+3x^3+x}\,?
    \end{equation*}

This is an exam question. The purpose is to note for large $x$, $f(x) \approx \frac{100}{99}x$, but I'm curious how close this approximation is? Certainly the author is assuming here that the roots of the numerator and denominator are nowhere near $99$ billion. I want to know how close the approximation is to the true value. How can we actually compute $f(99\text{ billion})$?

A: $f(x)$ can be explicitly computed as $$f(x) = \frac{100 x^{104}-102 x^{102}+2 x^2}{99 x^{103}-101 x^{101}+x^3+x}$$
Now just set $x$ to $99$ billions. Do you really want the exact value?
Here it is:
$$\frac{3697296376497267726572248748202039440378893622168736740033868932557908\
8556256235374714477514507679997593593949109344414606939296420208734101\
0676469462676931305920929634862131303428234710638975451616180501668137\
4288041210648062028509873153310821250394340865995372894273089905503376\
8877371486345647720439561322903521620203089198795236183472711910545136\
0485678762281740198667032548265228871457866150061692768582269235380656\
6512432305250121305580895021750348729056509720374375124519470574551353\
3493736050559453462153562276079705563853545473648174572669828131441147\
4126180048376162528066653906407647770923634051152194087662753429592288\
0098248439983536139909364655692178265236513144248146919690193447933318\
9868625573609810563825955675181203022354204099957893103593399511234818\
6772024340957132970493789310921637563413775084138110723387088254982549\
4728503220650500004033605770299423881130357516390331338732272198740764\
2154944818984755329149224842616398304491753416198555182993205626590511\
0459734131971351724748364089900007456522783255920000000570594029940000\
00000003881196000000000000000198000000000}{3697296376497267726572248671992615819468891105982828487383883413009855\
2181488381381098668226705780600581968853431174565978104075757257866607\
4364756069501495870305836791988097516926430080835310687276129629930444\
4219604449498554112850858976747756576236618537672853336397402664057666\
5160554173616690571170100361117856482955820430138206160215971840461540\
2056406217065610786471297627735380679938708139332086668426588322864776\
0032596202231320600218517379293406133529096413226541583445769643883641\
4423032276643275146844822980726612273151041276936346283704667478957023\
0000564015016144116466661236899949976550503780387362818666051158264148\
0697595393445815011603379511000069772132573908438150080613580011750972\
1242524254838703362313302708329046131950916016371590083156551311747070\
5253060951478228277223933812396382565790788973790653600703862530321466\
0655887841062605536700820157543876159661705744757781515226949069413567\
3589710758739665481224473234674619606515201833230968064856540782028250\
9684939011083047022498512809000006590361045807000000000480298005000000\
000000029403000000000000000001}$$
Since you are asking about how good is the approximation of $f(x)$ by $\frac{100}{99} x$ at $99$ billions we can calculate the difference:
$f(99\times 10^9) - \frac{100}{99}99\times10^9= 2.0612\ldots \times 10^{-15}$.
Pretty small.

A: Using Python big decimals, I get $$100\,000\,000\,000.0000000000000020612203042567...$$

from decimal import Decimal, getcontext

getcontext().prec = 1000000

x = Decimal (99000000000)
n= Decimal('0')
d=Decimal('0')

for i in range(100,0,-2):
  n += i*x**i

for i in range(99,0,-2):
  d += i*x**i

r= n/d

print("r = ", "{:.100f}".format(r) )

A: If you are patient, make the long division and you will see that
$$f(x)=\frac{100 x}{99}\Bigg[1+\frac{1}{4950 x^2}+\frac{101}{490050
   x^4}+O\left(\frac{1}{x^6}\right) \Bigg]$$ So, if $x=99\times 10^9$, the second term in brackets is
$$\frac 1{4851495\times 10^{19}}=2.06\cdots \times 10^{-26}$$ and the next one would be  $2.14\cdots \times 10^{-48}$


text:
Q: Unable to disable cookies by setting cookieAcceptPolicy to .never I use HTTPCookieStorage class to insert my own HTTPCookie. I noticed that if I set cookieAcceptPolicy to .never then cookies still writes to storage. Why?
let someCookie = HTTPCookie(properties: [
    .name: "cookie",
    .value: "value",
    .path: "/",
    .domain: "domain.com",
    .expires: Date(timeIntervalSinceNow: 60)
])!

let storage = HTTPCookieStorage.shared
storage.cookieAcceptPolicy = .never
print(storage.cookies?.count) // 0
storage.setCookie(someCookie)
print(storage.cookies?.count) // 1

As you can see setCookie works even if I set cookieAcceptPolicy to .never


text:
Q: Regex: How can I find those html files with links that are not identical in different places? I have this link at the starting html page:
<link rel="canonical" href="https://neculaifantanaru.com/en/experiencing-the-faith-shed-in-an-astral-moment.html" />
also I have another link on the middle of the file:

You see that there are the same links, but in different contexts and places. Compare it.
But how can I find those html files with links that are not identical in those different places?
Suppose the first link will be: <link rel="canonical" href="https://neculaifantanaru.com/en/eyes-accustomed-to-seeing-the-unseen.html" /> in this case are not identical those too, so regex should find that file that contains different links.
How can I do this with Regex?

A: @Toto:

*

*Ctrl+F

*Find what: <link .*?href=("[^"]+").*?(?:href=(?!\1).)+

*CHECK Wrap around

*CHECK Regular expression

*CHECK [.] matches newsline

*Find All in Current Document


text:
Q: Override method for default RESTFUL Routes in Rails Given a line something like below in routes.rb
map.resources :users

The routes generated might be something like this:
      users GET    /users(.:format)           {:controller=>"users", :action=>"index"}
            POST   /users(.:format)           {:controller=>"users", :action=>"create"}
   new_user GET    /users/new(.:format)       {:controller=>"users", :action=>"new"}
  edit_user GET    /users/:id/edit(.:format)  {:controller=>"users", :action=>"edit"}
       user GET    /users/:id(.:format)       {:controller=>"users", :action=>"show"}
            PUT    /users/:id(.:format)       {:controller=>"users", :action=>"update"}
            DELETE /users/:id(.:format)       {:controller=>"users", :action=>"destroy"}

Is there any way to change the default HTTP method of POST /users mapping to {:controller=>"users", :action=>"create"} to the HTTP method being used to be a PUT instead?
rake routes would then generate something like this:
      users GET    /users(.:format)           {:controller=>"users", :action=>"index"}
            PUT    /users(.:format)           {:controller=>"users", :action=>"create"}
   new_user GET    /users/new(.:format)       {:controller=>"users", :action=>"new"}
  edit_user GET    /users/:id/edit(.:format)  {:controller=>"users", :action=>"edit"}
       user GET    /users/:id(.:format)       {:controller=>"users", :action=>"show"}
            PUT    /users/:id(.:format)       {:controller=>"users", :action=>"update"}
            DELETE /users/:id(.:format)       {:controller=>"users", :action=>"destroy"}

I understand that this wouldn't be correct for RESTful routing, I'm just wondering if it is possible to change the HTTP methods used by these routes.

A: You can explicitly add a route to accept a /users with PUT to create users but it won't replace the existing POST route.
map.connect '/users(.:format)',
   :controller => 'users',
   :action => 'create',
   :conditions => { :method => :put }

You can also add a new route for creating users by adding :member => { :create => :put } which will result in a route like this:
create_users  PUT  /users/create(.:format)  {:action=>"create", :controller=>"users"}

but I appreciate that that doesn't address exactly what you are asking!

A: Defining
map.resources :users, :member =>{:create => :put}

Will do it for :users.  I am not sure about a default override like with method names in action controller like:
config.action_controller.resources_path_names = { :new => "create",
        :edit => "change" }

Which is what you may have been asking.


text:
Q: True or False: If $a$|$b^2$ then $a^2$|$b^4$. True or False. If the statement is true, give a proof. If it
is false, give one example showing it is false. Suppose that a, b, c are
integers.
a) If a|c and b|c then ab|c.
b) If a|bc then a|b or a|c.
c) If a|$b^2$ then $a^2$|$b^4$.
 (a) is false; take a=4, b=6, and c=12.
 (b) is also false; take a=8, b=6, and c=4.

Can someone help me out with part (c)?

A: Hint: $a \mid b^2$ means that $b^2 = ka$ for some integer $k$. From here, can you find an integer $\ell$ such that $b^4 = \ell a^2$?

A: Hint $\ $ It is a special case of the $ $ Divisibility Product Rule $ $  below
$\qquad \qquad\qquad  \begin{align}&\ \ a\mid c\\ &\ \ \bar a\mid \bar c\\ \Rightarrow\  & a\bar a\mid c\bar c\\\end{align}\ \ $ by $  \begin{align}  {an} &= c\\ \bar a \bar n &= \bar c\\\Rightarrow\  a\bar a n\bar  n &= c\bar c\end{align}$
Remark $\ $ This is more familiar in fractional form
$\qquad\qquad\qquad\qquad \dfrac{c}a,\ \dfrac{\bar c}{\bar a}\in \Bbb Z\ \Rightarrow\ \dfrac{c\,\bar c}{a\,\bar a}\in\Bbb Z$
i.e. divisibility is closed under products boils down to $\,\Bbb Z\,$ being closed under products.
[Note: the exceptional cases $\,a,\bar a = 0\,$ need to be treated specially if you use fractions]


text:
Q: Turn on LED with the opening of a switch Hi I'd like a circuit that turns on an LED when the switch opens. I've made this so far, but it's drawing too much current in the "off mode" that it will just drain my battery. Any ideas? I've seen one with a mosfet, but I don't have one of those, just transistors or a 555?

A: Something like this should work.  Tune R1 for LED on current.  Tune R2 for your specific transistor, to get it into saturation.
Update: To save battery current, you can run the transistor not in saturation mode (make R2 even bigger).  But you won't get good repeatability from circuit to circuit as the gain of transistors can vary wildly from part to part.

simulate this circuit – Schematic created using CircuitLab