How to idetify the phonetic alphabets in MS SQL database tables

Question: We have inserted more than 100000 records through Import flat file functionality in sql server management studio. It was inserted successfully.
But some of column values contained characters like é and ö .
It got converted into  while storing in sql column for all above characters like(ö,é).
Moreover the below SQL statements is not giving any results.
select * from Temp where column1 like '%%'

The data with these characters in the tables are being displayed with a symbol(question mark in a diamond).
Please help as to how can I insert the data keeping the phoentic symobols intact.
Comment: Can you give a few example of data of the import file and the data you have now on MS SQL?
Comment: Also please give the definition of the table you inserted into.
Comment: Hi @FrancescoMantovani. Möller in the file is M�ller in the database
Answer: Your data contains some characters like é and ö. But when you see in the database, it's stored "?" instead of that, right?
I think, your database does not support all characters. I would recommend to change it to something like this:
character set: utf8
collation: utf8_general_ci

Hope to help, my friend :))
Answer: character set: utf8
collation: utf8_general_ci
Answer:

SELECT
 *
FROM TEMP
WHERE SOUNDEX(COLUMN1) LIKE SOUNDEX('A')

strong text


Calculate the limit of the number sequence $\sqrt{2n-8}^{\frac{1}{n-4}}$

Question:
Calculate the limit of the number sequence $\sqrt{2n-8}^{\frac{1}{n-4}}$

$\sqrt{2n-8}^{\frac{1}{n-4}}=((2n-8)^\frac 1 2)^\frac{1}{n-4}=(2n-8)^\frac{1}{2n-8}\implies \lim_{n\to\infty} (2n-8)^\frac{1}{2n-8}=(2n-8)^0\to 1$ Is that enough to prove, that the limit is $1$? Did I forgot any steps that are necessary?
We haven't discussed L'Hopital's rule yet. It would be helpful if you could give me hints without the Rule of L'Hopital
Comment: $\lim_{n\to\infty} (2n-8)^\frac{1}{2n-8}=\infty^0$, so it is possible not be $1$, but this case is $1$
Comment: Use a substitution to show you have $\lim_{n-\rightarrow\infty} n^{1/n}$. This should be familiar...
Answer: Take logarithm. Use L'Hopital's Rule to show that $\frac 1{ 2n-8} \ln (2n-8) \to 0$. So the answer is $1$.
To show that $\frac {\ln x} x \to 0$ as $x \to \infty$ without the use of LHopital's Rule you can use the following argument:
$\ln (1+x) \leq x$ for all $x \geq 0$. Now  $\frac {\ln x} x  = 2 \frac {\ln \sqrt x} x \leq 2\frac {\sqrt x -1} x=\frac 2 {\sqrt x}-\frac 2 x \to 0$.
Comment: @Doesbaddel I have given another proof using the fact that $\ln (1+x) \leq x$. [This inequality can be proved by noting that $\ln (1+x) -x$ is decreasing on $[0,\infty)$ and has the value $0$ at $0$.
Comment: We haven't discussed L'Hopital's rule yet. I will edit my post.
Comment: Thank you! ${}{}$
Answer: Following along from your answer, we are trying to compute $lim_{n \rightarrow \infty} (2n-8)^{\frac{1}{2n-8}}$, writing $m = 2n-8$, and noting that $m = \phi(n) = 2n-8$ is in fact a bijection, it is clear $lim_{n \rightarrow \infty} (2n-8)^{\frac{1}{2n-8}} = lim_{m \rightarrow \infty} ,m^{\frac{1}{m}}$ which is a standard limit you can choose to evaluate however you like. To show it exists, it is enough to notice $m^{\frac{1}{m}} = \exp(\frac{1}{m}Log(m))$, and $\frac{1}{m}Log(m) \rightarrow 0$ as $m \rightarrow \infty$, so your limit is $1$.
Answer: If you are not allowed L'Hopital then consider $(\sqrt{2n - 8})^{1/(n-4)}$.  It is easy to combine the square root with the existing exponent to see that this is $(2n-8)^{\frac 1{(2n-8)}}$. Now, look at $\lim_{t \to \infty} t^{\frac 1t}$ along the positive integers. Note that
by Bernoulli's inequality,we have $e^x \leq 1+ x$ for all real $x$, so using this gives :
$$
1 \leq t^{\frac 1t} = e ^{\ln t/t} \leq 1+ \ln t/t
$$
for every $t \geq 1$ a positive integer. Since $\ln t/t \to 0$ as $t \to \infty$, we see that by the squeeze theorem, $\lim_{t \to \infty} t^{\frac 1t} = 1$. Now, the sequence $(2n-8)^{\frac 1{2n-8}}$ is a subsequence of this sequence, so it must have the same limit i.e. $1$.
Answer: Use that
$$\sqrt{2n-8}^{\frac{1}{n-4}}=\left(2n-8\right)^{\frac{1}{2n-8}}=e^{\frac{\log (2n-8)}{2n-8}} \to 1$$
indeed
$$\frac{\log (2n-8)}{2n-8} \to 0$$
to prove that let consider as $x\to \infty$
$$\frac{\log x}{x} \to 0$$
indeed by $x=e^y$
$$\frac{\log x}{x} =\frac{\log e^y}{e^y}=\frac{y}{e^y}\to 0$$
since eventually $e^y\ge y^2$.
Answer: The problem can be reduced to the evaluation of $\lim_{n\to \infty} n^{1/n}$. Here is one way to evaluate it. If $n>3$ then you can show that the sequence $n^{1/n}$ is decreasing and clearly it is bounded below by $1$. Therefore it tends to a limit $L$ with $L\geq 1$.
Next we derive a contradiction by assuming $L>1$ and thereby establish that the desired limit is $1$. If $n^{1/n}\to L>1$ then there is some number $k$ with $1<k<L$ and a positive integer $m$ such that $n^{1/n}>k$ for all $n>m$. This means that $n>k^n$ for all $n>m$.
Let $k=1+h$ with $h>0$ and then $$k^n=(1+h) ^n>\frac{n(n-1)}{2}h^2$$ if $n>2$. And $n>k^n$ therefore implies that $$n>\frac{n(n-1)}{2}h^2$$ for all $n>\max(2,m)$. This means that $n-1<2/h^2$ and this is clearly false as LHS of the inequality tends to $\infty$ as $n\to\infty $ whereas the RHS remains fixed.


If $R$ is a commutative ring with unity and $R$ has only one maximal ideal then show that the equation $x^2=x$ has only two solutions

Question: If $R$ is a commutative ring with unity and $R$ has only one maximal ideal then show that the equation $x^2=x$ has only two solutions.

I know that $0$ and $1$ are the solutions, but I can't proceed from there.
Comment: The phrasing this question usually occurs in is "A local ring has only trivial idempotents." It's true even for noncommutative local rings, by the same arguments given below. (A noncommutative local ring is one with a unique maximal right ideal, or, equivalently, a unique maximal left ideal.)
Answer: Let $M$ be the maximal ideal of $R.$ Then $R= \{ units \} \cup M.$ Now suppose $x(x-1)=0.$ If $x$ is a unit then multiplying by the inverse gives $x=1.$ If $x-1$ is a unit then multiplying by its inverse gives $x=0.$ Thus if $x\neq 0,1$ is to solve $x(x-1)=0$ then $x$ and $x-1$ are both not units, and hence both in $M.$ But then $ 1= x - (x-1)\in M$ which is nonsense.
Comment: could you please explain me "Thus if $x\neq 0,1$ is to solve $x(x-1)=0$ then $x$ and $x-1$ are both not units, and hence both in $M.$ But then $ 1= x - (x-1)\in M$ which is nonsense."
Comment: may be i am not understanding the way u have written the combined sentense as I must confess m weak in understanding english
Comment: @Tsotsi If $x$ is a solution of $x(x-1)=0$ and $x$ is not $0$ or $1$, then $x$ can not be a unit (since if $x$ is a unit, we can solve $x(x-1)=0$ by multiplying both sides by $x^{-1}$ to get $x=1$ ) and $x-1$ can not be a unit (since if $x-1$ is a unit, we can solve $x(x-1)=0$ by multiplying both sides by $(x-1)^{-1}$ to get $x=0$). Since $R = \{ units \} \cup M,$ and $x, x-1$ are both not units, we have $x\in M$ and $x-1\in M.$ Since $M$ is an ideal, it is closed under subtraction, so $x-(x-1)\in M$ so $1\in M.$ But this is a contradiction, since $M$ is a maximal (and hence a proper) ideal.
Answer: Suppose that $r \in R$ satisfies $r^2=r$.  Since $(r)+(1-r)=R$, one of the principal ideals $(r)$ or $(1-r)$ is not contained in the maximal ideal $M$.  But then $(r)=R$ or $(1-r) = R$, i.e. $r$ or $1-r$ is a unit.
If $x$ is a unit satisfying $x^2=x$, then $x=1$ (dividing by $x$).  Thus $r=1$ or $1-r=1$.


How to configure annotator and annotation modules in Drupal 7?

Question: I would like to provide an MS Word -like annotations (review comments) functionality in some text areas of my Drupal 7 website.
I have experimented with the co.ment and annotator - annotation Drupal 7 modules, and the second solution seems lighter and more appropriate for my requirements.
Unfortunately there is very poor documentation on the annotator and annotation modules and I cannot configure the storing of my annotations.
I have read the annotator library documentation but I do not know how to implement either the store or authentication and permissions plugins on my Drupal 7 website.
From the Annotator module page, what I understood is that by installing the Store plugin together with the Annotation module you use your own storing and not Annotateit.org service.
I have downloaded and installed the required libraries (annotator and Gettext) and from the Annotator configuration page I have enabled the Store plugin with the default Store url options. But my annotations do not get stored and I do not get any exceptions or other info, so that I can see what is going wrong.
Any suggestions please on what may be missing? I can provide more details where needed.
Answer: I stumbled across the same problem today. Proper way to install everything:

Download the annotator libraries in /sites/all/libraries/annotator
Download jquery_update and set jquery v.1.8 to be used
Download and enable the annotator module and its dependencies (e.g. libraries)
Download and enable the annotation module
Do not change any configuration options

For a minimal installation, I have just used the markup and store plugins. Some things that might get in the way of the annotations being saved:

You need to have Clean URLs installed
If Drupal is not installed in the root of your domain (for example if it's in http://example.com/subsite instead of http://example.com) you may have to change the configuration of the store plugin to point at /subsite/annotation/api instead of /annotation/api

You can manage the permissions to create, edit, view or delete annotations through the permission system of the annotation module.
Also, keep in mind, that if you create the annotation while you are browsing node/3 through the URL: http://test.drupal/node/3#overlay-context=node/6, the annotation WILL NOT appear if you visit: http://test.drupal/node/3. That caused me a lot of headaches. You can check whether your annotations have been saved in the admin/content/annotation path.
NOTICE:
When downloading the annotator library from github make sure that you download the annotator-full.1.2.9.zip not annotator.1.2.9.zip.


Passing variables from hook_mail to cutom twig template

Question: Custom twig template into hook_mail()
$body_content = array(
    '#theme' => 'mail_body_content',
    '#node' => $node,
);

I would like to access to node Entity and display value into the twig
myfield_name: {{ node.get('field_myfield_name').value }}

Render code
$renderedContent = \Drupal::service('renderer')->renderPlain($body_content);

Only myfield_name: is display.
How to get / pass the variable to twig ?
Answer: Rather than using node get to print a value just use this in twig.

node.field_myfield_name.value

Otherwise preprocess your twig and get only required fields over sending complete node object to twig.
function theme_name_preprocess_mail_body_content(&$variables) {
  $variables['myfield_name'] = $variables['node']->field_myfield_name->value; //$variables['node'] will be render $node from your hook_mail() function.
}

And in Twig myfield_name will work
Answer: Passing content (hook_mail):
$body_content = array(
    '#context' => [
        'node' => $node,
    ],
);
$renderedContent = \Drupal::service('renderer')->renderPlain($body_content);
$message['body'][] = $renderedContent;

Get content (twig template file):
myfield_name: {{ context.node.get('field_myfield_name').value }}


AB test, but, more like ABCDEFGH

Question: When doing an AB test (for website variations), I understand you should check the significance before drawing conclusions with any of the tools you can find googling "ab test calculator", now how would you do that with more than 2 variables?
Let's say I have this data :
<code>Variation   Impressions   Clicks
A           400           20
B           300           10
C           100           2
</code>
What conclusion can I draw from that? If I stick with the AB test (which I feel is wrong), I can do :
A vs B : no significant difference
B vs C : no significant difference
So I could conclude that, overall, there is no difference there and no variation is bad enough to stop testing.
But if I do A vs C : significant difference! So now I want to stop C.
OK so what I feel is that there is another way to compare these. What would it be?
Thanks!
Answer: You may want to read up on Analysis of Variance, also known as ANOVA. Any introductory applied statistics textbook will explain ANOVA to you.
Here are some CrossValidated questions that may be helpful - you may want to sort by votes and skim the first few pages of results.
Of course, you can't apply ANOVA to just one data point per A/B/C group, nor should you draw conclusions from $n=1$ observation each, but I assume you know this.
Comment: Thx for showing me the right direction.

I'm just a web developer trying to figure out what's the best option for my site, so TBH I was looking for a magic unicorn where I could just put my values and draw conclusions just like those AB significance calculator you can find online.

If you have some more minutes would you care to explain what conclusions you would draw from my fictitious example? If this is not "statistically significant" and you can't draw conclusions you can change the values. Ah if you don't have the time, thanks anyway, the first answer is much appreciated!!!
Comment: Ah there was a limit of characters in the comment so I cut that part but since I can add another comment I'll put it anyway : I started reading the Wikipedia and there's many stuff I don't understand there either, that's why I'm asking you for a little more, but obviously I will spend more time on it and hopefully I'll understand more soon (hopefully before 2018 :)
Comment: OK, some days later : sounds like your last sentence prevent me from drawing conclusions from my dataset so ANOVA not appropriate to my needs. Thanks anyway.

AB test, but, more like ABCDEFGH


Why is the number of non zero rows in row echelon form of the matrix the rank of the matrix

Question: I have no idea about how to prove this statement hence require a proof. The only definition I have is that rank is the highest order square submatrix of a matrix which has non-zero determinant.Our professor has given the statement in question as a definition without any prrof hence asking for help.Thanks!
Comment: Is the rank preserved at each step of Gaussian elimination?
Answer: The rank of a matrix also tells you how many linearly independent vectors it has i.e. if rank is 2 then there will be 2 linearly independent vectors in the matrix. And these vectors will be the columns (given your vectors are the columns of the matrix) that contain leading 1's in the rref of said matrix. And if you observe, you will see that the number of leading 1's will always be equal to the number of non-zero rows in the rref of a matrix. Thus rank = # of non-zero rows in the rref of a matrix.


Parte da string em shell script

Question: Estou com dificuldade para conseguir separar parte de uma string em shell script.
T=$(df /dev/sda1)
echo $T

Saida:
Filesystem 1K-blocks Used Available Use% Mounted on /dev/sda1 81000912 11432088 65408212 15% /

Gostaria de pegar apenas o 15%, de preferencia sem a porcentagem.
Estou testando o comando sed, porém não obtendo sucesso.
Answer: De facto T=$(df /dev/sda1) está a executar um comando df ... e
a guardar a sua saída em T.
(1) afinar o camando:
através de man df ou de df -h vê-se que há uma opção que
permite selecionar que campos queremos: df --output=pcent
$ df --output=pcent /
Use%
50%

(2) Selecionar apenas (ou seja grep -o) os números: grep -Po '\d+'
$ df --output=pcent / | grep -Po '\d+'
50

(3) Montar na script
T=$(df --output=pcent / |grep -Po '\d+')
echo $T

Comment: Algum comentário/sugestão acerca do voto negativo?
Answer: Outra alternativa é a seguinte:
 T=$(df /dev/sda1 | awk '{print $5}' | tail -n 1 | cut -d '%' -f 1)
 echo $T
 50

O comando df é usado para relatar uso de espaço em disco do sistema de arquivos.
Já o awk é linguagem de programação que permite a manipulação de textos a partir de uma sequência de padrões.
O tail é um comando nativo do Linux que permite visualizar arquivos textos.
E por fim, o comando cut, seguindo a tradução livre, serve para "cortar" strings.
Então, a sequência de comandos detalhada fica da seguinte forma:
df /dev/sda1 # Relatar uso de espaço em disco do sistema de arquivos
awk '{print $5}' # Da saída anterior, pega só a coluna 5
tail -n 1 # Da saída anterior, retornar somente a última linha
cut -d '%' -f 1 # Da saída anterior, corta a partir de % para a esquerda

O símbolo | no shell, permite jogar para o comando seguinte o output do comando anterior.
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: Coloquei mais info senhor Bot !

Parte da string em shell script


Play MP3 in browser

Question: I'm trying to allow a user on my site to click a button and via an ajax call load an mp3 file that is created on the server to their browser and then begin playing that file. The file cannot be publicly accessible sense it contains user account specific information. So, I've created the server side code that creates the mp3 but I do not know how to stream the file to the browser from my controller. Here is my current controller method.
def play_mp3
    t = TextToSpeech.new(current_user, "Play this text in the saved mp3 file")
    mp3_file = t.text_to_speech
end

Comment: In your controller code you can return arbitrary data with [`send_file`](https://api.rubyonrails.org/v5.2.1/classes/ActionController/DataStreaming.html).
Comment: @tadman Ok, so I am able to use this to save the file from the browser, but how would I load this in with javascript so the user could essentially hit play and the file is created on the server and then played in their browser?
Comment: Your browser doesn't care how it got the file, only that it did. Presumably you can use some JavaScript widget that plays music from remote sources, of which there are dozens. If you have a URL that returns valid MP3 data, it's going to be fine.
Answer: <audio autoplay controls="controls">
   <source src="/YOURMP3FILE.mp3" />
</audio>

Comment: Didn't realize it would be that simple but this essentially is what I'm after. Thanks
Comment: That'll work in some browsers some of the time, but there are JavaScript wrappers around the `` that make it work on more browsers more reliably. This minimal solution is a great start though.

Play MP3 in browser


How to prevent Suspicious Link message in GMail?

Question: We are sending HTML emails from Microsoft365 to our clients and these emails contain a hyperlink to an item in a Sharepoint list in one of our Sharepoint sites.
I have only tested this in GMail, not sure whether the issue is only isolated here or on other email clients as well. When clicking the link in GMail, the below "Suspicious Link" popup message appears. Clicking 'Proceed' works, and brings the client to wherever he needs to be.
But we would like to avoid this popup message altogether.
The URL is in this format:

https://xyz.sharepoint.com/sites/sitename/Lists/listname/EditForm.aspx?ID=123

I have tried 2 variants, and both are having the same issue:
{theURLagain}

and
Link to our Sharepoint

Anyone has an idea how we need to write the HTML to prevent this? Or is it not related to how the HTML is written?
Thanks!
Answer: The following thread is discussing the same question, I hope this may help
https://support.google.com/mail/thread/4242603?hl=en&msgid=8208054
Answer extracted from the thread:
This solved the problem for me:
Go to postmaster.google.com.
On the bottom-right, click the + button.
In the box that pops up, enter your authentication domain.
Next, prove that you own the domain by adding a DNS TXT or a DNS CNAME record.
After I completed that, I stopped getting that 'untrusted' message within a few minutes.
Comment: How do we add a DNS TXT or CNAME record for a Sharepoint site? We don't own the domain. It's xyz.sharepoint.com


How to find caret position of textbox in wpf

Question: How to find caret position of textbox in WPF. I'm open to your ideas, because textbox haven't caret position. Is there a way to do this ?
Comment: With regard to your comment to one of the answers, and with the help of the documentation i linked to, you can figure out the caret position in a line of your multi-line text quite easily. Step 1: `TextBox.CaretIndex` property will give you the index of the caret in the overall string. Step 2: `TextBox.GetCharacterIndexFromLine(...)` can give you the starting index of each line. Given this information, you can (A) figure out in which line the current caret index is, and (B) what the relative index/position of the caret is in relation to the starting index of that line. Happy coding!
Comment: What do you mean WPF textbox has no caret position? Have you looked at the documentation for it? Hint: When looking at its documentation, search (Ctrl+F) for "Caret". Documentation here: https://learn.microsoft.com/en-gb/dotnet/api/system.windows.controls.textbox?view=netframework-4.7.2#properties
Comment: I got it. Thank you very much for response.
Answer: int caretPostion = myTextBox.CaretIndex;

Comment: @Nasirli01, you did not mention anything of that in your question. The answers you will get depend on the quality and amount of information in your question, obviously...
Comment: This is show just column. I need line and column position
Answer: I think this should work:
int caretPosition = myTextBox.SelectionStart;

Comment: There is no need for it it wil stil find it 0 selection length is still a selection
Comment: There is no selection currently in the text box. What now...?
Comment: you are right. The value of SelectionStart indeed seems to always coincide with the value of CaretIndex, even if there is no actual (visible) selection in the textbox. I guess i will have to take a look at the TextBox reference source to figure out whether there might be subtle differences between these two properties or not. (Update: Well, the getter for CaretIndex just returns the value of SelectionStart. Funny that...)


Setting environment variables in mod_wsgi for Django

Question: I'm running Django on an RHEL instance under Apache/mod_wsgi, and I'm having issues setting some environment variables for the Python process.  All of the components (Apache, Python, mod_wsgi, external libraries) are built from source, not installed from the repos.
The specific issue is support for Oracle support.  I am able to connect to Oracle instances without a problem if I set the ORACLE_HOME and LD_LIBRARY_PATH on the command line when firing up Python myself, but I can't seem to get those variables passed through to the WSGI process.
The specific error message I get in the Apache logs is:
ImproperlyConfigured: Error loading cx_Oracle module: libclntsh.so.11.1: cannot open shared object file: No such file or

directory
I have tried setting the variables in the VirtualHost (using SetEnv), Apache's envvars file, the apache user's .bashrc file, and the .wsgi file (using os.environ['ORACLE_HOME']='...'), all with no effect.  In the first three cases, the variables don't seem to make to to Python at all--printing os.environ['ORACLE_HOME'] indicates that no value has been set.
I have also tried rebuilding mod_wsgi.so from source with the LD_RUN_PATH evn var set, per the advice here: http://groups.google.com/group/modwsgi/browse_thread/thread/91dfa97330dfca2/474f818304d741d4
However, that was also ineffective.
What am I missing?  How can I get those env vars successfully passed through?  Thanks in advance!
Answer: In Ubuntu, placing
export ORACLE_HOME=<your oracle home>
export LD_LIBRARY_PATH=<your library path>

in /etc/apache2/envvars seems to do the trick.
If nothing else helps, you can edit your Apache startup scripts and put above
export lines just before Apache daemon startup (I recall I did something like this looong time ago on Debian).
Answer: Since you built Apache from source code, you could have added to the 'envvars' file in same directory as 'httpd' executable the lines:
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/some/path/to/oracle/lib/directory
export LD_LIBRARY_PATH

The LD_RUN_PATH method when compiling mod_wsgi should also work, but since you don't show the exact methods you used, ie., commands executed, to try and get that work, can't comment on why it didn't work. It would be of the form though:
make distclean
./configure
LD_RUN_PATH=some/path/to/oracle/lib/directory make
sudo make install

So, set LD_RUN_PATH in same line when running 'make'. If you set it seperately as environment variable before running 'make', you must 'export' the environment variable else make will not pass it through to compiler.
Answer: The key seems to have been adding the Oracle libraries to ld.so.conf.
Answer: Another possible solution is to set LD_LIBRARY_PATH in the start up script -- e.g. in /etc/init.d/httpd:
export ORACLE_HOME=<your oracle home>
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME/lib


Given an odd $x$ there is an $m,n$ such that $2^n + 1 = 3^m x$?

Question: I'm curious about this question: Is it true that for any odd number $x\in 2\mathbb N + 1$ there exists numbers $m,n\in \mathbb N \cup \{0\}$ such that
$$2^n+1 = 3^mx$$
Edit: I'm not trying to make this over-complicated and maybe there is somethng easier than what I am thinking. But, if Pillai's conjecture is true then the answer should be negative for most $x$.
Comment: I suppose $x=27$ has no solution
Comment: I've fixed the title to $2^n + 1 = 3^m x$.
Answer: $7$ is one such number than cannot be expressed as $(2^n+1)/3^m$. For otherwise $3^m\cdot7=2^n+1$ for some $m,n$ positive integers. Thus $2^n+1=0 \mod 7$. But $2^n$ cannot have in $\mod 7$ values other than $2,4,1$ and so $2^n+1$ can have values only $2,3,5$ and none of these are $0\mod 7$.
Comment: Please use [mathstyle](http://math.stackexchange.com/help/notation).
Comment: I took the liberty to review and edit it with $\TeX$-formatting. @Adelafif: Feel free to change if either if I made a mistake or it can be improved to match your intention.
Comment: BTW: There is no need to write $(2^n)+1$ rather than $2^n+1$ since order of operations make those equal, and the latter is the simplest form.
Answer: Here are some$\newcommand\leg[2]{\left(\frac{#1}{#2}\right)}\newcommand\ifs{\text{if }}\let\v\nu$ criteria. Either way, I don't expect there to be a simple characterisation of such $x$.

If $m>0$, then for $2^n+1$ to be a multiple of $3$, $n$ should be odd. From $2^n+1\equiv0\pmod x$ we have $(2^{(n+1)/2})^2\equiv-2\pmod x$, so $-2$ is a quadratic residue modulo $x$. Because
$$\leg{-2}p=\leg{-1}p\leg2p=\begin{cases}-1&\ifs p\equiv5,7\pmod8\\1&\ifs p\equiv1,3\pmod8\end{cases}$$
we obtain that every prime divisor of $x$ is $\equiv1,3\pmod8$. (Because $3^2\equiv1\pmod8$ this implies in particular that $x\equiv1,3\pmod8$.)
If $m=0$ we simply have $x=2^n+1$ as a necessary and sufficient condition.
By Zsigmondy's theorem, if $n$ has $\tau(n)$ positive divisors, then $2^n+1$ has at least $\tau(n)$ distinct prime divisors (unless $n=3$). This lets us conclude for example that $x$ cannot be a power of $3$ (though you might prove this using more elementary methods) unless for $x=1,3,9$. Also, if $x$ is given, Zsigmondy gives an upper bound on the number of prime divisors of $n$.
If $m>0$ the Lifting The Exponent gives the exact exponent of $3$ in the factorisation of $n$:

Lemma. (Lifting The Exponent, special case)
  Let $p$ be an odd prime and $a,b\in\mathbb Z$ such that $p\mid a+b$ but $p\nmid a$. If $k$ is odd, then $\v_p(a^k+b^k)=\v_p(a+b)+\v_p(k)$, where $\v_p(k)$ denotes the exponent of $p$ in the prime factorisation of $k$.

So if $m>0$, then $n$ is odd hence $\v_p(n)=m-1$ by LTE. Combined with Zsigmondy this gives some more interesting partial results, such as: if $x=p^k$ is a prime power (with $p>3$ because $p=3$ is impossible, see above), then $n$ is prime. If $n>3$, then by LTE we have $m=1$, so $2^n+1=3p^k$.
Comment: Thanks. Though I marked a post as the answer, I do appreciate a more general answer like the one you are trying to do.
Comment: Can someone help, does this mean that the question is true?
Answer: For $x > 8$, $n \geq 3$, so $2^n + 1 = 1 \mod 8$.
$3^m = \begin{cases}3 \mod 8 & \text{ if } m \text{ odd} \\
1 \mod 8 & \text{ if } m \text { even}\end{cases}$
Looking at the equation $\mod 8$, we must therefore have
$1 = 3x \mod 8$ or $1 = x \mod 8$
So any solution must have $x = 1 \mod 8$ or $x = 3 \mod 8$, since the inverse of $3 \mod 8$ is $3$. So there are no solutions with $x > 8$ and $x = 5 \mod 8$ or $x = 7 \mod 8$ .
Comment: You mean any solution must be x=3 mod 8 (since it should be the inverse of 3 mod 8). Well ok, at least we have restricted the possible solutions mod 8...


how to write 2D char array into a file

Question: How do I write a 2D char array to a file. I searched for the solution everywhere, but didn't find an answer.
void printDATA(){
String[][] stringArray = Arrays.copyOf(data, data.length, String[][].class);
char[][] charArray = new char[stringArray.length][stringArray[0].length];
            for(int i = 0; i < stringArray.length; i++)
            {
                for(int j = 0; j < stringArray[0].length; j++)
                {
                    charArray[i][j] = stringArray[i][j].charAt(0);
                }
            }
        File file = new File("result.doc");
        try {
            //FileWriter fout = new FileWriter(file);//Gives error
            PrintWriter fout = new PrintWriter(file);//This also gives error
            fout.write(charArray);
            fout.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Answer: The Writer API does not support writing arrays of arrays. Only int (which should really be a char), String, or char[]. Loop over the arrays to write.
for (int i = 0; i < charArray.length; i++) {
    fout.write(charArray[i]);
}

You will probably want to throw in newline characters as well.
Comment: Actually i really want to print either 2D char array or 2D string array. Is there any alternative method..??
Comment: Not using common APIs. It would help to explain what you mean by printing a 2D array. Take this array: `String[][] test = { { "foo", "bar", "baz" }, { "1", "12", "123" }, { "the", "quick", "brown", "fox" } };`. What are you expecting the program to print?
Answer: Pseudo-code:
for(int i =0;i< 1st dimension; i++)
   { for(int j =0;j< 2nd dimension; j++)
        {
          write (array[i][j])
          write (some symbol)
        }
  write (some other symbol)
   }

Then you will need to remember the delimiting symbols when you want to read from the file.
Then you will need to read the whole file as String and split it using the 1st symbol then the 2nd symbol.
For example, lets take the following 2D array:
apple orange pineapple.
banana tomato grape.
You can write it to a file as 1D string as:
apple,orange,pineapple;banana,tomato,grape;
Then when you read the file as string, you split on ";" and get:
apple,orange,pineapple
banana,tomato,grape
then split each one at "," and re-build your 2D array.
Comment: That is if you don't want to use any API or complex code
Comment: @M I think file handling using  FileWriter only support one dimensional char array. Any other OutputStream method or alternative method..?

how to write 2D char array into a file


This family of relations is the intersection of what two manifolds

Question: when an infinite cone intersects a plane we get conics and we get the generic equation $$Ax^2+Bxy+Cy^2+Dx+Ey+F=0$$ But what happens if we start with a similar equation, and try to determine the surfaces, (I am assuming one would need to a plane) $$Ax^3+Bx^2y+Cxy^2+Dy^3+Ex^2+Fxy+Gy^2+Hx+Iy+J=0$$ Or if you show that such a manifold would be impossible to exist. (by showing that all 2D? manifolds either miss some curves in the family or add extra)
Answer: It's the image of the (affine) Veronese map $(x, y) \mapsto (x^3, x^2y, xy^2, y^3, x^2, xy, y^2, x, y)$. This is the graph of a map $\mathbf{R}^2 \to \mathbf{R}^7$, so is diffeomorphic to $\mathbf{R}^2$, in particular a manifold. Intersecting it with the hyperplane $Az_1 + \dots + I z_9 = -J$ (where $z_1, \dots, z_9$ are the coordinates on $\mathbf{R}^9$) and looking at the diffeomorphic preimage in $\mathbf{R}^2$ gives you exactly that equation.
If you go through the same construction for the degree $2$ curve you get a surface in $\mathbf{R}^5$ (intersected with a plane), not the cone in $\mathbf{R}^3$ you might expect. The issue is that in the $\text{cone} \cap \text{plane}$ picture, the plane does not come with a choice of coordinates so choosing different ones gives different equations. A different way of fixing this is to say that up to some change of coordinates, every degree $2$ curve in the plane is given by a simpler equation
$$A(x^2+y^2) + 2Bxy + C(x^2 - y^2) + F = 0$$
and now this is given by intersecting the image of $(x, y) \mapsto (x^2 + y^2, 2xy, x^2 - y^2)$ with a plane in $\mathbf{R}^3$. You can check that the image is a cone, cut out by the equation $z_1^2 = z_2^2 + z_3^2$. You do lose something, this is no longer a manifold at $(0,0,0)$ and that it is a manifold away from this point is trickier to prove (implicit function theorem).
If you don't need the cone to be the standard cone then you can take the even "simpler" equation
$$Ax^2 + Bxy + Cy^2 + F = 0.$$
Similarly in the degree $3$ case you can reduce to curves of the form
$$Ax^3 + Bx^2y + Cxy^2 + Dy^3 + Ex^2 + Fxy + Gy^2 + J = 0$$
and you get the image of $(x,y) \mapsto (x^3, x^2y, xy^2, y^3, x^2, xy, y^2)$ in $\mathbf{R}^7$, but again this image is not a manifold at the origin. It is at all its other points, again using the implicit function theorem though the equations defining it might be tricky to figure out if you haven't seen them before.
Comment: Wow. above me. so since our hyperplane has nine cordinates, does that mean are 2D manifold is in nine dimensional space
Comment: A priori, yes. But even the conic section case the "cone" is a priori in $\mathbf{R}^5$, (so that the plane has $6$ coefficients) and you can restrict to $\mathbf{R}^3$ by for example varying the curve in $\mathbf{R}^2$ up to translation. Here too you can reduce the ambient dimension to $\mathbf{R}^7$ by the same trick.
Comment: @MichaelToth added some details about reducing the ambient dimension at the cost of losing smoothness.


Use of Bijection for computation

Question:
Compute the last three digits of
  $$\sum_{k=1}^{2017} k^3*\binom{2017}{k}$$

I'm looking for combinatoric way to "translate" this into something much easier to compute. The Sum is the number of ways of choosing a $k$-member committee with three jobs within them (can all be the same person).
    I think we could do this by choosing the jobs first and then the committee. We proceed by casework on jobs.
One person has all three jobs:
$2017\cdot 2^{2016}$
One person has two jobs:
$2017\cdot 2016\cdot 2^{2015}$
Every job is occupied by a different person
$2017\cdot 2016\cdot 2015\cdot 2^{2014}$
However if we add these cases up it is not equal to our original summation. How can I fix this?
Thanks!
Answer: Consider $n$ people.  Your three cases are:

$\binom{n}{1}2^{n-1}$
$\binom{n}{2}2!\binom{3}{2} 2^{n-2}$
$\binom{n}{3}3! 2^{n-3}$

Summing these yields the identity
$$\sum_{k=1}^n k^3 \binom{n}{k}=n^2(n+3)2^{n-3}$$
Now compute the right hand side $\pmod{1000}$ when $n=2017$.
Comment: Thanks! Your solution made me realize I forgot ordering within jobs!

Use of Bijection for computation


How Functional components are working without essential render function?

Question: While going through the docs find that render function is a essential life cycle method. In the case of functional components ,there is no render function.?
Answer: Yes when using class components componentDidMount, componentWillUnmount(), render() are essential life cycle methods. In react functional components there is the useEffect Hook and in your case the:
return (

Header

);

to replace the render function
Answer: Yes, you are correct. In functional components, there is no need for a render function.
A functional component is just a plain JavaScript function that returns JSX. A class component is a JavaScript class that extends React.Component which has a render method. When defining a class component, you have to make a class that extends React.Component. The JSX to render will be returned inside the render method.
Source: https://www.twilio.com/blog/react-choose-functional-components


How to report Ordinal Logistic Regression results?

Question: I am analysing multiple Likert Style statements with an Ordinal Logistic Regression. I have many different factors that I am taking into account, from job to research area to location.
I read that it is good practise to put results in a table, with the coefficient, CIs and the P-Value. However I do not want the reams of tables this will generate (as the way to show significance with the OLR is by looking at all factors' P values rather than one for the whole group). Do you think it would be acceptable just to write whether there was or was not significant results for each likert outcome, elaborating further in a text passage for the factors that influenced the result (i.e. reporting the coefficient / CI and P).
Apologies I know this is a simple question I just wanted opinion on what is deemed acceptable. Many thanks.
Comment: I really like Garcia's (2021) chapter (Chapter 8) on OLR. I don't think that I can copy what he'd say here due to copyright, but if you are from the human sciences and if you have the chance, he details how to perform n' how to report it. Overall, he brings the coefficients into the text by "an ordinal regression was performed n' the X condition increases the probability of being more certain (b = , p < 0.05) and Y condition decreases this probability (b = , p < 0.05) so on" (179). He also brings a line plot with the mod's predictions (using predict()) for each condition, which I really liked!
Answer: Some journals will accept it, some won't.  When I review papers that just say whether variables were significant or not, I require that they be rewritten to include effect size.  It need not be "reams of tables" and, in nearly all cases, should not be.  You generally need one table for each regression. If you have many bivariate regressions it is often possible to combine them into one table, provided that you make it clear what you have done and why you have done it.


Prove that $f(x)=\frac x{e^x-1}$ for $x\neq 0$, $f(0)=1$, is $C^\infty$

Question: How to prove that $f : x \mapsto \frac{x}{\exp(x)-1}, \ x\neq 0$, and $1$ if $x=0$ is $\mathcal{C}^{\infty}(\mathbb{R})$.
For $x\neq 0$ , $f'(x)=\frac{\exp(x)-1-x\exp(x)}{(\exp(x)-1)^2}$, so we can extend $f'$ to $0$ taking : $f'(0)=-\frac{1}{2}$. Then we can conclude that $f \in \mathcal{C}^1(\mathbb{R})$.
Now maybe an induction could work but the calculation of the successive derivatives seems tricky.
Thanks in advance !
Comment: I guess there is a mistake in the function because it is not well defined at $x=1$.... maybe it is $f(x)=\frac{\exp(x)}{1-\exp(x)}$ ?
Comment: @DavidJaramillo Indeed it was a typo !
Answer: A possible approach is the following. Consider the function $g=1/f$, and use the Taylor expansion of the exponential function. The remark the derivatives of $g$ at zero are never equal to zero, and conclude that $f$ is infinitely often differentiable at zero.
Comment: Can we use a Taylor expansion in a neighborhood of $0$ for $g$ ?
Comment: It is indeed possible, but I realize that my approach requires some basic knowledge of complex analysis.
Comment: Where I saw the statement there were two questions : prove that $f \in \mathcal{C}^{\infty}(\mathbb{R})$ then prove that $f$ has a Taylor expansion in a neighborhood of $0$ (the convergence radius will be $\le 2\pi$ by the way)...
Answer: HINT.-The limit of $f(x)$ when $x\to0$ exists and is in fact equal to $1$ so one can well define $f(0)=1$ but the second derivative of $f(x)$ is equal to
$$e^x\left(x+\frac{2}{(e^x-1)^3}\right)$$ and the limit of $\dfrac{2e^x}{(e^x-1)^3}$ does not exists for $x\to0$ (we have $-\infty$ when $x\to0^-$ and $+\infty$ when $x\to0^-$)
Comment: I found $f''(x)=\frac{\exp(x)(\exp(x)(x-2)+x+2)}{(\exp(x)-1)^3}$ and the extension would be $f''(0)=\frac{1}{6}$...
Comment: Verify your calculation, maybe I am wrong. Anyway $f$ is not $\mathcal{C}^{\infty}(\mathbb{R})$ as you have proposed (I guess it is on $\mathbb R^+\setminus \{0\}$ but this is not important here).
Comment: According to the statement the first question is to prove that $f\in \mathcal{C}(\mathbb{R})$ then to prove that $f$ has a Taylor expansion in a neighborhood of $0$...


Multiple imputation for missing count data in a time series from a panel study

Question: I am trying to tackle a problem which deals with the imputation of missing data from a panel data study(Not sure if I am using 'panel data study' correctly - as I learned it today.) I have total death count data for years 2003 to 2009, all the months, male & female, for 8 different districts and for 4 age groups.
The dataframe looks something like this:
         District  Gender Year Month    AgeGroup TotalDeaths
         Northern    Male 2006    11        01-4           0
         Northern    Male 2006    11       05-14           1
         Northern    Male 2006    11         15+          83
         Northern    Male 2006    12           0           3
         Northern    Male 2006    12        01-4           0
         Northern    Male 2006    12       05-14           0
         Northern    Male 2006    12         15+         106
         Southern  Female 2003     1           0           6
         Southern  Female 2003     1        01-4           0
         Southern  Female 2003     1       05-14           3
         Southern  Female 2003     1         15+         136
         Southern  Female 2003     2           0           6
         Southern  Female 2003     2        01-4           0
         Southern  Female 2003     2       05-14           1
         Southern  Female 2003     2         15+         111
         Southern  Female 2003     3           0           2
         Southern  Female 2003     3        01-4           0
         Southern  Female 2003     3       05-14           1
         Southern  Female 2003     3         15+         141
         Southern  Female 2003     4           0           4

For the 10 months spread over 2007 and 2008 some of the total deaths from all districts were not recorded. I am trying to estimate these missing value through a multiple imputation method. Either using Generalized Linear Models or SARIMA models.
My biggest issue is the use of software and the coding. I asked a question on Stackoverflow, where I want to extract the data into smaller groups such as this:
         District  Gender Year Month    AgeGroup TotalDeaths
         Northern    Male 2003     1        01-4           0
         Northern    Male 2003     2        01-4           1
         Northern    Male 2003     3        01-4           0
         Northern    Male 2003     4        01-4           3
         Northern    Male 2003     5        01-4           4
         Northern    Male 2003     6        01-4           6
         Northern    Male 2003     7        01-4           5
         Northern    Male 2003     8        01-4           0
         Northern    Male 2003     9        01-4           1
         Northern    Male 2003    10        01-4           2
         Northern    Male 2003    11        01-4           0
         Northern    Male 2003    12        01-4           1
         Northern    Male 2004     1        01-4           1
         Northern    Male 2004     2        01-4           0

Going to
         Northern    Male 2006    11        01-4           0
         Northern    Male 2006    12        01-4           0

But someone suggested I should rather bring my question here - perhaps ask for a direction? Currently I am unable to enter this data as a proper time-series/panel study into R. My eventual aim is to use this data and the amelia2 package with its functions to impute for missing TotalDeaths for certain months in 2007 and 2008, where the data is missing.
Any help, how to do this and perhaps suggestions on how to tackle this problem would be gratefully appreciated.
If this helps, I am trying to follow a similar approach to what Clint Roberts did in his PhD Thesis.
EDIT:
After creating the 'time' and 'group' variable as suggested by @Matt:
> head(dat)
     District Gender Year Month AgeGroup Unnatural Natural Total time                    group
1 Khayelitsha Female 2001     1        0         0       6     6    1     Khayelitsha.Female.0
2 Khayelitsha Female 2001     1     01-4         1       3     4    1  Khayelitsha.Female.01-4
3 Khayelitsha Female 2001     1    05-14         0       0     0    1 Khayelitsha.Female.05-14
4 Khayelitsha Female 2001     1     15up         8      73    81    1  Khayelitsha.Female.15up
5 Khayelitsha Female 2001     2        0         2       9    11    2     Khayelitsha.Female.0
6 Khayelitsha Female 2001     2     01-4         0       2     2    2  Khayelitsha.Female.01-4

As you notice, there's actually further detail 'Natural' and 'Unnatural'.
Answer: You can use the Amelia package to impute the data (full disclosure: I am one of the authors of Amelia). The package vignette has an extended example of how to use it to impute missing data.
It seems as though you have units which are district-gender-ageGroup observed at the monthly level. First you create a factor variable for each type of unit (that is, one level for each district-gender-ageGroup). Let's call this group. Then, you would need a variable for time, which is probably the number of months since January 2003. Thus, this variable would be 13 in January of 2004. Call this variable time. Amelia will allow you to impute based on the time trends with the following commands:
library(Amelia)
a.out <- amelia(my.data, ts = "time", cs = "group", splinetime = 2, intercs = TRUE)

The ts and cs arguments simply denote the time and unit variables. The splinetime argument sets how flexible should time be used to impute the missing data. Here, a 2 means that the imputation will use a quadratic function of time, but higher values will be more flexible. The intercs argument here tells Amelia to use a separate time trend for each district-gender-ageGroup. This adds many parameters to the model, so if you run into trouble, you can set this to FALSE to try to debug.
In any event, this will get you imputations using the time information in your data. Since the missing data is bounded at zero, you can use the bounds argument to force imputations into those logical bounds.
EDIT: How to create group/time variables
The time variable might be the easiest to create, because you just need to count from 2002 (assuming that is the lowest year in your data):
my.data$time <- my.data$Month + 12 * (my.data$Year - 2002)

The group variable is slightly harder but a quick way to do it is using the paste command:
my.data$group <- with(my.data,
                      as.factor(paste(District, Gender, AgeGroup, sep = ".")))

With these variables created, you want to remove the original variables from the imputation. To do that you can use the idvars argument:
a.out <- amelia(my.data, ts = "time", cs = "group", splinetime = 2, intercs = TRUE,
                idvars = c("District", "Gender", "Month", "Year", "AgeGroup"))

Comment: About the error message: there was a typo in my answer. The `time` and `group` should be quoted in the call to `amelia`. For the bounds, you can use `Inf` or `-Inf` in the place of the upper bound to get a one-sided bound.
Comment: Thanks @Matt. Amelia imputes now - but not quite well for this set of data. Will have to look into other ways to impute. You  don't have any other recommendations? I'm first going to look at how imputation by regression is going to go.
Comment: Thank you so much for your response! I've been playing with `Amelia` for a bit but gave up (prior to this). I've previously seen the vignette (but lost it somehow!) Just had a quick look at it and will throughly go through it. One problem I now have is that I'm uncertain on how to create the `group` and `time` variables. (I tried creating them for time series analysis/forecasting, but got a loop around it.) I'm sure it's in the vigette - so I'll get back to you if I'm struggling. Thanks again :)
Comment: Glad it's useful. I added an example of how to create those variables. Hope that helps.
Comment: Thanks for the examples @Matt. For some strange reason it gave me an error when I used "ts=time" and "cs=group". I just replace "time" and "group" by the respective column number and then it worked.

`a.out=amelia(dat,ts=time,cs=group,splinetime=2,intercs=TRUE,idvars=c("District","Gender","Month","Year","AgeGroup"),bounds=bds)
Amelia Error Code:  6
 The 'ts' variable  is out of the range of
 possible column numbers or is not an integer.`
Comment: For the bounds I followed the vignette and created bounds using: `bds <- matrix(c(6, 7, 8,0, 0,0, 500, 500,500), nrow = 3, ncol = 3)`
I basically just chose 500 as a random upper limit. I did try just to not give a third column, but `Amelia` warned that it requires the third one. Is there perhaps a way to just specific a lower limit?
Comment: I added an example of the data in the question - perhaps if this caused the Error? But I doubt it.


LMDB increase map_size

Question: I was working with LMDB++ (the C++ wrapper for LMDB) and I got this error:
terminate called after throwing an instance of 'lmdb::map_full_error'
    what():  mdb_put: MDB_MAP_FULL: Environment mapsize limit reached

Some googling told me that the default map_size is set low in LMDB. How do I go about increasing map_size?
Answer: The default LMDB map size is 10 MiB, which is indeed too small for most uses.
To set the LMDB map size using the C++ wrapper, you ought to call lmdb::env#set_mapsize() right after creating your LMDB environment and prior to opening the environment or creating your transaction.
Here's a basic example that increases the map size to 1 GiB:
/* Create and open the LMDB environment: */
auto env = lmdb::env::create();
env.set_mapsize(1UL * 1024UL * 1024UL * 1024UL);
env.open("./example.mdb", 0, 0664);

If you are calculating a large map size as in the above example, take care to include the appropriate type suffix (UL or ULL) on your integer literals, or else you may encounter silent integer overflow and be left wondering why the map size did not increase to what you expected.
See also the documentation for LMDB's underlying C function mdb_env_set_mapsize() for the authoritative word on how the map size works.
Comment: is it possible to limit the size of entries instead of the memory size?

LMDB increase map_size


Multi-file C++ compilation

Question: (hopefully) quick question that I can't find the answer to:
I have been given a brief assignment in C++. We are to write a 3-file program. There will be a function file, a header file, and a driver file. Here's what I've got so far:
Header (test.h):
#include <iostream>
using namespace std;
#ifndef TEST_H
#define TEST_H

int foo (int bar);

#endif

Function (test.cpp):
#include <iostream>
#include "test.h"
using namespace std;

int foo (int bar){
    bar++;
}

Driver (drive.cpp):
#include <iostream>
#include "test.h"
using namespace std;

int main(){
    int x = foo(2);
    cout << x << endl;
    return x;
}

When I try to compile drive.cpp, I get the following error:
drive.cpp:(.text+0xe): undefined reference to `foo(int)'

So...what am I doing wrong?
Comment: For the love of Stroustrup, don't use `using namespace ...` in a header.
Comment: `#include ` should probably be `#include "test.h"`
Comment: test.h and test.cpp have no reason to `#include `.
Answer: For a small project like this, simply compile all .cpp files at once:
g++ main.cpp driver.cpp

For a larger project, you separate the compile and link steps:
compile:
g++ -c main.cpp -o main.o
g++ -c driver.cpp -o driver.o

link:
g++ main.o driver.o

Or rather, you'd have a makefile or IDE do this for you.
Answer: In drive.cpp, instead of
#include <test.h>

make it
#include "test.h"

This is the variant of #include syntax that is used for header files of your own program (not system header files).  When you use this version the preprocessor searches for include files in the following order:

In the same directory as the file that contains the #include statement.
In the directories of any previously opened include files in the reverse order in which they were opened. The search starts from the directory of the include file that was opened last and continues through the directory of the include file that was opened first.
Answer: You need to do one of two things:
Compile all the files at once
# replace 'driver.exe' with what you want your executable called
g++ -Wall -ggdb -o driver.exe main.cpp driver.cpp

Compile all the files to object files and then link the object files:
# again, replace 'driver.exe' with what you want your executable called
g++ -Wall -ggdb -o main.o -c main.cpp
g++ -Wall -ggdb -o driver.o -c driver.cpp
g++ -Wall -ggdb -o driver.exe main.o driver.o

As a side note, you should probably change
#include <test.h>

to
#include "test.h"

and putting "using namespace std;" in a header file is going to cause you copious grief later on.
Answer: in test.cpp, change the return line to this:
return bar++;

Multi-file C++ compilation


Salvar arquivo no banco MySql usando ajax e função do php

Question: Preciso salvar arquivos que eu ja consigo selecionar em um modal usando uma função js.
Abaixo segue o html do modal

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

Selecione o arquivo

                    <form method="post" name="ajax_form" id="ajax_form">
                        Arquivo

                                    Selecione… <input type="file" id="file_arquivo" accept="file_extension|image/*" name="file_arquivo" style="display: none;" >

                            <input type="text" class="form-control" readonly>

                        <input id="acao" name="acao" value="salva_arquivo" type="hidden" />
                        <input id="ex_users_arquivo" name="ex_users_arquivo" type="hidden" />
                    </form>

                         Try selecting one or more files and watch the feedback
                     -->

                        "/>

                    Cancelar
                    Alterar

                <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Cancelar</button>
                <button type="button" class="btn btn-primary" id="btn_modal_salvar_arquivo">Salvar</button>

                    ×
                Confirmação

                Tem certeza que deseja sair desta pagina? Todos os dados não salvos seram perdidos

                Cancelar
                Confirmar

Answer: Não entendi muito bem, você deseja enviar o formulário via ajax?
Para enviar via ajax é simples, você pode utilizar esse código:
jQuery("#ajax_form").submit(function(){
  var dados = new FormData(this);
  var url = "URL QUE RECEBE OS DADOS DO FORM";
  $.ajax({
      url: url,
      type: 'POST',
      dataType: 'JSON',
      data:  dados,
      mimeType:"multipart/form-data",
      contentType: false,
      cache: false,
      processData:false,
      success: function(data)
      {
         alert("Enviado com sucesso");
      }
  });

  return false;
});

Pronto com esse código assim que o formulário for submetido ele chama essa função que envia os dados


Contact form - leaving the form and resuming it later

Question: Is it possible to have a contact form in drupal, which you can save, and resume later?
Answer: Yes, you can build a contact form with the Webform module and use its "Save Draft" feature.


Better methodologies to make causal recommendations from correlated data?

Question: I work as a data scientist at a SAAS company. We have an outcome variable, Y, that we consider "success" for our customers. We have a bunch of additional outcome variables X1, X2, X3 that come chronologically before Y and are highly correlated with Y. The goal is to identify which Xs to prioritize and develop interventions for (i.e. advertise those features to increase adoption), with the goal of increasing Y.
The relationship between the Xs and Y is not clear. While there may be some causal element (doing X causes Y), a more reasonable model might be a latent structure, where some unobserved Z causes X and Y to go up in parallel.
The proposed approach has been to just fit some model to measure the correlation between the Xs and Y (logistic regression, random forest), and prioritize the Xs that most strongly correlate with Y as the variables to create interventions for. I worry this will waste a lot of time and effort chasing correlations that will have no impact on on Y, but short of setting up experiments (which there's no appetite for), I can't think of a better analytic method to make recommendations about the importance of various Xs. How would you approach this problem?
Answer: I guess one thing to think about is why you think the correlations between X and Y won't be causal, in the sense that manipulating X wouldn't lead to increases in Y. The most common case would be confounding: that an unobserved variable is a cause of both X and Y leading you to see a spurious relationship.
If that's the case there are two main strategies. If you can think of what U might be and can measure it then (with some assumptions) you could include this in your model and be more confident the prediction from X to Y is causal.
If that's not possible, another strategy is to think of a third variable, Z, which you think predicts X, but does NOT predict Y directly.  So a causal diagram would look like
Z -> X -> Y
U -> X
U -> Y

If you can find a variable Z that satisfies this condition (and it's really important that Z doesn't have a direct relation to Y, and also isn't related to U) then you can use instrumental variable methods to get a causal method for X on Y. Another name for this is a natural experiment.
One classic example in economics is the attempt to estimate the effect of army service on earnings. There are lots of potential confounders of this relationship, but during the Vietnam war army service was determined by lottery, and (from memory) the first letter of your surname was used to determine how early you got called up. See Angrist and Imbens' Mostly Harmless Econometrics for this and other nice examples. Their treatment of fitting these models is quite focussed on an approach called, 2-stage-least squares, which is perhaps slightly older and less flexible than using path analysis (e.g. with lavaan in R) but the principles are the same.
It's hard to say more without knowing the substantive area, but another excellent introduction to this field is Judea Pearl's Book of Why. It's a popularisation of his much denser book, Causality which has been very influential in the field, specifically in the use of causal diagrams to determine whether and how to make causal inferences from observational data.


the discrete family of closed sets cover

Question: When I study on the proof of every paracompact space is collectionwise normal, I have problem.
Let $X$ be a paracompact space and $\{F_s\}_s\in S$ be a discrete family of closed subsets of $X$. Then for each $x\in X$, we can choose a neighbourhood $H_x$ of the point $x$ whose closure meets at most one set $F_s$. But how? we don't know the family of closed discrete sets covers $X$? How can we say for each $x$?
Answer: Assuming that the space is Hausdorff, it's just the definition of discrete collection.

A collection $\mathscr{D}$ of subsets of a space $X$ is discrete if and only if for each $x\in X$ there is an open nbhd $U_x$ of $x$ such that $U_x$ meets at most one member of $\mathscr{D}$.

Now use the fact that a Hausdorff paracompact space is regular to conclude that there is an open set $V_x$ such that $x\in V_x\subseteq\operatorname{cl}V_x\subseteq U_x$.
Comment: No, I mean that how can you say $X$ is a discrete space. You can just say for every $x\in D\in \mathcal{D}$,there exists a neighbourhood $U_x$.....
Comment: @user89330: I don't understand: no one is saying that $X$ is a discrete space.
Comment: I mean that every point of $X$ is isolated point? No.   You should just say for every point of $D\in \mathcal {D}$ is isolated point.
Comment: @user89330: No: the elements of $\mathscr{D}$ need not be points. I suspect that you don't understand what a discrete family is. $\{[2n,2n+1]:n\in\Bbb Z\}$ is a discrete family of closed sets in $\Bbb R$, because for each $x\in\Bbb R$ the open interval $\left(x-\frac14,x+\frac14\right)$ meets at most one of those closed intervals.
Comment: For every $D\in \mathcal{D}$ is discrete subset in $X$. So, every point of $D$ is isolated point in $X$. In the proof, we can find a cover of $X$ which is important in the proof. my question is every point of $x\in X$ isolated point? otherwise, how can we cover $X$
Comment: @user89330: No, that is **not** what it means for $\mathscr{D}$ to be a discrete collection. The members of $\mathscr{D}$ do **not** have to be discrete. And $\mathscr{D}$ is **not** in general a cover of the space.
Comment: So, ı could not understand the proof. could you explain how we can find a cover of $X$, if possible
Comment: @user89330: Hold on for a couple of minutes while I finish answering another question.
Comment: ohh, I see. Because of the definition of discrete family, we can find an open neighbourhood for each $x\in X$.I think I mixed the definition of the discrete sets and the discrete family.These are different.
Comment: thanks. one more question, if we have a countable point finite open family( covers $X$), can we find a development for $X$?
Comment: @user89330: Not in general, no: $\{X\}$ is always a countable point-finite open cover of $X$. Did you mean a stronger condition?
Comment: I think that if I have a countable point finite cover, for each $x$, I can find  finite basic set $B_i$ in any base, which contained  $x\in X$. The union of the basic sets  can be base. by using this base can we find a development?
Comment: @user89330: It's harder than that. Let $Y$ be any space that is not developable, and let $X=\Bbb N\times Y$, where $\Bbb N$ has the discrete topology. Then $\{\{n\}\times Y:n\in\Bbb N\}$ is a point-finite open cover of $X$, but $X$ is not developable.
Comment: I mean that, by using base can I construct a development in general?
Comment: what is the most comman way to construct a development? Could you advise any reference book?
Comment: @user89330: I'm still really not sure just what construction you have in mind to get the development, or what you're assuming about the space. Are you assuming that the space is metacompact (every open cover has a point-finite open refinement)?
Comment: No, I just wonder the relation with the base and the development.
Comment: @user89330: I don't know of any good book treatment of the topic. You might try searching the literature on the so-called *normal Moore space conjecture*: a Moore space is a $T_3$ developable space, so most of the spaces that you'll encounter are developable.
Comment: @user89330: To begin with, every developable space is first countable, so you need that right away. But developability is really a pretty strong property, and there aren't any simple ways to get it just starting with first countability. // You're very welcome.


Utilizar de Hash, sem adicionar uma cadeia Salt a senha, pode tornar a senha vulnerável?

Question: A pouco tempo precisava descobrir qual hash havia sido utilizado para salvar a senhas no banco de forma que as mesmas não fossem salvas direto de acordo com o que o usuário lança no momento de seu cadastro. Pesquisando encontrei o seguinte site, que se você sabe a senha inicial você consegue ver os resultados que as hash's vão gerar em cima dessa senha. isso me pareceu de certa forma vulnerável pois assim que eu descobri qual Hash havia sido utilizada, e como eu tenho acesso acesso ao banco onde as senha ficam salvas, bastou que eu comparasse o que estava armazenado no banco com o que o site me gerava e assim descobri qual Hash havia sido utilizado.
Minha questão é:
Até onde utilizar uma cadeia salt na senha original auxilia para que a senha seja ainda mais segura, pois seria necessário além de acessar o banco e ter acesso as senhas seria necessário saber qual cadeia salt foi utilizada, tornando assim mais difícil descobrir qual a senha original cadastrada pelos usuários.
Link para conteúdo sobre Salt
Comment: É uma boa pergunta esta sua. Creio que todos os pontos levantados já estejam respondidos com detalhes em [Como fazer hash de senhas de forma segura?](https://pt.stackoverflow.com/questions/2402/como-fazer-hash-de-senhas-de-forma-segura),
Comment: Uai, você mesmo já respondeu sua duvida rs => **necessário além de acessar o banco e ter acesso as senhas seria necessário saber qual cadeia salt foi utilizada**
Comment: Minha questão é, se realmente faz diferença utilizar uma cadeia Salt em cima da senha original antes de aplicar o Hash, pois hoje em dia é aplicado uma hash em cima da senha inicial cadastrada e já é salva no banco direto, isso pode ser algo vulnerável
Comment: Qual algoritmo está usando? SHA1? SHA512?
Comment: @PauloSérgioDuff SHA 256
Answer: Não existe um ponto em que seja totalmente seguro usar um algoritmo de hash.
Um problema é o ataque de dicionário em cima de hashes. Serviços como https://crackstation.net/ podem facilmente quebrar um hash como, por exemplo, o SHA256. Restringir que o usuário use senhas complexas para driblar isso (com caracteres, números, letras maiúsculas...) pode não ser tão fácil, visto que a maioria dos problemas de segurança vem por fatores humanos, como o phishing, que consegue uma taxa de 45% de conversão segundo a empresa de segurança ReturnPath.O que te passa uma responsabilidade maior na hora da segurança. Um outro problema ao usar SHA256, deixa vulnerável ao ataque por processamento por força bruta (isso vale para algoritmos ultrapassados como MD5 e SHA1). Portanto, é 'falsa' a ideia de que usar salt deixa o algoritmo mais seguro por si só (no sentido de existir opção mais segura). No caso do seu problema, um SQL injection poderia revelar informações do banco de dados para comparação do salt.
Isso não quer dizer que não existem opções. Algumas delas:

1) Forçar um cadastro de senhas complexas. Se o escopo da aplicação
permitir.
2) Introduzir token dentro do hash (caso não seja possível a opção
1).
3) Usar bcrypt. O algoritmo bluefish permite a criação de parâmetro
de processamento para aumentar a complexidade do hash.


Head Position in Swimming

Question: I am trying to fix my head and hip positioning by looking down instead of forward and pressing my chest and / or head down.
It's kind of awkward to press your chest down while also looking down and keeping your head at the surface of the water. My friend tells me that I was swimming with my whole body about an inch below the surface. But I'm pretty sure it was faster.
In some videos, Phelps looks like he's looking pretty far forward, so I tried to look a little forward and press only my chest. That felt like it really worked to get my hips on the surface and my head at the top, but I was told that my head was still underwater and it also didn't feel quite as fast. It was also hard to press the chest without feeling like I was looking way too far forward.
I'm sure I'll get used to this, but when I press my chest down, I feel like I have so much less breath. I'm a sprinter, so it's less of a big deal, but I'm hoping that goes away eventually or is at least normal?
Some of the later positions I've tried for head and hip position have made my upper lats through my shoulders through the top of the arm ache/hurt, and this aching is accentuated when I switch to a kickboard for kicking sets. I think I've become lazy in my arm pulls as I work on other technical issues (which may be contributing to this), but part of it I think is that my arm is floating above my head and body so when I rotate and pull the arm, it doesn't have as much power.
Thorpe complicates the whole issue because apparently he lets his hips drop a little so he can use his legs to power him along better.
What can I do to alleviate these issues and how can I get a better head and hip position for sprinting?
Answer: @ Millie Smith.. while doing front crawl aka Free style. Don't look forward it will drop your hips down and during breathe recovery you'll find yourself struggling to come up to water surface to breathe. Instead keep your Head + Back + Hip linear.And movement of these must be same and synchronized. Make sure these 3 make a linear line rather than an arc or bow like posture. This will keep your body more closer to surface.
      As you described above you are more bit faster while keeping your body under water. Obviously you are right about this. But you are a sprinter not under water swimmer so definitely you will be needing more breathes. And breathes will be easy only when your body is more closer to water surface. One more thing keep your body relax and full of air by continuous breathing.. automatically you'll be on water surface
Hope this will help...
Answer: Keeping your body below the surface is quicker than trying to plow through the water. Think of it as in submarine vs. a speed boat. Submarine glides through the water nice and smooth, but a speed boat has this huge wave at the front as it tries to go forward. So, in swimming, eliminating or minimizing this bow wave is the key to swim faster (in other words - reducing drag).
You should feel like you are swimming downhill. It feels awkward, but it is the way to go. However, everyone is a bit different, so if you feel your feet are kicking air, you will need to ease off on the pressure of your chest and head into the water.
Regarding the use of the kickboard, you are better off kicking on your sides while looking down and maintaining your hips at the surface.
Here is a good article that explains it well: http://blog.swimator.com/2011/01/your-body-as-tree-log-correct-head.html

Head Position in Swimming


How to show that this equation has 2 real valued solution?

Question: The real-valued solutions of  the equation $|dy/dx|+|y|+a=0$ are needed to be found in different cases for $a$. So I took the case 1st when $a=0$ then $y(x)=0$ is the only real-valued function and then I took the case 2nd when $a>0$ then there is no real-valued function. But I could not find the number of the solution when $a<0$.
In the third case, for the solution to be real-valued, $y$ should be lesser than $a$ so I am wondering; can there be two real-valued functions be determined; $y(x)=0$ and $|y|<a$.
Please help.
Thanks in advance.
Answer: Dispensing of the absolute values gives us four possibilities
$$dy/dx,y\geq 0$$
$$dy/dx\geq 0,y<0$$
$$dy/dx<0,y\geq 0$$
$$dy/dx,y<0$$
This gives us four differential equations
$$\frac{dy}{dx}=y-a$$
$$\frac{dy}{dx}=-y-a$$
$$\frac{dy}{dx}=y+a$$
$$\frac{dy}{dx}=-y+a$$
This gives us solutions of
$$ce^x+a$$
$$ce^{-x}+a$$
$$ce^{x}-a$$
$$ce^{-x}-a$$
where $c$ is an arbitrary constant.


Quick Ratio Test Question

Question: So I was given the following prompt:
"Test the convergence or divergence of the following series."
$\sum_{n=0}^{\infty}(\frac{n!}{2*5*8*...*(3n+2)})$
I guess I'm a bit confused about what the limit would look like in this specific context. I understand that the ratio test needs to be used here and that the limit might look like the following: $\lim_{x \to \infty}\frac{\frac{(n+1)!}{(3n+3)}}{\frac{n!}{3n+2}}$, but I guess I'm a bit confused about how to find this limit. Any help would be appreciated!
Answer: \begin{equation}
\begin{array}{l}
\lim _{n \rightarrow \infty}\left|\frac{\frac{(n+1) !}{3(n+1)+2}}{\frac{n !}{3 n+2}}\right| \\
\begin{array}{l}
\lim _{n \rightarrow \infty} \mid \frac{(n+1) !(3 n+2)}{(3 n+5)(n !)} \\
\lim _{n \rightarrow \infty}\left|\frac{n(3 n+2)}{(3 n+5)}\right|
\end{array} \mid \\
\lim _{n \rightarrow \infty}\left|\frac{3 n^{2}+2 n}{3 n+5}\right|
\end{array}
\end{equation}
This limit diverges.

Quick Ratio Test Question


Knapsack Problem with Multiple Properties

Question: Problem Description
I have many examples (say $N$) to choose from to train my machine learning model. However, I could only select $n \ll N$ based on a set of $K$ attributes $\{a_1, a_2, \cdots, a_k\}$ already measured for the dataset.
Now I would like to find these $n$ samples so that the sum of the $K$ columns is maximized while the weights are as uniform as possible.
What I Tried
This looks like a knapsack problem but with multiple attributes. However, direct Google search does not seem to give me a lot of relevant results as I am looking for an existing software package that could solve this problem (or perhaps its relaxed version).
Numerical Example
Suppose I would like to select $n=3$ samples from a dataset of $N=5$ samples and $K=4$ attributes.
<code>     A    B    C    D
0  0.7  0.4  0.8  0.5
1  0.7  1.0  0.3  0.7
2  0.8  0.5  0.4  0.8
3  0.8  0.3  0.6  0.5
4  0.2  0.8  0.6  0.2
</code>
which is generated with the code below:
<code>import string
import itertools

import numpy as np
import pandas as pd

np.random.seed(42)

N = 5
n = 3
K = 4

measures = np.linspace(0.1, 1, 10)
df = pd.DataFrame(
    data=np.random.choice(measures, size=(N, K)),
    columns=list(string.ascii_uppercase)[:K],
)
</code>
By enumerating all cases, I obtain a table that looks like following:

choice
A
B
C
D

0
(0, 1, 2)
2.2
1.9
1.5
2

1
(0, 1, 3)
2.2
1.7
1.7
1.7

2
(0, 1, 4)
1.6
2.2
1.7
1.4

3
(0, 2, 3)
2.3
1.2
1.8
1.8

4
(0, 2, 4)
1.7
1.7
1.8
1.5

5
(0, 3, 4)
1.7
1.5
2
1.2

6
(1, 2, 3)
2.3
1.8
1.3
2

7
(1, 2, 4)
1.7
2.3
1.3
1.7

8
(1, 3, 4)
1.7
2.1
1.5
1.4

9
(2, 3, 4)
1.8
1.6
1.6
1.5

Then I would like the selected samples to best trade off the two constraints:

The sum of all $K$ columns are large enough.
The entropy of weights is large enough: the more uniform the "weights", the better.

So by these considerations, according to the plot below, I should choose samples indexed 0, 1, 2 or 0, 2, 4.
Comment: What does it mean to maximize some measure of each column?  Maximin?  An explicit numerical example might help clarify what you want.
Comment: It sounds like you have one constraint and two objectives and you want to find the Pareto frontier.
Comment: @RobPratt Thank you for your suggestion. I sorted my head a little bit and I admit I was not specific enough. I added the "Numerical Example" section for your reference.
Comment: You can formulate this problem as MILP
Comment: @RobPratt Yes, that is correct.
Comment: Crossposted to OR.SE: [Knapsack Problem with Multiple Properties](https://or.stackexchange.com/q/10614/491)
Answer: Let $x_i$ the indicator of choosing the sample $i$, $a_{i,k}$ the measure of the sample $i$ for the attribute $k$. Isn't your problem equivalent to:
$$\min \sum_{i=1}^{N} \left(\sum_{k=1}^{K} a_{i, k}\left(1-\log\left(a_{i,k}\right)\right)\right)x_i : \sum_{i=1}^N x_i = n$$
Comment: You also need to consider the other objective of maximizing the sum.
Comment: You can use Gurobi to solve it directly.
Comment: Thank you for your answer! This looks right to me. Can you also provide a numerical simulation that solves my toy example (I do not know much about numerical optimization software though I do have Gurobi installed)?


Any limitations of app launchEvent

Question: I've got
app.on(app.launchEvent, function (args)
{
        alert({title: "ERROR", message: "test", okButtonText: "Close"});
}
The alert doesn't display.
Are there limitations as to what can be done within that callback.
Looks like the Android context is not set up at this time and causes problems with other plug-ins also.
Answer: lauchEvent must be defined before application.start(...); in app.js file, if it's after start line it won't fire and same if it's inside other files it won't fire as that lauchEvent is already over or quite possible that dialog is skipped too as it's discarded while moving over to pages
Comment: It's before application.start();
Comment: so only explanation is that dialog is fired and works and is closed at same time because of navigation to mainModule, as dialog don't stop execution of code so code after that still continue

Any limitations of app launchEvent


How to handle nulls in IEqualityComparer?

Question: The following method is from XUnit Assert class:
public static void Equal<T>(IEnumerable<T> expected, IEnumerable<T> actual, IEqualityComparer<T> comparer);

And I am using it as:
IEnumerable<Decimal?> x = getXValues();
IEnumerable<Decimal?> y = getYValues();

Assert.Equal(x, y, new DecimalToleranceEqualityComparer(0.01m));

I am using an IEqualityComparer because is fine to consider 2.526 equal to 2.524.
I get an error because DecimalToleranceEqualityComparer is only for Decimal ...
x and y might have null values. DecimalToleranceEqualityComparer is:
  public class DecimalToleranceEqualityComparer : IEqualityComparer<Decimal> {

    private readonly Decimal _tolerance;

    public DecimalToleranceEqualityComparer(Decimal tolerance) {

      _tolerance = tolerance;

    }

    public Boolean Equals(Decimal x, Decimal y) {

      return Math.Abs(x - y) <= _tolerance;

    }

    public Int32 GetHashCode(Decimal obj) {

      return obj.GetHashCode();

    }

  }

I suppose if 2 values are nulls they should be consider equal ...
How to change the IEqualityComparer so that it handles nulls?
Comment: `IEqualityComparer`?
Answer: This code works for me. The real trick is in the imlementation of the Equals method. Also keep in mind the null check in the GetHashCode.
static void Main(string[] args)
{
    IEnumerable<Decimal?> x = new List<Decimal?> { 1.51m, 3, null };
    IEnumerable<Decimal?> y = new List<Decimal?> { 1.6m, 3, null };

    Assert.Equal(x, y, new DecimalToleranceEqualityComparer(0.1m));
}

public class DecimalToleranceEqualityComparer : IEqualityComparer<Decimal?>
{
    private readonly Decimal _tolerance;

    public DecimalToleranceEqualityComparer(Decimal tolerance)
    {

        _tolerance = tolerance;

    }

    public Boolean Equals(Decimal? x, Decimal? y)
    {
        if (!x.HasValue && !y.HasValue)
        {
            // Both null -> they are equal
            return true;
        }
        else if (!x.HasValue || !y.HasValue)
        {
            // One is null, other is not null -> not equal
            return false;
        }
        else
        {
            // both have values -> run the actual comparison
            return Math.Abs(x.Value - y.Value) <= _tolerance;
        }
    }

    public Int32 GetHashCode(Decimal? obj)
    {
        if (obj.HasValue)
        {
            return obj.GetHashCode();
        }
        else
        {
            // Here decide what you need
            return string.Empty.GetHashCode();
        }
    }
}

Comment: I was going to upvote until that `string.Empty.GetHashCode()` appeared! Just use `return obj.GetHashCode()`, no need to check for `null`. `GetHashCode` is defined by `Nullable`. Although that isn't technically correct, as objects which compare equal will have different hash codes, which is against the rules. I think the only technically correct implementation of `GetHashCode()` would be to return 0 always, or throw `NotSupportedException`
Answer: One option that comes to mind could be implementing new equality comparer for nullable decimal type IEqualityComparer<decimal?> which could use your existing DecimalToleranceEqualityComparer internally. Something like
public Boolean Equals(Decimal? x, Decimal? y) {
    return (x.HasValue && y.HasValue)?
     _decimalToleranceEqualityComparer.Equals(x.Value,y.Value)
    : x == y;
}

Answer: You are supplying a list of Nullable<decimal>'s and your IEqualityComparer is expecting a list of Decimal's.
With a rewrite like this you should be fine:
public class DecimalToleranceEqualityComparer : IEqualityComparer<decimal?>
{
    private readonly decimal _tolerance;

    public DecimalToleranceEqualityComparer(decimal tolerance)
    {
        _tolerance = tolerance;
    }

    public bool Equals(decimal? x, decimal? y)
    {
        if (!x.HasValue && !y.HasValue) return true;
        if (!x.HasValue || !y.HasValue) return false;

        return Math.Abs(x.Value - y.Value) <= _tolerance;
    }

    public int GetHashCode(decimal? obj)
    {
        return obj.GetHashCode();
    }
}


Find all $p$ primes such that $-8$ is quadratic residue modulo $p$

Question: I need help with finding all $p$ primes such that $-8$ is quadratic residue modulo $p$.
I know that :
$(\frac{-8}{p})=(\frac{-1}{p})(\frac{8}{p})=(\frac{-1}{p})(\frac{2^2}{p})(\frac{2}{p})=(\frac{-1}{p})(\frac{2}{p})=(-1)^{\frac{p-1}{2}}
(-1)^{\frac{p^2-1}{8}}$
But I'm not sure how to continue, I wanted to use CRT but 4 and 8 are not coprime....
How can I continue from here?
Answer: Hint 1: Show that $(-1/p) = 1$ if and only if $p \equiv 1 \pmod{4}$ (consider using Euler's Criterion).
Hint 2: Show that for $p \equiv 1 \pmod{4}$, $2^{(p - 1)/2} \equiv (-1)^{(p - 1)/4} \pmod{p}$, and thus $(2/p) \equiv (-1)^{(p - 1)/4} \pmod{p}$ by Euler's Criterion. Similarly, for $p \equiv 3 \pmod{4}$, show that $2^{(p - 1)/2} \equiv (-1)^{(p + 1)/4} \pmod{p}$, and thus $(2/p) \equiv (-1)^{(p + 1)/4} \pmod{p}$. One way to do this is start with $2^{(p - 1)/2} \left(\frac{p - 1}{2} \right)!$ on one side of an equivalence modulo $p$, expand the factorial term by term, and show that the other side evaluates to $(-1)^{(p - 1)/4} \left(\frac{p - 1}{2} \right)!$ and $(-1)^{(p + 1)/4} \left(\frac{p - 1}{2} \right)!$ for $p \equiv 1 \pmod{4}$ and $p \equiv 3 \pmod{4}$, respectively. (Gauss's Lemma is also possible for this part).
Hint 3: If you complete both the above steps, you will have classifications of primes $p$ for which $-1$ and $2$ are quadratic residues or nonresidues modulo $p$. This gives you a classification of $p$ where $-8$ is a quadratic residue, since as per your equation, we consider the case where $(-8/p) = (-1/p)(2/p) = 1$, or $(-1/p) = (2/p) = \pm 1$.
Also: if the moduli in a system of congruences are not relatively prime, only consider the cases where the congruences are consistent with each other. For example, if we have the system $x \equiv 1 \pmod{4}$ and $x \equiv 5 \pmod{8}$, the second congruence is a stronger version of the first (since $x = 8k + 5 = 4(2k + 1) + 1 \equiv 1 \pmod{4}$). On the other hand, the system $x \equiv 1 \pmod{4}$ and $x \equiv 3 \pmod{8}$ is inconsistent and not possible.
Comment: So the answers will be - $p= 5 (mod 8) , p=3 (mod 8)$?
Comment: Sorry, I have actually made an error in my answer; please see the edit to Hint 2. $p \equiv 3 \pmod{8}$ is correct, but $p \equiv 5 \pmod{8}$ is not since $2$ is a non-residue in that case. Though, your answer being wrong may be due to my misinformation. Apologies for that.


Repeating text field on user profile

Question: In the user profiles, I would like to have an education field grouping. In this grouping I'd like to have these text fields.

Degree: BS/BA, MA/MS, PhD, Post Doc, etc
University
Year Graduated
Area of Study

Now, my users will have multiple degrees and such.
Can I create a "repeating" group of these four fields from 0 to infinity?
Comment: possible duplicate of [multiple Value of group of fields in CCK](http://drupal.stackexchange.com/questions/19578/multiple-value-of-group-of-fields-in-cck)
Answer: If you're working in Drupal 7, check out the Field Groups Module.

Fieldgroup will, as the name implies, group fields together. All
  fieldable entities will have the possibility to add groups to wrap
  their fields together. Fieldgroup comes with default HTML wrappers
  like vertical tabs, horizontal tabs, accordions, fieldsets or div
  wrappers.

If you're on Drupal 6, you want the MultiGroup module, which is a part of the 3.x branch of CCK.
Answer: Field collection should be a good way to do it.

Repeating text field on user profile


What does this three-number notation mean in football?

Question: What does 0-0-1 and 1-0-0 mean in this notation for two teams at a tournament?

Germany (0-0-1, 0 points) vs. Sweden (1-0-0, 3 points)
Answer: In association football, people usually denote first number of wins, then number of draws, and then number of losses.
So, in this case it means 0 wins, 0 draws, 1 loss for Germany and 1 win, 0 draws, 0 losses for Sweden.


Selecting Substring SQL

Question: I need to select a substring that is found between (). The starting and ending position will vary, as well as the length of the substring. I have had moderate success with the following but not 100%.
It will work for some values but not for others, it return blanks and will also change the values capitalization format, in other words if value is 'TEST' it will display as 'Test'.
SELECT SUBSTRING(columnName, CHARINDEX('(', LEN(columnName)),
CHARINDEX(')', columnName) - CHARINDEX('(',columnName)) AS INPUT
FROM tableName

Update There is only 1 set of parentheses ()
Comment: There's no way that query will change the case of the substring, can you provide an example?
Comment: So can you clarify - what problem have you faced with your query? And how is it concerned to character case changing?
Comment: The character case is the least of my concerns. My biggest concern is that this query will select the correct substring between () for some values but for other it will completely miss.
Comment: What 'others'? Provide examples of what it's missing. The more we guess, the more chance we'll get it wrong.
Answer: This will work provided you only have a single occurence of ( and ):
SELECT
    SUBSTRING(columnName,
              CHARINDEX('(', columnName)+1,
              CHARINDEX(')', columnName) - CHARINDEX('(', columnName)-1)
FROM tableName

If you have values that do not have any (...) content, add this where clause:
WHERE    CHARINDEX('(', columnName) > 0 AND
         CHARINDEX(')', columnName) > CHARINDEX('(', columnName)

Comment: This query gives me the following error:
Invalid length parameter passed to the LEFT or SUBSTRING function.
Comment: Then not all your data has a `(....)` value. I've added a `WHERE` clause to cope with that.
Answer: To account for no, nested or incomplete ()
;with t(f) as (
    select 'aaa(bbb)ccc' union
    select 'aaa(bbbccc' union
    select 'aaabbb)ccc' union
    select 'aaa()ccc' union
    select '(aaa(?))ccc'
)

select f,
case when patindex('%(%)%', f) > 0
    then substring(f, charindex('(', f ) + 1, (len(f) - charindex(')', reverse(f))) - charindex('(', f ))
    else ''
end
from t

>>

f             (No column name)
aaa()ccc
aaa(bbb)ccc   bbb
(aaa(?))ccc   aaa(?)
aaa(bbbccc
aaabbb)ccc

Answer: In Postgres, you can do this using POSIX regular expression capture:
=> select substring('This (might) work' from '[(](.*)[)]');
 substring
-----------
 might

It appears SQL server does offer regexp support, but I'm not familiar with it and I don't have a platform to run a test case.  This particular example is tricky because you have to get the quoting of the delimiters () right.
Comment: Not sure this is an answer, there's nothing like that in SQL Server!
Comment: REGEX is only available when using a CLR based proc (i.e. a stored proc written in, for example, C#), not something I would recommend in this case.

Selecting Substring SQL


From Arraylist to Array

Question: I want to know if it is safe/advisable to convert from ArrayList to Array?
I have a text file with each line a string:
1236
1233
4566
4568
....

I want to read them into array list and then i convert it to Array. Is it advisable/legal to do that?
thanks
Comment: You *can*, but you haven't given us nearly enough information to tell you whether it's a good idea or not.
Comment: ArrayLists's are fine.  The only reason I can see for converting to an Array is if you need to call a method that requires it.
Answer: Yes it is safe to convert an ArrayList to an Array. Whether it is a good idea depends on your intended use. Do you need the operations that ArrayList provides? If so, keep it an ArrayList. Else convert away!
ArrayList<Integer> foo = new ArrayList<Integer>();
foo.add(1);
foo.add(1);
foo.add(2);
foo.add(3);
foo.add(5);
Integer[] bar = foo.toArray(new Integer[foo.size()]);
System.out.println("bar.length = " + bar.length);

outputs
bar.length = 5

Comment: `The method toArray(T[]) in the type ArrayList is not applicable for the arguments (char[])`
Comment: What if ArrayList is empty?
Comment: @AaronFranke You are trying to convert non primitive Character to primitive char. In java all arrays are created equal EXCEPT primitive ones. Maybe create and copy the array by hand in a for loop, OR if you like streams you can `map` to `char` and then call toCharArray on the stream
Answer: This is the best way (IMHO).
List<String> myArrayList = new ArrayList<String>();
//.....
String[] myArray = myArrayList.toArray(new String[myArrayList.size()]);

This code works also:
String[] myArray = myArrayList.toArray(new String[0]);

But it less effective: the string array is created twice: first time zero-length array is created, then the real-size array is created, filled and returned. So, if since you know the needed size (from list.size()) you should create array that is big enough to put all elements. In this case it is not re-allocated.
Comment: `new String[0]` is actually more efficient. https://shipilev.net/blog/2016/arrays-wisdom-ancients/
Comment: good explanation of the difference between `new String[0]` and `new String[size]`
Answer: ArrayList<String> myArrayList = new ArrayList<String>();
...
String[] myArray = myArrayList.toArray(new String[0]);

Whether it's a "good idea" would really be dependent on your use case.
Comment: thanks, just curious to know: i don't need to declare the array size?
Comment: JavaDocs are your friend. If the array being passed in is too small a new array is returned. The other version of the method that takes no args returns an array of `Object`
Answer: assuming v is a ArrayList:
String[] x = (String[]) v.toArray(new String[0]);

Answer: This is the recommended usage for newer Java ( >Java 6)
String[] myArray = myArrayList.toArray(new String[0]);

In older Java versions using pre-sized array was recommended, as the
  reflection call which is necessary to create an array of proper size
  was quite slow. However since late updates of OpenJDK 6 this call was
  intrinsified, making the performance of the empty array version the
  same and sometimes even better, compared to the pre-sized version.
  Also passing pre-sized array is dangerous for a concurrent or
  synchronized collection as a data race is possible between the size
  and toArray call which may result in extra nulls at the end of the
  array, if the collection was concurrently shrunk during the operation.
  This inspection allows to follow the uniform style: either using an
  empty array (which is recommended in modern Java) or using a pre-sized
  array (which might be faster in older Java versions or non-HotSpot
  based JVMs).
Answer: Most answers work as accepted. But since Java 11, there's another way to use toArray() method using method reference operator or double colon operation (::).
Here's an example:
ArrayList<String> list = new ArrayList<>();

// ... add strings to list

// Since java 11
String[] strArray = list.toArray(String[]::new);

// before java 11, as specified in the official documentation.
strArray = list.toArray(new String[0]);

Answer: I usually use this method.
public static void main(String[] args) {

    ArrayList<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(3);

    int[] arr = list.stream().mapToInt(i -> i).toArray();

    System.out.println(Arrays.toString(arr)); // [1, 2, 3]
}

Answer: ArrayList<String> a = new ArrayList<String>();
a.add( "test" );
@SuppressWarnings( "unused")
Object[] array = a.toArray();

It depends on what you want to achieve if you need to manipulate the array later it would cost more effort than keeping the string in the ArrayList. You have also random access with an ArrayList by list.get( index );
Answer: The Collection interface includes the toArray() method to convert a new collection into an array. There are two forms of this method. The no argument version will return the elements of the collection in an Object array: public Object[ ] toArray(). The returned array cannot cast to any other data type. This is the simplest version. The second version requires you to pass in the data type of the array you'd like to return: public Object [ ] toArray(Object type[ ]).
 public static void main(String[] args) {
           List<String> l=new ArrayList<String>();
           l.add("A");
           l.add("B");
           l.add("C");
           Object arr[]=l.toArray();
           for(Object a:arr)
           {
                String str=(String)a;
                System.out.println(str);
           }
      }

for reference, refer this link http://techno-terminal.blogspot.in/2015/11/how-to-obtain-array-from-arraylist.html
Answer: One approach would be to add the Second for Loop where the printing is being done  inside the first for loop. Like this:
static String[] SENTENCE;

public static void main(String []args) throws Exception{

   Scanner sentence = new Scanner(new File("assets/blah.txt"));
   ArrayList<String> sentenceList = new ArrayList<String>();

   while (sentence.hasNextLine())
   {
       sentenceList.add(sentence.nextLine());
   }

   sentence.close();

   String[] sentenceArray = sentenceList.toArray(new String[sentenceList.size()]);
  // System.out.println(sentenceArray.length);
   for (int r=0;r<sentenceArray.length;r++)
   {
       SENTENCE = sentenceArray[r].split("(?<=[.!?])\\s*"); //split sentences and store in array

       for (int i=0;i<SENTENCE.length;i++)
       {
           System.out.println("Sentence " + (i+1) + ": " + SENTENCE[i]);
       }
   }

}

From Arraylist to Array


is there a way to add a  to every column header using Material Table React

Question: Hi I am trying to add a  to every cell of table. I am using Material table here: https://material-table.com/#/docs/features/component-overriding
I tried like this:
<Table
  onChangePage={handleChangePage}
  page={props.currentPage}
  totalCount={props.totalCount}
  options={{
    paging:true,
    pageSizeOptions:[10, 15, 25, 50],
    pageSize: props.rowsPerPage,
    padding: "dense",
    search: false,
    toolbar:false,
    headerStyle: TableHeaderRow, <--- cssproperties
    rowStyle:TableRow <--- cssproperties
  }}
  columns={columns} <--- variable columns:TableColumn[]
  data={dataAct} <---- data generated from API
/>

Actually, I defined the headerStyle in options, but what I really want is adding a

  headerValueHere}

for every header.
I added label tag to cells like using render in defining columns:
const getDocumentTypeForRow = rowData => {
  return (
    <Tooltip title={rowData}>

        {rowData}

    </Tooltip>
  )
};

const columns: TableColumn<>[] = [
  {
    title: 'Due Date',
    field: 'remediation_due_date',
    render: data => getDocumentTypeForRow(data.remediation_due_date)
  },
]

But how to do this for headers???
Answer: You may pass JSX or HTML to title
const columns: TableColumn<>[] = [
  {
    title: Due Date,
    field: 'remediation_due_date',
    render: data => getDocumentTypeForRow(data.remediation_due_date)
  },
]

You may do live editing here and see the results
https://material-table.com/#/docs/features/styling
columns={[
        {
          title:
Heading 1
, field: 'name',
          cellStyle: {
            backgroundColor: '#039be5',
            color: '#FFF'
          },
          headerStyle: {
            backgroundColor: '#039be5',
          }
        },
        { title: 'Surname', field: 'surname' },
        { title: 'Birth Year', field: 'birthYear', type: 'numeric' },
        {
          title: 'Birth Place',
          field: 'birthCity',
          lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' },
        },
      ]}


Understanding andThen() function

Question: Consider the following example:
public static void main(String[] args) {
    Function<String, Integer> f1 = str ->  str.length();
    f1.andThen(i -> {
        System.out.println("length is " + i);
        return "why do I need to return a String here?";
    }).apply("12345");
}

I'm trying to understand why do I have to return String.
What's the logic behind that? I'd expect that andThen would accept a Consumer<Integer> let's say or something similar.
So why do andThen() requires me to return the type of the original input?
Comment: `Function length = str ->  str.length(); Function hex = val -> Integer.toHexString(val); Function lengthInHex = length.andThen(hex);`  Is that incomprehensible? Alternatively: `Function length = String::length; Function lengthInHex = length.andThen(Integer::toHexString);`
Comment: Take a string to get its length `andThen` do some transformation on the String using its length and return it.
Comment: Because the parameter is not of type `Consumer` but `Function`. See [`Function#andThen`](https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html#andThen-java.util.function.Function-).
Answer: What you want can be achieved via
Function<String, Integer> f1 = str ->  str.length();
Consumer<Integer> printer = i -> System.out.println("length is " + i);
printer.accept(f1.apply("12345"));

andThen is for chaining functions together. Functions always have results.

Understanding andThen() function