Linearity of map between tangent space and derivation space

Question: Let $v_a:=v|_a:=(a,v)\in\mathbb{R}^n_a:=\{a\}\times\mathbb{R}^n$ be a geometric tangent vector and $D_v|_a\in\mathcal{D}(\mathbb{R}^n)$ be a derivation, to be precise, a directional derivative. For $f\in\mathcal{C}^\infty(\mathbb{R}^n)$ the latter is defined as
$$D_v|_af:=D_vf(a):=\frac{d}{dt}|_{t=0}f(a+tv).$$
I want to show that the map $v_a\mapsto D_v|_a$ is linear, i.e. for $v,w\in\mathbb{R}^n$ and $\lambda\in\mathbb{R}$: $$D_{v+\lambda w}|_a=D_v|_a+\lambda D_w|_a.$$
How does one do this?
Comment: It seems that you already had the answer...
Comment: It came to me as I wrote the question.
Answer: Let $v_a=v^ie_i|_a$ and $w_a=w^je_j|_a$ for some basis $(e_k|_a)_{k\leq n}$ of $\mathbb{R}^n_a$. Then, using the chain rule, we have
$$D_v|af=\frac{d}{dt}|_{t=0}f(a+tv)=v^i\frac{\partial f}{\partial x^i}(a).$$
Now we can evaluate $D_{v+\lambda w}|_af$ for some arbitrary $f$ using that equation. This leaves us with
$$D_{v+\lambda w}|_af=(v^i+\lambda w^i)\frac{\partial f}{\partial x^i}(a)=v^i\frac{\partial f}{\partial x^i}(a)+\lambda w^i\frac{\partial f}{\partial x^i}(a)=D_v|_af+\lambda D_w|_af.\qquad\square$$


What makes the 2018 ball tampering scandal in Australia vs South Africa so significant?

Question: Ball tampering is illegal by the laws of cricket. It is, however, relatively common. Players at the highest levels are caught and punished regularly, with an instance every year or two.
Normally these punishments are fairly mild, amounting to a caution or a fine. This seems in keeping with the nature of the offence, for which there is little clear evidence that it confers much, if any, advantage.
The 2018 Australian scandal, though, has seen bans and resignations from three players and the head coach. This is many orders of magnitude more severe than usual.
I understand there are aspects of this which make it more serious than usual: the fact it was premeditated, and that it was planned by two senior players who pressured a junior to enact it. I appreciate that some of the players involved have been revealed as unpleasant hypocrites, who have previously denounced cheating.
But nonetheless, a year's ban compared to a small fine seems an astronomical escalation. Why?
Comment: (For avoidance of doubt, this is a personal comment. It is not meant to represent the views of the moderation team). I think it's interesting why CA have handed down such heavy punishment - but I'm not sure it's a great Stack Exchange question as it runs the risk of people weighing in with *their* opinions, rather than answering with CA's reasons - and as far as I know, CA's statements on this have been somewhat bland, sticking to the decisions made rather than the reasons behind them. [I have talked about it in The Clubhouse](https://chat.stackexchange.com/rooms/2433/the-clubhouse).
Comment: Folks, please remember comments are there to *improve and clarify* the question, not to answer it. If you want to answer it, please post an answer.
Comment: Never gets an answer but never hurts to ask: why the downvote? Explaining will help me (and others) improve future questions.
Comment: I didn't downvote, but this is attracting close votes for being "primarily opinion based". While downvotes and close votes *should* be different, they're often highly correlated.
Comment: @philip-kendall ah, ok. I thought it was a good question and a good fit. Happy to delete if not.
Answer: Australia has always been the most outspoken cricketing nation in regards to cheating and doping. Remember Shane Warne himself was suspended for a year when he was caught for doping and this was after all he did was take diet pills with banned substances in (After his mother told him he looked fat on TV, apparently).
For them to be caught cheating so blatantly must be a massive embarrassment for a nation that has prided themselves on being honest and hard playing. So the bans seem to be in line with their previous attitudes.
That being said, it will be highly unlikely that we see Warner and Smith ever play for Australia again, these bans may, in all honesty, may just as well have been permanent, because I cannot really see CA every picking such players that have been such a disgrace ever again.


Sort of Abel Differential Equation

Question: I am trying to solve differential equation of the following type: $$y y'=f(x)y+g(x)y'$$
This looks somewhat similar to Abel equations but not quite. Any ideas on how to approach it?
Many thanks!
Comment: what do we know about $$f(x),g(x)$$?
Comment: Not much: they are continuously differentiable functions. Perhaps I can prove that $f(x)$ is decreasing and $g(x)$ is increasing, if it helps.
Comment: would help - since for nonlinear equations a solution a soluble up to integration. I mean if you by chance had $g(x) = \int_0^x f(s) ds$ then we could write your equation as $$\frac{d}{dx}y^2 = 2\dfrac{d}{dx} \left( y\int_0^x f(s)ds\right)$$
Answer: Hint:
$yy'=f(x)y+g(x)y'$
$(y-g(x))y'=f(x)y$
This belongs to an Abel equation of the second kind.
Let $u=y-g(x)$ ,
Then $y=u+g(x)$
$y'=u'+g'(x)$
$\therefore u(u'+g'(x))=f(x)(u+g(x))$
$uu'+g'(x)u=f(x)u+f(x)g(x)$
$uu'=(f(x)-g'(x))u+f(x)g(x)$

Sort of Abel Differential Equation


I have a *.domain.com cert and would like to use it as my root CA cert

Question: I have a *.domain.com cert and would like to use it as my root CA cert. Just for clarification. I just brought a wildcard certificate. I was wondering if I could pull it into my Domain Controller CA and have it issue all the certificate across my domain? Computer or Web or Server certificates.
Comment: What are the BasicConstraints on your certificate?
Answer: This is not posible, you can only use this one certificate for all your services on third level domain under domain.com. Wildcard certificate don't give you ability generate subsequent certificates.
If you want generate your own certificates, need own CA. This CA must be installed on all host, which need trust issued certificates
Comment: +1 Check the 'Key usage' field on the wildcart certificate. It will almost certainly report 'Digital Signature, Key Encipherment'. A CA signing cert will report 'Certificate Signing, Off-line CRL Signing, CRL Signing' or similar.


Inserir um video do youtube numa pagina html

Question: Gostaria de inserir um video em uma pagina web, mas não consigo. Qual é o problema que contém neste código?
<object width="425" height="344">

    <param name="movie" value="https://www.youtube.com/watch?v=JBjjnqG0BP8"></param>
    <param name="allowFullScreen" value="true"></param>

  <embed src="https://www.youtube.com/watch?v=JBjjnqG0BP8" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344">
  </embed>
</object>

Answer: Com este código é possível inserir um vídeo em sua pagina HTML:

Você precisa pegar o endereço EMBED no Youtube http://imageshack.com/a/img537/6295/refUy4.png
Onde está X e Y você preenche com o tamanho adequado.


Is correlation between parameters a problem when fitting a Bayesian model using MCMC?

Question: Assuming some Bayesian model, for example:
$$y \sim N(X\beta, \sigma)$$
where this model has:
Response vector:
$$ y = \pmatrix{y_{1} \\ y_{2} \\ \vdots \\ y_{n}}  $$
Predictor matrix:
$$
\pmatrix{
x_{11} & x_{12} & \ldots & x_{1p} \\
x_{21} & x_{22} & \ldots & x_{2p} \\
\vdots & \vdots & \ddots & \vdots \\
x_{n1} & x_{n2} & \ldots & x_{np} \\
}
$$
Parameter set:
$$ \beta = \pmatrix{\beta_{0} \\ \beta_{1} \\ \vdots \\ \beta_{p}}, \text{ and } \sigma $$
Prior distributions:
$$ p(\beta_{i}|\theta_{\beta_{i}}), \text{ for } i = 1,\dots,p \text{ and } p(\sigma|\theta_{\sigma}) $$
where $\theta_{\alpha}$ denotes the set of hyperparameters corresponding to the probability distribution for parameter $\alpha$.
Now, multicollinearity amongst the predictor variables in $X$ can lead to parameter estimate issues.
Also, correlation within the sample draws for a given parameter can lead to unreliable posterior distributions (i.e. $ p(\beta_{i}^{t}|\theta_{\beta_{i}},\beta_{i}^{t-1},\ldots,\beta_{i}^{1}) \ne p(\beta_{i}^{t}|\theta_{\beta_{i}}) $).
However, is correlation between parameters problematic (i.e. $ p(\beta_{i}|\theta_{\beta_{i}},\beta_{j}) \ne p(\beta_{i}|\theta_{\beta_{i}}), \text{ } i \ne j $)? By problematic, I mean both in terms of causing algorithmic problems and interpretability problems, insofar as the two can be separated.
It seems to me that, ultimately, correlation between parameters could be problematic in practice (particularly when the goal of the analysis is to focus on the marginalized distributions of a subset of all parameters) due to prolonged time required for the MCMC procedure to efficiently explore the support of all the parameters.
However, in theory, regardless of how long this may take, if the chain(s) mix(es) sufficiently well (which is a necessary condition for any MCMC Bayesian analysis, I guess), then the joint posterior distribution will be sufficient to extract marginalized distributions through integration of nuisance parameters.
In other words, the issue is an issue of runtime and the feasibility thereof. Without optimizations and speed-up tricks, correlation between parameters can lead to longer runtimes to achieve the true joint posterior distribution, but both algorithmic robustness and interpretability will be unaffected assuming a given MCMC routine is provided with enough time to sufficiently explore the parameter spaces.
Answer: TLDR: There will almost always be correlation in the parameters in the Bayesian world; even if you use independent priors. Correlation might affect mixing rates, but that is going to be on a case by case basis. In general, you want to ask, "how can I account for the correlations"? Multivariate estimators of the asymptotic covariance of your estimators let you do that.

There are two "correlations" between parameters that are present in this scenario (and in general in most MCMC scenarios)

Correlation between parameters in the posterior. So the true covariance in the posterior is not a diagonal matrix.
Lag correlation across parameters as a consequence of MCMC sampling.
So $Cov\left(\beta_1^{(1)}, \beta_2^{(1+k)}\right)$, etc. (Look at a cross-correlation plot to see how significant these lag correlations are).

Just like in frequentist settings, correlation does not necessarily impact the point estimates for the posterior means, but it affects the quality of the point estimate. So if $\mu = (\beta_0, \dots, \beta_p, \sigma)$ is the $p+2$ dimensional vector of interest, and you obtain $N$ MCMC samples ($\mu_i$), the point estimate is
$$\mu_n = \dfrac{1}{N}\sum_{i=1}^{N} \mu_i. $$
The two correlations mentioned above affect the quality of this estimator, since due to the Markov chain CLT,
$$\sqrt{n}(\mu_n - \mu) \overset{d}{\to} N_{p+2}(0, \Sigma)\,, $$
where $\Sigma$ is a $(p+2) \times (p+2)$ covariance matrix. Interestingly, $\Sigma$ breaks up nicely and explains exactly the two correlations mentioned above
$$\Sigma = \underbrace{Var(\mu_1)}_{\text{Posterior covariance structure}} + \underbrace{2 \sum_{k=1}^{\infty} Cov(\mu_1,\mu_{1+k})}_{\text{Covariance due to correlated samples}}. $$
Just like in the usual MLE setup, if you can account for $\Sigma$, you account for all the correlation in estimation process. Recently consistent estimators for $\Sigma$ have been proposed, and you can now actually use these to say, "well this is the amount of error in the estimator, so do I have enough samples?". The R package mcmcse lets you estimate $\Sigma$. You can also use functions called multiESS and minESS in it to find out how many effective samples you need, and what your effective sample size is. These calculations are done using estimates of $\Sigma$, and thus account for the correlation.
This paper explains in detail.


In the views are not displayed in the widget attributes field Form add to cart

Question: I need to display the attributes of the widgets in the representations in the Form add to cart, at the moment I have shown only a choice of the number and Add to Cart button
Now this (is not right):

How do I need to make it (what you need):

In the second image I have in the base table of contents it is possible to select the field of Content: Product variations and in it there are all the necessary attributes to me colors and sizes.
In the first image I have a base table Search API prime field Commerce item: Form add to cart in does not display attributes such as color or size selection, I can not achieve that result as the second image I have of the field Content: Product variations, as it were, I did not connect the relationship, the entity does not have the right, there is a field Indexed, Commerce item and some of the fields Content.
This capability is necessary for me to make a quick order from the catalog.
Comment: I understood your requirement, but it will not understandable by all, better edit your post and ask your question clearly.
Answer: Try to use instead Content: Product variations field Content: Rendered Node witn selected to render custom view mode like a "Product variation".
In display custom view mode should be disable all fields, but Add to cart form keep enable.
Comment: Спасибо, Андрей :)


Query Regarding Mumps Statement

Question: what is the meaning of F :":::A:""T"""::$X::::"*":J%% this statement?
Answer: This statement is not valid syntax.
The F or FOR command followed by a single space must be in the following form:

F[OR]  lvn = forparameter

  forparameter  ::=
     │ expr1                          |
     │ numexpr1 : numexpr2 : numexpr3 |
     │ numexpr1 : numexpr2            |

lvn is a local variable name.
In your code, there is no lvn= following the for command.
More details in the annotated MUMPS Standards.
Answer: Agreed, this is an invalid Mumps line.  Some context might help if you're still looking for an answer.
Something else to keep in mind is that if there are 2 spaces after the F[OR] statement, then it will infinitely loop.  Usually a line like that will also contain a:
Q[UIT]:condition

for example:
 NEW A
 SET A=""
 F

OR SET A=$ORDER(^GLOBAL(A)) QUIT:A=""  DO SpecialStuff(A)
Hope that helps!

Query Regarding Mumps Statement


HTML Drag and Drop em celular (telas touchscreen)

Question: Estou pensando em fazer um painel usando os recursos de Drag and Drop do HTML.
Exemplo retirado de w3schools

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}
div {
  width: 50px;
  height: 50px;
  padding: 10px;
  border: 1px solid #aaaaaa;
}

Arraste para o retângulo:

Gostaria de saber, como faço para deixar funcional esse recurso quando for aberto em um celular (ou outra tela touchscreen), pois o "clique" é diferente:

Se eu tocar e soltar, seria um clique
Se eu tocar e segurar, abre as opções
Answer: Eu já tive esse problema e acabei usando essa solução: http://bernardo-castilho.github.io/DragDropTouch/
O script do Bernardo Castilho sobrescreve os eventos e faz eles ficarem compatíveis com o touch, pode resolver o seu problema.
jQuery também tem uma solução, mas como você postou o código em puro javascript, acho que essa solução esteja mais de acordo com o que procura.
Aqui o arquivo js: DragDropTouch.js
Answer: Recomendo o uso do Sortable:

Rubaxa/Sortable Esse cara é um plugin que usa recursos nativos para drag and drop responsivo, ele pode ser implementado com qualquer framework CSS


From the given data, prove the following relation for the determinants

Question:
Suppose $\Delta=\begin{vmatrix} a_1&b_1&c_1 \\ a_2&b_2&c_2 \\ a_3&b_3&c_3 \end{vmatrix}$ and $\Delta *=\begin{vmatrix} a_1+pb_1&b_1+qc_1&c_1+ra_1\\\ a_2+pb_2&b_2+qc_2&c_2+ra_2\\a_3+pb_3&b_3+qc_3&c_3+ra_3\end {vmatrix}$, then prove that $\Delta*=\Delta (1+pqr)$

The solution given to me went along the following lines
They initially split the determinant $\Delta*$ in sum of two determinants along $C_1$
$$\Delta* =\begin {vmatrix} a_1&b_1+qc_1&c_1+ra_1\\\ a_2&b_2+qc_2&c_2+ra_2\\a_3&b_3+qc_3&c_3+ra_3\end {vmatrix} + \begin{vmatrix} pb_1&b_1+qc_1&c_1+ra_1\\\ pb_2&b_2+qc_2&c_2+ra_2\\pb_3&b_3+qc_3&c_3+ra_3\end {vmatrix}$$
In the first determinant apply $C_3\rightarrow C_3-aC_1$ and then $C_2\rightarrow C_2-rC_3$
In the second determinant take $p$ common, then apply $C_3\rightarrow C_3-C_2$ and then take $r$ common from $C_3$
I performed all those given operations, but I didn't find them very useful because I still ended up with a lot of letters and I couldn't see how it was getting to the answer. Is the given solution wrong, if so, then how should I solve it?
Answer: In the second determinant, factor out $p$, then $C_2\to C_2-C_1$. Factor out $q$ and $C_3\to C_3-C_2$. Factor out $r$. Now you have $pqr$ times $\Delta$.
Answer: The idea is to be able to avoid explicitly calculating any determinants at all, and instead use manipulations to express $\Delta^*$ in terms of $\Delta.$
For the first determinant, if you instead use $C_3\to C_3-rC_1$ and then $C_2\to C_2-qC_3,$ then you'll see exactly $\Delta$ for the first determinant.
For the second, you'll start as recommended (by taking $p$ common), then do $C_2\to C_2-C_1.$ Do you think you can take it from there?
Comment: So the given steps were wrong?
Comment: The given steps only make things more complicated and then force explicit determinant calculation. They aren't "wrong," *per se*, but they aren't helpful.
Comment: Multiplication by $a$ in this case means introducing a new number right?
Comment: It seems so, yes.
Comment: Well, that's just dumb


java.lang.ArrayIndexOutOfBoundsException while sorting an integer array

Question: Scenario:
I need to read an array of integers from the standard inputstream, reorder it in such a way that a prime number is always followed by two even numbers ensuring that the prime and even numbers are picked up from the array in the order in which they are present to build the prime-2even set. Any remaining numbers that can't be part of the set can be
placed at the end of the array in the order in which they appear. The input(in multiple lines) and expected output(in multiple lines) as below:
Input:
8 5 9 7 8 5 4 6 8

Expected output:
5 8 4 7 6 8 9 5

Attempt:
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int totalElements = Integer.parseInt(scanner.nextLine());

    Integer[] integers = new Integer[totalElements];
    Integer[] primeTwoEvens = new Integer[totalElements];
    Integer[] leftOvers = new Integer[totalElements];

    for (int i = 0; i < integers.length; i++) {
        integers[i] = scanner.nextInt();
    }

    // LOGIC
    int notNullCounter = 0; // Variable to track how many elements of integers array has been set to null.
    while (notNullCounter != integers.length) { // Repeat this process until all the elements of the integers array are null.
        for (int i = 0; i < integers.length; i++) { // Iterate the integers array and check for primeTwoEvens and populate the primeTwoEvens array.
            if (integers[i] != null) { // Is the element of integers array to be processed null? If no, proceed.
                if (isPrime(integers[i])) { // Is the element of integers array prime? If yes, proceed.
                    System.out.println(integers[i] + " is prime..."); // Print statement for debugging purpose.
                    primeTwoEvens[i] = integers[i]; // Since the element of integers array is prime, add it to the primeTwoEvens array.
                    integers[i] = null; // Set this index of integers array to null.
                    notNullCounter++;   // As one element of integers array has been set to null, increment the null counter.

                    int evenCounter = 0; // Variable to track even number occurrences.
                    while (evenCounter != 2) { // Repeat this process until 2 even numbers are not found.
                        for (int j = ++i; j <= integers.length; j++) { // Iterate the remaining elements of integers array and check for next two even numbers.
                            if (isEven(integers[j])) { // Is the element of integers array even? If yes, proceed.
                                System.out.println(integers[j] + " is even..."); // Print statement for debugging purpose.
                                evenCounter++; // Since the element of integers array is even, increment the even counter.
                                primeTwoEvens[++i] = integers[j]; // Since the element of integers array is even, add it to the primeTwoEvens array as well.
                                integers[j] = null; // Set this index of integers array to null.
                                notNullCounter++; // As one element of integers array has been set to null, increment the null counter.
                            }
                        }
                    }
                } /*else { // Element is not prime.

                }*/
            }
        }
        //break;
    }// End of while

    /*System.out.println("@@@@@@@@@@@@ PRINTING THE FINAL SORTED ARRAY  @@@@@@@@@@@@");
    for (Integer integer : integers) {
    System.out.println(integer);
    }*/
}

throws me an java.lang.ArrayIndexOutOfBoundsException
Output:
5 is prime...
8 is even...
4 is even...
6 is even...
8 is even...
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
    at Ideone.main(Ideone.java:125)

Line 125:
if (isEven(integers[j]))

Note: I am restricted to using Java standard API and JDK 7.
How do I solve the problem and the final task?
Comment: isn't easier to just classify your numbers in 3 different list? (prime, even and non-both) and then just arrange them everytime a `primeTwoEven` occur?
Answer: I think the previous line (before Line 125) should be
for (int j = ++i; j < integers.length; j++)
Not <=
Answer: You could try this:
public static void main(String[] args) {
    // Read your file (I just copy your example to an array)
    Integer[] integers = new Integer[] { 8, 5, 9, 7, 8, 5, 4, 6, 8 };

    List<Integer> prime = new ArrayList<Integer>(), even = new ArrayList<Integer>();
    List<Integer> other = new ArrayList<Integer>(), ordered = new ArrayList<Integer>();

    // Start adding until 1st prime appear
    boolean firstPrime = false;

    for (Integer number : integers) {
        if (isPrime(number)) {
            prime.add(number);
            firstPrime = true;
        } else if (firstPrime && isEven(number)) {
            even.add(number);
        }

        // To have control of the order of appearance
        if (firstPrime) other.add(number);

        // If I have at least 1 prime and 2 even, then add them
        // to my ordered list and remove them from all my other lists
        if(prime.size() >= 1 && even.size() >= 2){
            ordered.add(prime.get(0));
            ordered.add(even.get(0));
            ordered.add(even.get(1));

            other.remove(prime.get(0));
            other.remove(even.get(0));
            other.remove(even.get(1));

            even.remove(1);
            even.remove(0);
            prime.remove(0);
        }
    }

    ordered.addAll(other);

    System.out.println(ordered);
}

If you run this example, you will have
[5, 8, 4, 7, 6, 8, 9, 5]


Moving from WHM to Office 365 for mail

Question: I have signed up for Office 365 and have set it up to use my current domain - I have verified the DNS etc and done the DNS setup in WHM where I added the new DNS records to the zone.
The problem is when I try to set up an account in Outlook it fails as it cannot find the server settings (there is no error message as such, it just asks to verify the email address is correct which it is).
I went to https://www.testexchangeconnectivity.com and did a test for Office 365 Exchange Domain Name Server (DNS) Connectivity Test - this fails due to:
Attempting to resolve the host name mail.mydomain.com in DNS.
The host name resolved successfully.
IP addresses returned: MY_WHM_SERVER_IP

Testing mx record configuration mx value 'mail.mydomain.com'.
Mx values do not match allowed values.

MX Records don't exist or aren't correctly configured for your domain in Office 365. The MX value
'mail.mydomain.com' doesn't match one of the allowed
values:mail.eo.outlook.com,mail.protection.outlook.com,mail.messaging.microsoft.com,invalid.outlook.com

Looking in WHM there is an entry for mail in DNS zones which reads:
mail 14440 IN CNAME mydomain.com.

In the connectivity test, should mail.mydomain.com still be resolving to my server IP address? Should I remove the above entry for mail from the DNS zone setup or replace it with something else? If not, any idea what else might be causing it to not find the server settings?
Thanks
Answer: The solution to this for me was three fold.
First off you either need to remove the existing MX record completely from WHM or you can choose Email Routing Remote Mail Exchanger which means it ignores the local mail exchanger and always uses external option. For some reason, setting current MX to 1 and Office 365 didn't work for me and it was always trying to use local.
Additionally, when you add a user to Office 365 you need to login online (i.e. browser) before trying to add them to Outlook. If you don't and you try to setup the account in Outlook using the temporary password it fails.
Whilst Microsoft are not aware of this or why, you MUST include a full stop/period after most of the DNS entries for WHM. For example, for the mx record you are told to enter:
MX  0   @           YOURDOMAIN.mail.protection.outlook.com  1 Hour

To get this work in WHM, you need to use:
MX  0   YOURDOMAIN.COM. YOURDOMAIN.mail.protection.outlook.com. 3600

Note the period after YOURDOMAIN.COM and also after YOURDOMAIN.mail.protection.outlook.com - finally, you need to enter 3600 and not 1 as WHM uses seconds for TTL. @ wouldn't work for me either but YOURDOMAIN.COM. worked fine.
Finally, the TXT value needs to be entered inside quotes - again Microsoft tried to get me to remove them but it only works when they are quoted so
v=spf1 include:spf.protection.outlook.com -all

should be entered as
"v=spf1 include:spf.protection.outlook.com -all"

for the TXT value.
Hope this helps someone else!

Moving from WHM to Office 365 for mail


Problem related with solution to the differential equation $y'=|y|^{\frac12},y(0)=0\,$

Question: I am stuck on the following problem that says :

Which of the following is a solution to the differential equation $y'=|y|^{\frac12},y(0)=0\,$ where square root means the
  positive square root ?

$y(t)=\frac{t^2}{4}$
$y(t)=-\frac{t^2}{4}$
$y(t)=\frac{t|t|}{4}$
$y(t)=-\frac{t|t|}{4}$

MY ATTEMPT: Taking $y>0,$ I get from the differential equation $y'=|y|^{\frac12},y(0)=0 \implies 2\sqrt y=x $. Now, after
looking at the options ,I am not sure which of the aforementioned options is correct . Can someone help?
Comment: Unfortunately no interval has been mentioned in the question. So,it can be $(-\infty, +\infty)$ .
Comment: Hint: Since $y' \ge 0$, the solution must be an increasing function. (That at least tells you that some of the options are incorrect; to verify that there really is a correct option you must compute a litte.)
Comment: In what *interval*?
Comment: Check each $y$ in each subinterval $(-\infty,0]$, $[0,+\infty)$. And double-check $y'(0)$ (all/some the $y$s are differentiable in 0?).
Comment: the answer is 3
Comment: @HansLundmark thanks a lot sir for the valuable input. Got your point.
Comment: Why can't you just compute $y'$ and $|y|^{1/2}$ for each of the proposed answers?
Answer: redefine $y'$ without modulus into two functions into two intervals, solve every one try to put them in one form you will get the answer 3
$$y'=(-y)^{\frac{1}{2}}\to y=-\frac{t^2}{4}=\frac{t|t|}{4}\ \ \text{when $t,y\le0$}$$
$$y'=(y)^{\frac{1}{2}}\to y=\frac{t^2}{4}=\frac{t|t|}{4}\ \ \text{when $t,y\ge0$}$$
Comment: When answers are already proposed, it is usually easier to check them by just substituting into the ODE and see if it's satisfied, rather than solving the ODE and try to match the results.
Answer: Only 3, is a solution.
But it is noteworthy, that this particular initial value problem does not enjoy uniqueness. Another solution of the same IVP is $y\equiv 0$ - In fact, this IVP has infinitely many solutions.


Access a variable from a jsp file

Question: I have created two jsp pages. I passed a list from jsp page and displayed the contents of the list in the second page using this: ${user.rate},${user.location}etc..
Now, I want to store one of these elements in a local variable for performing some arithmetic operations. I don't know how to save the variables locally and use it.
Kindly help me.
Comment: I'd say you're in the wrong place. StackOverflow is for programming questions only, and this seems like it belongs either to https://superuser.com or https://serverfault.com
Answer: I found the answer. I used c tags to store my values.
<c: set var=name_of_variable value=${user.location} />
And I can access the variable using the 'name_of_variable'.

Access a variable from a jsp file


Gerando um número pseudo-aleatório com base em uma entrada

Question: Preciso gerar um número aleatório baseado em outro número de entrada, de modo que, para o mesmo número de entrada, a função deve sempre gerar o mesmo número de saída.
Por exemplo, meuRand(4) sempre retornaria 236 (ou qualquer outro número), e meuRand(11) sempre retornaria 1747. Não há problema se por acaso meuRand(xx), com xx diferente de 4, também retornasse 236.
Esses valores são só para ilustrar.
Por hora, tenho essa função, que encontrei aqui, devidamente portada para C, como exemplo:
double noise(int x) {
    x = ((x << 13) ^ x);
    x *= x * 15731;
    x += 789221;
    x *= x;
    x += 1376312589;
    x &= 0x7fffffff;
    return 1.0 - ((double)x / 1073741824.0);
}

Essa função retorna valores no intervalo de -1 até 1, mas isso não é problema. O retorno ser um número inteiro ou de ponto flutuante é indiferente.
O objetivo final desses números aleatórios é realmente gerar um mapa com um Perlin Noise 2D. Por isso gostaria de testar meu algoritmo com outra função de geração de números aleatórios, e preferencialmente, que essa função fosse rápida de ser calculada.
Precisa ser um algoritmo, não pode ser algo como utilizar esse esquema em C, para sempre gerar o mesmo número com base no 4, por exemplo:
srand(4);
rand();

pois o código final nem sempre será executado em C, C++, C# etc.
Comment: [Pergunta relacionada](http://pt.stackoverflow.com/q/9026/215) (não é exatamente uma duplicata, mas algumas respostas lá podem se aplicar aqui)
Comment: Oi mgibsonbr! Valeu, eu tinha visto essa pergunta, mas não a primeira resposta. Acho que dá para fazer um teste :)
Comment: "O retorno ser um número inteiro ou de ponto flutuante é indiferente." Sugeriria trabalhar sempre com inteiros, para não ter problema se mudar de arquitetura de processador (se for desejado que o mapa seja igual em qualquer máquina). Dependendo do tipo de mapa que fizer, uma diferença de arredondamento ou precisão pode te dar um vale numa máquina e uma colina em outra.
Comment: Concordo, @Bacco, isso é perigoso em várias aplicações! Mas nesse caso particular, não! Ainda bem ;)  Dessa vez, basta que o resultado fique "bonito" e está OK!
Answer: A solução mais simples que posso oferecer é usar simplesmente uma função de hash - como o MD5 (ou algo mais sofisticado - embora creio que no seu caso é mais importante que a função seja rápida). Elas oferecem o que você busca (mesma saída para a mesma entrada), são amplamente suportadas por diversos sistemas e linguagens de programação, e são consideradas - em teoria pelo menos (pois servem de base para muitos sistemas criptográficos) - como indistinguíveis na prática de números aleatórios.
E, se o que você quer é uma sequência de números aleatórios - não somente um - ainda é possível utilizar o número original como semente de uma sequência, e a partir daí ir incrementando um contador para gerar o número seguinte (ou qualquer outro depois dele). Ex.:
aleatorio(semente, indice) = MD5(semente + indice)

Outros algoritmos (como alguns propostos numa pergunta relacionada) podem ser ainda mais eficientes, mas se o que se busca é portabilidade eu usaria isso como primeira opção.
Comment: Realmente, você sacou algo que esqueci de dizer na pergunta... Seria bom que a função fosse rápida :) Vou testar todas as alternativas.
Comment: Acabei de encontrar outra forma de gerar esse tipo de número aleatório. Depois dá uma olhada na resposta que acabei de colocar aqui, para compartilhar o conhecimento com o pessoal :)
Answer: Acabei de encontrar uma forma de gerar esse tipo de número pseudo-aleatório, criada pelo próprio idealizador do Perlin Noise, Ken Perlin.
Ele deixou um de seus talks disponíveis online aqui. Ao longo da explicação, ele leva para um de seus outros sites, onde mostra o algoritmo original.
Por completude, e pelo fato do algoritmo não ser patenteado/estar disponível online (além de eu já ter feito as devidas referências), vou colocar o algoritmo dele aqui:
/* coherent noise function over 1, 2 or 3 dimensions */
/* (copyright Ken Perlin) */

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#define B 0x100
#define BM 0xff

#define N 0x1000
#define NP 12   /* 2^N */
#define NM 0xfff

static p[B + B + 2];
static float g3[B + B + 2][3];
static float g2[B + B + 2][2];
static float g1[B + B + 2];
static start = 1;

static void init(void);

#define s_curve(t) ( t * t * (3. - 2. * t) )

#define lerp(t, a, b) ( a + t * (b - a) )

#define setup(i,b0,b1,r0,r1)\
    t = vec[i] + N;\
    b0 = ((int)t) & BM;\
    b1 = (b0+1) & BM;\
    r0 = t - (int)t;\
    r1 = r0 - 1.;

double noise1(double arg)
{
    int bx0, bx1;
    float rx0, rx1, sx, t, u, v, vec[1];

    vec[0] = arg;
    if (start) {
        start = 0;
        init();
    }

    setup(0, bx0,bx1, rx0,rx1);

    sx = s_curve(rx0);

    u = rx0 * g1[ p[ bx0 ] ];
    v = rx1 * g1[ p[ bx1 ] ];

    return lerp(sx, u, v);
}

float noise2(float vec[2])
{
    int bx0, bx1, by0, by1, b00, b10, b01, b11;
    float rx0, rx1, ry0, ry1, *q, sx, sy, a, b, t, u, v;
    register i, j;

    if (start) {
        start = 0;
        init();
    }

    setup(0, bx0,bx1, rx0,rx1);
    setup(1, by0,by1, ry0,ry1);

    i = p[ bx0 ];
    j = p[ bx1 ];

    b00 = p[ i + by0 ];
    b10 = p[ j + by0 ];
    b01 = p[ i + by1 ];
    b11 = p[ j + by1 ];

    sx = s_curve(rx0);
    sy = s_curve(ry0);

#define at2(rx,ry) ( rx * q[0] + ry * q[1] )

    q = g2[ b00 ] ; u = at2(rx0,ry0);
    q = g2[ b10 ] ; v = at2(rx1,ry0);
    a = lerp(sx, u, v);

    q = g2[ b01 ] ; u = at2(rx0,ry1);
    q = g2[ b11 ] ; v = at2(rx1,ry1);
    b = lerp(sx, u, v);

    return lerp(sy, a, b);
}

float noise3(float vec[3])
{
    int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11;
    float rx0, rx1, ry0, ry1, rz0, rz1, *q, sy, sz, a, b, c, d, t, u, v;
    register i, j;

    if (start) {
        start = 0;
        init();
    }

    setup(0, bx0,bx1, rx0,rx1);
    setup(1, by0,by1, ry0,ry1);
    setup(2, bz0,bz1, rz0,rz1);

    i = p[ bx0 ];
    j = p[ bx1 ];

    b00 = p[ i + by0 ];
    b10 = p[ j + by0 ];
    b01 = p[ i + by1 ];
    b11 = p[ j + by1 ];

    t  = s_curve(rx0);
    sy = s_curve(ry0);
    sz = s_curve(rz0);

#define at3(rx,ry,rz) ( rx * q[0] + ry * q[1] + rz * q[2] )

    q = g3[ b00 + bz0 ] ; u = at3(rx0,ry0,rz0);
    q = g3[ b10 + bz0 ] ; v = at3(rx1,ry0,rz0);
    a = lerp(t, u, v);

    q = g3[ b01 + bz0 ] ; u = at3(rx0,ry1,rz0);
    q = g3[ b11 + bz0 ] ; v = at3(rx1,ry1,rz0);
    b = lerp(t, u, v);

    c = lerp(sy, a, b);

    q = g3[ b00 + bz1 ] ; u = at3(rx0,ry0,rz1);
    q = g3[ b10 + bz1 ] ; v = at3(rx1,ry0,rz1);
    a = lerp(t, u, v);

    q = g3[ b01 + bz1 ] ; u = at3(rx0,ry1,rz1);
    q = g3[ b11 + bz1 ] ; v = at3(rx1,ry1,rz1);
    b = lerp(t, u, v);

    d = lerp(sy, a, b);

    return lerp(sz, c, d);
}

static void normalize2(float v[2])
{
    float s;

    s = sqrt(v[0] * v[0] + v[1] * v[1]);
    v[0] = v[0] / s;
    v[1] = v[1] / s;
}

static void normalize3(float v[3])
{
    float s;

    s = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
    v[0] = v[0] / s;
    v[1] = v[1] / s;
    v[2] = v[2] / s;
}

static void init(void)
{
    int i, j, k;

    for (i = 0 ; i < B ; i++) {
        p[i] = i;

        g1[i] = (float)((random() % (B + B)) - B) / B;

        for (j = 0 ; j < 2 ; j++)
            g2[i][j] = (float)((random() % (B + B)) - B) / B;
        normalize2(g2[i]);

        for (j = 0 ; j < 3 ; j++)
            g3[i][j] = (float)((random() % (B + B)) - B) / B;
        normalize3(g3[i]);
    }

    while (--i) {
        k = p[i];
        p[i] = p[j = random() % B];
        p[j] = k;
    }

    for (i = 0 ; i < B + 2 ; i++) {
        p[B + i] = p[i];
        g1[B + i] = g1[i];
        for (j = 0 ; j < 2 ; j++)
            g2[B + i][j] = g2[i][j];
        for (j = 0 ; j < 3 ; j++)
            g3[B + i][j] = g3[i][j];
    }
}


Flyway Gradle Plugin with Cloud Spanner - No database found to handle url

Question: I'm trying to setup Flyway for Google Cloud Spanner (beta) using the flyway gradle plugin but it gets the error below when executing ./gradlew flywayinfo.
> Error occured while executing flywayInfo
  No database found to handle jdbc:cloudspanner:/projects/<my-project>/instances/<my-instance>/databases/<my-db>

build.gradle
plugins {
 id 'java'
 id 'org.flywaydb.flyway' version '7.13.0'
}

...

dependencies {
 implementation(
  'org.flywaydb:flyway-gcp-spanner:7.13.0-beta'
 )
}

flyway {
 url = 'jdbc:cloudspanner:/projects/<my-project>/instances/<my-instance>/databases/<my-db>'
}

The values in the url correspond to my project and instance names.
I've also tried:

using a service account key in the end of the URL
adding the com.google.cloud:google-cloud-spanner-jdbc:2.3.2 JDBC driver dependency (implementation)
I'm behind a proxy but I have set it in my gradle.properties with systemProp.http.proxyHost and systemProp.http.proxyPort (also for https)

Using Flyway CLI and the API programmatically works.
Answer: It seems like the error comes from flyway implementation here. Your issue seems somewhat similar with https://github.com/flyway/flyway/issues/3028.
Consider opening a new issue here: https://github.com/flyway/flyway/issues


Admin overlay intermittently fails

Question: I wish I could provide a more specific example of this, or some event that seemed to trigger it, but here's the best I can do:  I have happily used my admin overlay for most of my CMS work for months now in D7 with the Bartik theme.  And the other day, mysteriously it became the case that when I am browsing my site, I will "fall out" of admin overlay mode sometimes.
I just am suddenly on a page as an anonymous viewer would be, with neither the overlay, nor the standard edit, track, etc. content tabs of an admin user.  I can still hit the back button, to return to it, and I can still directly enter administrative menus, but an occasional page, and not always the same ones, cause me to fall out of admin mode.
Does this sound like any behavior anyone could identify, or help me identify a process in order to identify?
Comment: I've experience this as well.
Answer: I think it was a PHP memory limit.  I upped that, and don't seem to have this problem anymore.

Admin overlay intermittently fails


Show that if $\langle u,v\rangle_1=0\implies\langle u,v\rangle_2=0$ then $\langle{\cdot},{\cdot}\rangle_1=c\langle{\cdot},{\cdot}\rangle_2$

Question:
Let a vector space with two inner product defined. If for every $u,v\in V$ s.t. $\langle u,v\rangle_1=0$ then $\langle u,v\rangle_2=0$ show that $\langle{\cdot},{\cdot}\rangle_1=c\langle{\cdot},{\cdot}\rangle_2$ for some $c>0$.

This is the exercise 11 on page 191 of Linear algebra done right, third edition of Axler. I had proven the statement for finite dimensional $V$ using and orthonormal basis for $(V,\langle{\cdot},{\cdot}\rangle_1)$.
However the existence of an orthonormal basis is not ensured for infinite dimensional vector spaces. My question: I must assume that the dimension of $V$ is finite for this exercise, or there is a way to prove the statement?
EDIT: I found the same exercise here, but the answer is not understandable to me, when it says that if it is true for any subspace $V'$ of $V$ it remains true for $V$, why?
Comment: The proposed link does not assume $V$ is finite dimensional
Comment: @Jorge, you are right. I will edit.
Answer: Suppose that you can show that for any $V'$ there is a constant $c$ with $\langle u,v \rangle_1=c\langle u,v\rangle_2$.
First prove that the $c$ is the same for every $V'$.
Pick $V'$ and $V''$, if we consider $V^{'} + V^{''}$ we get that the constants of $V'$ and $V^{''}$ are both equal to the constant of $V^{'}+V^{''}$.
Finally, pick $u$ and $v$ in $V$. We wish to prove that $\langle u,v \rangle_1=c\langle u,v\rangle_2$. Easy, consider $V^{'}=span\{u,v\}$ and enjoy!


Are off-the-cloud desktop applications dead?

Question: Although somewhat related to this question, I have what I think is a different take on it.
Is a desktop app that has no connections to the "cloud" dead? I believe that some things are going to continue to be on the machine (operating systems obviously, browsers, some light-weight applications), but more and more things are moving to network-based applications (see Google Docs for office suites, GMail and other web-email clients for email, flickr for photo management, and more).
So other than the lightweight applications, is there anything that, in 5 to 10 years, will continue to be (either out of necessity or just demand) remain on the desktop and off the cloud?
Comment: What does it mean for a technology to be dead? It's not a black or white thing. Is ASP dead, or MFC, or Cobol?
Comment: You could also have a desktop application that's "cloudified" by service like http://pinemango.com - Taking away the need to rewrite desktop application into web-based.
Answer: 10 years or more ago this would have been, "Are non-internet applications dead?"
There's things the cloud does better than desktop applications, and in those places I'm sure non-cloud applications will become increasingly rare.  But there's plenty of applications where you might not want to use the cloud, the benefits don't outweigh the costs, or the complexity just isn't worth it.
It's a new tool, and it's a better tool than desktop applications for many things.  However, you don't throw away a hammer when you buy a screwdriver, you simply reserve it for when a nail needs to be driven.
Answer: Video editing and other resource intensive tasks will probably stay off the cloud for a long time.
Comment: I thought about that. Then thought about PhotoSynth. That's got to be some heavy image processing, although static images...
Comment: Resource intensive tasks are perfect for the cloud as you can distribute the processing across hundreds or thousands of nodes
Comment: You can also do CPU intensive tasks in runtimes such as the JRE. Not everything needs be ECMAScript.
Comment: @John, yes you can distribute the processing but you also have to distribute the data.
Answer: IDE's will probably be "off the cloud" for a long time, if ever... powerful customizable editors like Emacs will also probably stay "off the cloud" for a while.
Comment: if a long time is 10-15 years, I agree. But it will happen.
Comment: IDEs are one of the first things I'd want on the net. NetBeans, for instance, already has some collaboration features. It'd great to be WebStartable. Just launch the app from any (safe) machine and get to work with colleagues.
Comment: http://pinemango.com offers cloud desktop environments where a real IDE can be offered directly from a browser! Note: It also comes with collaborative feature enbaled if needed.
Answer: If I look at the application that we've selling and at the applications I've written as a consultant, I must very much agree with you. Most of them are useless if there is no internet connection. Some do work in disconnected mode, some don't, but all of them are pretty useless if you cannot connect to the big supporting system hidden far far away.
On the other hand, I wouldn't want to say that everything will move into the cloud in 5 years. Too much work with porting. There will be desktop applications that will function as a thin and offline-able client (just like, for example, Google Reader does if you install Gears) and there will be fully "clouded" :) applications.
I have no idea what will happen in 10 years. If I put myself 10 years back (and that is very easy to do as I was writing a lot for a local computer magazine in that time), I totally couldn't predict how the computing will become internet-dependant in 2008.
Comment: +1 Don't believe the conventional wisdom and the conventional predictions. Slightly off topic. 10 years ago everyone was predicting that "content would be king" and you'd only make a profit from the Internet if you owned content. Then came Google, YouTube, Facebook, and this place.
Answer: Gosh, I hope not as that's my job.
The main piece of software I write controls electronic hardware (PXI boards and the like) for testing.  Without "real" hardware, there's nothing to test.  Even the very nature of the tests themselves prevent simultaneous access (once you set the state of a switch, you don't want someone else moving it).
So as long as you interact with any hardware, you're off-the-cloud.
Oh, and some companies have security issues with being on the Internet; I'd say security would also drive desktop apps with no connections.
Answer: There's no reason that many corporations will move to an online system simply because of security concerns.
For example, One of the greatest assets of Outlook is to go offline and continue working.  Sure Google Gears has similar functionality, but then you're trusting Google with your corporate security.
Answer: Such applications are dead since 15 years, ever since Sun took market leadership with their JavaStation.
No, wait. They did not. And things are not "more and more" moving to network-based applications. Sure, there is Webmail, but even GMail is FAR away from the comfort of modern Outlook or Thunderbird Clients. Same for office. Google Docs is a nice toy for ocasional use, but it's vastly inferior to conventional Office suites.
The Desktop is not dead and it will not die anytime soon. Internet Applications are alternatives in some situations, but be are just starting getting proper functionality and performance. Let's face it: JavaScript performance is still a Joke, the IDE Support is not there yet and Browsers are too unstable at the moment.
Google Chrome, IE8 and Firefox 3.1 start to go in a better direction, but it will take years for them to be mature enough to create JavaScript applications that actually can fully replace desktop apps. But that would require some proper standardization accross browsers, and we all know that this will not happen before the next millennium or so.
Comment: Not sure I agree with "FAR away from the comfort of modern Outlook" or "vastly inferior to conventional Office suites".

I gave up MS Office a couple years ago for OpenOffice, and I've now given that up for Google docs.  I've never looked back. I've not once wished for MS Office
Comment: And I still use Word to write my Blog Posts :-) MS Office 2007 is actually quite good, but it's overkill for small lists and documents, yet in my corporate environment it's lightyears ahead of Google Docs. OpenOffice is also a good alternative, that then depends.
Answer: About 1% of users actually use Google Docs&Spreadsheets full-time. Almost all of the rest use Microsoft Office. So, no, off-the-cloud applications are not dead simply because a Google office suite exists. And those are, really, the only high-profile true web applications out there that are meant as desktop app replacements.
Webmails are a special case though. It actually makes sense to use those rather than a desktop app, since your email is next-to-useless without a connection anyway. But most applications don't NEED a full-time Internet connection. A word processor certainly doesn't.
What will definitely remain on the desktop:

Games
Small apps (calculator, notepad type of stuff)
Anything that generates data that needs to be secure (I don't imagine tons of people or companies want to trust their accounting details to Google, for example)
Web browsers (obviously)
IDEs (Visual Studio via Ajax? Come on...)
Auxiliary development tools (SVN, etc), since good security policy would forbid their use through a web browser
Anything that needs high enough performance that network latency would be an impediment

What will probably remain primarily on the desktop, at least for the next 5 years:

Office tools (unless web-based limitations can be lifted... which would require much better-performing web browsers than we have now)
Photoshop and such tools
Chat clients (web-based equivalents are disappointing so far)

That's not to say that any of the above cannot have an Internet-based component, of course.
Answer: I personally will never leave my stuff on the web under someone else's control.  All of my photos and e-mails I keep on local hard drives that I control.
I prefer to make my own stuff available to me through the web on my own hardware.  The only way to have reasonable performance and be productive when offline is to use local apps.
To me the future will be local, but remotely accessible and synchronized.  At least for the next 20 years or so.
Not only do I think it's not dead, I think it's the way everyone will want to go once we have a few disastrous failures (ie, websites disappearing with users content that isn't backed up anywhere or severe privacy breeches as some large company loses control of access to the data they are protecting).


UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 55: character maps to

Question: I am new to Python and am hoping that someone could please explain to me what the error message means.
To be specific, I have some code of Python and SPSS combined together saved in Atom, which was created by a former colleague. Now since the former colleague is not here anymore, I need to run the code now. What I did was I ran the code below from SPSS22.
    begin program.
    import spss,spssaux,imp
    abcvalid = imp.load_source('abcvalid', "I:/VALIDITY CHECK/Python Library/2016/abcvalid2016.py")
    import abcvalid
    abcvalid.fullprocess("9_26_2016","M:/Users/Yli\2016 SURVEY/DOWNLOADS/9_26_2016/","M:/Users/Yli/2016 SURVEY/Legacy15.sav")
    end program.

Then I got the following from the output.
    Traceback (most recent call last):
      File "<string>", line 5, in <module>
      File "I:/VALIDITY CHECK/Python Library/2016/abcnvalid2016.py", line 2067, in fullprocess
        dataprep(date,filepath,legacypath)
      File "I:/VALIDITY CHECK/Python Library/2016/abcvalid2016.py", line 2006, in dataprep
        emailslower(date,filepath)
      File "I:/VALIDITY CHECK/Python Library/2016/abcvalid2016.py", line 1635, in emailslower
        DATASET ACTIVATE comment_data.""".format(date,filepath))
      File "C:\PROGRA~1\IBM\SPSS\STATIS~1\22\Python\Lib\site-packages\spss\spss.py", line 1494, in Submit
        cmdList = spssutil.CheckStr(cmdList)
      File "C:\PROGRA~1\IBM\SPSS\STATIS~1\22\Python\Lib\site-packages\spss\spssutil.py", line 166, in CheckStr
        s1 = unicode(mystr,locale.getlocale(locale.LC_CTYPE)[1])
      File "C:\Program Files\IBM\SPSS\Statistics\22\Python\lib\encodings\cp1252.py", line 15, in decode
        return codecs.charmap_decode(input,errors,decoding_table)
    UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 55: character maps to <undefined>

I know there are similar questions on this site, but the questions and answers were too hard for me to comprehend. If someone could please help me, I'd really appreciate it!
Thank you in advance!
Answer: On a similar problem with same error message i did something like this and it worked good for me.
with open(workfile, 'r', encoding='utf-8') as f:
    read_data = f.read()
f.close()

Comment: Is the `f.close()` necessary here? Isn't it included in the `with` statement
Answer: First, here is a minimal example reproducing your error on Windows:
import subprocess

with subprocess.Popen("cmd /c echo ü", stdout=subprocess.PIPE, text=True) as Process:
    for Line in Process.stdout:
        print(Line)

To my understanding, the problem is this (I put together some information and examples which I have found, but am not certain everything is correct. I welcome corrections.)

The ü character is code point 252 = 0xfc in Unicode, https://unicode-table.com/en/00FC/).
Python correct passes the ü character to the console, as you can test using this example (be sure to save the file as UTF-8):

import subprocess

print(ord('ü'))
subprocess.call("cmd /c echo ü")

I am not sure why this is working in the first place. (This answer may be why: https://stackoverflow.com/a/32176732/880783)

The console uses something else than Unicode internally. For example, in the ASCII table, the ü character is at position 129 = 0x81 (sounds familiar?).
So when the console returns that character, Python thinks its a Unicode codepoint, but 0x81 is not defined. Hence the error.

The key is to make Python understand that how what it gets from the process is encoded. In my example (Windows console), I have tried a couple of encodings (see the list here) like this:
import subprocess

Encoding = 'cp850'
with subprocess.Popen("cmd /c echo ü", stdout=subprocess.PIPE, text=True, encoding=Encoding) as Process:
    for Line in Process.stdout:
        print(Line)

'ascii' fails with an ordinal not in range(128) error (probably does not cover extended ASCII).
'cp1252' fails with character maps to <undefined>
'latin_1' works, but outputs a box character (``) on my debug console in VS Code.
'cp850' seem to works, outputting a ü character.

So I will stick with 'cp850' for now and see how it goes.
Answer: It's hard to be sure about what is going on here as there is a lot of code off stage, but the error message is telling you that there is an invalid character in the input stream.  Code x81 is undefined in code page 1252, which is the code page in effect.  That's the western Europe/US default code page.  The program is trying to convert a presumed code-page string to Unicode, so that fails.
My guess is that the input is actually not encoded with cp 1252.  Something is messed up in in the Statistics current code page or with Unicode mode.  You might need to set the SPSS Statistics locale to something different or to turn Unicode mode on or off.  See SET LOCALE and SET UNICODE in the Command Syntax Reference on how to do this.
If you can say more about your locale and what this code is doing, we might be able to provide more information.
Comment: Thank you so much for the detailed explanation! I'll see if I can fix it. Thank you!!!
Answer: if you importing file in python and getting this error provide file encoding type
for example
before
import numpy as np
import csv

with open("terrorismData.csv", "r") as file_obj:
file_data = csv.DictReader(file_obj, skipinitialspace = True)
file_list = list(file_data)

after
with open("terrorismData.csv", "r",encoding="ISO-8859-1") as file_obj:
file_data = csv.DictReader(file_obj, skipinitialspace = True)
file_list = list(file_data)


Filter a list based on another list condition

Question: I have two lists, one has data that comes from the client, and the other one comes from my DB, which means that this data is already contained in my DB.
What I am trying to do is, based on my client's list, filter it with my database list and return only the data that do not contain in my DB, so I can handle the non-duplicates one before inserting it.
To filter this data, I am trying to use LINQ with multiple conditions (bank data).
  List<BalanceQuery> result = new List<BalanceQuery>();

  clientList.ForEach(y =>
  {
    result = dbList.Where(x =>
      (y.BankCode != x.BankCode) ||
      (y.Agency != x.Agency) ||
      (y.AccountNumber != x.AccountNumber)).ToList();
  });

But for some reason, it is not working properly. Any idea?
Thanks
Answer: Let's say you have a class like below:
class CustomerInformation
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

As you said, you have two lists, let's say you have two lists like below:
List<CustomerInformation> dbList = new List<CustomerInformation>
        {
            new CustomerInformation{Id=1, FirstName="Raju",   LastName="Ahmed"},
            new CustomerInformation{Id=2, FirstName="Tahira", LastName="Biswas"},
            new CustomerInformation{Id=3, FirstName="Shohag", LastName="Mia"},
            new CustomerInformation{Id=4, FirstName="Saiful", LastName="Islam"}
        };

        List<CustomerInformation> csutomerList = new List<CustomerInformation>
        {
            new CustomerInformation{Id=1, FirstName="Raju",   LastName="Ahmed"},
            new CustomerInformation{Id=2, FirstName="Tahira", LastName="Biswas"},
            new CustomerInformation{Id=3, FirstName="Shohag", LastName="Mia"},
            new CustomerInformation{Id=4, FirstName="Saiful", LastName="Islam"},
            new CustomerInformation{Id=5, FirstName="Anny", LastName="Bishwas"},
            new CustomerInformation{Id=6, FirstName="Kabita", LastName="Roy"},
            new CustomerInformation{Id=7, FirstName="Zahidul", LastName="Emon"}
        };

Now you want to get those DB list that are not present in the customer list with somespecific condition, so just try this:
 var newList = csutomerList.Where(cusItem => !dbList.Any(dbItem => cusItem.Id == dbItem.Id && cusItem.FirstName == dbItem.FirstName && cusItem.LastName == dbItem.LastName));

it will first find out all the data that are present in both lists and then simply deduct them.
Sample Output:

Full code here:
    static void Main(string[] args)
    {
        AvailableData();
        Console.ReadKey();
    }

    public static void AvailableData()
    {
        // Create two lists.
        List<CustomerInformation> dbList = new List<CustomerInformation>
        {
            new CustomerInformation{Id=1, FirstName="Raju",   LastName="Ahmed"},
            new CustomerInformation{Id=2, FirstName="Tahira", LastName="Biswas"},
            new CustomerInformation{Id=3, FirstName="Shohag", LastName="Mia"},
            new CustomerInformation{Id=4, FirstName="Saiful", LastName="Islam"}
        };

        List<CustomerInformation> csutomerList = new List<CustomerInformation>
        {
            new CustomerInformation{Id=1, FirstName="Raju",   LastName="Ahmed"},
            new CustomerInformation{Id=2, FirstName="Tahira", LastName="Biswas"},
            new CustomerInformation{Id=3, FirstName="Shohag", LastName="Mia"},
            new CustomerInformation{Id=4, FirstName="Saiful", LastName="Islam"},
            new CustomerInformation{Id=5, FirstName="Anny", LastName="Bishwas"},
            new CustomerInformation{Id=6, FirstName="Kabita", LastName="Roy"},
            new CustomerInformation{Id=7, FirstName="Zahidul", LastName="Emon"}
        };

        var newList = csutomerList.Where(cusItem => !dbList.Any(dbItem => cusItem.Id == dbItem.Id && cusItem.FirstName == dbItem.FirstName && cusItem.LastName == dbItem.LastName));

       foreach (var cust in newList)
        {
            Console.WriteLine("Customer Id :{0} | Customer Name: {1} | Last Name: {2} ",cust.Id,cust.FirstName,cust.LastName);
        }
        Console.ReadKey();

    }
}

class CustomerInformation
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Answer: Preliminary
This answer assumes you are using an ORM such as EF or EF Core. The code is not tested, it is only here to give you the right direction to solve your problem. Some open questions will need to be answered to reach your final solution.
Also your question seems contradictory sometimes: you are mentioning client lists, while the function you show returns a List<PrePaymentBalanceQuery>. I assume here we are speaking about client lists, and that I could leave aside some unclear points. Anyway, if I'm off please let me know and I'll either edit this answer or remove it.
Analysing the existing code and the question
Since the code is not doing what you want, let's first understand what it does.
You want to filter your in-memory Client list based on some data stored in your database.
clientList.ForEach(y =>
{
    result = dbList.Where(x =>
      (y.BankCode != x.BankCode) ||
      (y.Agency != x.Agency) ||
      (y.AccountNumber != x.AccountNumber)).ToList();
});

return result;

This code is not filtering a Client list.
What it does is, for each Client:

Calculate something and store that something into a variable called result.

So on each successive iteration, the content in the variable result is replaced by new content.
In the end, the variable result just contains the calculation made for the last client, which is not what you are trying to achieve.
Conclusion: you shouldn't use ForEach here. ForEach is not a filtering operator. Linq has a filtering operator: Where, which should be used here.
Side note: ForEach is not a Linq method extension. It is a method of the List class.
It might seem surprising at first, but it is for a good reason. ForEach is not pure (in the functional programming sense), it will introduce side effects, so it is against the general principles of Linq. Purity is not enforced in Linq, but is generally desirable.
How to try to solve this
Here is a first version filtering the clientList:
var FilteredClientList = clientList.Where(c => !dbList
      .Any(dbc =>
          (c.BankCode == dbc.BankCode)
          && (c.Agency == dbc.Agency)
          && (c.AccountNumber == dbc.AccountNumber))
  );

return FilteredClientList;

What does it do?
It builds a new client list by keeping clients from clientList only if there is no such client in the database.
An in-memory client is considered to be in the database if there exists a database client that has the same Bankcode, the same Agency, and the same AccountNumber.
However, there is a problem. While this works functionally, it makes potentially a lot of calls to your database: one for each client.
To understand this, you have to be aware of the difference between Linq to Objects and Linq to Entities.
See linq to entities vs linq to objects - are they the same?
How to fix this? it depends on your particular situation.
If your client list is small, you could keep it that way, and be willing to pay for a SQL query for each of your clients.
If your database list is small, you could simply get it in memory first, and do all the work in memory.
var ClientsFromDb = dbList.
    .Select(c => new
    {
        c.BankCode,
        c.Agency,
        c.AccountNumber
    })
    .ToList()

var FilteredClientList = clientList.Where(c => !ClientsFromDb
      .Any(cc =>
          (c.BankCode == cc.BankCode)
          && (c.Agency == cc.Agency)
          && (c.AccountNumber == cc.AccountNumber))
  );

This might also be improved by the use of a Join operator.
But what if your database client list is too big?
You could first retrieve all the matching clients in your database, in one database query, and then use that in-memory list to filter your actual list.
See Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator for pointers.
Answer: A more LINQ approach would be like. It's tested from my side.
 result =
        (from cl in clientList
         where !dbList.Any(x => x.AccountNumber == cl.AccountNumber && x.BankCode == cl.BankCode && x.Agency == cl.Agency)
         select cl).ToList();


Adding related user fields to comment field

Question: I have a content type which has a field that prints post related comments.
My users have a couple of extra fields like name and last_name. Is there a possibility to add the first and last name of a user to a comment they've written, instead of just the username and profile picture?
function mysite_preprocess_node(&$variables) {
    $node = \Drupal::routeMatch()->getParameter('node');
    if($node && $node->getType() == 'berichten'){
        $variables['user'] = User::load($node->getOwnerId());

        $variables['field_reacties'] = $node->field_reacties->view('full');

    }

}

This is how I currently receive the comments view and show it to the related post.
Answer: I figured out that I can just receive user related fields from a comment by doing this {{ comment.getOwner.field_naam.value }}
took me a while to figure that out, but it's handy for custom templates! :D


Calculating the distribution of a compound random variable

Question: Given $X\sim U(1, 0)$ and $Y\sim Exp(1)$, determine the density function of $Z:=\frac{X}{Y}$.
Now, without looking up how to do it I tried to figure it out myself.
The value of the density function $f_X(x)$ is the continuous analog of the probability that $X=x$, right? I realize that $\mathbb P(X=x)=0$ fore every $x$, but it seemed so far that reasoning about random variables this way produced correct results.
Also, the continuous analog of a sum is an integral.
Now, $f_Z(z)=f_\frac{X}{Y}(z)$. There is an infinite number of ways that the quotient of $X$ and $Y$ could produce $z$ so I integrated over all of them like this $\int_{-\infty}^{+\infty}f_X(x)f_Y(x/z)dx$. Now, since $f_X$ is zero everywhere but on $[0,1]$ where it's one, the integral becomes $\int_0^1f_Y(x/z)dx=z(1-e^{-1/z})$.
This all seemed logical to me but then I tried the reverse. Integrating over the possible values of $Y$ and then making $X$ match them.
$\int_{-\infty}^{+\infty}f_Y(y)f_X(zy)dy=\int_0^{+\infty}e^{-y}f_X(zy)dy=\int_0^{1/z}e^{-y}dy=1-e^{-1/z}$
Why doesn't this give the same result?
I'm really hoping that I didn't just make a simple calculation mistake. Actually, maybe I'm hoping I did just that so my method can be salvaged.
I would appreciate any insight.
Comment: What is B(1,0)?  B is for Beta, Bradford, Binomial, Birnbaum, Bettyboop ...
Comment: @wolfies Oh sorry. That was supposed to be $U$. For uniform.
Answer: The ratio distribution is evaluated by the integral:
$$\begin{align}
f_Z(z) & = f_{X/Y}(z)
\\ & = \int_\Bbb R \lvert y\rvert f_X(yz)f_Y(y)\operatorname d y
\\ & = \int_0^{1/z} y e^{-y} \operatorname d y
\\ & = 1-e^{-1/z} (\tfrac 1 z + 1)
\end{align}$$

Going back to  first principles.
$\begin{align}
P(Z\leq z) & = P(X \leq Yz)
\\ & = \int_0^\infty\int_{0}^{\min(yz,1)} e^{-y}\operatorname d x\operatorname d y
\\ & = \int_0^{1/z} e^{-y}\int_0^{yz} 1\operatorname d x\operatorname d y + \int_{1/z}^\infty e^{-y}\int_0^1 1\operatorname d x\operatorname dy
\\ & = z\int_0^{1/z} ye^{-y}\operatorname d y + \int_{1/z}^\infty e^{-y}\operatorname dy
\\ & = \left(z-e^{-1/z} (z+1)\right) +\left(e^{-1/z}\right)
\\ & = z(1-e^{-1/z})
\\[2ex] f_Z(z) & = \frac{\mathrm d}{\mathrm d z}\Big(P(Z\leq z)\Big)
\\ & = 1-(1+\tfrac 1 z)e^{-1/z}
\end{align}$
In general, when $X>0,Y>0$: $$\begin{align}f_Z(z) & = \frac{\mathrm d}{\mathrm d z} \int_0^\infty\int_0^{yz} f(x,y)\operatorname d x\operatorname d y \\ & = \int_0^\infty y f(zy,y)\operatorname d y\end{align}$$
Comment: Can you point out what's wrong with my reasoning above?
Comment: It seems like the formula is what I had in my second attempt with the extra $|y|$ in it. Is there an intuitive explanation?
Comment: Does this help? @LukaHorvat


Software that allows playing in different temperaments

Question: Do you know of any software out there that will allow me to play in different musical temperaments (e.g. Well temperament and Meantone temperament)?  I'm especially interested in software that accepts MIDI input.
Comment: Also check discussion at http://music.stackexchange.com/questions/3103/software-for-microtonal-midi
Comment: I found this question by nearly asking a very similar one.  I'd like to be able to hear the same piece of music in a bunch of different temperaments without having to program it myself or buy expensive software -- ideally somebody already has a collection of MP3s or something.  Should I ask that separately or just leave this comment here?
Comment: Does anyone know such an app for iOS?
Answer: Logic Pro has built-in controls for using different temperaments.  Check out the link below:
http://documentation.apple.com/en/logicpro/usermanual/index.html#chapter=43%26section=6%26tasks=true
It allows you to either select a pre-configured tuning system, or customize your own.  MAX/MSP is another solution, but if you don't have programming experience, using this as an option might be significantly more trouble than it's worth.  However, you could
Here are some other links I found, but cannot personally vouch for:
http://www.cycling74.com/forums/topic.php?id=7392
(If you have MAX, you could use this file to convert MIDI input to specific frequencies).
http://emusician.com/tutorials/emusic_playing_cracks/
(article describing various software programs suited for alternate tunings)
http://www.justonic.com/
Answer: The MIDI program Timidity can be adjusted to any tuning you want, though it requires a little bit of work.
Update:
Timidity supports playing just intonation very easily:
<code>   -Z file, --freq-table=file
          Cause  the  table of frequencies to be read from file.  This is useful to define a tuning different from 12-equal temperament.  If ``pure'' is specified, TiMid‐
          ity++ plays in trial pure intonation.

          -Zpure[n(m)], --pure-intonation=[n(m)]
                 Play in trial pure intonation by Key Signature meta-event in the MIDI file.  You can specify the initial keysig by hand, in case the MIDI file  does  not
                 contains  the meta-event.  Optionally, n is the number of key signature.  In case of sharp, n is positive.  In case of flat, n is negative.  Valid values
                 of n are in the interval from -7 to 7.  In case of minor mode, you should put `m' character along with -Zpure option.
</code>
To make your own, arbitrary tunings, see this.
Comment: see  also: http://music.stackexchange.com/questions/12566/what-file-format-does-timiditys-z-or-freq-table-option-require
Comment: Timidity also allows you to send specific audio frequencies with each note.  If you use a tuning with more than 12 notes in an octave and you use tuning tables then you reduce the overall octave range you have available (eg, using 128-EDO means you only get one octave). But if you send the exact audio frequency you want with each note then you are not limited in your octave range. You do this with sysex commands which makes it trickier but it does give you tremendous power and allowing for something like 196608-EDO over 10.666 octaves.
Comment: @phoog: I agree it is not pretty, but isn't that exactly what just tuning is supposed to be? I guess I am asking: "I think of just intonation as, for example, [this](https://en.wikipedia.org/wiki/Just_intonation#Diatonic_scale); what do you mean when you think of just intonation?"
Comment: For just intonation, does it adjust the intonation dynamically?  If not, it's not really just intonation.
Comment: @phoog: I don't understand your comment. I thought traditionally just intonation simply means tuning with rational frequency ratios. Dynamically adjusted intonation is something different. Can you elaborate for me?
Comment: @WillieWong you can't tune a fixed diatonic scale in just intonation because the rational frequency ratios don't add up.  For example, if you are tuning in C major, and your C-to-E ratio is 5:4, then you cannot have a 3:2 fifth for all of the chords C major, G major D minor, and A minor.  If three of those fifths are at a 3:2 ratio, the fourth will be at 40:27.  It's not pretty.
Comment: @phoog: are you _requiring_ just intonation to be also transpositionally invariant? With a fixed tuning, yes, the two are not compatible. But I don't think most people require transpositional invariance when they talk about just intonation.
Comment: Historically, nobody ever tuned keyboards that way.  Early keyboards for monophonic music were probably tuned in Pythagorean tuning (i.e. 3-limit just, with 7, 8, or 9 pitch classes), but by the time the third began to be consonant, people would have been tempering the scale.  It's not like they were playing music with sour fifths because they didn't know better.  "Just intonation" describes how an ensemble of instruments with varying pitch can tune, not how a keyboard can be tuned.  I'm not talking about transposition, but about the ability to play all the consonant intervals in a single key.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/95915/discussion-between-phoog-and-willie-wong).
Answer: Midi actually has a 20-year old ratified specification extension just for this. Any synth that supports that extensions should support those temperaments (although you might need an appropriate midi interface too).
The wikipedia page for the extension page lists a number of soft-synths that support the extension.
Answer:
Denemo (music score editor. free.) supports a few temperaments.

Some Synth plugins (vsti...) lets you choose the temperament. Ideal, if you want to play live with a midi keyboard. Edirol Orchestral was one, but I think it's discontinued.
Answer: Mutabor allows you to use arbitrary tunings and works on a couple of platforms. It accepts MIDI input from keyboards and files. On Mac I've had some trouble getting it set up, and the translation to English is not done yet, but it has great potential...
Answer: Pianoteq. You should really look at this physical-modeling piano virtual instrument plugin . Not only does it support all the historical temperaments, it models many kinds of harpsichords, fortepianos, pianos, and other instruments. It sounds excellent and is light on system requirements, and it's available for Mac, PC and Linux.
Answer: http://www.TallKite.com/alt-tuner.html
Alt-tuner is a midi effect for your Digital Audio Workstation, very powerful. You can sweep the whole spectrum of meantone (1/3 comma, 2/7 comma, 1/4 comma, 1/5 comma, 1/11 comma = 12-ET, 0 comma = pythagorean) and you can even do this with a foot pedal as you are playing, via midi learn. It also does well-temperament, any kind. It does just intonation with commatic shifts, called tapnotes. It does ADAPTIVE just intonation, which adjusts all the pitches very slightly (2-3¢) as you play, for a better sound than quarter-comma meantone, which has fifths flat by 5.5¢, and min 7ths and maj 9ths flat by 11¢.
You can also switch back and forth between all these tunings with foot pedals as you play - as to Monica Cellio's comment above - no need for mp3s, just play and listen!
Answer: Korg and Yamaha synths each support a fairly large number of different temperaments.  Other makes may as well, these are just the ones I have owned.  I'm surprised the companies don't advertise this feature.
Comment: I had a Roland digital piano that supported this feature as well, though I've since sold it.
Comment: Actually most digital pianos and synths support a fairly **small** number of temperaments! For example, the popular Casio Privia series supports 16 temperaments, but only one meantone (when at least two would be needed, see https://en.wikipedia.org/wiki/Meantone_temperament) and only two well temperaments (when at least five would be needed, see https://en.wikipedia.org/wiki/Werckmeister_temperament and https://en.wikipedia.org/wiki/Kirnberger_temperament and https://en.wikipedia.org/wiki/Well_temperament). Kawai supports different total number, but the very same three well and meantone ones.
Answer: Every virtual organ software that I know of can handle multiple temperaments:

Hauptwerk (proprietary)
GrandOrgue (open source)
jOrgan (open source)
Answer: According to wikipedia, "A microtuner or microtonal tuner is an electronic device or software program designed to modify and test the tuning of musical instruments (in particular synthesizers) with microtonal precision, allowing for the design and construction of microtonal scales and just intonation scales, and for tuning intervals that differ (or not) from those of common Western equal temperament." See:
http://en.wikipedia.org/wiki/Microtuner
"Hardware microtuners" listed there includes "ORIENTAL / WORLD SCALE MIDI CONVERTER", "FSU Dynamic Microtuning Box", and "H-Pi Instruments Tuning Box TBX1".
"Software microtuners" listed there includes "chelles et Modes (Mac & PC)", "alt-tuner", "L'il Miss' Scale Oven (Mac)", "microtuner Max/MSP object", "Scala (Windows, Linux, Mac)", "Tobybear MicroTuner VST plugin (Windows)". "Tune Smithy (Windows)", and "Mutabor".


How to do Hybrid Encryption in NodeJS in given below steps?

Question: Steps for Encryption
1) Generate a 16 digits random number. Say RANDOMNO.
2) Encrypt RANDOMNO using RSA/ECB/PKCS1Padding and encode using Base64. Say encryptedKey.
3) Perform AES/CBC/PKCS5Padding encryption on request payload using RANDOMNO as a key and iv-initialization vector. Say encrypted_data.
4) Now client may choose to send IV in request from one of the below two options.
a. Send Base64 Encoded IV in the "iv" tag. (Recommended Approach)
b. Send IV as a part of encrypted data itself.

bytes[] iv = IV
bytes[] cipherText = symmetrically encrypted Bytes (step3)
bytes[] concatB = iv + cipherText
encryptedData= B64Encode(concatB)

Please can someone help me on the above?. I tried my level best to find the solution.
I tried the bellow query, I am not sure that this is wrong or right
var request = require("request");
var crypto = require('crypto');
var fs = require('fs');

var object = {name : "Test", age : '28'}

var keyProfile = crypto.createPublicKey(fs.readFileSync(__dirname + '/publickey.txt'));
  var packetData = Buffer.from(JSON.stringify(object));

var randomno = 'SwAW1D8kbcXVrq31'//Randomly generated string of length 16 (OR 32).
  var encryptedKey = crypto.publicEncrypt({ key: keyProfile, padding: crypto.constants.RSA_PKCS1_PADDING }, Buffer.from(randomno)).toString('base64');

  // Symmetric encryption
  var iv = crypto.randomBytes(16);
  var cipher = crypto.createCipheriv('aes-128-cbc', randomno, iv);
  var encryptedData = cipher.update(packetData, 'utf8', 'base64');
  encryptedData += cipher.final('base64');
  console.log(encryptedData)

Comment: The client says this is wrong, And they are not able to decrypt the response.
Answer: var request = require("request");
var crypto = require('crypto');
var fs = require('fs');
var object = {name : "Test", age : '28'}
var keyProfile = crypto.createPublicKey(fs.readFileSync(__dirname + '/publickey.txt'));
var packetData = Buffer.from(JSON.stringify(object));

var randomno = 'SwAW1D8kbcXVrq31'//Randomly generated string of length 16.
var encryptedKey = crypto.publicEncrypt({ key: keyProfile, padding: crypto.constants.RSA_PKCS1_PADDING }, Buffer.from(randomno)).toString('base64');
var iv = crypto.randomBytes(16);
var cipher = crypto.createCipheriv('aes-128-cbc', randomno, iv);
var encryptedData = cipher.update(packetData, 'utf8', 'base64');
encryptedData += cipher.final('base64');
return encryptedData

Comment: It will be better if you add explanation for your code.


jsPDF incluir css

Question: Como faço para salvar essa DIV, com a formatação css, se for mais fácil fazer com table, tambem pode, pois o que preciso é somente mostrar essa DIV com valor dentro.
Será gerado lado a lado.

var doc = new jsPDF();
var specialElementHandlers = {
    '#editor': function (element, renderer) {
        return true;
    }
};

$('#btGerarPDF').click(function () {
    doc.fromHTML($('#etiqueta').html(), 0, 0, {
        'width': 170,
            'elementHandlers': specialElementHandlers
    });
    doc.save('teste.pdf');
});

102030

102030

<button id="btGerarPDF">gerar PDF</button>
Comment: Olá amigo, já utilizei esta biblioteca, porém não com css inline. Já experimentou utilizar `@media print { }` em um arquivo `.css` separado? Tem mais informações sobre este tipo de media query aqui neste link: http://www.joshuawinn.com/css-print-media-query/
Comment: @LeandroSimões Bom dia. Penso no PDF por causa do controle das margens. Irei imprimir etiquetas duas colunas usando impressora matricial, e a folha é mais estreita que A4.
Answer: O jsPDF não suporta a leitura do estilo das CSS do utilizador, conforme descrito na documentação. A unica alternativa que começo e usei é a utilização do html2Canvas.
O

$(document).ready(function(){

 //pdf
 $("#pdfDownloader").click(function(){

        html2canvas(document.getElementById("printDiv"), {
            onrendered: function(canvas) {

                var imgData = canvas.toDataURL('image/jpeg');

                //console.log('Image URL: ' + imgData);

                var doc = new jsPDF('p','mm','a4');

                doc.setFontSize(10);

                doc.text(10, 15, 'Filter section will be printed where.')

                doc.addImage(imgData, 'jpeg', 10, 20);

                doc.save('sample.pdf');
            }
        });

 });
});
.xpto{
    width:600px;
    height:1000px;
    background:white;
    padding:5px;
}

table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />
    <link rel="stylesheet" type="text/css" href="app.css" />

<button type="button" id="pdfDownloader">Download</button>

    Company
    Contact
    Country

    Alfreds Futterkiste
    Maria Anders
    Germany

jsPDF incluir css


build java method to change two textViews

Question: I have two buttons and two textViews , when i click "add2_A" ,then "score1" is updated and increment by 2 .
the same is "add2_B" will increment "score2"
i want to use only one method for both of them ..the problem is that the app crash !
this is my java code :
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class app2 extends AppCompatActivity implements View.OnClickListener
{
public int number =0;
public int id;
TextView txt1= (TextView) findViewById(R.id.score1);
TextView txt2 = (TextView) findViewById(R.id.score2);
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_app2);

}
@Override
public void onClick(View v){
   id=v.getId();
}

public void increment2(){
    number =number +2;
    if(id ==R.id.add2_A)
        txt1.setText(number);
    if(id== R.id.add2_B)
        txt2.setText(String.valueOf(number));
}}

edit :
this is XML code for calling "increment2" method :
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/points2"
android:layout_margin="8dp"
android:id="@+id/add2_A"
android:onClick="increment2"/>

edit :
i solved it and it works now ..this is the code after editing :
public class app2 extends AppCompatActivity  {
public int number =0;
public int id;
public TextView txt1;
public TextView txt2;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_app2);
    txt1= (TextView) findViewById(R.id.score1);
    txt2 = (TextView) findViewById(R.id.score2);
}

public void increment2(View v) {
    number = number + 2;
    id = v.getId();
    if (id == R.id.add2_A) {
        txt1 = (TextView) findViewById(R.id.score1);
        txt1.setText(String.valueOf(number));
    }
    if (id == R.id.add2_B) {
        txt2 = (TextView) findViewById(R.id.score2);
        txt2.setText(String.valueOf(number));
    }
}

edit :
this is what appears in the logcat and there's no other messages in the message bar :
  Process: com.example.mayouza.myapplication2, PID: 2553
                                                                              java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.mayouza.myapplication2/com.example.mayouza.myapplication2.app2}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2567)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                                                                                at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:120)
                                                                                at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:151)
                                                                                at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:31)
                                                                                at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:55)
                                                                                at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:33)
                                                                                at android.support.v7.app.AppCompatDelegateImplN.<init>(AppCompatDelegateImplN.java:33)
                                                                                at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:201)
                                                                                at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:185)
                                                                                at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
                                                                                at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
                                                                                at com.example.mayouza.myapplication2.app2.<init>(app2.java:11)
                                                                                at java.lang.Class.newInstance(Native Method)
                                                                                at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2557)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Comment: could you attach the error message?
Comment: edited the question ..
Comment: The error doesn't come from this activity, but probably missing ComponentInfo.
Comment: can you guess what's missing ?i'm already have a GPU issue
Comment: Can you post your layout activity_app2.xml?
Comment: `increment2` is never called in your code... Put all that code into onClick. Don't store `id` as a field
Comment: increment2 is called in the XML ..i posted it
Comment: Whenever you use `android:onClick` that method must be 1) public 2) void 3) accept a View parameter. Otherwise, your code crashes
Comment: @cricket_007 thanks i could solve it using this answer i was missing the view parameter ..i need to note that the duplicated question you mentioned in the link didn't solve the problem that's why i asked again.
Comment: It actually does solve the stacktrace you've posted and the code in the question. The onClick problem is a different error completely, and also tells you that the method needs a View parameter if you read it
Comment: Note: your views aren't changing after onCreate, so you should only use findViewById once for each view, not everytime a click happens
Comment: i'm not good at reading stacktrace yet ,,and thanks for the note you're right
Answer: You will not be able to successfully call findViewById() before you call setContentView() because view hiearchy has not  built yet.
You need to move call to findViewById() after call to setContentView().
setContentView(R.layout.activity_app2);
txt1= (TextView) findViewById(R.id.score1);
txt2 = (TextView) findViewById(R.id.score2);

Comment: post your code where you call increment2().
Comment: i did ,, the app opened but when i click the button it crashes again


Conversão especificada não é válida no ExecuteScalar

Question: O erro de conversão especificada não é válida acontece no código:
if (command.ExecuteScalar() == DBNull.Value)
{
    resultados[j2][i2] = 0;
}
else
{
    resultados[j2][i2] = (double)(decimal)command.ExecuteScalar(); /* <<---- */
}

A query que estou executando no mysql é:
SELECT IFNULL(AVG(VL_M4000010),0)
FROM HT_MA4_ESS_SEG
WHERE YEAR(TS_SAMPLETM) = 2015
    AND MONTH(TS_SAMPLETM) = 1
    AND TIME(TS_SAMPLETM)
    BETWEEN '00:00:00' AND '00:15:00'

O resultado do query via MySQL Workbench é 0.
Já tentei fazer a conversão sem o (decimal) apenas com o (double), de forma que ficaria (double)command.ExecuteScalar();.
Answer: Vou considerar que o tipo de resultados é double. Então faça uma conversão em vez de um cast:
Convert.ToDouble(command.ExecuteScalar());

Coloquei no GitHub para referência futura.
Não tem porque usar o TryParse() aqui porque esse dado consegue ser convertido sempre.
Comment: Perfeito, funcionou! Muito obrigado!
Answer: Outra alternativa é utilizar o Double.TryParse.
string value;
double number;

value = Double.MinValue.ToString();
if (Double.TryParse(value, out number))
   Console.WriteLine(number);
else
   Console.WriteLine("{0} is outside the range of a Double.",
                     value);

value = Double.MaxValue.ToString();
if (Double.TryParse(value, out number))
   Console.WriteLine(number);
else
   Console.WriteLine("{0} is outside the range of a Double.",
                     value);

Exemplo retirada de:
https://msdn.microsoft.com/pt-br/library/3s27fasw(v=vs.110).aspx


Linear Optimization Problem with a constraint on the cost functin

Question: Is there a known algorithm ( similar to simplex algorithm) that solves the following problem:
Maximize $c^Tx$ subject to the constraints $Ax\leq b$ and $c^Tx\leq \alpha$. It would be nice if you can provide a link to an article or software implementation of such problems.
Thanks
Answer: Well of course, all you do is add $c^T$ as a row to your $A$ matrix, and $\alpha$ to your $b$ vector. That is,
$$\bar{A}\triangleq \begin{bmatrix} A \\ c^T \end{bmatrix} \quad \bar{b}\triangleq \begin{bmatrix} b \\ \alpha \end{bmatrix}$$
And then you solve using any preferred algorithm:
$$\begin{array}{ll}
\text{maximize} & c^T x \\
\text{subject to} & \bar{A} x \leq \bar{b}
\end{array}$$
Here's how this works: let $\alpha_{\max}$ be the solution to the original problem (without the extra $c^Tx\leq\alpha$ constraint), and let $\alpha_{\min}$ be the solution to the minimization $$\begin{array}{ll}
\text{minimize} & c^T x \\
\text{subject to} & A x \leq b
\end{array}$$
(Note: it's possible one of these extremes will be infinite.)
Now select any value $\alpha\in[\alpha_{\min},\alpha_{\max}]$ and add your extra constraint $c^Tx\leq \alpha$ as I've shown above. When you solve this modified model, the optimal point $x^*$ will achieve exactly $c^Tx^*=\alpha$.
Again, I'm sorry for misreading the problem earlier! I hope this clarifies matters.
Comment: This problem arises naturally in financial planning. You have an existent portfolio with certain weights and projected returns for each of these weights. You like to achieve a maximal certain return  below a certain return threshold while keeping control of how you change the weights ( not too much trading). So I hope you can see that the restriction I introduced is natural ( total return of the portfolio is just the weighted average of the projected returns)
Comment: because sometimes you don't care about global maximums but only about local ones. I am not interested in any maximum but only maximum in a certain region.
Comment: Why must the modified program be unfeasible if $c^Tx^*>\alpha$? Clearly $x^*$ cannot be optimal, as it is not feasible, but there could exist a different optimal solution for the modified program.
Comment: so what you're saying that with your modification if there is no solution to the original model there will be no solution to your modification?
Comment: Of course I am asking about it but you solved my problem so for that I am very thankful and I am giving you all the credit! But suppose that we found $x*$ in the original problem such $c^Tx^{*}>\alpha$ does it mean that if I will use the new set up (with \bar(A) it will give me a point $x_0$ and the maximum will be exactly $\alpha?$ This exactly what I am looking for!
Comment: I'm afraid I misread your problem as a minimization, not a maximization. My approach to adding a row to $A$ and $b$ still works, but most of what I said before is irrelevant. I'm sorry for leading you astray; I'm deleting many of my comments above. @Daryl, now I understand your confusion too.
Comment: No that's fine. I am happy with your trick. I didn't realize that I can add constraints satisfied by the cost function itself. The trick you suggested should do the job.
Comment: Great. I've modified my answer accordingly.


How to see all changes made by an admin

Question: Is it possible to somehow pull a report on an admins activity on a Drupal 7 site? I'd like to know for example any development changes, and settings changes, and database changes that an admin on a site has performed.
I've found some modules that help with that, but its too late to install them now.
Comment: You can view a simple list of sessions and page edits using the system log at admin/reports/dblog
Answer: Administration Notifications this is a simple module that can be used for communication of site changes/updates between the site designer/developer, and the site owners.

if you maintain a drupal installation for another company, you can use
  this module to inform them when you have updated versions of the site
  (ex drupal 7.1 -> 7.2), updated modules on the site (i.e.
  Administration Notifications 7.x-1.0 -> 7.x-1.1), added new modules,
  or changed the site design in some manner.

or you can try Activity module.

The Activity module keeps track of the things people do on your site
  and provides mini-feeds of these activities in blocks, in a
  specialized table, and via RSS. The module is extensible so that any
  other module can integrate with it. The messages that are produced are
  customizable via the admin interface and are context sensitive.
Comment: Beware: activity is practically abandoned.

How to see all changes made by an admin