Draw and find the Length of $x = t + 4, y = t^2 + 1$

Question: I want a confirmation for this exercise.
My try:
pic
Thanks.
Comment: It is dx (I am not good at painting)
Answer: Using the formula $$l=\int_{t_0}^{t}\sqrt{\dot{x^2}+\dot {y^2}}dt=\int_{0}^t\sqrt{1+4t^2}dt$$
The indefinite integral has the form $$\frac{1}{2} \sqrt{4 t^2+1} t+\frac{1}{4} \sinh ^{-1}(2
   t)$$
Answer: You set up the definite integral correctly:
$$L=\int_4^6 \sqrt{1+y'^2}dx=\int_4^6 \sqrt{1+(2x-8)^2}dx$$
However, you are adding $2(2x-8)^2$ without reason.
Instead, denote: $2x-8=t$ to get:
$$L=\int_0^4\sqrt{1+t^2}\cdot \frac12dt,$$
which you can evaluate by changing $t=\tan y$ or $t=\sinh y$ as shown here. Answer must be approximately $4.64678$ as shown here.


Definir CSS de acordo com navegador

Question: Encontrei um comando para alterar CSS no Firefox:
@-moz-document url-prefix() {
    body {
        background: #f00;
    }
}

Esse comando vai colocar um fundo vermelho somente no firefox, por exemplo.
Achei muito útil, mas gostaria de saber se tem como eu fazer isso com outros browsers, mas nesse estilo, sem o uso dos "

Definir CSS de acordo com navegador


Visual Studio 2012 app could not load file or assembly

Question: The infamous Could not Load file or Assembly "filename.dll" or one of its dependencies.
I get this error when a client tries to run my mixed c/c++/c# app developed in VS2012. I used Process Monitor to see exactly which modules are not being loaded and got some weird results.
On the developer computer, where VS2012 is installed, everything runs fine.
The client computer does not have any visual studio installed, however they do have .NET 4.0 and the Redistributable update.
For some reason when the program is run on the client computer, a handful of C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System(*.INI) files are queried. Since these are the only files that do not exist, I am fairly confident that this is the issue.
Now, why when ran on the developer computer are these files not queried, but when ran on the client computer these files become necessary?
Answer: you can use the fusion utility(Assembly binding log viewer) to determing the problem
run command prompt as admin, fuslogvw.exe this tool will help you determine all referenced assemblies calls in your program and including the broken references.
it helped me a lot while trying to resolve some unmapped ioc registries.
you can learn more about it here
http://msdn.microsoft.com/en-us/library/e74a18c4.aspx
Comment: Okay after using dependency walker it was found that the missing file was msvcr110.dll. This brings up another question though: why, after installing VC++ 2012 Redistributable, is this file still not installed?


Algoritmo não entra no Catch (try/catch)

Question: Estou aprendendo programação e me deparei com o try catch, contudo meu código nunca entra no catch..
<?php
class NewsLetter{
    public function cadastrarEmail($email){
        if(!filter_var($email,FILTER_VALIDATE_EMAIL)):
            throw new Exception("Este email é invalido",1);
        else:
            echo"ok";
        endif;
    }
}

$Newsletter = new NewsLetter();

try{
    $Newsletter->cadastrarEmail("@haha");
} catch(Expection $e){
    echo"aaaaaaaaaaa";
    echo"Erro: ".$e->getCode();
}
?>

Answer: O problema é que você escreveu errado Exception
catch(Expection $e)

o correto seria
catch(Exception $e)


Select muito lento, como melhorar?

Question: Tenho uma tabela de cadastro de artesãos com cerca de 90 mil registros. Eu criei o SQL abaixo para me retornar o total de artesãos em cada uma das regiões que eles estão cadastrados. Apesar de funcionar, está lento, demorando mais de 30 segundos para retornar os registros.
Como posso melhorar?
    SELECT
        coordenacao.descricao AS nome,
        COUNT(artesao.codigo) AS qtde
    FROM
        municipio, artesao, coordenacaomunicipios, coordenacao
    WHERE
        artesao.codMunicipio = municipio.codigo AND
        coordenacaomunicipios.codMunicipio = municipio.codigo AND
        coordenacaomunicipios.codCoordenacao = coordenacao.codigo AND
        artesao.codStatus = 1
    GROUP BY
        coordenacao.descricao
    ORDER BY
        coordenacao.codigo

Comment: Funcionou algum das soluções abaixo ?
Answer: Tente criar os índices de buscas mysql.
ALTER TABLE municipio ADD INDEX(codigo);
ALTER TABLE artesao ADD INDEX(codMunicipio);
ALTER TABLE coordenacaomunicipios ADD INDEX(codMunicipio, codCoordenacao );
ALTER TABLE coordenacao ADD INDEX(codigo, codStatus);

Comment: agora funcionou obrigado, criei todos os indices que vc falou e mais o indice ALTER TABLE status ADD INDEX(codigo);
Answer: Tensa usar o INNER JOIN na junção das tabelas ao invés desse monte de AND no WHERE:
SELECT
        coordenacao.descricao AS nome,
        COUNT(artesao.codigo) AS qtde
    FROM
        municipio
        INNER JOIN artesao ON municipio.codigo = artesao.codMunicipio
        INNER JOIN coordenacaomunicipios ON coordenacaomunicipios.codMunicipio = municipio.codigo
        INNER JOIN coordenacao ON coordenacaomunicipios.codCoordenacao = coordenacao.codigo
    WHERE
        artesao.codStatus = 1
    GROUP BY
        coordenacao.descricao
    ORDER BY
        coordenacao.codigo

Comment: A principio isso vai dar no mesmo.
Comment: nenhuma das duas funcionou, criei os índices e uso o meu sql ou esse que você me passou, continua a mesma coisa "A mostrar registos de 0 - 24 (28 total, O Query demorou 32.6235 sec)"

Select muito lento, como melhorar?


Solve for x if $z$ is a complex number such that $z^2+z+1=0$

Question: I was given a task to solve this equation for $x$:
$$\frac{x-1}{x+1}=z\frac{1+i}{1-i}$$
for a complex number $z$ such that $z^2+z+1=0$.
Solving this for $x$ is trivial but simplifying solution using the given condition is what's bothering me. Thanks ;)
Comment: Notice that this means that $z$ is a cubed root of unity
Answer: $$\frac{x-1}{x+1}=z\frac{1+i}{1-i}=z\frac{(1+i)^2}{(1+i)(1-i)}=zi$$
Applying componendo and dividend, $$x=\frac{1+zi}{1-zi}=\frac{(1+zi)^2}{(1-zi)(1+zi)}=\frac{1-z^2+2iz}{-z}=-2i+z-z^2$$ as $z^2+z+1=0\implies z^3=1$
Comment: "Solving this for x is trivial but simplifying solution using the given condition is what's bothering me" ($z^2 + z + 1 = 0$)
Comment: @Mathmo123, Is the edited version decent enough?
Comment: Works for me :)
Comment: Thanks. I was not familiar with roots of unity until now.
Answer: You said that solving for $x$ was trivial, so I imagine you were able to get to:
$$x=\frac{1+zi}{1-zi}$$
This is equal to:
$$x=\frac{\left(1+zi\right)^2}{(1-zi)(1+zi)}=\frac{1+2zi-z^2}{1+z^2}$$
Since $1+z+z^2=0$ we can conlude that $1+z^2=-z$ and also that $1=-z-z^2$. We substitute that into the expression to get:
$$x=\frac{(-z-z^2)+2zi-z^2}{-z}=\frac{-z-2z^2+2zi}{-z}=1+2z-2i$$
$$x=1+2z-2i$$


Can't log in to Drupal instance after duplicating database

Question: I wrote a quick script to pull down a live drupal database on to a machine on a local network, and that works fine.
I also made a copy of the actual Drupal instance on my own machine.
I edited settings.php to use the db on the network, and everything appears to be working correctly when I run the site from localhost, except I can't log in.
At first I thought I should just change the password directly using MySQL, but that didn't work. Then I tried running update.php, which also didn't work.
I'm stuck, why won't it accept the username/password? I have double checked that I'm using the correct login credentials on the live site, and it works fine.
Edit: The site was duplicated from a Linux server onto a Windows 7 machine, if that makes any difference.
Answer: First check whether $cookie_domain is set to localhost or not?
If it is set as the URL of the live site then it might not work. I faced this issue previously.
Other cause might be clean urls. You can check whether clean URL is enabled in your localhost or not.
You can check whether mod_rewrite is on or not here. If clean url is causing problem then you can disable from your database. If you want to disable clean url goto your database find variables table, find clean_url variable and set it to 0.
Comment: I had the same problem, disabling clean URLS fixed it. I used `drush vset clean_url 0 --yes` though
Comment: That line is commented out on both the live server and my local machine. I tried changing it to localhost to see if it helped any, but the problem persists.
Comment: checked clean url settings ?
Comment: Are you suggesting I turn it off? How would I do that if I can't log in?
Comment: first check if mode_rewrite is on in your localhost ? It enables clean urls. If you want to disable goto your database find variables table, find clean_url variable and make it to 0
Comment: I have added it check it out..
Comment: Problem was in $cookie_domain. You saved my life, man! Thanks.


Is it possible to play cello on a midi keyboard?

Question: Is it possible to play this Bach piece on a MIDI keyboard

 with instrument set to cello?
Edit: I messed up the original question by confusing cello with violin.
Comment: possible to *play it*, or *play it so it sounds exactly like that video*, or...?
Comment: exactly like that video or something really close..
Answer: [Answer tweaked after question update]
Possible... ermm... yes.
Sound good... unlikely.
It is possible to make midi cello & violin sound good, but it isn't really a case of 'dial in the sound on a midi keyboard & hit the right notes'
At least, you need some kind of controller structure, mapping velocity to volume isn't enough - you need to be able to map attack separately from volume, vibrato separately as intensity & speed, string 'overhang' depending on whether the next note is the same or a different string, note-glissando/slides, etc.
The standard sound set from any keyboard with 'built-in' sounds is very unlikely to be at all convincing without significant post-production.
[Opinion source: I was employed for a decade by a major multinational electronic instrument maker (name on request;) to produce such things as onboard & point-of-sale style & song demos for their products - & I'm extremely aware of the difference between what you can achieve with a month's work for a demo vs what is actually possible to simply 'play']
Listen to some of the demos on these links, possibly some of the finest solo emulations I have heard. [I own both these 'instruments' but have no affiliation to this company.]
Embertone Blakus cello
Embertone Friedlander violin
Using a standard Midi keyboard, it is quite difficult to get sufficient controller data to truly emulate a cello/violin in realtime - though you can tweak afterwards in a sequencer. For realtime playing & post production, these days I use this system for iPhone/Pad as a further control surface - http://hexler.net/software/touchosc
*I just realised that very same Bach prelude is one of the Blakus demos... though I don't think it's as good as it could have been made, & is presented in a significantly smaller 'space' & closer-miked, it's a fair attempt at the piece.
Comment: Jeeze, that Embertone Blakus is impressive. (My only experience with MIDI instruments is from the default Finale and Sibelius players 5-10 years ago, though.)
Comment: wow that blakus bach piece is almost there. thank you for linking to that. I have a roli rise 25 so there is '5 dimensions' of input, so i am guessing that should be enough to control all the parameters.
Answer: It's possible to emulate just about any instrument using a MIDI keyboard, and a module capable of producing sampled sounds. You ask about violin, then feature a cello piece. Note wise it'll work, using a cello sound will be far better, but you'll need to emulate the vibrato on the longer notes. A lot of keyboards have a mod wheel, which can be programmed to do that.
Comment: Very impressed by the Roli seaboard! If anything can do it, that will! Obviously, that only facititates the playing aspect, you still need a good cello sound from a synth, etc.
Comment: oops you are right. I updated the question to be consistent. I have a roli seaboard which can do vibrato on per note basis. Looks like I can start learning cello as my first instrument.
Comment: I am totally blow away by it, I got it as a gift. Since I haven't played any instrument before, I am not quite sure how to go about learning to play cello on it. Do you think I should take lessons from a regular cello teacher and try to figure out translation to roli myself. Not even sure where to find a teacher that would accommodate this. I have some experience with synth and sound programming.
Comment: It's pretty intuitive, but I bet finding a teacher who knows about is ain't going to be easy.


Cell formula to use a different sheet with sheet.name

Question: I'm struggling with coding a cell formula to use a different sheet but getting the sheet name using
sheet.name:
Set sht = Activesheet
 Sh_name = sht.Name
 Range("C4").Formula = _
   "=SUMIF(""'"" & Sh_name &""'!$D:$D"",'Trial balance'!B4,""'"" & Sh_name &""'!$G:$G"")"

this is what I did but it's not working...
any ideas why?
thanks
Answer: Set sht = ActiveSheet
Sh_name = sht.Name
Range("C4").Formula = "=SUMIF('" & Sh_name & "'!$D:$D,'Trial balance'!B4,'" & Sh_name & "'!$G:$G)"

Why? Let's have an hard-coded sheet name like 'Sheet1'. Our code would be:
Range("C4").Formula = "=SUMIF('Sheet1'!$D:$D,'Trial balance'!B4,'Sheet1'!$G:$G)"

And now we are going to use "Sheet1" as hard-coded sheet name but concatenating the fixed structure of the formula with the sheet name.
Range("C4").Formula = "=SUMIF('" & "Sheet1" & "'!$D:$D,'Trial balance'!B4,'" & "Sheet1" & "'!$G:$G)"

To concatenate strings you have to write a list of strings, separating them by the ampersand '&'. A string could be a text between doulbe-quotes or a variable name.
The final step is to replace the strings "Sheet1" with a variable name, like your Sh_name:
Sh_name = "Sheet1"
Range("C4").Formula = "=SUMIF('" & Sh_name & "'!$D:$D,'Trial balance'!B4,'" & Sh_name & "'!$G:$G)"

Your expected result:
Set sht = ActiveSheet
Sh_name = sht.Name
Range("C4").Formula = "=SUMIF('" & Sh_name & "'!$D:$D,'Trial balance'!B4,'" & Sh_name & "'!$G:$G)"

Comment: Nicely explained. (Alas, no idea as to correctness.)
Answer: Range("C4").Formula = _
 "=SUMIF('" & Sh_name & "'!$D:$D,'Trial balance'!B4, '" & Sh_name & "'!$G:$G)"


Get friday from week number and year in javascript

Question: I have week number and year, need to find out date (friday) in that week and year.
function getFriday(week_num, year)
{
    ?

    return friday_date_object;
}

How do I do that?
Comment: @JM4 He means that if we call getFriday(2,2011) it will return a date object of the 2nd Friday in 2011 (14th Jan 2011)
Comment: Surely getDay(day_num, week_num, year) would be more useful?
Comment: "You need to convert that to Friday of that particular week"? - Please reword your question - it is hard to tell what you are asking for exactly.
Comment: @Jim day_num is always 5 (friday), your function will return same result, yes
Comment: @JM4 reworded my question a bit
Answer: The week #1 is the week with the first Thursday.
Here is a function to get any day:
var w2date = function(year, wn, dayNb){
    var j10 = new Date( year,0,10,12,0,0),
        j4 = new Date( year,0,4,12,0,0),
        mon1 = j4.getTime() - j10.getDay() * 86400000;
    return new Date(mon1 + ((wn - 1)  * 7  + dayNb) * 86400000);
};
console.log(w2date(2010, 1, 4));

week numbers start at 1 until 52 or 53 it depends the year.
For the day numbers, 0 is Monday, 1 is Tuesday, ... and 4 is Friday
Answer: Use the  date.js library. It's great for all date-related functions.
Answer: Here's some quick code
var DAY = 86400000;

function getFriday(weekNum, year) {
  var year = new Date(year.toString()); // toString first so it parses correctly year numbers
  var daysToFriday = (5 - year.getDay()); // Note that this can be also negative
  var fridayOfFirstWeek = new Date(year.getTime() + daysToFriday * DAY);
  var nthFriday = new Date(fridayOfFirstWeek.getTime() + (7 * (weekNum - 1) * DAY));
  return nthFriday;
}

Split some variables for readability.
But if you find yourself writing more complex time operations, you're better using a library instead.
Comment: new Date(2010) gives Thu Jan 01 1970 with Chrome
Comment: What is the DAY variable representing?
Comment: @Blake, the number of milliseconds in a day
Comment: @Mic: Oops. Yes, it tries to parse 2010 as the number of seconds, instead of year. `new Date(2010)` behaves differently than `new Date("2010")`. Changed code to reflect that, thanks for the observation.
Answer: i think if i should not use any date library i would:
assuming u use a christian week, where sunday is the frist day of the week. this is neccessary to find out if the first days in a year belong to the first week of the year or not.
create an array. months = new Array(31,28,31, ... )
if(year % 4 == 0) then february has 29 days.
days = num_week * 7;
then iterate over the month and decrease days by month[current]. if days gets negative increase days with the current month days again.
result: year-(current+1)-days
i hope this helps you. what u have to add on your own is the handling for january and the first days.
Comment: leap year is calculated like this:
`((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)`


Calcular frete para mais de um produto no carrinho Woocommerce

Question: Quando adiciono apenas um produto no carrinho ele mostra as opções de frete que configurei, porém quando tem mais de um produto não tem opção para frete e solicita verificar forma de entrega.
Segue link da loja para simulação:
loja
Como faço para calcular o frete para vários produtos no mesmo carrinho?
Answer: Amigo, tente alterar o peso do produto, vi que está usando quilos, troque para gramas.
O produto "Emergência LED 100-240 V – Bivolt( da blumenau)" está com 200 centímetros, realmente é 2 metros?


Simple inverse function question - $f(X) = \frac{2}{X}$.

Question: I have been studying functions and how to find the inverse of a function which so far I have found straight forward. However, I have had some difficulty while trying to find the inverse of function $f(X) = \frac{2}X$. I have the answer sheet to the question, which says the answer is "$f^{-1}(x) = \frac{2}x$".
I took the function to mean that the input maps to $2$ divided by $X$, so I thought the inverse would be $2$ multiplied by $X$, or "$f^{-1}(x) = 2  x$"
Am I making a mistake with the notation? I have found much more complicated functions easier to find the inverse of, I'm not sure what rookie mistake I'm making here.
Comment: I wouldn't get into the habit of taking the operations backwards, because then you'll be completely stumped at cases like $y = \frac{x}{x + 1}$. Know how to algebraically manipulate equations as that is all you'll be doing later on.
Answer: Set $y=f(x)=\frac{2}{x}$, and solve for $x$.  We multiply both sides by $x$ to get $xy=2$, and divide both sides by $y$ to get $x=\frac{2}{y}$.  Hence $f^{-1}(y)=\frac{2}{y}$, and (by changing variables) $f^{-1}(x)=\frac{2}{x}$.
Time to check our work.  We calculate $$f^{-1}(f(x))=\frac{2}{f(x)}=\frac{2}{\frac{2}{x}}=\frac{2}{1}\frac{x}{2}=x$$
This proves that $f^{-1}(x)=\frac{2}{x}$ is indeed the correct inverse.
Answer: $y=2/x$ iff $xy=2$ iff $x=2/y$. Hence $f^{-1}(x)=2/x$
Answer: Your error is understandable. Note however that, with $f(x) = \frac2x$ we have:
$$\begin{cases}f(1) = 2\\f(2) = 1\\f(4) = \frac12\\\cdots\end{cases}$$
so the inverse can't certainly be $f^{-1}(x) = 2x$ given that it will only work for one of the examples above. To find the inverse, just solve the equation
$$f(x) = \frac2x$$ for $x$. One usually writes that as $y = \frac2x$ and solves for $x$. The equation writes the image as a function of the object. Since you want to find the object as a function of the image, solve the equation for the object:
$$y = \frac2x \iff x = \frac2y \implies f^{-1}(x) = \frac2x$$
Comment: this is great, knew I was doing something stupid. Thank you!


train data using libsvm with best C and Gamma

Question: Hi I'm using libsvm (in VS2010) for training my data , I scaled the input and output data successfully using svm-scale.c and my data is ready to be trained ...
Now I have two problems:
1).
as I've read from LIBSVM documentation I realized that first I need to train my scaled data and obtain a model. then use this model for predicting the final result but the problem is when I want to train my system I don't know what is the best choose for my model parameters and specifically  (C,g) for training my data !!!.
what I do is that first I load my scaled data, then by using a svm_problem I fill svm_nodes with my train data then call this function :

struct svm_model *svm_train(const struct svm_problem *prob,                    const struct svm_parameter *param);

2).
Also I'm not sure about the correct function calling of libsvm functions -> I mean I first use svm_train  and then svm_predict to see the result , and I don't know if I should call sth else or not ?!

Model = svm_train(My_data,My_param); //I don't know how to fill my_param
svm_node Test_Vector = svm_scale_data(x); //using the same algorithm as scaled_training data
double result = svm_predict(Model,Test_Vector);

Thanks
Comment: I realized that using cross validation I can get the best c,gamma as grid.py do in python interface .... If somebody knows sth about this too I'd appreciated that ....
Answer: If you want to call LIBSVM via C++, you can optimize parameters by letting LIBSVM do cross-validation internally. When doing so, you just need to loop over the parameter tuples (C, gamma) you want to test and let LIBSVM perform cross-validation instead of proper training.
You can get LIBSVM to perform cross-validation with the following API function:
void svm_cross_validation(const struct svm_problem *prob, const struct svm_parameter *param, int nr_fold, double *target);

To answer your other question: yes, it is perfectly fine to call svm_train() followed by svm_predict().
Comment: sorry but can you please explain more about the meaning of internal optimization ? you mean I should call svm_train() and this function itself optimizes it's parameters internally ?!!! can you provide a pseudo code for a whole operation (from training and getting the best parameters to test the new samples and see the result ?)
Comment: Parameter optimization is always up to the user. You can use the provided cross-validation API function to test the efficacy of a given parameter tuple. You must implement a grid search method yourself (e.g. iterate over several values of C+gamma and test which one is best using `svm_cross_validation`).


What does a symmetric matrix transformation do, geometrically?

Question: I need some visual intuition behind what exactly a symmetric matrix transformation does. In a $2 \times 2$ and $3 \times 3$ vector space, what are they generally?
Comment: Adding to the comment above - the image of the unit circle under the transformation by the symmetric matrix is an ellipse, whose axes point in the directions of the eigenvectors of the symmetric matrix.
Comment: Just look at the image of the unit circle.
Answer: A real symmetric matrix is always orthogonally diagonalizable, meaning that there's a basis for $\mathbb R^n$ consisting of mutually perpendicular eigenvectors of the matrix. Thus you can understand multiplying a column vector by a symmetric matrix geometrically as:

Express the input vector in a different rectangular coordinate system that depends on the matrix.
Multiply each coordinate by some constant that depends on which axis in the new coordinate system it corresponds to -- that is, stretch, shrink or flip each axis independently of each other.
Express the result back in the original coordinate system.


Finding Limit of n-th root sequence

Question: Disclaimer: I'm a starting-level-student.
How do I prove or deny this?
 $$\lim_{n\to \infty} \sqrt[n]{2^n - n^2} = 2$$
I have a feeling that this expression doesn't getting closer to 2 but I can't find how to prove this.
I've tried 2 ways:
First -
$$|\sqrt[n]{2^n - n^2} - 2| < \epsilon$$
from the definition of limits, trying to evaluate this expression and deny it but I'm not getting anywhere.
So can I get some help on how to solve this ?
Comment: Really ??? Do you really mean that : $(a-b)^n=a^n-b^n$
Comment: If you know this fact: 'when $n\to\infty$ exponential growth wins over power growth' you can focus your attention to $2^n$ as $n^2$ is irrelevant
Comment: Are you familiar with the natural logarithm function?
Comment: @Dr.MV No, this is yet to be studied.
Answer: HINT: write your Limit in the form $$2\sqrt[n]{1-\frac{n^2}{2^n}}$$
Comment: As note to make this more generally applicable, when dealing with $n$-th roots that contain multiple terms, one of which is raised to the power of $n$ or a multiple of $n$, it is useful to factor that out. A second example of doing this could be $\sqrt[n]{e^n + 2^n} = 2\sqrt[n]{\dfrac{e^n}{2^n} + 1} = 2e\sqrt[n]{\dfrac{1}{2^n} + \dfrac{1}{e^n}}$.
Comment: Thanks! but I guess I don't really understand How to get rid of the nth-square root?
Answer: You may exploit the following inequality: if $a>b>0$, for any $n\geq 1$ we have
$$ n(a-b)b^{n-1}\leq a^n-b^n \leq n(a-b)a^{n-1}\tag{1}$$
Proof: it simply follows from $a^n-b^n=(a-b)(a^{n-1}+a^{n-2}b+\ldots+a b^{n-2}+b^{n-1})$. There are $n$ terms of the form $a^j b^k$ and each of them is $\leq a^{n-1}$ and $\geq b^{n-1}$due to $b<a$.
Now we may consider $a=2$ and $b=\left(2^n-n^2\right)^{1/n}$. We get
$$ 2-(2^n-n^2)^{1/n}\leq \frac{n^2}{n \left(2^n-n^2\right)^{\frac{n-1}{n}}}\leq \frac{n}{2^{n/2}}\tag{2} $$
where the last inequality holds for any $n$ large enough. Now $(2)$ clearly proves that
$$ \lim_{n\to +\infty}\left(2^n-n^2\right)^{1/n}=2 \tag{3} $$
as wanted.

$(1)$ might look as an overkill, but it is a useful inequality for proving, for instance,
$$ \lim_{n\to +\infty}\int_{0}^{n}x^n\left(1-\frac{x}{n}\right)^n\,dx = \int_{0}^{+\infty}x^n e^{-x}\,dx = n! $$
leading to Euler's product formula for the $\Gamma$ function.

Finding Limit of n-th root sequence


Simulate a random number of sums of random variables?

Question: I'm trying to solve an exercise (not homework, and it does not come with solutions) that asks to provide an algorithm to simulate a probability $P(Y<y)$ and the expected value $E[Y]$ of a random variable $Y$. Also the algorithm must have a fixed number $N>0$ of steps (number of pseudo-random $\rm Uniform(0,1)$ variables that the algorithm must generate).
I understand that if I can simulate $N$ copies of $Y$ (call them $Y^{(1)}, \ldots, Y^{(N)}$), then I can estimate $P(Y<y)$ as the ratio between the number of $Y^{(i)}$'s inferior to $y$ and $N$. Similarly, $E[Y]$ can be estimated as $\frac{1}{N}\sum_{i=1}^N Y^{(i)}$.
However, suppose
$$Y = X_1 + \ldots + X_R,$$
where $X_1,X_2,\ldots$ is a sequence of iid variables and $R$ is a discrete uniformly distributed random variable over $\{1,2,\ldots,n\}$, for some fixed $n>0$. Also suppose that one $\rm Uniform(0,1)$ variable is enough to simulate one and only one $X_i$.
Now, since presumably $R$ is independent of each $X_i$, what would be the appropriate way to proceed and why: simulate $R$ once, have it fixed, that is simulate $\lfloor N/r \rfloor$ copies of $Y$ ($r$ would be the simulated value of $R$), or instead use a while cycle and alternate between simulating $R$ followed by $X_1,\ldots,X_R$?
Thanks.
Comment: It depends on why the simulation is being performed. For instance, if you are doing it to study the distribution of some function of $Y$, then you can achieve greater accuracy by simulating $R$ *exactly* (with no sampling error). Simply generate $n(n+1)/2$ iid realizations of $X$ and compute the sums of the first $n$ of them, then the next $n-1$, ..., and so on down to the sum of the last one.  This gives $n$ realizations of $Y$, for an average cost of $(n+1)/2$ uniforms per realization.
Comment: Of course: it is understood that when you need $N$ iid values of $Y$, you will generate $2N/(n(n+1))$ groups of $n(n+1)/2$ of them. Besides the computing efficiency potentially gained by generating these realizations in groups, there is a greater efficiency achieved by decreasing the sampling variance, which means you can estimate properties of $Y$ using smaller values of $N$ than you would otherwise need.
Comment: Thank you, that was an interesting approach, however note that $N$ and $n$ could be different, and your method neither uses $N$ uniforms ($n(n+1)/2$ instead) nor gives $N$ copies of $Y$. But this can be easily adapted.
Answer: If I understand the question correctly, you should not fix $R$ based on only one sampling of the distribution of $R$.
The result would not give the right characteristics for $Y$. ($Y$ has what is known as a compound distribution.)
In effect you'd be sampling from $f_{Y|R}(y|R=r^{(1)})$, and you want to be sampling instead from $f_{Y}(y)$, which means you needs to sample over the whole distribution of $R$.
Instead, the second approach will be the way to go - simulate $R$ each time, so on iteration $i$ you get some sample value $r^{(i)}$, then simulate $r^{(i)}$ independent $X$'s and sum them, to get your sample value for $Y^{(i)}|r^{(i)}$ (i.e. $y^{(i)}$). Over repeated sampling, this will yield the appropriate marginal for $Y$; in effect the sampling scheme 'integrates out' the conditioning on $R$.
That is, do the second thing, not the first thing.
Comment: Thank you, somehow because $R$ is uniform, I thought simulating it once would be enough.


Proof of Closest Point Theorem in Hilbert Space

Question: The theorem:
Let $C$ be a non-empty closed convex subset of a Hilbert space
$X$, and let $x \in X$. Then there exists a unique $y_0 \in C$ such that $||x-y_0|| \le ||x - y||$ all $y \in C$. In other words there is a point in $C$ which is closest to $x$.
I'm reading a proof here (https://www0.maths.ox.ac.uk/system/files/coursematerial/2014/3075/48/15B4.2-webnotes-all.pdf, p.4) and have two questions about the initial steps in the prooof (I can follow the later steps.):

"Let $d = inf\{||x - y||: y \in C\}$" I think that the infimum should exist by the property (axiom) of completeness of the real numbers. $\{||x - y||: y \in C\}$ is a set of real numbers which is bounded below (all norms are $\ge 0$) and therefore has a greatest lower bound - is this correct ?
"Let $(y_n)$ be a sequence of points in C such that $||x - y_n|| \to d$". I think such a sequence should exist by the following reasoning: With $d = inf\{||x - y||: y \in C\}$ then for any $\epsilon > 0$ there must be a point $y$ in $C$ such that $||x - y|| \lt d + \epsilon$ (otherwise $d$ is not the infimum). If for this point $||x - y|| = d $ then $y_0 = y$ and we are finished: $(y_0)$ is a one element convergent sequence. Otherwise $||x - y|| = d + \epsilon`$ where $\epsilon` \le \epsilon$ and I can repeat the process to find a different point where $||x - y|| \lt d + \epsilon`/2$ and so generate a convergent sequence. I'm not sure this is valid, and it occurs to me that unless $C = \{y_0\}$ there are probably an infinite number of points at each step and the Axiom of choice is then required to extract a convergent sequence. Any help would be appreciated.
Comment: So what part of your question is *about* the axiom of choice?
Comment: @AsafKaragila In forming the countably infinite sequence $(y_n)$ it seems to me that each $y_i$ has to be chosen from a set of points satisfying $||x - y_i|| \lt d + \epsilon$, and that in general, if this set contains two points then it contains an infinite number. So we have to select one element from each infinite set in an infinite family of sets. Does this not require AOC ?
Comment: Probably it does. But the statement is about the closure, not sequential closure.
Comment: @AsafKaragila Thanks. I'm not uncomfortable with AOC, I just hadn't previously seen any mention of dependence on it in this context.
Comment: That is because functional analysis without the axiom of choice is like intentionally cutting your thumb.
Answer: 1) You are correct. Every set that is bounded below in $\mathbb{R}$ has a least lower bound.
2)The standard why to show that there exists such a sequence $(y_n)$ is as follows. Let $n\in\mathbb{N}$ then as d is the infimium, $d+\frac{1}{n}$ is not a lower bound so there exists $y_n$ such that $d<||x-y_n||<d+\frac{1}{n}$. This gives a sequence of points $(y_n)$. Then it should be obvious that $||x-y_n||\rightarrow d$.


Converting the value of a string to a variable of KeyValuePair

Question: I was doing something like this :
foreach( KeyValuePair<int,SOME_CLASS> reader in _readerDict )
{
  var selectedReader = reader;

  var antenna1 = selectedReader.Value.Antenna1IsEnabled;
  var antenna2 = selectedReader.Value.Antenna2IsEnabled;
  var antenna3 = selectedReader.Value.Antenna3IsEnabled;
  var antenna4 = selectedReader.Value.Antenna4IsEnabled;
}

But then again I want to do something like the following :
foreach( KeyValuePair<int,SOME_CLASS> reader in _readerDict )
{
  var selectedReader = reader;

  for( var idx = 1; idx <= 4; idx++ )
  {
    var antennaIsEnabled = string.Format( "selectedReader.Value.Antenna{0}IsEnabled", idx );

    // cast the value of antennaIsEnabled as a KeyValuePair<int,SOME_CLASS> variable datatype here
    ....
  }
}

Is there anyway for me to cast the value of antennaIsEnabled as a KeyValuePair variable datatype?
Comment: KeyValuePair needs 2 parts, the key and the value. Your string will be splitted then? Key = "selectedReader" and Value = "AntennaIsEnabled"
Comment: I think he has a string that contains "string strA = ..." and he wants to make this a dictionary, so the key word be "strA" and the value would be "selectedReader.Value.AnetnnaIsEnabled".
Comment: Sorry guys, I just edited the question to be more precise.
Answer: I suppose you want to extract the selectReader as key and AntennaIsEnabled as value
string[] parts = strA.Split('.');
var list = new List<KeyValuePair<string, string>>();
list.Add(new KeyValuePair<string, string>(part[0], part[2]));

Need to add some error checking...
Answer: Try using FastMember library to access your properties as strings.
Answer: It sounds like you want a result that looks like this:
Dictionary<int, bool> AntennaIsEnabled = new Dictionary<int, bool>();
foreach( KeyValuePair<int,SOME_CLASS> reader in _readerDict )
{
  var selectedReader = reader;

  //From your example
  AntennaIsEnabled.Add(1, selectedReader.Value.Antenna1IsEnabled);
  AntennaIsEnabled.Add(2, selectedReader.Value.Antenna2IsEnabled);
  AntennaIsEnabled.Add(3, selectedReader.Value.Antenna3IsEnabled);
  AntennaIsEnabled.Add(4, selectedReader.Value.Antenna4IsEnabled);
}

Then you can access the state of each antenna by using a syntax like AntennaIsEnabled[2].


What's the standard format for representing true and false values in an HTTP header?

Question: I need to add a custom header to an HTTP request, and its value's type will be boolean. However, HTTP header values are all strings. So what is the common practice for representing a boolean in this case? 0/1, false/true, False/True, off/on, etc?
E.g.
My-Header: 1

Or what's generally recommended, i.e. the most commonly used convention?
Answer: UPDATE: it might make the most sense to use a header exists vs doesn't exist convention as implied here
HTTP Header Operation http header .EXISTS

Returns a Boolean TRUE if an instance of the specified header type exists. Following is an example:
http.req.header("CacheControl").exists

i think the answer is ?0 vs ?1
Structured Field Values for HTTP > 3.3.6. Booleans

Boolean values can be conveyed in Structured Fields.
The ABNF for a Boolean is:

sf-boolean = "?" boolean
boolean    = "0" / "1"

A Boolean is indicated with a leading "?" character followed by a "1"
for a true value or "0" for false. For example:

Example-Boolean: ?1

check out Sec-Fetch-User:

Syntax
Sec-Fetch-User: ?0
Sec-Fetch-User: ?1
Values
The value is a Boolean Structured Header.
?0 The navigation request was triggered by a user activation.
?1 The navigation request was triggered by something other than a user
activation.

but fwiw, Save-Data also seems to be a standard/official "boolean" header that accepts values "on" vs "off"
Save-Data

A boolean that indicates the user agent's preference for reduced data
usage.

(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers)

A numerical value indicating whether the client wants to opt in to
reduced data usage mode. on indicates yes, while off (the default)
indicates no.

also confusingly, the ABNF page actually says:

boolean = ( "true" / "1" ) /
( "false" / "0" )


Why is this linear transformation unique?

Question: I'm reading Hoffman and Kunze's linear algebra book and on page 112 the authors state the following theorem as a consequence of previous commentaries:

I didn't understand why this transformation is unique.
Answer: Suppose $T^t_1$ and $T^t_2$ are two linear transformations with the property above. Then for each $g$, we have $T^t_1(g)=T^t_2(g)$. Why? Well, the property above says exactly "$T^t(g)$ is the map which sends $\alpha$ to $g(T\alpha)$".
What's really going on here is the following: the rule $$T^tg(\alpha)=g(T\alpha),$$ or better yet $$T^t(g)={}"\alpha\mapsto g(T\alpha)"$$ describes a unique function from $W^*$ to $V^*$; it then turns out that this map is actually a linear transformation.
Comment: ha ok! I think I misunderstood what the authors say by "unique"
Comment: @user42912 They just mean that there is only one linear transformation with that property.


Need confirmation on how iSCSI RAID storage works

Question: I have a Dell PowerEdge server with Windows Server 2019 that has an iSCSI target set up with 30 iSCSI LUNs. The HDDs are set up in a RAID-6. I have some IP cameras that have the ability to record directly to an iSCSI target that I can't get to record to this iSCSI storage. According to the datasheet for them, they specifically state that they support recording to iSCSI storage on a RAID-5 array. My question is - is the RAID level of the storage where the LUNs are stored presented to a client over iSCSI? The old server that this is replacing did have a RAID-5, and was recording, and now I'm wondering if the RAID-6 array may be being presented to the camera, which has no idea how to write to a RAID-6.
Comment: "support recording to iSCSI storage on a RAID-5 array" is a rather bizarre statement. Please quote the datasheet verbatim.
Comment: iSCSI is 1:1 connection to transfer blocks between an initiator and a target, you won't be able to connect the DVR and also a server to the same iSCSI backend at the same time, so I'm not sure the value add here, to access the video you must connect via the DVR system.  The raid level does not matter.  Are you working with a Bosch Security DVR? Looks like this supports basic ip/password auth, once connected it should show all LUNs allocated to you, basic host acl should be fine to test it out.
Comment: This is copy/pasted directly from the datasheet: "The iSCSI RAID5 storage support  enables the cameras to function as a conventional DVR". The camera model is fairly old, cicra 2005/2006, predating RAID-6 becoming common and as such I'm wondering if it might be able to detect over iSCSI that the storage is something other than RAID-5 and therefore not able to write to it.
Comment: Yeah, that still makes absolutely no sense. Does it not say anything else about it?
Comment: Not about their iSCSI support, just that one sentence.
Comment: "I have some IP cameras that have the ability to record directly to an iSCSI target".
Whoever connects to an iSCSI target and wants to write something onto it, needs to have exclusive access (unless you have some form of clustering in place).
Thus, please clarify: are the IP cameras directly writing on the iSCSI LUNs, or does the server act as a man-in-the-middle?
Answer:
is the RAID level of the storage where the LUNs are stored presented to a client over iSCSI?

No.
The iSCSI initiator (client) sees a LUN presented as a simple drive for block storage. It can't see what's really behind it, whether RAID, HDDs, SSDs, SAS, SATA, ... (I'm assuming you've created the LUN images on the RAID 6 array by "To create an iSCSI virtual disk, start the New iSCSI Virtual Disk Wizard".)
First, you need to make sure that the network connectivity is AOK (ping the target from initiator or vice versa). Add the target to the initiator. Make sure the target sees the initiator. Grant the initiator access to the desired LUN(s) in "Access servers". Check whether the initiator can mount the LUN(s).
Comment: +1 - The client hasn't the faintest clue about the RAID level or any other physical details of what is backing the LUN.
Comment: I would agree. Initiator doesn't know about the Array configured. In case of HW RAID arrays, OS usually doesn't know about the array level. Everything is handled on the controller level. In any case, I think it is worth running tests before putting it in production, as mentioned above.


Como fazer validação de um array se ele possui objetos dentro dele ou não? React JS

Question: Tenho um código feito usando React JS e funciona assim, tenho um componente select, e este é reutilizado várias vezes e as informações que ele recebe sempre vem de um array, só que agora preciso mandar um array de objetos como pode ser ver:
const plans = [{"text" : "PRO","value" : 1},{"text" : "PRO","value" : 1}]

Aqui eu chamando meu componente e fazendo ele receber os valores desse array de objetos:
<Select
    onChange={value => setQuery(Object.assign(query, { tipoUsuario: value }))}
    placeholder="Selecione o plano"
    items={plans}
/>

Aqui o meu componente:
export default props => {
    return (

            <select
                onChange={input => props.onChange(input.target.value)}
                className="block appearance-none w-full bg-white border border-gray-400 hover:border-gray-500 px-4 py-2 pr-8 rounded shadow leading-tight focus:outline-none"
            >
                <option>{props.placeholder}</option>
                {props.items.map((element, key) => {
                    return <option key={key} value={element.value}>{element.text}</option>
                })}
            </select>
    )
}

Eu preciso que esse meu componente consiga receber meu array de objetos, só que ao receber ele precisar fazer uma verificação se é um array comum ou se é um array com objetos dentro, pois dessa forma ai ele recebe tranquilamente o objeto, só que quando eu preciso de um select que só utiliza um array simples a a aplicação quebra, ai preciso dessa verificação para que quando não for um array com objetos meu componente seria dessa forma:
<option key={key}>{element}</option>
Já pesquisei pra caramba e não achei nada que conseguisse me ajudar.
Solução:
export default props => {
    return (

            <select
                onChange={input => props.onChange(input.target.value)}
                className="block appearance-none w-full bg-white border border-gray-400 hover:border-gray-500 px-4 py-2 pr-8 rounded shadow leading-tight focus:outline-none"
            >
                {props.placeholder && <option>{props.placeholder}</option>}
                <ListOptions items={props.items} />
            </select>
    )
}

const ListOptions = ({ items }) => {
    if (items)
        return items.map(element => {
            return typeof element === 'string' ? (
                <option>{element}</option>
            ) : (
                <option key={element.value} value={element.value}>
                    {element.text}
                </option>
            )
        })
    return <option>None</option>
}```

Comment: Oi Anderson, tudo bem? Cara, eu não entendi muito bem seu código. Tipo, você tem um componente `` que recebe como itens a **constante plans**. Porque ela muda de array pra array de objetos? Teria como detalhar melhor o código até mesmo mostrando o método completo? A resposta do @HelloWorld funciona, mas as vezes uma simples mudança aí poderia nem precisar de adicionar mais uma função.
Comment: Não é só um componente , existem mais dois, e esses dois recebem um array comum, enquanto somente um deles recebe esse array de objeto.
Answer: Se todos os dados de cada índice do teu array forem do mesmo tipo, tu pode verificar o tipo de um dos indices e com base nisso escolher qual tipo de option tu vai renderizar.
Pode verificar assim:
if(typeof(element[0]) === 'object') {
   renderOption1()
} else {
   renderOption2()
}


Show Block when Listing one Content type

Question: I have a silly question, i have one content type "ABC" and i have create a view page for listing all contents of that type with path "/abc". Next, i create a block which is listing all content of type "DEF", and configure the block "DEF" to show only when i'm listing the content "ABC", but not work.
Only work when i'm configure the block and put on "pages" restriction page like "/abc" path.
I'm doing something very wrong.
Any hint?
Comment: Hi there, is this question about drupal 7 or 8? please add tag.
Comment: Sorry, it's for the drupal 8. I can't edit my own post.
Answer: Please follow these instructions carefully:
1) Go to /admin/structure/block and click on "Pleace block" button in the region you want to add your view block, for example "Content" region.
2) Now you will see at least three tabs:"Content types", "Pages", "Roles"
3) In tab "Content types" select "DEF" type content
4) Be sure on tab "Pages" is selected the radio button option "Show for the listed pages", leave empty the text area on this tab.
5) Save block.
Hope this help.
Comment: Sorry may be i didn't explain correctly or I missing something. I already do that but didn't work. First created a view for listing one type of content. And when visit the "url" /list-abc can't saw the content type of DEF. May be i'm doing something wrong.


Funções async dentro de setInterval dando Syntax Error no HTML

Question: Bom dia/noite pessoal, estou com um problema bem chato, estou a criar um site para um projeto de biologia da escola, sobre celulas. Nesse site tenho preciso fazer um loop que executa uma ação, espera X segundos e executa outra ação, espera mais Y segundos e volta ao inicio do loop.
Achei alguns codigos usando funções async mas quando tento aplica-las o browser executa uma vez e me retorna um erro de Uncaught SyntaxError: Unexpected identifier na linha numero 1 do html(a cada 2s ele me joga o erro dnv).
JS:
    function first(){
    setTimeout(() => {
    console.log('first')
    }, 1000);
    }

    function second(){
    setTimeout(() => {
    console.log('second')
    }, 1000);

    }

    let run = async ()=>{
    await first();
    await second();
    }

    setInterval(run(), 1000);

Quando comento essa parte, o erro some. Não tenho muito conhecimento sobre async e await, mas já tentei de tudo para fazer isso e ate agora esse é método mais promissor. Espero que entendam o que eu quis dizer, muito obrigado e possivelmente boa noite.
Answer: O erro está acontecendo porque você não está passando uma função para o setInterval.
setInterval recebe dois parâmetros; uma função, e o tempo em milissegundos para executar essa função. Agora veja o que você está fazendo aqui:
setInterval(run(), 1000);

run é uma função, mas ao utilizar run() você está invocando a função e passando o retorno dela como parâmetro para o setInterval. Porém run() não tem um retorno, é undefined, seu setInterval está sendo invocado como setInterval(undefined, 1000), e isso é um erro.
Você poderia invocar seu setInterval como setInterval(run, 1000), ou você poderia também declarar uma função anônima, assim como você fez no setTimeout:
setInterval(() => {
    run();
}, 1000);

Isso resolveria o erro declarado na pergunta. Existe mais um erro nesse código relacionado ao await

await serve para esperar a resolução de uma Promise. A sua função first e second não emitem nenhum tipo de sinal para sinalizar que elas terminaram de executar, o await não sabe o que ele deve esperar.
Você precisa embrulhar essas funções em uma promise. Ao invocar o resolve da promise, você estará emitindo esse sinal de que o await precisa para continuar rodando.
function first() {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log('first')
            resolve()
        }, 1000)
    })
}

function second() {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log('second')
            resolve()
        }, 1000)
    })
}

Agora sim, refatorando todo o código você teria:

function first() {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log('first')
            resolve()
        }, 1000)
    })
}

function second() {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log('second')
            resolve()
        }, 1000)
    })
}

async function run() {
    // loop infinito
    while (true) {
        await first();
        await second();
    }
}

// ironicamente, você nem precisava de um setInterval
run();


Are these two types of updater functions for setState in React equal?

Question: I've recently learned about updater functions for setState in React.
And now I've seen this concept used in two different ways. Let's say we have a state object like this:
interface State {
  readonly expanded: boolean;
  readonly slugs: string[];
}

state: State = { expanded: false, slugs: [] }

I have seen updater functions used like this:
this.setState(prevState => ({ ...prevState, expanded: !prevState.expanded }));

And like this:
this.setState(({ expanded }) => ({ expanded: !expanded }));

I've tried this out myself to see if there is a difference between using the two, but I couldn't find one (besides the amount of characters ). My intuition just tells me that the first way might be more safe because the second way state (in this case slugs) might be overwritten?
Edit: This questions has been flagged as a duplicate of this question, but it is inherently different, because I was wondering about the functionalities of setState and not about how TypeScript's type annotation works. I merely provided the TypeScript types for clarity. I'm sorry this question caused confusion. English is not my main language and I didn't know how to express this more clearly. Luckily someone understood and answered the question perfectly.
Comment: @BhojendraRauniyar I believe type declaration here is used just to demonstrate inner structure of `state`.
Comment: @skyboyer OP is not confused with `state` but the use of different syntax and where destructuring helps to understand.
Comment: @BhojendraRauniyar yes, and he is asking whether functional and return-an-object version of `setState` have any difference in this context.
Comment: Possible duplicate of [How is this type annotation working in React code without TypeScript?](https://stackoverflow.com/questions/52351864/how-is-this-type-annotation-working-in-react-code-without-typescript)
Comment: Also, look at [this post](https://stackoverflow.com/questions/52699006/prevent-this-state-to-be-used-with-setstate/52699118#52699118) for further help.
Comment: ah, yes,  but to answer both results the same, understanding about destructuring will obviously help the OP.
Comment: @J.Hesters Let us know how you think now, if you're still curious about something, then it would be our pleasure to provide answer.
Comment: It seems OP asked and run away. @J.Hesters SO is busy even in weekend. So, stay with us when you ask question. Otherwise, you'll get some downside.
Comment: @BhojendraRauniyar Relax, I'm still here. Reading all your guys comments now. Thank you for your help!
Comment: @skyboyer You were right!
Answer: If you look into the source code, especially into setState and enqueueSetState, you can see the following piece of code:
if (typeof partialState === 'function') {
  partialState = partialState.call(
    pu blicInstance,
    currentState,
    publicInstance.props,
  );
}

// Null and undefined are treated as no-ops.
if (partialState === null || partialState === undefined) {
  return;
}

this._renderer._newState = {
  ...currentState,
  ...partialState,
};

What that means is that
this.setState(({ expanded }) => ({ expanded: !expanded }));

will end up being:
state = {...prevState, {expanded: !expanded}}

and
this.setState(prevState => ({ ...prevState, expanded: !prevState.expanded }));

will end being:
 state = {...prevState, ...{...prevState, expanded: !prevState.expanded}}

I think the second one is basically poor understanding on how the updater function works.
Comment: `state = {...prevState, {...prevState, expanded: !prevState.expanded}}` should be `state = {...prevState, ...{...prevState, expanded: !prevState.expanded}}`(it would raise syntax error otherwise)
Comment: @BhojendraRauniyar The one you have mentioned does not seem to have anything to do with the question.
Comment: may you please add few notes on nested objects in `state` when spread operator is actually required?
Comment: Thank you! This exactly answers my question.
Answer: As the React' official doc State Updates are Merged said, React will merges the object you provide into the current state, not overwrite the whole state.
Answer: Both the statement would result in the same behavior - updation of expanded value.
If you read through the setState method's documentation, React expect the method to return the value that needs to be overridden. React merges the return of the method to the previous state object and does a diff. In the first clause, all the other state variables are the same, except the expanded and in the second clause, only expanded is mutated.
Answer: To understand with the second code, you may look in attached duplicate post, but I found your case a little bit different. Thus, answering here.
this.setState(prevState => ({ ...prevState, expanded: !prevState.expanded }));

Here, the use of ...prevState is just unnecessary. It's because react's setState handles the particular state and merge other states.
this.setState(prevState => ({ expanded: !prevState.expanded }));

You'll only need to use merging when you'll need to update the properties nested in the particular state. For example, if you have something like:
state = {
  people: {
   male: 1033,
   female: 234,
   other: 100
  }
}

Now, in this case you may merge people value when you only update the male count like:
this.setState(prevState => ({ people: { ...prevState.people, male: 1045 } }))

Which can simply be written destructuring like:
this.setState(({people}) => ({ people: { ...people, male: 1045 } })

Comment: Awesome this enhances Sulthan's answer even more! Thank you both for your help.


Rendering error messages from failed authentication in React-Redux and React Router DOM v4

Question: TL;DR version: In a React-Redux project with React Router DOM v4 how do I take the server response from an axios.put in an ./actions file and import into my "smart components" in ./containers so it can be used in auth logic and rendered as messages for the user (e.g., "Invalid credentials").
Long version: So I have been learning React-Redux and started with the Stephen Grider courses on Udemy. What is adding to my confusion stems from the fact that the intro/intermediate course is in React Router DOM v4 and the advanced course is in React Router v2. Spending a lot of time converting over to v4.
Anyway, getting protected routes and rerouting after successful login stuff sorted at. The problem I have now is getting responses from the server into a Redux-React container.
For example, if the login credentials are wrong, the login API responds with a 400 error. I should be able to take this response and render a message like The credentials provided are invalid. I can get the response in my ./actions/authentication file and console.log() it, but just can't get it into the ./containers/authentication/signin.js.
The Stephen Grider tuts using React Router v2 work fine. Here is the code from his project, followed by mine:
// ./actions/index.js

import axios from 'axios';
import { browserHistory } from 'react-router';
import {
  AUTH_USER,
  UNAUTH_USER,
  AUTH_ERROR,
  FETCH_MESSAGE
} from './types';

const ROOT_URL = 'http://localhost:3090';

export function signinUser({ email, password }) {
  return function(dispatch) {
    axios.post(`${ROOT_URL}/signin`, { email, password })
      .then(response => {
        dispatch({ type: AUTH_USER });
        localStorage.setItem('token', response.data.token);
        // The below no longer works as of React Router DOM v4
        browserHistory.push('/feature');
      })
      .catch(() => {
        dispatch(authError('Bad Login Info'));
      });
  }
}

export function authError(error) {
  return {
    type: AUTH_ERROR,
    payload: error
  };
}

// ./components/auth/signin.js

import React, { Component } from 'react';
import { reduxForm } from 'redux-form';
import * as actions from '../../actions';

class Signin extends Component {
  handleFormSubmit({ email, password }) {
    // Need to do something to log user in
    this.props.signinUser({ email, password });
  }

  renderAlert() {
    if (this.props.errorMessage) {
      return (

          Oops! {this.props.errorMessage}

      );
    }
  }

  render() {
    const { handleSubmit, fields: { email, password }} = this.props;

    return (
      <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
        <fieldset className="form-group">
          Email:
          <input {...email} className="form-control" />
        </fieldset>
        <fieldset className="form-group">
          Password:
          <input {...password} type="password" className="form-control" />
        </fieldset>
        {this.renderAlert()}
        <button action="submit" className="btn btn-primary">Sign in</button>
      </form>
    );
  }
}

function mapStateToProps(state) {
  return { errorMessage: state.auth.error };
}

export default reduxForm({
  form: 'signin',
  fields: ['email', 'password']
}, mapStateToProps, actions)(Signin);

// ./reducers/index.js

import {
  AUTH_USER,
  UNAUTH_USER,
  AUTH_ERROR,
  FETCH_MESSAGE
} from '../actions/types';

import { combineReducers } from 'redux';
import { reducer as form } from 'redux-form';
import authReducer from './auth_reducer';

const rootReducer = combineReducers({
  form,
  auth: authReducer
});

export default rootReducer;

export default function(state = {}, action) {
  switch(action.type) {
    case AUTH_USER:
      return { ...state, error: '', authenticated: true };
    case UNAUTH_USER:
      return { ...state, authenticated: false };
    case AUTH_ERROR:
      return { ...state, error: action.payload };
    case FETCH_MESSAGE:
      return { ...state, message: action.payload };
  }

  return state;
}

Mine is just slightly modified due to trying to get this working with React Router DOM v4. I put comments in the code that may be of some interest. The ./reducers have been unchanged except for import... from.
// ./actions/authentication/index.js

import axios from 'axios';
import { ROOT_URL } from '../../../config/settings/secrets.json';

const AUTH_USER = 'auth_user';
const UNAUTH_USER = 'unauth_user';
const AUTH_ERROR = 'auth_error';

export function signinUser({ username, password }) {
    return function(dispatch) {

        axios.post(`${ROOT_URL}/api/auth/token/`, { username, password })
            .then(response => {
            dispatch({ type: AUTH_USER });
            localStorage.setItem('token', response.data.token);
            })
            .catch(() => {
            dispatch(authError('Bad Login Info'));
        });
    }
}

export function authError(error) {
    // Can console.log() this out and payload does show 'Bad Login Info'
    // How to get it innto the signin.js container though?
    return {
        type: AUTH_ERROR,
        payload: error
    };
}

// ./containers/authentication/signin.js

import React, { Component } from 'react';
import { reduxForm, Field } from 'redux-form';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import * as actions from '../../actions/authentication';

const renderInput = field => {
    const { input, type } = field;
    return (

            <input {...input} type={type} className='form-control' />

    );
}

class Signin extends Component {
    handleFormSubmit({ username, password }) {
        this.props.signinUser({ username, password });
        // This is a bad idea since it will pass anything if username and password is entered
        // Thus why trying to take the server response and use that
        if (username !== undefined && password !== undefined) {
            this.props.history.push('/home');
        }
    }

    renderAlert(errorMessage) {
        // Cannot console.log() any of this out
        // this.renderAlert() doesn't seem to be getting triggered
        if (errorMessage) {
            return (

                    Oops! {this.props.errorMessage}

            );
        }
    }

    render() {
        const { handleSubmit } = this.props;

        return (
            <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>

                    Username:
                    <Field name='username' type='username' component={renderInput} />

                    Password:
                    <Field name='password' type='password' component={renderInput} />

                {this.renderAlert()}
                <button action="submit" className="btn btn-primary">Sign in</button>
            </form>
        );
    }
}

function mapStateToProps(state) {
    console.log(state);
    return { errorMessage: state.auth.error };
}

Signin = connect(mapStateToProps, actions)(Signin);
Signin = reduxForm({
    form: 'signin'
})(Signin);
export default withRouter(Signin);

Edit: Consulting this image as refresher for the React-Redux data flow. Seems like most everything is working up to getting it back into the container, so is mapStateToProps failing somehow?
Comment: Try to change `if (errorMessage) {...` to `if (this.props.errorMessage) {...`.
Comment: Yea, still nothing. Can't `console.log()` anything out, at least can't figure out how to from the `./containers/signin.js`.
Answer: Oh man, I wasn't exporting my action types (AUTH_USER, UNAUTH_USER, and AUTH_ERROR) so that they could properly be consumed by the reducers.
// ./actions/authentication/index.js

export const AUTH_USER = 'auth_user';
export const UNAUTH_USER = 'unauth_user';
export const AUTH_ERROR = 'auth_error';

The missing export caused the issue.


Como integrar um código Java com um em JavaScript?

Question: //retorna o usuário logado no sistema
public class ContextObject {

    public static Usuario getUsuario() {
        ContextObject contextObject = ContextFactory.getContextObject();
        return contextObject.usuario;
    }

}

//mostra em uma função alert() o usuário logado

Tendo em vista que esses dois códigos estão em arquivos diferentes.
Estou fazendo isso mas não está certo, como devo fazer? Preciso pegar o retorno do código java e mostrar o que esta chegando na função alert do javascript.
Comment: Se o código javascript for executado do lado do cliente e o código java estiver do lado do servidor, parece-me uma tarefa difícil de executar. Nesse caso AJAX poderá ser uma solução para esse problema.
Answer: Inicialmente você deveria ter um método que retornasse um json com os dados desejados, pode ser na mesma classe.
Mas envolveria uma configuração REST que não citarei aqui, mas pode encontrar neste link e aqui.
O método você anota seu método com @GET e @Produces("application/json") e a classe com a anotação @Path("/caminho").
Também deverá anotar sua classe usuário com @XmlRootElement.
No seu javascript você pode chamar o método via GET do HTTP.
Algo assim:
$(function () {
    $.getJSON("/caminho", function(data) {
        alert(data.nome);
    });
});

Comment: data seria o nome da classe?
Comment: cria a rest pra min? nunca fiz nada do tipo :(
Comment: Não, data é o argumento que estou passando para o método. Usei data pois significa dados em português. É meio que um padrão, mas pode ser o nome da classe se desejar. Sobre o REST postei dois links que ensinam a fazer, é só seguir o tutorial.


Multiple users mounting a shared server utilizing Git

Question: I am wondering if this type of setup would be good for Git. We have a server that contains source code, when we make code changes it must also be tested on this server. To avoid pulling the code locally making changes, syncing back up to the server for testing and then committing, we are wondering if we can mount the server locally.
Our concern is that git will track changes of all users since we are sharing the same (mounting the same) repository. Is there a way we can set this up and have Git track each users change independently, possibly through ssh-keys?
Answer:
Is there a way we can set this up and have Git track each users change independently, possibly through ssh-keys?

Yes, providing you use the git wrapper I wrote, VonC/gitw
It uses the SSH_CONNECTION environment variable and ask you, at the first git command, who you are.
Then, for the rest of the session, all your git command will be done with the proper GIT_AUTHOR_NAME/GIT_AUTHOR_EMAIL.
If you are connecting from the same fixed IP, you won't even been asked who you are at your next SSH session.
That way, each use makes commits with their proper user.name/user.email.
Comment: Thanks for reaching out and congrats on 1mil rep! Trying the install your wrapper on centos and have a few follow up questions. From the install guide there is one step that I don't quite understand "put the gitw generate in the previous step" could you elaborate more on this? Additionally I was also looking through the shell script and noticed a few interesting commands "ok" "error" and "info" as these are not recognized by centos can I simply change them to echo?
Comment: @gitquestion926 The `build.bat amd` executed on a PC (with Go installed) will have generated the `gitw` binary.
Comment: @gitquestion926 And I just pushed the missing `echos` file: a simple git pull, and those `ok`, `error` and `info` will work!
Comment: Ohh I see the confusion I looked at them as if they were separate install instructions. Do you know which version of GO you used to compile? I just installed go1.15.6 on my windows but when I run `build.bat amd` I'm seeing `usage: link  [options] main.o` . There is also a line before it stating `not a git repository`, it did successfully download `go-prompt` `sys` `term` and `go-runewidth`
Comment: @gitquestion926 Did you clone the repository? Di you launch `build amd` from within that clone repository folder?
Comment: Yes, here is a screenshot of the output I'm seeing. https://imgur.com/a/aUMsybi
Comment: @gitquestion926 `gitw-master` does not look like the name of a cloned repository, but rather an archive of the project uncompressed: if you don't see a `.git` subfolder in that `gitw-master`, he build won't work.
Comment: @gitquestion926 You need to `git clone https://github.com/VonC/gitw` and `cd gitw`
Comment: My mistake, thank you for all the troubleshooting help. I'm unfortunately  still seeing an issue that I think may have to do with the go version? Here is a new output https://imgur.com/a/cgJtSyY One thing I noticed is that after the clone I don't see a .git folder .  On the screenshot the clone is on the left and the build is on the right
Comment: @gitquestion926 Left side looks good. Right side should work. I am using Go 1.15.3. Try and replace the first line of `build.bat` by `@echo on`, and grab a screenshot of what the build does.
Comment: Here is a screenshot using go1.15.6 with echo on https://imgur.com/a/RE1TOkD
Comment: @gitquestion926 Right! I see.... the locale used will make the commands time and date return a different value which means the day/hours are not properly parsed
Comment: @gitquestion926 Can you uncomment line 18 (remove rem) and comment line 19 (rem). line 22, replace dtStamp24 by dtStamp9.


(Ionic 2) Grouping label inside select box

Question: I need to create the multiple checkbox  select box that have grouping label inside the box.
Example
-Appetizer:
---Salad
---etc
-Main Course:
---Steak
---etc
-Desert:
---Ice Cream
---etc
This is my code:

<ion-select [(ngModel)]="food" multiple="true">
                        <ion-label>Toppings</ion-label>
                        <ion-option>Bacon</ion-option>
                        <ion-option>Black Olives</ion-option>
                        <ion-option>Extra Cheese</ion-option>
                        <ion-option>Mushrooms</ion-option>
                        <ion-option>Pepperoni</ion-option>
                        <ion-option>Sausage</ion-option>
 </ion-select>

How to create the grouping label inside the ion-select? Thanks..
Answer: A good way to do this is to add the disabled tag to the "label".
This will cause the option to not be selectable, you can then add a class to it in order to adjust the look as needed.
<ion-select [(ngModel)]="food" multiple="true">
    <ion-option disabled>Toppings</ion-option>
    <ion-option>Bacon</ion-option>
    <ion-option>Black Olives</ion-option>
    <ion-option>Extra Cheese</ion-option>
    <ion-option>Mushrooms</ion-option>
    <ion-option>Pepperoni</ion-option>
    <ion-option>Sausage</ion-option>
 </ion-select>

Comment: Label used to work, they have tightened it up a bit since then
Comment: Thanks for the update, I know ionic is getting a lot of updates with Angular 2. I only started using it recently. It must've been removed
Comment: Adding it as `ion-label` doesn't work. It should be `ion-option` like the rest of the options.
Comment: Is there anyway "Not to display a checkbox for disabled option". I tried  css selector  button .alert-md .alert-checkbox-icon to remove border color but it doesn't work
Answer: I use it in IONIC 5/6
In .html File
    <ion-select multiple class="group-select">
      <ion-select-option disabled class="option-group-custom"> -- EU Group 1 -- </ion-select-option>
      <ion-select-option>Add Knowledge</ion-select-option>
      <ion-select-option>Share Knowledge</ion-select-option>
      <ion-select-option>Other</ion-select-option>
      <ion-select-option disabled class="option-group-custom"> -- EU Group 2 -- </ion-select-option>
      <ion-select-option>Option 1</ion-select-option>
      <ion-select-option>Option 2</ion-select-option>
    </ion-select>

and in global.scss
.option-group-custom {
  .alert-checkbox-icon {
    display: none;
  }

  .alert-checkbox-label {
    padding-left: 10px;
  }
}


$\eta_{\epsilon}*u$ satisfies heat equation

Question:
If $u(x,t)$ satisfies the heat equation then $\eta_{\epsilon}*u$ also satisfies it, with $\eta(x)=e^{\frac{1}{|x|^2-1}}$ for $|x|<1$ and $0$ else and $\eta_{\epsilon}(x):=\frac1{\epsilon^{n}}\eta(\frac{x}{\epsilon})$

It is not mentioned which heat equation (homegeneous or not). I think, one has to get then;
$\partial_t(\eta_{\epsilon}*u)=(\eta_{\epsilon}*\partial_t u)$
$\Delta_{xx}(\eta_{\epsilon}*u)=(\eta_{\epsilon}*\Delta_{xx}u)$
then the difference should be zero, but which property is used to justify the differentiaion under the integral, that the support of $\eta$ is bounded or that both functions are twice differentiable
Answer: You are definitely using that $u$ is twice differentiable in $x$ and differentiable in $t$. You also need to show/assume that $\eta_{\varepsilon}\in L^1(\mathbb{R})$.


weighted one-hot encoding

Question: I am using one-hot encoding to transform my categorical variable. But it's not just a presence-absence situation. Consider the variable as a device that can have with different brands as well as different model numbers. So, for example it can be Sony 10, Sony 10.5, or LG 2000, LG 3200. The brands differ and the model numbers have their own range too.
What I did was something like this:
I convert:
---------------------------
|   Index   | Device
---------------------------
|   0       | Sony,10
|   1       | Sony,10.5
|   2       | LG,2000
|   3       | LG,3200

to:
---------------------------
|   Index   | Dev_Sony | Dev_LG
---------------------------
|   0       | 10       | 0
|   1       | 10.5     | 0
|   2       | 0        | 2000
|   3       | 0        | 3200

Question: I am using multiple linear regression. Using the above encoding, the model numbers (e.g. 10 vs 10.5) are useful when comparing devices of the same brand, but I'm not sure if they make sense in comparison with other brands. So, I was wondering if there is a better way of encoding such data.
UPDATE
based on the answer, my dataframe would look like this:
|   Index   | Dev_Sony | Dev_LG  | Model_Number
---------------------------
|   0       | 1        | 0       | 10
|   1       | 1        | 0       | 10.5
|   2       | 0        | 1       | 2000
|   3       | 0        | 1       | 3200

Answer: Make two categorical variables, Device with values Sony, LG, ... and Model_Number with values 10, 10.5, 2000, 3200, ... . Then Model_Number is nested within Device.  See then How do you deal with "nested" variables in a regression model?   for how to model this.
But, very shortly, if you are using R then use the nesting operator / in the formula language, y ~  Device/Model_Number + ....
Comment: No, I mean `Dev/Num`  (which can be read Dev, and within Dev, Num) expands into `Dev + Dev:Num`. A good discussion is in https://www.springer.com/gp/book/9780387954578
Comment: I was implementing this today and realised that I forgot about one part. In practice, I'd still need to get the dummy variables for the devices. So, I'd still end-up with columns of unique devices. R should be doing the same behind the scene (I get the dummy_codes in Python using the Pandas library). Please have a look at the `Update` based on your answer. And then, I'll have `Dev` and `Dev*Num` in the formula.
Comment: The data frame in your update looks fine.
Comment: Also, multicollinearity itself is a problem anyway, since, in your approach, all dummy variables will be almost perfectly collinear with their interaction terms (interaction is 0 when a dummy variable is 0, and a positive number (`Dev*Num` when the dummy variable is 1) . My point is since they are collinear, we can then drop one of them, say the dummy variable itself, and we end up using only the interaction term, which is exactly what I used in the first place (the second dataframe in the question)
Comment: Thanks for the answer. I'm using `Python`, if I understand your other post correctly, it should be modelled as "conditional variables": `y ~ Device + Device:Model_Number`? and why `Device/Model_num` rather than `Device*Model_num`? Can you give me a textbook reference where I can read more about this?
Comment: Those two notations are equivalent!

weighted one-hot encoding


Suppose that $R$ is a commutative ring with unity, $a \in R$, and $\varphi(r) = ar$ defines a ring homomorphism. Prove that $a$ is idempotent.

Question:
Suppose that $R$ is a commutative ring with unity, $a \in R$, and $\varphi(r) = ar$ defines a ring homomorphism $\varphi$. Prove that $a$ is idempotent, i.e. that $a = a^{2}$.

This is exercise 15 from chapter 17 of A First Course in Abstract Algebra: Rings, Groups and Fields, Second Edition by Marlow Anderson and Todd Feil.
Here is my attempt at a solution.
Attempt
By definition of $\varphi$, $\varphi(a^{2}) = aa^{2} = a^{3}$. But since $\varphi$ is also a ring homomorphism, $\varphi(a^{2}) = \varphi(aa) = \varphi(a)\varphi(a) = aaaa = a^{4}$.
Now, $a^{3} = a^{4}$ $\dots$

This is as far as I get. I really want to perform multiplicative cancellation and get the answer from here, but I do not know if $a$ is the additive identity and I do not know if $R$ is an integral domain, so that really isn't an option.
I'm not sure how to proceed.
I believe the homomorphism's multiplication preserving property will be important. This suggests that there is some product $xy$ such that when $\varphi$ is applied, it will take on two values with different terms that will then provide the equality $a = a^{2}$ after some algebraic manipulation.
Answer: Note that $\varphi(1_R)=a$. But also
$\varphi(1_R)=\varphi(1_R\cdot1_R)=a\cdot a=a^2$.


What should I set LR to before calling main() in an embedded processor?

Question: So I'm trying to write a baremetal OS on an armV7 cortex-a8 using GCC and I ran into a bit of a problem.
After I finished setting up the C environment in assembly and jumped to main, I noticed my stack frame was not being kept track of properly. On further inspected it looks like the LR register is being pushed onto the stack as the function that called main() and it's screwing up the debugger.
Problem goes away if I set LR to 0 - but is this the proper way of dealing with this?
Comment: Might be useful to include a fragment of your start-up code - the preparation and call to `__main` and the handling if `__main` should return.  Typically if main returns, you call an endless-loop, force a reset, or call an exception handler - either way, LR will not be used, so it matters little what you set it to, but the debugger has little choice that to interpret it if it is non-null since it has otherwise no knowledge of the call depth.
Comment: May be you can change instruction from ```BL main``` to ```B main``` from assembly. See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0489e/Cihfddaf.html for more information.
Comment: Zero is typical for the older ARM ABI (APCS and `-mapcs-frame`).  The AAPCS can be marked with 'cant undwind', but then you embedded bare metal binary needs lots of exception tables, at least where a stack trace will take place.  So, the answer depends.  [Here is an interesting  approach](http://www.mcternan.me.uk/ArmStackUnwinding/).
Answer: The document Exception handling ABI for the ARM architecture  suggests this:

The runtime environment must ensure a stack unwind cannot proceed beyond the valid stack region, possibly by marking the caller of main() as EXIDX_CANTUNWIND.

This should happen if you use the .cantunwind directive in your startup code.


Change Add to cart button text in Drupal 7

Question: I am using Drupal 7 and Ubercart 3. I want to change the text for the button "Add to cart", how can I achieve this?
Any help, thanks.
Answer: The string overrides module is handy for these kind of things.
Provides a quick and easy way to replace any text on the site.

Features

Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the Locale module
Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you
  need a few easy text changes.


Bringing a subview to be in front of all other views

Question: I am working on integrating an ad provider into my app currently. I wish to place a fading message in front of the ad when the ad displays but have been completely unsuccessful.
I made a function which adds a subview to my current view and tries to bring it to the front using
[self.view bringSubviewToFront:mySubview]

The function fires on notification that the ad loaded (the notification is from the adprovider's SDK). However, my subview does not end up in front of the ad. I imagine this is made purposely difficult by the ad provider, but I wish to do it regardless. I am currently discussing with the provider whether or not this can be allowed. But for the time being, I just want to see if it's even possible.
Is there anyway I can force a subview of mine to be the top-most view such that it will not be obstructed by anything?
Answer: try this:
self.view.layer.zPosition = 1;

Comment: i was searching 3 years after the solution =)
Comment: Unfortunately this can not change the gesture responding order.
Comment: This only puts the view in front, but not all the gesture and touch events.  so  when the user tries to touch the view,  it will touch some other view.   The solution by @jere is the correct one.
Comment: Can I ask why you sent this reply 3 years after this question was posted?
Comment: Thank you for this answer. Was useful for a Map pin issue (I wanted to force one on top of the others)
Comment: i was searching 12 years after the solution =)
Comment: how to make the above view active
Comment: Well if you do this repeatedly for some arbitrary close by views, they both have zPosition == 1, and that's not ok. (without custom zPosition logic)
Answer: What if the ad provider's view is not added to self.view but to something like [UIApplication sharedApplication].keyWindow?
Try something like:
[[UIApplication sharedApplication].keyWindow addSubview:yourSubview]

or
[[UIApplication sharedApplication].keyWindow bringSubviewToFront:yourSubview]

Comment: Doesn't work for iAd banner views... which is a common "needs to be on top" problem. (iAds are not allowed in non-VCs)
Comment: or [parentview bringSubviewToFront:yourSubview]    , where parentview is the inmediate view of the subview
Answer: Swift 2 version of Jere's answer:
UIApplication.sharedApplication().keyWindow!.bringSubviewToFront(YourViewHere)

Swift 3:
UIApplication.shared.keyWindow!.bringSubview(toFront: YourViewHere)

Swift 4:
UIApplication.shared.keyWindow!.bringSubviewToFront(YourViewHere)

Hope it saves someone 10 seconds! ;)
Comment: What if I want to bring the keyWindow itself to the front ? I am facing an issue where the keyWindow stays on the back for some reason...
Answer: I had a need for this once. I created a custom UIView class - AlwaysOnTopView.
@interface AlwaysOnTopView : UIView
@end

@implementation AlwaysOnTopView

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.superview && [keyPath isEqual:@"subviews.@count"]) {
        [self.superview bringSubviewToFront:self];
    }

    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    if (self.superview) {
        [self.superview removeObserver:self forKeyPath:@"subviews.@count"];
    }

    [super willMoveToSuperview:newSuperview];
}

- (void)didMoveToSuperview {
    [super didMoveToSuperview];

    if (self.superview) {
        [self.superview addObserver:self forKeyPath:@"subviews.@count" options:0 context:nil];
    }
}

@end

Have your view extend this class. Of course this only ensures a subview is above all of its sibling views.
Comment: This is brilliant!
Answer: As far as i experienced zposition is a best way.

self.view.layer.zPosition = 1;
Answer: Let me make a conclusion. In Swift 5
You can choose to addSubview to keyWindow, if you add the view in the last.
Otherwise, you can bringSubViewToFront.
let view = UIView()
UIApplication.shared.keyWindow?.addSubview(view)
UIApplication.shared.keyWindow?.bringSubviewToFront(view)

You can also set the zPosition. But the drawback is that you can not change the gesture responding order.
view.layer.zPosition = 1

Answer: In c#, View.BringSubviewToFront(childView);
       YourView.Layer.ZPosition = 1;
both should work.
Answer: In Swift 4.2
UIApplication.shared.keyWindow!.bringSubviewToFront(yourView)

Source: https://developer.apple.com/documentation/uikit/uiview/1622541-bringsubviewtofront#declarations
Comment: No they changed in Swift 4.2, Please have a look at https://developer.apple.com/documentation/uikit/uiview/1622541-bringsubviewtofront#declarations @LuigiTaira


Dacpac Upgrade database Times a little silly

Question: Edit: Updated to state it isn't hanging, just takes AGES!
I'm trying to update an existing sql server database using a dacpac.
I can create a new SQL server database with the (stripped down) example below in 30 seconds.
The issue I'm having is that using the same dacpac, rerunning the procedure (so it is updating an existing database rather than creating afresh) takes 20 minutes.
Is this kind if time difference what is to be expected? Having used redgate's SqlCompare comprehensively, I'm finding the time unpaletable.
The third param of the deploy method is UpgradeExisting which I'm setting to true - Is this all I need to do or am I missing something??
void Deploy(string TargetConnectionString, string TargetDatabaseName, string pathToSourceDACPAC)
{

    DacServices dacServices = new DacServices(TargetConnectionString);

    //Set up message and progress handlers
    dacServices.Message += new EventHandler<DacMessageEventArgs>(dbServices_Message);
    dacServices.ProgressChanged += new EventHandler<DacProgressEventArgs>(dbServices_ProgressChanged);

    //Load the DACPAC
    DacPackage dacpac = DacPackage.Load(pathToSourceDACPAC);

    //Set Deployment Options
    DacDeployOptions dacOptions = new DacDeployOptions();
    dacOptions.AllowIncompatiblePlatform = true;

    //Deploy the dacpac
    dacServices.Deploy(dacpac, TargetDatabaseName, true, dacOptions);

}

//Event handlers...
void dbServices_Message(object sender, DacMessageEventArgs e)
{
    OutputThis("DAC Message", e.Message.ToString());
}

void dbServices_ProgressChanged(object sender, DacProgressEventArgs e)
{
    OutputThis(e.Status.ToString(), e.Message.ToString());
}

NB the program disappears into the ether on the dacServices.Deploy line..
Comment: What happens if you try to just generate a script from within SSDT itself? Does it still take a while to build/publish? Is it the build action or the publish action that takes the longest times? Do you have a lot of DB References? If so, have you considered stripping out unnecessary objects from them? How many objects do you have in your target DB / Project? The time will increase as more objects are added because you're comparing those. You may also want to try using SQLPackage.exe to push the changes and/or gen a script to see how that works. Not the end goal, but could help to troubleshoot
Comment: Hi @PeterSchott. Within SSDT it takes around 10 seconds to create the script, likewise if I create the script via sqlpackage.exe However if I use the deploy via a dacpac, or create diff script via the API using string the GenerateDeployScript(rather than .Deploy in the original Q) it takes in the region of 20 minutes. The database is relatively small (200 tables, 200 views, 150 functions, 700 sp's..)... nothing rediculous, & the target db is currently empty. The figures are when running on local machine so network isn't an issue either.
Comment: End to end process of creating a script via sqlpackage and deploying updates via sqlcmd is around 20s so I'll probably end up doing that... I'd just like to be able to understand  the time differences.
Answer: OK, the silly times were experienced while running through the debugger (VS2012). Once compiled the times were 25 or so seconds when chosing the Memory DacSchemaModelStorageType, or 45 or so seconds when chosing the File DacSchemaModelStorageType .
I guess this just means that debugging is a pain in the whatsit!
Comment: @Mark - as I mentioned above check whether you are getting a lot of warnings as all the antlr ones are first chance exceptions which pause the app, pass control to the debugger (vs) which decides whether to break or continue - even if you have first chance exceptions disabled, that is what you get with the debugging api (visual studio has no control over it) - it is a massive overhead if there are alot of exceptions.
Comment: I have also been having the same problems. But my solution contains 7 databases with references to each other, and about 3500 stored procedures amongst them. Running through the debugger it takes about 2 hours to deploy! But if I run my compiled app, it takes 10 minutes. Thanks for the tip!!!
Comment: @MarkWhitfeld - 2 hours...yikes!
Answer: If you are finding it much slower under a debugger, do you have many warnings?
Warnings are generally generated by the antlr parser it uses and the parser throws exceptions which are very expensive.
Work to fix the warnings and the build time should come down.
Ed
Comment: Thanks Eddie for the tip I'll check into that. It's been running live on 100's of clients for over 18 months now so it's not at the top of the priority list to check, and obviously they're running in release mode. We don't have a "0 warnings on compile" policy rightly or wrongly, so it's entirely possible warnings have been raised and ignored :|
Answer: We had the same problem - dacpac deploys would perform fine when running tests but run very slow while debugging tests.
In my case, the dacpac had a bunch of .sql scripts which seeded some test data into the database. One of these scripts was autogenerated from SSMS, so it was 40,000 lines long, something like this:
INSERT [dbo].[Resource] ([CategoryId], [StoreCode], [LocaleCode], [ResourceName], [ResourceText]) VALUES (1, N'AU', N'en-AU', N'AD', N'Andorra')
GO
INSERT [dbo].[Resource] ([CategoryId], [StoreCode], [LocaleCode], [ResourceName], [ResourceText]) VALUES (1, N'AU', N'en-AU', N'AE', N'United Arab Emirates')
GO
INSERT [dbo].[Resource] ([CategoryId], [StoreCode], [LocaleCode], [ResourceName], [ResourceText]) VALUES (1, N'AU', N'en-AU', N'AF', N'Afghanistan')

etc, for 40,000 lines, i.e. 20,000 INSERT AND GO statements.
I was able to see that script was causing the problem by querying my dbo.Resource table while I was debugging and seeing that the script in question was executing slowly, as the number of rows in that table was still increasing.
I rewrote that script using some Notepad++ macros to have fewer INSERT statements, and to insert 1000 rows on each INSERT, e.g.
INSERT [dbo].[Resource] ([CategoryId], [StoreCode], [LocaleCode], [ResourceName], [ResourceText]) VALUES
(1, N'AU', N'en-AU', N'AD', N'Andorra'),
(1, N'AU', N'en-AU', N'AE', N'United Arab Emirates'),
(1, N'AU', N'en-AU', N'AF', N'Afghanistan'),
...
GO

and that fixed the problem.
Comment: Good to know, Matt. Thanks
Answer: Hopefully someone will have some dacpac specific advice, but since you mentioned SQL Compare was faster, you may want to have a look at package based deployments as part of Red Gate's Deployment Manager tool, which has built-in support for SQL Server databases.
Comment: Hi @Justin, thanks for the reply. We'd taken a look at DM and alas the license requirements were not a good fit with our workflow.


Tips and what to avoid using OData in a multitenant DB SaaS environment

Question: Looking at data access for a multitenant SaaS database for a UI5 app I have two choices - JSON or OData. OData has some features of interest. However, I have concluded that I cannot use OData because of security issues.
In particular I am concerned that OData is a form of query language. As a very rough comparison this is like a SQL statement being composed at the client and sent to an ODBC server for processing. In a multitenant DB I will separate data between owners using, say, and org_id. If it were a SQL query I would have to include select data from table where org_id=this_tennant and .... If I can discover another tenants org_id then I can use an OData explorer to modify the query and pass into the OData source.
In a JSON data interface I would call a REST method that would mask how the data is accessed, and I would not need to expose secret details such as the org_id token. Granted the JSON / REST approach involves more work.
Or do I misunderstand OData ?
Another similar question was asked some time ago but some time has passed so I shall ask again.
Comment: What are the security issues you think about?
Comment: Thanks. I have added a para to the question.
Answer: The approach of OData is to define how RESTful APIs can be build. It adds a lot of concepts and conventions (e.g. entity types and sets, URL conventions, common query parameters, request format, batch support...) to plain REST and therefore provides you a standard for building your API.
However, it does not define where your data is coming from, but in most cases it will be database. Of course it would be possible to expose your database tables via an OData service in a generic way, but I would expect that the provider of the framework clearly describes how to handle and protect different tenants.
A more specific answer would require more information about the framework you will use.
Comment: Thanks Matbtt. At the moment I have a gap to fill between SQL Server database where data will reside, and the client. Traditionally I would write C# services calling SQL stored procedures to server and update data, and would handle the org_id behind the service out of the clients view. I see the investment in metadata creation for OData being significant and so I am looking for clear reasons to pursue OData, or not. I will read up on OData for SQL Server.
Comment: You're welcome. If you are using C# you should be able to create OData service more or less easily! ;)


Proof of lemma in order to prove Cauchy-Schwarz inequality

Question: I am trying to prove the Cauchy-Schwarz inequality without defining a new function to do so. Specifically I am trying to show that:
$$\left(\sum_{k=1}^n a_kb_k\right)^2 = \sum_{k=1}^n a_k^2 \sum_{k=1}^nb_k^2 - \frac{1}{2}\sum_{k=1}^n\sum_{j=1}^n(a_kb_j-a_jb_k)^2$$
Does anyone have any advice on how to proceed?
Answer: Expand the square:
$$\sum_{k=1}^{n} \sum_{j=1}^{n} (a_k b_j - a_j b_k)^2=\sum_{k=1}^n \sum_{j=1}^n (a_k^2 b_j^2 - 2 a_k b_k a_j b_j + a_j^2 b_k^2)$$
$$=\sum_{k=1}^n \sum_{j=1}^n a_k^2 b_j^2 - 2 \sum_{k=1}^n \sum_{j=1}^n a_k b_k a_j b_j  + \sum_{k=1}^n \sum_{j=1}^n a_j^2 b_k^2$$
Using the distributive property we see this equals
$$\left(\sum_{k=1}^n a_k^2\right)\left(\sum_{j=1}^n b_j^2\right) - 2 \left(\sum_{k=1}^n a_k b_k\right)\left(\sum_{j=1}^n a_j b_j\right)+ \left(\sum_{j=1}^n a_j\right)\left(\sum_{k=1}^n b_k\right).$$
The first and the third terms are equal, so we get
$$2\left(\sum_{k=1}^n a_k^2\right)\left(\sum_{j=1}^n b_j^2\right) - 2 \left(\sum_{k=1}^n a_k b_k\right)\left(\sum_{j=1}^n a_j b_j\right).$$
Rearrange the terms.


Evaluate $\int \frac{xe^x}{1+x^2}dx$

Question:
Evaluate $\int \frac{xe^x}{1+x^2}dx$

My attempt: I tried to evaluate the integral by parts considering $\frac{x}{1+x^2}$ as first function and $e^x$ as second function but did not get anything useful.
Comment: You may have to represent the result in terms of $\mathrm{Ei}(x)$ i.e. Exponential integral.
Comment: If you are familiar with Complex Analysis, then you can express your integrand as $\frac{z\cdot e^z}{1+z^2}=\frac{z\cdot e^z}{(1+iz)(1-iz)}$. This is easily solved by using Residue Theory. E.g. check E. Stein, R. Shakarchi "Complex Analysis".
Comment: This is equivalent to solving the differential equation $$ g(x)+g'(x)=\frac{x}{x^2+1}.$$ The non-elementary exponential integral cannot be avoided since the RHS has simple poles at $x=\pm i$.
Comment: You can perform partial fraction decomposition, and then use the $Ei(x)$.
Comment: Was the original question a definite integral?
Answer: \begin{align}
\int\frac{x\mathrm{e}^x}{x^2+1}\,\mathrm{d}x&=\int\frac{x\mathrm{e}^x}{\left(x-i\right)\left(x+i\right)}\,\mathrm{d}x \\ & = \int\left(\frac{\mathrm{e}^x}{2\left(x+i\right)}+\dfrac{\mathrm{e}^x}{2\left(x-i\right)}\right)\mathrm{d}x \\ &= \frac{1}{2}\underbrace{\int\frac{\mathrm{e}^x}{x+i}\,\mathrm{d}x}_{\equiv I_1}+\frac{1}{2}\underbrace{\int\frac{\mathrm{e}^x}{x-i}\,\mathrm{d}x}_{\equiv I_2}
\end{align}
To evaluate $I_1$ make $u=x+i$. This change of variable give us
$$I_1=\mathrm{e}^{-i}\int\frac{\mathrm{e}^u}{u}\,\mathrm{d}u=\mathrm{e}^{-i}\operatorname{Ei}\left(x+i\right),$$
since
$$ \int\frac{\mathrm{e}^u}{u}\,\mathrm{d}u=\operatorname{Ei}\left(u\right), $$
where $\operatorname{Ei}$ is the Exponential integral. A similar approach with $u=x-i$ gives
$$I_2=\mathrm{e}^{i}\int\frac{\mathrm{e}^u}{u}\,\mathrm{d}u=\mathrm{e}^{i}\operatorname{Ei}\left(x-i\right).$$
Thereby,
$$ \int\frac{x\mathrm{e}^x}{x^2+1}=\frac{\mathrm{e}^{-i}\operatorname{Ei}\left(x+i\right)+\mathrm{e}^i\operatorname{Ei}\left(x-i\right)}{2}+C.$$

Evaluate $\int \frac{xe^x}{1+x^2}dx$


Rapi.dll / OpenNETCF slow issues on Visual Studio

Question: I am referencing OpenNETCF.Desktop.Communication (Rapi.dll) in my project and have the following problem:
When I for ex. "private RAPI mobjRapi = new RAPI();"...
it takes about 5 minutes to execute that statement. I am basically trying to copy a file from a mobile device
An additional issue which might be related is that when I click "Windows Mobile Device Center" in control panel. I get the message "Windows Mobile Device Center is starting up" with the splash screen and then just disappear without opening the application.
More about my setup:

Windows Vista 64-bit
Visual Studio 2005 (C#)
Windows Mobile Device Center 6.1 Recently installed
Psion Workabout PRO mobile product scanner connected with USB (the device is accessable from My Computer)

Thanks in advance
Answer: Have you setup a device partnership in Windows Mobile Device Center? Please make sure you do, because otherwise it can cause problems trying to debug from Visual Studio.
You can check under Control Panel -> Sync Center if there already is a partnership for your device. If not, please attach the device to the USB port and when the WMDC screen comes up, go through the option of setting up a partnership. After this the WMDC screen should indicate that the device is connected and you're ready to go.
Comment: yes thank you that was indeed the problem I found yesterday.

The = new RAPI() hangs when IdccMan.Advice() is called and there is not partnership with WDMC and the mobile device.

The fact that I couldn't get WDMC running was because of what I believed was issues with WDMC and Vista 64-bit.  Un-installing WDMC and the re-install with the WDMC drivers upgrade for Vista 64 enabled me to open the app and set up a partnership