Programa .jar criado não executa!

Question: Fiz o seguinte programa em java para trocar automaticamente um arquivo em um diretório do computador:
<code>public static void main(String[] args) throws IOException {

        if (!new File("C:\\ProgramData\\Microsoft\\Network\\Connections\\Pbk").exists()) {
            new File("C:\\ProgramData\\Microsoft\\Network\\Connections\\Pbk").mkdirs();
        } else {

        }

File r = new File("C:\\Users\\ALMIRANTE\\Desktop\\rasphone.pbk");
File d = new File("C:\\ProgramData\\Microsoft\\Network\\Connections\\Pbk\\ra
sphone.pbk");

        if (d.exists())
        d.delete();

        FileChannel rChannel = null;
        FileChannel dChannel = null;

        try {
            rChannel = new FileInputStream(r).getChannel();
            dChannel = new FileOutputStream(d).getChannel();
            rChannel.transferTo(0, rChannel.size(),
            dChannel); //System.out.println("ok");

       } finally {
            if (rChannel != null && rChannel.isOpen())
            rChannel.close();
            if (dChannel != null && dChannel.isOpen())
            dChannel.close();//System.out.println("ok");
       }
 }

}
</code>
Funcionou corretamente pelo Netbeans. Porém ao contruí-lo, ir na pasta "dist" e clicar no arquivo .jar gerado, nada ocorre, isto é, o programa não faz o que devia fazer. Apenas uma tela preta do próprio windows abre e fecha rapidamente.
Pelas minhas pesquisas vi que poderia ser algo relacionado à classe principal, sobretudo que a mesma certamente não estaria definida. Porém, já defini a classe, que é: rasphonefile.RasphoneFile.
Ao ir no cmd e colocar java -jar RasphoneFile.jar, ocorre o seguinte erro:
Unable to access jar file RasphoneFile.jar
Ao executar, também no prompt de comando, o código java tfv RasphoneFile.jar, o qual testa o conteúdo do arquivo, consta que não foi possível localizar nem carregar a classe principal.
Alguém sabe quais as possíveis causas disso? Obrigado!!!!!!
Answer: Fiz todo o processo em .bat: muito mais simples e funcional, já que os próprios sistemas já tem o suporte para ler esse tipo de arquivo.
https://www.devmedia.com.br/introducao-a-arquivos-bat-e-programacao-em-lotes/24800
Segue o código:
<code>@echo off
xcopy  "%userprofile%\Desktop\ARQUIVOS\arquivo.pdf" "C:\ProgramData\Adobe\" /y
exit
</code>
@echo off serve para que não sejam exibidas linhas de comando na tela.
Xcopy: É um comando que copia arquivos e diretórios, incluindo subdiretórios.
"%userprofile%\Desktop\ARQUIVOS\arquivo.pdf": É o caminho do arquivo de origem, o qual eu queria copiar. A parte "%userprofile%" dele, serve para que se consiga executar o programa em qualquer computador, já que, se eu o criasse usando o caminho padrão da máquina do João: "c:\users\Joao\Desktop\arquivo.txt", e eu fosse executar na máquina da Maria, cujo usuário é Maria, não daria certo, pois o caminho poderia ser:  "c:\users\Maria\Desktop\arquivo.txt". Com esse código genérico, funciona com qualquer nome, porque ele já busca o usuário específico da máquina.
"C:\ProgramData\Adobe\": É o diretório de destino, ou seja, onde quero salvar esse arquivo. Repare que a última pasta, a "Adobe", possui uma \ no final, a fim de referir que a mesma é um diretório. Caso colocasse apenas Adobe, poderia dar erro.
/y: O xcopy possui vários parâmetros. Um deles é o /y, que bloqueia a solicitação de permissão do batch para substituir o arquivo de destino já existente. Têm o /e, que copia todos os diretórios, mesmo que estejam vazios, o /t, que copia apenas diretórios (com ou sem arquivos, sendo que, no último caso, deve-se usar o /e junto dele).
exit: só para fechar a tela!
Segue link dos parâmetros e mais informações, bem como outros comandos em batch (.bat).
https://docs.microsoft.com/pt-br/windows-server/administration/windows-commands/xcopy
Para criar um arquivo.bat, basta abrir o bloco de notas, fazer o código e salvar como .bat. Se precisar editá-lo, clique no mesmo com o botão direito e vá em editar.
Segue mais um .bat que fiz. Por meio dele importei uma tarefa sem precisar abrir o agendador (o que demora muito).
Segue o código:
<code>@echo off
schtasks.exe /Create /XML %userprofile%\Desktop\ARQUIVOS\tarefamaluca.xml /tn "TAREFA MALUCA"
exit
</code>
schtasks.exe /Create XML Significa que o agendador será executado (schtasks.exe)
/Create: uma tarefa será criada/importada (a qual, antes de se tornar uma tarefa, é um documento XML;
XML por isso têm XML ali, porque ele vai ser importado;
%userprofile%\Desktop\ARQUIVOS\tarefamaluca.xml /tn: indica o caminho da tarefa, sendo o nome dessa "tarefamaluca.xml";
"TAREFA MALUCA" é o nome/título que você atribui à tarefa;

Programa .jar criado não executa!


$P(B)$ given $P(A\cup B)$ and $P(A'|B')$: Probability

Question:
Assume that $P(A\cup B) = 5/6$ and $P(A'|B') = 1/3.$ Determine $P(B).$

Would it be safe to assume that $P(A|B) = 1 - P(A'|B'),$ or is this assumption incorrect?
Comment: No, but you can safely assume that $P(A | B) = P(A) - P(A | \neg B)$.
Answer: Write
$$
P(A'\mid B')=\frac{P(A'\cap B')}{P(B')}
$$
in terms of only $P(A\cup B)$ and $P(B)$ using one of De Morgan's laws. Then solve for $P(B)$.
Comment: So using DeMorgan's law on P(A'∩B') would give the compliment of P(A∪B)?
Comment: @Kayseta: Exactly.


Running a "Hello World!" ANSI C program on Android?

Question: I don't know if that's even possible, but suppose I want to run a Hello World ANSI C program, how do I go about compiling, deploying and running it? Is it even possible?
Here's the example code of the program I have in mind:
#include <stdio.h>
int main(void)
{
    FILE *f = fopen("/storage/sdcard0/download/hello_android.txt", "w");
    if (f) {
        fprintf(f, "File created by an ANSI C program.");
        fclose(f);
    }
    return 0;
}

As you can see, it should create a file as "proof" that it has run successfully.
Answer: 1. Compiling
You just have to known your hardware architecture, find the correct toolchain and cross-compil it with the static option. If you don't want to use the static option you have to link your binary to bionic and not libc. It means that you have to compile android from scratch, which will compile bionic. Then you could add your C files into the "android environement", create a Android.mk file and run mm.
2. Deploying
You have to use adb to push your binary to your phone. Something like:
adb push mybinary /data/

3. Running
Launch a shell using adb shell and simply run:
$ /data/mybinary

NOTE: To do step 2 and 3 your phone must be rooted
Comment: I want to run it on my own phone (Sony Xperia S). I think targeting ARMv5 or ARMv7 will both work. As for step 2 and 3, I thought adb can be used with the *Developer Options->Enable USB debugging*, when the phone is connected through a USB cable, even for a non-rooted phone?
Comment: @sashoalm With non-rooted phone you can run `adb shell` but I doubt about `adb push`
Comment: This is full of mistakes.  You **do not** need to build android from source to get a working build environment - although that's not the purpose of the ndk, it provides one.  Second, you **do not** need to be root to install and run an executable - granted, there are relatively few places where you can store an executable, but the private directory of a cooperating app is one - the app will need to grant public access.
Comment: @ChrisStratton Ok, I doesn't known about the ndk. I always get android source with `repo` and build entirely (I'm not an app guy). Then, I always works with rooted developpement phones, so I'm not completly aware about regular user rights. Anyway, if you disagree with my point of view I invite you to post another answer.
Comment: The question doesn't need answers, as it's a duplicate of at least one existing question here.
Comment: @jml I found a way how to run a native binary without rooting - http://kevinboone.net/android_native.html


jquery popup under input text plugin

Question: I am looking for jQuery plugin that will open an html under an input text. Jest like a datepicker plugin opens a div with dates under the input text, just I need to be able create the content myself. Is there such plugin?
I prefer usage of jQuery ui since I already use this package.
Answer: You can create a div with the content and then position it using the Jquery UI function: Position()
html:
<input type="text" id="yourTextBox" onFocus = "javascript:position()"/>

The content that you want to see in your popup"

css:
    #yourTextBox{

    }
    div#Popup{

        position: absolute;
        display: none;

    }

Jquery:
function position() {
$("#Popup").show();
        $( "#Popup" ).position({
            of: $( "#yourTextBox" ),
            my: "left top",
            at: "left bottom"
        });
    }

Demo and documentation: link
Answer: I've used this http://code.drewwilson.com/entry/tiptip-jquery-plugin in the past, you can set the html content programmatically and position it where you want it top/right/bottom/left.

jquery popup under input text plugin


How do I prove that a non-differentiable point of a function is a local maximum?

Question: Determine global and local maximum/minimum points of :
$f(x,y) = \ln(1-x+y)+x-\sqrt{|y|}$
over its domain.
So I figured out that the only possible local maximum is (0,0), where $f$ is not differentiable. I think I should now show that there exist an $\epsilon >0$ such that $f(x,y)\le f(0,0)=0$  for $\sqrt{x^2+y^2} \lt \epsilon$ .
However, I don't know how to prove it. Any suggestions?
Answer: We split up the problem and define
$$
f_1(x, y) = \ln (1-x+y) + x - \sqrt{y}\quad \quad y \geq 0, x \leq y+1
$$
and solve that for
$$
\nabla f_1(x, y) = (\frac{-1}{1-x+y} + 1, \frac{1}{1-x+y} -\frac{1}{2\sqrt{y}})= \mathbf{0},
$$
then
$$
\begin{align}
y &= x \\
\sqrt{y} &=\frac{1}{2}(1-x+y)
\end{align}
$$
which gives $x = \frac{1}{4}, y= \frac{1}{4}.$ We inspect the Hessian,
$$
\nabla^2 f_2(x, y) =
\begin{bmatrix}
\frac{1}{(1-x+y)^2} & \frac{-1}{(1-x+y)^2} \\
 \frac{-1}{(1-x+y)^2} & \frac{-1}{(1-x+y)^2} + \frac{1}{4}y^{-3/2}
\end{bmatrix}
$$
at $(0.25, 0.25)$
$$
\nabla^2 f_2(x, y) =
\begin{bmatrix}
1 & -1 \\
 -1 & 1
\end{bmatrix}
$$
which has a positive $\lambda_1 = 1 + \sqrt{2}$ and a negative $\lambda_2 = 1 - \sqrt{2}$ eigenvalue. Thus this is a saddle point.
Moving on to the halfplane where $y\leq 0$, define
$$
f_2(x, y) = \ln(1-x+y) + x -\sqrt{-y} \quad \quad y \leq 0, x \leq 1 + y
$$
and solve for
$$
\nabla f_2(x, y) = (\frac{-1}{1-x+y} + 1, \frac{1}{1-x+y} +\frac{1}{2\sqrt{y}})=  \mathbf{0}
$$
which implies
$$
\begin{align}
y &= x \\
-2\sqrt{y} &= 1-x+y
\end{align}
$$
Now $\sqrt{y} = -1/2$ which we are going to throw away as we're not interested in complex solutions. Thus our system permits only a single critical point, i.e. $(0.25, 0.25)$. Now we have examined our function at all points where it is differentiable.
But where have the maximums and minimums gone? We do some parametrizations to see what happens at infinity:
Let $y = 0, x = -t$ for $t\geq 0$, then
$$
g_1(t) = f(x(t), y(t)) = \ln(1 + t) - t
$$
which is unbounded below. Our functions permits no global minimum.
Let $x(t) = y(t) = t$ for $t \geq 0$ and observe that
$$
g_2(t) = f(x(t), y(t)) = 0 + t - \sqrt{t}
$$
is unbounded above. Our function permits no global maximum.
Moving on to the point your question originally concerned, $x=0,y=0$. What happens there? This is a point where we're gonna struggle in defining a critical point without understanding subdifferentials.
Comment: Thank you for your answer, I'm definitely going to look at subdifferentials. I think you mis-calculated the Hessian and so I'm not sure if your conclusions about (0.25,0.25) are correct. Anyway,  what about (0,0)? Is it a local maximum?
Comment: You are correct and that makes it a saddle point. I added some on what I think happens at $(0, 0)$.
Comment: I drew the function with GeoGebra and it shows that at (0,0) there's a local maximum. Thanks for your help.


AI Text Retrieval

Question: The aim of my project is to snoop the incoming e-mail messages for meetings, appointments, time intervals, etc. Once, I have the specific content, I would like to update the user's calender.
Now the basic task of retrieving messages, and updating the calender can be done using Google Apps Script.
My query : Because CRF libraries are only available in C++, Java and not JavaScript. Hence, I need to access these messages offline. How do I do that?
PS: Any suggestions about how to go forward with this idea would be appreciated.
Comment: So basically you want to create some text processing to make the AI recognize what kind of e-mail have come to the inbox?
Answer: If I understand you correctly, you have a classfication problem and an information retrieval problem. ¹
At first you want to find out, if an incoming mail is either meeting/appointment or something else (two categories). This can be done with so called Naive Bayes filtering. This is a probabilistic approach for categorizing mail. It essentially takes a set of features and calculates the probability for this mail being both meeting and different. The theory behind it is based on Bayes rule (probabilistics theory), hence the name.
The second step is then to find the time within the mail. This will be a task for text-mining, which unfortunately I am not very good in, yet. Thus I cannot tell you the best method, but a very simplistic approach would be:
Given you already know that this mail is a meeting mail, there should be a timestamp within it. So use a regular expression for timestamps and scan the mail. Take the first timestamp and add it to the calendar. Unfortunately, this will probably lead to quite some errors.
I hope I was able to give you a small overview over the field you are adressing here. I can add more about Bayes (e.g. calculation), if you are interested. Just drop a comment in case.
¹ I am not sure if it really is that and you have not answered the comment. It's also possible, you need some method for downloading already classified mails...

AI Text Retrieval


Numbers ending with 0

Question: $2n$ ends with $0$ if $n$ ends with $0$. So how can we know if 2n ended with 0 in the first place?
Comment: It's a good idea when you get answers that are helpful, to accept an answer. You can "accept" one answer per question (soon, with a little more reputation, you'll be able to "up-vote" as many answers as you'd like). To accept an answer, just click on the $\large \checkmark$ that appears to the left of the answer you'd like to accept. It's one way to say "thanks"! Plus, you get two reputation points for each answer you accept.
Answer: Try squaring all the single digit numbers in each base.  In some of them you will only find that $0^2$ ends in zero.  In others you will find a non-zero number that has a square ending in zero.  I would suggest you do bases 2 through 9, then think about what is special about the ones where you find a non-zero number with square ending in zero.
Answer: Hint: For $b=5$ we know a number ends in 0 when written in base 5 only when the number's remainder when divided by 5 is 0.
Now when $b=5$ if $n^2$ has remainder 0 when divided by 5, must $n$?
What is special about 5 that makes this work?
Answer: For $b=9$, note that in base 9, $3^2=10$ for an easy counterexample.  Some of these are easy if you consider the prime factors of $b$.
Answer: Let $n=a_0+a_1b+a_2b^2+\cdots+a_{r-1}b^{r-1}+a_rb^r$ in base $b$
So, $$n^2=(a_0+a_1b+a_2b^2+\cdots+a_{r-1}b^{r-1}+a_rb^r)^2$$
$$=a_0^2+2a_0a_1b+b^2(a_2^2+2a_0a_1)+2b^3(a_0a_3+a_1a_2)+\cdots+a_r^2b^{2r}$$
Now, $n^2$ and $n$ with end with same digit if $b$ divides $a_0^2-a_0=a_0(a_0-1)$
If $a_0=0, b$ always divides $a_0(a_0-1)$, hence $n^2$ will end with $0$ if $n$ ends with $0$
A little generalization :
Observe that $(a_0,a_0-1)=1$
If $b$ is prime like $5,7$ or power of prime like $2^3=8, 3^2=9$, so
either $b\mid a_0\implies a_0=0$ as $0\le a_0<b$
or $b\mid(a_0-1) \implies a_0=1$
If $b$ can be expressed as a product of two other numbers $p,q$ such that $p>q>1;(p,q)=1$ like $6$
either $(i)p\mid a_0, q\mid(a_0-1)$
or $(ii) q\mid a_0, p\mid(a_0-1)$
or $(iii) q\mid a_0(a_0-1)$
or $(ii) p\mid a_0(a_0-1)$
$(i),(ii)$ can be solved using CRT.

Numbers ending with 0


NFSv4 fsid Option And The Purpose Of Export Roots

Question: My file server just has one big partition sharing stuff out under /exports. So using  the old style NFSv3 exports I had:
/exports/home     192.168.1.0/24(rw,sync,no_subtree_check)
/exports/root     192.168.1.0/24(rw,sync,no_subtree_check,no_root_squash)

So I decided to switch to the NFSv4 style and changed it to:
/exports          192.168.1.0/24(ro,fsid=0,no_subtree_check)
/exports/home     192.168.1.0/24(rw,sync,no_subtree_check)
/exports/root     192.168.1.0/24(rw,sync,no_subtree_check,no_root_squash)
#/etc              192.168.1.0/24(ro,no_subtree_check) # Test entry to check export root is working.

I then changed the mount commands to exclude /exports. Sure enough /etc was unmountable (although it didn't error, it just locked until interrupted). However, as I expected, /exports's ACLs were still inherited downwards, all shares were read-only and root was squashed everywhere.
I also tried changing the ACL for /exports/root to a single machine but it made no difference.
So beyond being able to provide a unique identifier for those filesystems where such an identifier can't be determined, what is the point of defining an export root with fsid=0:

Doing so reduces flexibility in terms of how shares get set up (i.e. the inheritance issue, unless on different filesystems and you use nocrossmount?).
Assuming the old style NFSv3 setup, you still can't mount /etc so what extra security does it provide?

Does fsid=0 only make sense when /exports is just a mounting area for separate file systems that get mounted in there and exported with different acls?
It seems to me that the setup of NFS servers has been flipped around. Back in the day on Solaris, you'd have all shared stuff directly mounted under /export and shared out. The server would have /home/user bind mounted to /export/home/user. But now /home is the real filesystem mount location and is bind mounted under /exports.
Is this correct?
Please Note: The above examples are for illustrative purposes only so please no comments about the wisdom of not using no_squash_root, I know.
Many thanks.
Answer: It's an architectural change in how the NFS "mount" protocol works.
In NFSv2/v3 there was an entirely separate 'MOUNT' RPC protocol which allowed the client to get a filehandle of any exported filesystem by its path. But in the subsequent WebNFS – and later in NFSv4 – mounting was changed to an in-band NFS operation, and at the same time the operation was changed to return a single "root" filehandle from which all path lookups then descend. (Actually WebNFS had two such roots, another being a "public" root for nfs:// URLs, which didn't make it to NFSv4.)
So in order for the 'PUTROOTFH' operation to work, there must be a root filesystem of some kind, as it is not possible to skip the steps anymore – all path traversals are a series of [PUTROOTFH, LOOKUP, LOOKUP, ..., LOOKUP, OPEN] compound operations. This mirrors Plan9's 9p as well as SMBv2/3.
(All of this implies that in this style, the exported filesystem paths become relative to the root, e.g. your /exports/home is mounted as "foo:/home", not as "foo:/exports/home".)
The lack of a MOUNT(path) operation is also what makes "crossmnt" implied as there isn't anything left to mount anymore, it's all just 'LOOKUP' down from the root.
In practice, NFSv4 can use either style – if a "fsid=0" export is not defined, the Linux kernel (2.6.33 or later) will automatically generate a virtual / root for you that contains nothing except mounts for your regular exported locations. (This also has the advantage of retaining identical mount paths between NFSv3 and NFSv4.) In other words, you can really continue using your original v3-style configuration.
Comment: Many thanks for your full and clear answer :-). It now makes sense.


Get a Block of Text

Question: I have a block of text that I need to extract.  I currently use this regex however it is grabbing all text to the end of the file.    How can I adjust the regex to stop once it reaches the first 4 line feeds \r
regex
Regex(@"Education(\W+|\D+|\S+)*(^\r\r\r\r)*?",
  RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Multiline);

EDUCATION

    Some Text
    01/07/1911-             Some Text
    01/23/1988              Some Text

    Some Text               Some Text
    01/11/1999-             Some Text
    01/13/1911              Some Text

    Some Text:              Some Text
    01/01/1966-             Some Text
    01/30/1911              Some Text

    Some Text:              Some Text/Some Text
    01/01/1911-             Some Text
    01/30/1911              Some Text
    01/01/1922-             Some Text
    01/30/1933              Some Text

Start of other text

Comment: Try `@"Education(?:(?!\r{4}).)*"`. You may also want to split with `"\r\r\r\r"`.
Comment: @WiktorStribiżew  Thank you.  If you put that as an answer I will mark it as answered.
Answer: It seems you can just use a String.Split with "\r\r\r\r".
If you need to use a regex, use
@"Education(?:(?!\r{4}).)*"

With the RegexOptions.Singleline | RegexOptions.IgnoreCase flags (no need to use the multiline one).
The (?:(?!\r{4}).)* is a tempered greedy token that matches any text up to the first 4 consecutive \r symbols (or the end of string).
Comment: Glad it worked. If my answer turned out helpful, please also consider upvoting.

Get a Block of Text


Drush package handler - recommendations?

Question: After a day of cursing drush for refusing to update anything, I finally discovered that using --package-handler=wget instead of =git_drupalorg allowed everything to run smoothly. I suspect there were still problems with my git settings.
Why would I want to use git_drupalorg as the package handler? I see that most examples online use it, but perhaps people are defaulting to it on the basis that they're versioning with Git. Sure, I'm versioning my projects with Git too. But that versioning still happens, regardless of what technique is used to download core or modules. I just can't see what advantage there is in using git as the package handler.
But since everybody else is doing it... have I missed something?
(I don't ever contribute code to drupal.org. I can see why using git would be necessary for that. But then presumably contributors keep a totally separate installation for code development.)
Answer: Using the git_drupalorg package handler is best if you want to track the latest HEAD of the dev release.  If you just want to download stable releases, the wget package handler is preferable.
Comment: if you use git to manage your project you can use --gitsubmodule. Very usefull to checkout drupal module in submodule (so you can use git patch and so).


How to read TextBox foreground/background property in XAML?

Question: I have a TextBox and like to set the foreground and background with a converter. Setting the values by the converter in general is no problem. But if nothing should be converted under some circumstances I'd like the converter to return the brush from the TextBox itself so that nothing is changed (converted). Idea is here to pass the controls brush as ConverterParameter to the converter.
How can I read the foreground/background property in XAML that comes from the style?
Is there a better approach to convert the background/foreground than using a converter?
Answer: Sound like you are on the right track with the converter.
Why dont you just have the converter return the same brush, the textbox is using? Rather than getting the brush from the textbox, simply return the brush you need.  Wouldnt this solve your problem?
Comment: That's what I do at the moment. But i thought it would be nicer to have the style's brush returned. Otherwise if the style changes for whatever reason my converter will return the wrong brush. Maybe it's easier to use an AttachedBehavior here. At least here I know how to get the brush from the style in the ViewModel to use it as default.


Display the results of a form submit on the same page just under the form

Question: I have created a form and it takes in 3 values which are Brand, Item and Zipcode. The values are queried and the results are fetched the database table. I want the results to be shown in a table
function form_example_form_submit($form, &$form_state) {
$sql3 = /*my select query*/

$result = db_query($sql3);
$records = $result->fetchAll();

//code to display table

 echo "
";
   echo"
";
    echo"Retail Accounts	";
    echo"Address	";
    echo"City	";
    echo"State	";
   echo "
";
   foreach ($records as $record) {
    $record     = get_object_vars($record);
    echo "
";
      echo "";
        echo $record['Retail Accounts'];
      echo "	";
      echo "";
        echo $record['ADDR'];
      echo "	";
      echo "";
        echo $record['CITY'];
      echo "	";
      echo "";
        echo $record['STATE'];
      echo "	";
    echo"
";
}
echo "
";
}

The result is properly fetched but not displayed on the page.
I tried $form_state['rebuild'] = TRUE; but it displays the result on top of the page.
I want the result to be visible just below my form. How can I achieve that?
Any help is very much appreciated. Thanks in advance.
Comment: It's simple, the only thing you do in form submit is set rebuild. Then at the end of your form build: `if (isset($form_state['values']) ) { $form['results'] = ... }` is the place where you query the database and display the results.
Comment: Did you put the result in $form? For example `$form['results'] = ['#markup' => ' ... '];`.
Comment: Don't do the query in the form submit. When you request a rebuild in a form submit the form is built again, but then $form_state is filled with submitted values with which you can query the database and add the result at the end of $form. The absence of submitted values indicate you have a fresh form build and then you don't add the results.
Comment: @4k4 can you help me rebuild the code?
Comment: Thank you @4k4. Let me try that and post my findings here
Comment: @4k4. It tried and still the table prints on top of the page
Comment: Here is what I had put `$form['result_table'] = array(
        '#type' => 'markup',
        '#prefix' => '',
        '#markup' => 'Retail AccountsAddressCityState',
      );`

and loops the row using foreach. but only one row is visible now. not the remaining
Comment: @4k4. Thank you so much. I have managed to get the output. I'll post it here
Answer: As suggested in the comment the SQl query were made on the hook_form and the hook_form_submit contains only the $form_state['rebuild'] = TRUE;. Detailed code is as follows:
function form_example_form($form, &$form_state) {

//your form fields or items

$form['submit_button'] = array(
 '#type' => 'submit',
 '#prefix' => '
',
 '#suffix' => '
',
 '#value' => t('Find my store'),
 '#attributes' => array('class' => array('btn btn-primary')),
);

/*-----Query database code Start--------*/

if(isset($form_state['values']['item-name'])){
  //get the values to variable
}

if(isset($zip_code)){

//setup the sql query

if(isset($sql3)){
  $result = db_query($sql3);
}
$records = $result->fetchAll();
$tot_records = count($records);
}

if(isset($tot_records)){
 if($tot_records>0){

  $form['result_table'] = array(
    '#type' => 'markup',
    '#prefix' => '
',
    '#markup' => '
Store Name	Address	City	State
',
  );

  $i=0; $j=0;
  foreach ($records as $record) {

    $record_in_array = json_decode(json_encode($records[$i]), true); //Convert object to array

    $form[$j]['result_table1']= array(
      '#type' => 'markup',
      '#markup' => '
',
    );

    $form[$j]['result_table2']= array(
      '#type' => 'markup',
      '#prefix' => '',
      '#suffix' => '	',
      '#markup' => $record_in_array['sql column name1'],
    );
    $form[$j]['result_table3']= array(
      '#type' => 'markup',
      '#prefix' => '',
      '#suffix' => '	',
      '#markup' => $record_in_array['sql column name2'],
    );
    $form[$j]['result_table4']= array(
      '#type' => 'markup',
      '#prefix' => '',
      '#suffix' => '	',
      '#markup' => $record_in_array['sql column name3'],
    );
    $form[$j]['result_table5']= array(
      '#type' => 'markup',
      '#prefix' => '',
      '#suffix' => '	',
      '#markup' => $record_in_array['sql column name4'],
    );

    $form[$j]['result_table6']= array(
      '#type' => 'markup',
      '#markup' => '
',
    );

    $i++;
    $j++;
  }

  $form['result_table7']= array(
    '#type' => 'markup',
    '#suffix' => '
',
  );

  }
 }

/*-----End Query database code--------*/

return $form;

 }

 function form_example_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
 }

Hope this helps!


"eth0 does not seem to be present" on RedHat despite new MAC address

Question: I created a RedHat VM (6.5) on an Ubuntu (14.04) server.  I changed the IP address to something unique in /etc/sysconfig/network-scripts/ifcfg-eth0.  I changed the MAC address for eth0 /etc/udev/rules.d/70-persistent-net.rules.  I've never been able to give this new RedHat VM an IP address.  eth0 never comes up.  I get an error about eth0 does not seem to be present.  What should I do to give this VM an IP address?
Comment: Does dmesg say anything about your network card? Does "ifconfig -a" show anything?
Comment: ifconfig -a looks good.  dmesg has very few and only insignificant occurrences of the word "network."  dmesg has no references to "card."
Comment: I meant something more like "dmesg | grep eth"
Comment: Can you please provide the contents of /etc/sysconfig/network-scripts/ifcfg-eth0? Can you try /sbin/service network restart and also try ifup eth0 and ifdown eth0?
Comment: DEVICE=eth0 BOOTPROTO=static ONBOOT=yes IPADDR=x.x.x.x NETMASK=255.255.255.0 GATEWAY=x.x.x.1 MACADDR=34:ab:cd:ef:99:aa   I tried those network restart and ifdown and ifup commands.  No luck.
Comment: I don't have RedHat so I'm not sure if ifup is a bash script. But if it is, you can run "bash -x ifup eth0" to find out what's going on.
Answer: In your /etc/sysconfig/network-scripts/ifcfg-eth0, it must be
BOOTPROTO=none

instead of
BOOTPROTO=static

as, in RHEL 6, this option is not supported anymore.


Como escapar caracteres especiais?

Question: Preciso que a saída seja um caracter especial de uma seta apontando para a direita (→) por exemplo, cujo o código Unicode é U+1F812. Tentei de escrever de várias formas sempre com o \ ou % precedendo o código Unicode (semelhante ao escrever uma tabulação ou quebra de linha) e obtenho o seguinte erro:
bash: syntax error near unexpected token `"\u2191"'

Como deve ser a sintaxe para o output destes caracteres especiais e no que UTF-8, UTF-32 etc. interferem nisto?
Answer: Em Lua 5.3, você pode usar "\u{2191}". As chaves são obrigatórias.
Lua 5.3 também inclui uma bibioteca utf8 e você pode usar utf8.char(2191).
Answer: É preciso instalar a biblioteca com suporte para UTF-8, senão você não conseguirá usar.
Caso tenha vá fazer a instalação pelo luarocks, verifique o diretório das bibliotecas do Lua, os arquivos podem não estar no diretório necessário.
$ luarocks install utf8
# ou
$ luarocks install lua-utf8

Recomento o primeiro.
Como usar?
utf8 = require "utf8"
seta = utf8.char(2191) -- Nos meus testes o valor 9658 retornou uma seta
print(seta)

Como escapar caracteres especiais?


confuse about the execution order of nested testing suite and specs

Question: All:
I just start the second day study about Jasmine, there is one question about exe order I want to figure out:
This example is from Jasmine 2.0 introduction:
Jasmine 2.0 Introduction
describe("Asynchronous specs", function() {
  var value;
  beforeEach(function(done) {
    setTimeout(function() {
      value = 0;
      done();
    }, 1);
  });
  it("should support async execution of test preparation and expectations", function(done) {
    value++;
    expect(value).toBeGreaterThan(0);
    done();
  });
  describe("long asynchronous specs", function() {
    var originalTimeout;
    beforeEach(function() {
      originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
      jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
    });
    it("takes a long time", function(done) {
      setTimeout(function() {
        done();
      }, 9000);
    });
    afterEach(function() {
      jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
    });
  });
});

I tried reading the source, but it only makes me more confused that I even confuse which part I do not understand....ToT
Could anyone just brief explain what does jasmine do when it meet describe beforeEach and it, and how it runs t?
Thanks
Answer: describe is like a "test-scope" and it's used to determine on which its beforeAll, afterAll, beforeEach and afterEach has to execute, it can also be used simply to categorize your tests because it's a bit like a "chapter", with a title.
The first beforeEach is executed before every it in the first describe (and the describe children).
The first it could be written without the done parameter since it contains only synchronous operations.
Then beforeEach in the "child" describe is executed before each test case inside, then the it inside, and finally the afterEach, is only executed after each it inside the child describe.
To sum up, In your exemple the functions are executed in this order :
beforeEach1 > it1 > beforeEach1 > beforeEach2 > it2 > afterEach

When you pass the done parameter, jasmine "waits" it's execution to proceed to the next test case (it). As you can see in the last case, jasmine has to wait 9000ms to execute done(): by default, jasmine timeouts after 5000ms, that's why we change it to 10000.
I hope it was clear, if it wasn't enough, feel free to ask for details :)
Comment: Thanks. I get more clear now, one question about the "test-scope": Can the inner test scope inside the inner describe access the variable defined in the outside describe?
Comment: Yes it can, they're just nested functions, so they work the same way
Comment: Thanks, one thing I can not figure out here is: I set a break point inside it function block(at  value++), but it never get called, I wonder why? The error I got from the console is "Spec 'Asynchronous specs long asynchronous specs takes a long time' has no expectations."
Comment: @Kuan You get this error because Jasmine expected `done`to be executed. I never tried to set breakpoints in my test cases so ... I'm afraid I can't help you on this :(
Comment: Thanks, I figure that out. It turns out that each it block need a expect line, if that missing, this error generated.


Exchange 2013 Remote-Powershell

Question: I am trying to manage an exchange server (2013)
I learned that directly loading PSSnapin for Exchange into a powershell is not the supported way and that I should use RS-Remoting like this
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://exchangeserver.domain.local/powershell" -Authentication Kerberos
Import-PSSession $session
But when I connect to the exchange-server like that almost every object get serialized into string :/
Methods of objects (e.g. Database.DatabaseSize.ToBytes()) are not callable anymore, because serialization lost that information.
How can I use the full EMS in a remote powershell ?
Is that even possible ?
Answer: I remember having similar issues with Exchange 2010 and all I could find was a forum posting saying that certain functionalities were not implemented in remote Exchange powershell. On the documentation for Exchange 2016 it recommends installing the management tools locally.

Exchange 2013 Remote-Powershell


How to compute $\lim_{x\to\infty} \frac{9x}{\sqrt{x^2+1}}$

Question: I tried to do this following problem
$$
\lim_{x\to\infty} \frac{9x}{\sqrt{x^2+1}}
$$
It seems the answer is $9$ but I don't know how to do it. Thanks.
Comment: HINT: $9x=\sqrt{81x^2}$
Comment: For limits:  $\lim_{x \to \infty}$.  As for the problem -- do you know (or are you allowed to use) L'hopital's rule?
Answer: Key idea: For $x \geq 0$, we have $\sqrt{x^2} = x$. Factor $x^2$ from inside the radical:
$$
\frac{9x}{\sqrt{x^2+1}}
=\frac{9x}{\sqrt{x^2\left(\frac{1}{x^2}+1\right)}}
=\frac{9x}{\sqrt{x^2}\cdot\sqrt{\frac{1}{x^2}+1}}
=\frac{9x}{x\sqrt{\frac{1}{x^2}+1}}
=\frac{9}{\sqrt{\frac{1}{x^2}+1}}
$$
for $x> 0$. Now, when $x\to \infty$, what is the limit of ${\frac{1}{x^2}+1}$? Therefore, what is the limit of $\sqrt{\frac{1}{x^2}+1}$? And finally, what is the limit of $\frac{1}{\sqrt{\frac{1}{x^2}+1}}$?
Answer: $\lim\limits_{x\to\infty}\frac{9x}{\sqrt{x^2+1}}=$
$\lim\limits_{x\to\infty}\frac{\sqrt{81x^2}}{\sqrt{x^2+1}}=$
$\lim\limits_{x\to\infty}\sqrt{\frac{81x^2}{x^2+1}}=$
$\lim\limits_{x\to\infty}\sqrt{\frac{81}{1+\frac{1}{x^2}}}=$
$\sqrt{\frac{81}{1+0}}=$
$9$
Answer: An alternative approach to Clement C.'s one:
$1 = \frac{x}{\sqrt{x^2}} \ge \frac{x}{\sqrt{x^2 + 1}} \ge \frac{x}{\sqrt{x^2} +\sqrt{1}} =\frac{x}{x +1} = \frac{x+1-1}{x +1} = 1 - \frac{1}{x+1} \xrightarrow{x \to \infty} 1  $
$\Rightarrow \lim\limits_{x \to \infty} 9* \frac{x}{\sqrt{x^2+1}} = 9$


How to insert data into multiple tables in one query

Question: I created custom user registration form. the data get saved in the user table as required but the others field like fname,mobile and address are not getting saved in the following tables.
1. table name- field_data_field_name
  field name- field_fname_value

table name- field_data_field_mobile
field name- field_mobile_value
table name- field_data_field_address
field name- field_address_value

unfortunately i am not aware of how to insert data into three different table.so please help me with the solution for the same
i create another user registration from.the standard registration form is for doctor so they have different fields. this registration form is only for user to save basic information like address,fname and mobile number.this 3 fields are same as standard form fields.so thats why i want to insert this data into those tables.please help me
<code>  function register_form($form,&$form_state)
     {
     $form = array();

    $form['name'] = array(
    '#title' => 'Username',
    '#description' => 'choose a username',
    '#type' => 'textfield',
    '#required' => TRUE,
     );

    $form['mail'] = array(
    '#title' => 'email',
    '#description' => 'enter a valid email address',
    '#type' => 'textfield',
    '#required' => TRUE,

    );

     $form['fname'] = array(
        '#title' => 'Full Name',
        '#type' => 'textfield',
        '#required' => TRUE,
     );

     $form['mobile'] = array(
        '#title' => 'Mobile',
        '#description' => 'Mobile',
        '#type' => 'textfield',
        '#required' => TRUE,

      );
       $form['address'] = array(
        '#title' => 'Address',
        '#type' => 'textfield',
        '#required' => TRUE,
      );

    $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit'
    );
    return $form;
    }

    function register_form_submit(&$form, &$form_state) {
   $pass=user_password();

   $account = array(
  'name' => $form_state['values']['name'],
  'pass' => $pass,
  'mail' => $form_state['values']['mail'],
  'init' => $form_state['values']['mail'],
  'status' => 1,
  'access' => REQUEST_TIME,
  );
  user_save(drupal_anonymous_user(), $account);
  }
</code>
Comment: Are you aware that you can add fields to user registration form and not create another one? And are you aware that Drupal inserts automatically the data where they should be in the DB?
Comment: Why would you do that? What's wrong with using three queries?
Comment: ya but i create another user registration from.the standard registration form is for doctor so they have different fields. this registration form is only for user to save basic information like address,fname and mobile number.this 3 fields are same as standard form fields.so thats why i want to insert this data into those tables.please help me.
Comment: not find right answer till now.
Answer: It is impossible. Drupal uses MySQL by default, and MySQL's INSERT Syntax requires one and only one table name.
In theory you could use PostgreSQL and it's triggers - create a view from these 3 tables, and in insert trigger of that view perform inserts to underlying tables, but it wouldn't be universal solution, and I can't think of any particular reason to do it in one query anyway. If you need to ensure data consistency, DatabaseTransaction is the way.


The program '[4432] iisexpress.exe' has exited with code -2147023895 (0x800703e9)

Question: I have very frustrating issue with IIS Express. When I start debug everything is ok, but after few requests IIS hangs and crashes. My browser (Chrome Version 37.0.2062.120 m) waits for the response several seconds and then IIS Express stops running. My output is
The program '[4432] iisexpress.exe' has exited with code -2147023895 (0x800703e9).

and event log looks like this:
Log Name:      Application
Source:        Application Error
Date:          2014-09-18 14:12:24
Event ID:      1000
Task Category: (100)
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      COMP0008
Description:
Faulting application name: iisexpress.exe, version: 8.5.9748.0, time stamp: 0x5384d451
Faulting module name: clr.dll, version: 4.0.30319.34014, time stamp: 0x52e0b784
Exception code: 0xc00000fd
Fault offset: 0x000114a7
Faulting process id: 0x15f0
Faulting application start time: 0x01cfd3312b227e51
Faulting application path: C:\Program Files (x86)\IIS Express\iisexpress.exe
Faulting module path: C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Report Id: 0bd590d7-3f2d-11e4-82a5-7845c406525d
Faulting package full name:
Faulting package-relative application ID:
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="Application Error" />
    <EventID Qualifiers="0">1000</EventID>
    <Level>2</Level>
    <Task>100</Task>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated SystemTime="2014-09-18T12:12:24.000000000Z" />
    <EventRecordID>62449</EventRecordID>
    <Channel>Application</Channel>
    <Computer>COMP0008</Computer>
    <Security />
  </System>
  <EventData>
    <Data>iisexpress.exe</Data>
    <Data>8.5.9748.0</Data>
    <Data>5384d451</Data>
    <Data>clr.dll</Data>
    <Data>4.0.30319.34014</Data>
    <Data>52e0b784</Data>
    <Data>c00000fd</Data>
    <Data>000114a7</Data>
    <Data>15f0</Data>
    <Data>01cfd3312b227e51</Data>
    <Data>C:\Program Files (x86)\IIS Express\iisexpress.exe</Data>
    <Data>C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll</Data>
    <Data>0bd590d7-3f2d-11e4-82a5-7845c406525d</Data>
    <Data>
    </Data>
    <Data>
    </Data>
  </EventData>
</Event>

I have uninstalled all extensions in my Visual Studio 2013;
Cleared those folders:
Documents\IISExpress
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files

Still no success. My system: Windows 8.1 with all updates installed.
Any ideas?
EDIT:
I have also disabled Browser Link.
EDIT:
I have cleared
%HOMEPATH%\AppData\Local\Temp\iisexpress

and reinstalled IIS Express 8.  No change.
I have noticed that if I close browser when it waits for the response nothing happens, but then if I stop or restart debug session, I get this:

But when I wait several seconds, IIS crashes silently.
Comment: Did you get answer for your question?  I have this problem too.
Comment: I'd hedge my bet on an overflow or out of memory exception. Are there any background threads? Caching?
Comment: What kind of caching do you mean? My iisexpress.exe has 34 threads for now (7 managed) and its private working set is 158980K only.
Comment: Not really, but now it happens very rarely
Comment: Not sure of this, But changing the port number in your web project properties resolved my similar issue.
Comment: I'm with Steven V. 0xc00000fd indicates a stack overflow.
Answer: Windows error codes can be cryptic but easily understood with a simple process

From the error code 0x800703e9, take the last 4 characters 03e9
Using a Hexadecimal to Decimal Converter, convert 03e9 to its decimal counterpart, which in this case is 1001
Using cmd, type net helpmsg 1001 or whatever decimal value is returned.
A more friendly error message will usually appear... providing the original error code starts with 8007 which generally indicates it originated from Windows... or if no message appears then it probably didn't originate from a valid Win32 process.

In this instance, the error you received is Recursion too deep; the stack overflowed.


Copying prod multi-site installation to dev multi-site installation

Question: I am attempting to upgrade my Drupal 8.9.2 multi-site installation to D9. I was hoping to work this all out on a development installation, that is located in a subdirectory of my home directory on my NameCheap Shared Hosting plan.
When I first installed this installation, I did so using the tarball method from years ago. I then followed the instructions given here (https://www.drupal.org/docs/installing-drupal/add-composer-to-an-existing-site). I was able to get the current running prod version converted to use composer with out an issue.
Before I go and start messing with the files, and attempting to upgrade to D9 through composer on a prod installation, I wanted to copy these files over to another installation where I can use it as a sandbox. To do this I:

copied the files on my server to a new directory
made clone databases for the new installation
truncated all the cache tables in the cloned DB
changed all the database settings in the settings files to point to the cloned databases

I've done this before without any issues, and now I seem to be getting a WSOD error on all the sites running from the new installation. The error I'm getting is

PHP Fatal error:  Uncaught Error: Class 'Drupal\Core\Cache\DatabaseBackend' not found in ~/{new installation dir}/public_html/index.php:16.

If anyone has any thoughts what's going on I am all ears.
Thank you in advance
Answer:
I was able to get the current running prod version converted to use composer with out an issue.

If you have converted your site to use composer , you dont need to copy the whole code base into the new server. Just copy the config,custom modules, composer.json, composer lock files and other reqired files except the core, vendor and contributed modules into new server along with sites directory folder and run composer install in the root directory of the server.This can be done by initiating a git repo in the current code and using the default .gitignore file which is available in code.And cloning the same repo in new server.
As you have already copied all the files into new server.
Just run rm -Rf vendor , rm -Rf web/core and rm -Rf web/modules/contrib and run composer install from the root directory in the new server.
After doing this you will probably get your site running in Dev environment as well.
Comment: This worked like a charm! I figured there was an easy solution, I'm just rather new with composer, and trying to figure this all out as I go. Thank you very much @miststuden2011. I did have to change the `web` directory to `public_html` since that's where my host looks for files on my main domain, but I caught that before I started running the commands blindly ;)
Comment: Thanks for sharing your comments, miststudent2011 and Glaze. I am in the exact same boat with Namecheap and about to embark on fixing it to upgrade from D8 to D9.


Inconsistent cache values using Zend Cache with AWS ElastiCache across multiple servers

Question: We are using Zend Cache with a memcached backend pointing to an AWS ElastiCache cluster with 2 cache nodes.  Our cache setup looks like this:
$frontend = array(
    'lifetime' => (60*60*48),
    'automatic_serialization' => true,
    'cache_id_prefix' => $prefix
);
$backend = array(
    'servers' => array(
        array( 'host' => $node1 ),
        array( 'host' => $node2 )
    )
);
$cache = Zend_Cache::factory('Output', 'memecached', $frontend, $backend);

We have not noticed any problems with the cache in the past when using a single EC2 server to write and read from the cache.
However, we have recently introduced a second EC2 server and suddenly we're seeing issues when writing to the cache from one server and reading from another.  Both servers are managed by the same AWS account, and neither server has issues writing to or reading from the cache individually.  The same cache configuration is used for both.
Server A executes $cache->save('hello', 'message');
Subsequent calls to $cache->load('message'); from Server A return the expected result of hello.
However, when Server B executes $cache->load('message');, we get false.
As far as my understanding of ElastiCache goes, the server making the read request should have no bearing on the cache value returned.  Can anyone shed some light on this?
Comment: Additionally is the cache_id_prefix the same or a generated value?
Comment: I would assume this is a latency issue, have you tried to sleep(xxxx) and then perform the $cache->load from B?
Comment: Unfortunately, this is not the case.  Even hours later a value set from A is not readable from B.
Comment: Which version of PHP are you using?  I think the serialization is what is in play here.  Try disabling the auto serialization and see what happens.  The unfortunate side effect is that you have to serialize everything manually that is not a string.
Comment: I would try writing some test code using PHP's [Memcache](http://php.net/manual/en/book.memcache.php), removing Zend_Cache from the equation.  I never much liked the Memcache extension and have always favored [Memcached](http://php.net/manual/en/book.memcached.php) (but don't get me started on why the hell they added a 'd' to the client).  For one it supports compare-and-swap operations.
Comment: Hey guys, thanks for the feedback.  Unfortunately we are back down to 1 server (we were migrating from A to B at the time), so I haven't had a chance to test this any further in the last several days.  I will have some more info soon.  @Rich PHP 5.3.3, Zend 1.11.9, and the $prefix is a pre-determined value we use to 'partition' the cache (it was the same for both servers).  ficuscr, I may take your advice.  We _are_ using ZendCache's Memcached backend as [Elasticache](http://docs.amazonwebservices.com/AmazonElastiCache/latest/UserGuide/Introduction.html) is 'protocol compliant with Memcached.'
Answer: Can you tell what hash_strategy you are using for memcache? I've had problems in the past using the default standard but everything has been fine since changing to consistent:
http://php.net/manual/en/memcache.ini.php#ini.memcache.hash-strategy
Answer: With a normal hashing algorithm, changing the number of servers can cause many keys to be remapped to different servers resulting in huge sets of cache misses.
Imagine you have 5 ElastiCache Nodes in your cache Cluster, adding an sixth server may cause 40%+ of your keys to suddenly point to different servers than normal. This activity is undesirable, may cause cache misses and eventually swamping your backend DB with requests. To minimize this remapping it is recommended to follow consistent Hashing model in your cache clients.
Consistent Hashing is a model that allows for more stable distribution of keys given addition or removal of servers. Consistent Hashing describes methods for mapping keys to a list of servers, where adding or removing servers causes a very minimal shift in where keys map to. Using this approach, adding an eleventh server should cause less than 10% of your keys to be reassigned. This % may vary in production but it is far more efficient in such elastic scenarios compared to normal hash algorithms.  It is also advised to keep memcached server ordering and number of servers same in all the client configurations while using consistent Hashing. Java Applications can use "Ketama library" through spymemcached to integrate this algorithm into their systems. More information on consistent hashing can be found at http://www.last.fm/user/RJ/journal/2007/04/10/rz_libketama_-_a_consistent_hashing_algo_for_memcache_clients


Prove $x<\sqrt{x^2+1}$.

Question: Prove $x<\sqrt{x^2+1}$.
I am pretty sure this an easy question as the inequality seems obviously true, but I am not entirely convinced by my argument.
So I squared both sides (is this allowed?):
$x^2<x^2+1$, so $0<1$ so the inequality is obviously true.
However, I am unconvinced that this process is reversible due to the squaring, so could someone just explain whether this is correct?
Comment: Consider the cases $x <0$ and $x \geq 0$.
Comment: You can start with $x^2 < x^2+1$, and square root both sides. Make sure to remember that $\sqrt{x^2}=|x|$ and $|x| \ge x$.
Comment: If $x<0$ your inequality is obvious, since the right hand side is $\ge 0$. If $x\ge 0$ your squaring is correct, the squared inequality is equivalent to the original one and your proof works.
Comment: Consider the 3 cases $x<0$,$x=0$,$x>0$ separately.
Comment: In fact the reverse implies that $|x|<\sqrt{x^2+1}$ from here it is easy to continue just consider two cases.
Answer: You can not use squaring of the both sides directly because $x$ can be negative.
If so, you need to consider two cases: 1)$x\geq0$ and 2)$x<0$.
(in the last  the inequality is obvious.)
I think it's better to use a way without squaring:$$\sqrt{x^2+1}>\sqrt{x^2}=|x|\geq x.$$
Answer: By definition $\sqrt {x^2+1}\ge0$. If $x <0$, then $x <0\le \sqrt {x^2+1} \implies x <\sqrt {x^2+1} $. If $x\ge0$ we have:
$$
\underbrace {(\sqrt {x^2+1}+x)}_{\ge0}(\sqrt {x^2+1}-x)=1>0\implies x <\sqrt {x^2+1}.
$$

Prove $x<\sqrt{x^2+1}$.


Is $(x^2 + 1) / (x^2-5x+6)$ divisible?

Question: I'm learning single variable calculus right now and at current about integration with partial fraction. I'm stuck in a problem from few hours given in my book. The question is to integrate $$\frac{x^2 + 1}{x^2-5x+6}.$$
I know it is improper rational function and to make it proper rational fraction we have to divide
$$\frac{x^2 + 1}{x^2-5x+6}$$
I'm trying from sometime but couldn't find the right solution.
 Please help! Thank you in advance.
Answer: You can use long division. Another way is as follows:
\begin{align*}
\frac{x^2+1}{x^2-5x+6}&=\frac{(x^2-5x+6)+(5x-5)}{x^2-5x+6}\\
&=\frac{x^2-5x+6}{x^2-5x+6}+\frac{5x-5}{x^2-5x+6}\\
&=1+\frac{5x-5}{x^2-5x+6}
\end{align*}
As next step notice that $$x^2-5x+6=(x-2)(x-3)$$
and expand in partial fractions:
\begin{align*}
\frac{5x-5}{x^2-5x+6}&=\frac{A}{x-2}+\frac{B}{x-3}&&\text{Where }A\text{ and }B\text{ are constants}
\end{align*}
Answer: Given $\displaystyle \int\frac{x^2+1}{x^2-5x+6}dx = \int\frac{(x^2-5x+6)+(5x-5)}{x^2-5x+6}dx = \int 1dx+5\int\frac{(x-1)}{(x-2)(x-3)}dx$
Now Using Partial fraction Method::
$\displaystyle \frac{x-1}{(x-2)\cdot (x-3)} = \frac{A}{(x-2)}+\frac{B}{(x-3)}$
So we get $x-1 = A(x-3)+B(x-2) = (A+B)x+(-3A-2B)$
After Camparing the coefficient, we get $\displaystyle A+B=1$ and $3A+2B = 1$
So we get $\displaystyle A = -1$ and $\displaystyle B= 2$
So we get $\displaystyle \frac{x^2+1}{x^2-5x+6}dx = x+5\int \left[-\frac{1}{x-2}+\frac{2}{x-3}\right]dx$
Comment: how to divide both the fraction without your method.?
Comment: Simple Division Method.
Comment: Not really an answer to the question as given (I thought I saw something about the integral a while ago, a different q?)
Answer: Notice, $$\frac{x^2+1}{x^2-5x+6}=\frac{(x^2-5x+6)+5(x-1)}{x^2-5x+6}$$
$$=1+5\frac{x-1}{x^2-5x+6}$$
$$\implies \frac{x-1}{x^2-5x+6}
=\frac{x-1}{(x-2)(x-3)}$$   $$=\frac{A}{x-2}+\frac{B}{x-3}$$
By comparing the corresponding coefficients, we get $A=-1$, $B=2$, hence
$$\frac{x-1}{x^2-5x+6}=-\frac{1}{x-2}+\frac{2}{x-3}$$ Hence, we have  $$\frac{x^2+1}{x^2-5x+6}=1-\frac{5}{x-2}+\frac{10}{x-3}$$
Answer: Lot of good answers above. I understand now how this question will be solved. Since $f(x) /g(x)= quotient + remainder/divisor$, therefore on dividing both function we get -5+5x as remainder 1 as quotient and hence we get
1+ ((5x-5)/(x^2 - 5x + 6))
Answer: (x2+1)/(x2-5x+6)= (x2+1)/{(x-2)(x-3)}
By partial fraction
(x2+1)/(x-3)(x-2)= (Ax+B)/(x-2) +C/(x-3)
x2+1= Ax2+x(B-3A-C)-(B+2C)
Solving above equation,
We get
A=1, B=-7, C=10
So (x2+1)/(x2-5x+6)=(x-7)/(x-2) +10/(x-3)
=> 1+10/(x-3)-5/(x-2)
So integration will be
= x+10ln(x-3)-5ln(x-2)

Is $(x^2 + 1) / (x^2-5x+6)$ divisible?


Does cron @reboot run before systemd?

Question: A command defined as @reboot in the root crontab runs before or after systemd services?
Is it random or OS dependent?
Answer: Cron jobs can only start when the cron daemon is running, and of course systemd starts the cron daemon like every other service.
If it is important to run a specific job before or after something else, consider using a systemd timer/service to schedule it.

Does cron @reboot run before systemd?


Is this true: $P(X>x) = P(\log(X)>\log(x))$

Question: I can't find any theorem regarding this. I know it works for normal / lognormal distributions and as the logarithm is an affine transformation and the cdf is increasing it seems plausible but i can't find any reason/proof in favour or against.
Many thanks!
Alex
Comment: There is not much to prove, since $[X > x]$ if-and-only-if $[\log X > \log x]$, provided that $X$ is non-negative. In general, if $g$ is a measurable bijection between two spaces $\mathcal X$ and $\mathcal Y$ and $X \in \mathcal X$ with probability $1$ then $P(X \in A) = P(g(X) \in g(A))$ for any measurable $A$. This is because the events are the same, you are just defining the event of interest in two different ways.
Comment: Although the left hand side makes sense for $x=-1,$ what about the right hand side?  cc @Kedarps
Comment: Vanity, my comment provides a counterexample.  It shows you need to impose some conditions on both $X$ and $x.$
Comment: i guess only x > 0 has to hold for it to be satisfied right?
Comment: This is true because the logarithm function is a monotonically increasing function.
Comment: @Kedarps thanks! do you maybe have any formal proof / theorem verifying that? :)
Comment: @whuber, I should have specified that logarithm function is a monotonically increasing function, for positive values of $x$ :) I hope that's what you were getting at with the previous comment.
Comment: BTW, the logarithm is not an affine transformation.  See https://en.wikipedia.org/wiki/Affine_transformation for instance.
Comment: You are right, my bad :)
Comment: For added clarity, $\log$ is a bijection between $[0, \infty]$ and $[-\infty, \infty]$ so $X$ should be non-negative almost surely and we should have $x \ge 0$.
Comment: @guy - might want to post your comments as an answer, you'll get the (well-deserved) credit and everyone else will know this question has been answered!
Answer: The simple/heuristic explanation is for why this is true is that $[X > x]$ occurs if-and-only-if $[\log X > \log x]$ provided that both $X$ and $x$ are non-negative. Hence $[X > x]$ and $[\log X > \log x]$ are just two names for the same event, so the probability is the same.
I think the above description gets at the heart of what is going on, but since you asked for a "proof" I will also give something formal. Consider a probability space $(\Omega, \mathcal F, P)$ and let $X: \Omega \to \mathcal X$ be a random element and suppose $g: \mathcal X \to \mathcal Y$ is a bijection between the sets $\mathcal X$ and $\mathcal Y$.
Let $A$ be such that $[X \in A] = \{\omega : X(\omega) \in A\}$ is measurable, and recall that we define $P(X \in A)$ and $P(g(X) \in g(A))$ to be $$P(\{\omega \in \Omega: X(\omega) \in A\}) \quad \text{and} \quad P(\{\omega \in \Omega: g(X(\omega)) \in g(A)\})$$
respectively. However, because $g$ is a bijection, it is true that $x \in A$ if-and-only-if $g(x) \in g(A)$, i.e.,
$$
\{\omega \in \Omega: X(\omega) \in A\} =
\{\omega \in \Omega: g(X(\omega)) \in g(A)\}.
$$
Hence, $P(X \in A) = P(g(X) \in g(A))$.
To apply this to your problem, let $\mathcal X = [0, \infty]$ and $\mathcal Y = [-\infty, \infty]$ and $g(x) = \log x$. The set $A$ is $(x, \infty]$ and $g(A) = (\log x, \infty]$.
Answer: You can make your transformation more general. It just needs to be measurable.
If you define $\mathbb{P}_Y(Y \in A) = \mathbb{P}_Y(g(X) \in A) = \mathbb{P}_X(X \in g^{-1}(A))$ for a measureable $g$, where pre-image is defined as $g^{-1}(A) = \{ x : g(x) \in A\}$, then I think reasons why $\mathbb{P}_Y$ is still a valid probability measure is because the pre-image satisfies some properties, namely:

$g^{-1}\left(\bigcup_i A_i\right) = \bigcup_i g^{-1}(A_i)$, and
$g^{-1}(A^c) = \left[g^{-1}(A)\right]^c$.

This will mean $\mathbb{P}_Y$ is a valid probability measure because it satisfies all the axioms still, and so it will work for any set in the sigma field you throw into it, in particular the one you're looking at.
Comment: When writing my answer I realized you actually don't need $g$ to be measurable, or indeed very much measurablility at all. As long as $[X \in A]$ is measurable and you are working with a bijection you get trivially that $[g(X) \in g(A)]$ is measurable, even if $g(x)$ is not measurable. And $[X \in A]$ can be measurable without requiring that $A$ is measurable (with respect to whatever $\sigma$-field you are working with on $\mathcal X$).
Comment: @Taylor How do you define a measurable function  without referring to measurable sets?
Comment: @JuhoKokkala ah yep
Comment: @guy bijective functions are always measurable, so this is more general. Also, you use the pushforward measure without showing it exists. This is why it exists.
Comment: Do you have a source for bijection always being measurable? That seems unlikely, since bijections are fundamentally non-measure-theoretic objects, and are not necessarily connected to the underlying $\sigma$-algebras. My answer also goes through without referencing any $\sigma$-algebra other than $\mathcal F$ by making the assumption that $[X \in A] \in \mathcal F$. I don't use any measure or algebra other than $P$ and $\mathcal F$.
Comment: My heuristic for bijections not necessarily being measurable: there should $|2^{\mathbb R}|$ bijections from $\mathbb R$ to $\mathbb R$, but if I recall correctly there are only $|\mathbb R|$ many Borel measurable functions, so most bijections should not be Borel measurable. All bijections being Borel measurable also seems to violate Lusin's theorem.


Trocar dados do array entre 'S' e 'N'

Question: Tenho uma função que irei adaptar para um botão, que irá trocar um dado dentro de um array, entre S e N.
O código que tenho é:
var array = [{"nome":"1","faltou":"N","goleiro":"N","pago":"N"},{"nome":"2","faltou":"N","goleiro":"N","pago":"N"},{"nome":"3","faltou":"N","goleiro":"N","pago":"N"}];

function toggleArrayItem(a, v, d) {
        var i = a.findIndex(function(val){
                return val.nome === v;
            });
    if (i != -1){
      var data = a[i];
            if(d === 'faltou'){
        const isOn = (data.faltou = 'N');
        a[i] = ({"nome":data.nome, "faltou":isOn ? 'N' : 'S', "goleiro":data.goleiro, "pagou":data.pagou});
      } else if(d === 'goleiro'){
        const isOn = data.goleiro = 'N';
        a[i] = ({"nome":data.nome, "faltou":data.faltou, "goleiro":isOn ? 'N' : 'S', "pagou": data.pagou});
      } else if(d === 'pagou'){
        const isOn = data.pagou = 'N';
        a[i] = ({"nome":data.nome, "faltou":data.faltou, "goleiro":data.goleiro, "pagou": isOn ? 'N' : 'S'});
      }
    }
}

toggleArrayItem(array, '1', 'faltou');.

Só que não está funcionando corretamente, e queria diminuir o código. Estou usando localStorage em JSON.
Como proceder?
Answer: Você tem pequenos erros de escrita e lógica que fazem com que o seu código não funcione:

const isOn = (data.faltou = 'N'); - Repare que falhou a comparação na parte direita da expressão, e o que você queria fazer era data.faltou == 'N' ou até === como já tem em alguns locais. Para além disso o próprio valor está invertido pois isOn indica se está ligado ou seja se tem S mas no seu caso está a apontar para o N.
, "pagou":data.pagou - aqui coloca o valor de data.pagou que não foi definido no array original e por isso vai apanhar undefined. No array original foi definido pago

Corrigindo estes pormenores já dá o que espera:

var array = [{
  "nome": "1",
  "faltou": "N",
  "goleiro": "N",
  "pago": "N"
}, {
  "nome": "2",
  "faltou": "N",
  "goleiro": "N",
  "pago": "N"
}, {
  "nome": "3",
  "faltou": "N",
  "goleiro": "N",
  "pago": "N"
}];

function toggleArrayItem(a, v, d) {
  var i = a.findIndex(function(val) {
    return val.nome === v;
  });

  if (i != -1) {
    var data = a[i];
    if (d === 'faltou') {
      const isOn = (data.faltou === 'S');
      a[i] = ({
        "nome": data.nome,
        "faltou": isOn ? 'N' : 'S',
        "goleiro": data.goleiro,
        "pagou": data.pago
      });
    } else if (d === 'goleiro') {
      const isOn = data.goleiro === 'S';
      a[i] = ({
        "nome": data.nome,
        "faltou": data.faltou,
        "goleiro": isOn ? 'N' : 'S',
        "pagou": data.pago
      });
    } else if (d === 'pagou') {
      const isOn = data.pagou === 'N';
      a[i] = ({
        "nome": data.nome,
        "faltou": data.faltou,
        "goleiro": data.goleiro,
        "pagou": isOn ? 'N' : 'S'
      });
    }
  }
}

toggleArrayItem(array, '1', 'faltou');

console.log(array);

Quanto à simplificação, pode começar por usar uma Arrow Function no findIndex. Depois para trocar a propriedade desejada não precisa de criar um novo objeto igual apenas com uma propriedade diferente. Pode aceder diretamente pela propriedade que tem e alterar, desde que garanta que faz parte das propriedades que quer permitir alterar:

var array = [{
  "nome": "1",
  "faltou": "N",
  "goleiro": "N",
  "pago": "N"
}, {
  "nome": "2",
  "faltou": "N",
  "goleiro": "N",
  "pago": "N"
}, {
  "nome": "3",
  "faltou": "N",
  "goleiro": "N",
  "pago": "N"
}];

function toggleArrayItem(a, v, d) {
  var i = a.findIndex(val => val.nome === v);
  if (i != -1 && ['faltou', 'goleiro', 'pagou'].includes(d)) {
    a[i][d] = a[i][d] === 'S' ? 'N' : 'S';
  }
}

toggleArrayItem(array, '1', 'faltou');

console.log(array);

Como nota final sugiro nomes melhores para as variaveis. Deixei os nomes iguais aos que tinha para ser mais relacionavel com o seu código original mas a, v e d não são bons nomes e tornam o código complicado de ler
Comment: @GuilhermeLirio Sem problema. Se não funcionar é só colocar o `findIndex` como tinha originalmente. Mas desde já digo que é improvável que suporte `findIndex` e não Arrow Functions. Se olhar no [caniuse.com](https://caniuse.com/#search=Arrow%20Functions) e até no MDN vê que o suporte é muito elevado deixando só de fora o clássico IE.
Comment: @GuilhermeLirio Entender o código todo é sempre o ideal. o `includes` é um [método de Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) que testa se o array contem um elemento. É uma forma de evitar ter de fazer `if (d === 'faltou' || d == 'goleiro' || d === 'pagou')`, que normalmente até fica mais extenso mas no seu caso não ficou tanto porque a variável `d` tem um nome muito curto.
Comment: Obrigado pela resposta @Isac . Eu tenho quase certeza que essa a Arrow Function não funciona corretamente em apps híbridos em Android 4.4 e 5, mas irei testar e já dou um parecer.
Comment: Irei testar. No HTML funcionou perfeitamente. Obrigado pela ajuda!
Comment: eu sou do tipo de pessoa que gosta de entender o código: poderia me explicar o que faz o .includes(d) no seu código?
Answer: Olá, tenho outra sugestão, veja se atende:

 var array = [{
        "nome": "1",
        "faltou": "N",
        "goleiro": "N",
        "pago": "N"
    },
    {
        "nome": "2",
        "faltou": "N",
        "goleiro": "N",
        "pago": "N"
    },
    {
        "nome": "3",
        "faltou": "N",
        "goleiro": "N",
        "pago": "N"
    }];

    function toggleArrayItem(a, v, d) {

        a.forEach(item => {
            if (item.nome == v) {
                for (var prop in item) {
                    if (prop == d) {
                        item[prop]=item[prop] == 'S' ? 'N' : 'S';
                    }
                }
            }
        });

        console.log(a);
    }

    toggleArrayItem(array, '1', 'faltou');
Comment: Obrigado pela contribuição @AdjairCosta! Irei dar uma entendida no código também!

Trocar dados do array entre 'S' e 'N'


How do I find the name of database MySQL

Question: customer gave me all the information to connect to the database except the host name.
Is there any way to find out yourself what is the name?
Thanks,
Kropamk
Comment: What do you want to find, host name or database name? The question title and the question body both imply something different. The name of the selected database can be retrieved by `select DATABASE();`.
Comment: A host name is always required. Ask the customer to provide the host name.
Comment: go to the database which is created online you will see phpmyadmin like screen on top you will see host name....same as PHPMYADMIN show..
Comment: What's wrong with asking the customer to also tell you the host name?
Comment: I have a password, the user but do not have a host name
Comment: See [this](http://stackoverflow.com/q/8283248/1037210) question, if it can help though I don't think so.
Answer: No, you need the host name or IP.
Answer: Run following queries after in mysql command line client:
use information_schema;

select distinct table_schema from information_schema.tables;

Comment: Host name is always required
Answer: If You are using PHP, then for finding hostname use below code:-
echo $_SERVER['HTTP_HOST'];

and for finding database name in PHP use below code. The below code will give You the full list of databases.
// Usage without mysql_list_dbs()
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$res = mysql_query("SHOW DATABASES");

while ($row = mysql_fetch_assoc($res)) {
    echo $row['Database'] . "\n";
}


What are the alternatives to Socket Programming?

Question: I was browsing around for programming troubleshooters, and I was wondering what the alternate would be for Socket Programming; if there is one.
Comment: I think it would help if you clarify what you are trying to accomplish.  What do you consider an "alternate" to socket programming?  Do you mean an alternate to machine-to-machine communication or a broader scale including internet communication?
Answer: Assuming you have control over the protocol being used, you could go for a higher level of abstraction like .NET's Remoting or WCF.
Comment: Don't waste your time with Remoting.  It's being deprecated.
Comment: Hmm deprecated in favor of what?
Comment: jro, Mono's WCF support is limited, so Remoting is the only choice if you care about Mono.
Answer: TCPClient and UDPClient abstract you from the underlying sockets to some degree. They're nice to work with.
Answer: The question is rather vague and does not explain what MrM's issues with socket programming are, or what he is trying to accomplish.
An actual alternative to sockets would e.g. be (Win)Pcap, for which .net wrappers exist and that does not sit on top of the socket layer, as the other answers given so far.
There is also RDMA, which also does not use sockets, or much of the network stack at all, geared towards highest performance, but is not compatible with common IP networking.
Then there is the opposite approach: Getting high performance while still using standard sockets, by changing the underbelly with vendor-specific network stacks such as OpenOnload's. Many of these stacks however only run on the hardware of the specific vendor.


HOG features on different scales

Question: Suppose we calculate HOG features of image patches of different sizes, ranging from 64 * 64 to 128 * 128. Now, if we want to do k-means on these, should we normalize the patches which belong to different scale? I know HOG features are normalized, but does scale matter?
Answer: Normally, the HOG representations are normalized. However, you must be careful to the block size. In fact, you must have the same number of blocks, whatever the size of the image. Otherwise, you obtain descriptors of different lengths and the k-means cannot be performed. This means that when having larger images, you will have larger blocks. The resulting histograms will contain information from more gradients, so they aren't invariant at this stage. However, by applying the histogram normalization, the scale invariance of the final descriptor is obtained.
Yet, if you are not sure if the histogram normalization is well performed or not, you can extract the descriptor for an image and its resized version and compare them.
Good luck!

HOG features on different scales