How do I POST an array to a web api controller from an HttpClient?

Question: Inside a web api controller I have the following method:
[HttpPost]
public ProcessResultDto Process(int[] IDs)
{
}

I cannot change that signature or dll or anything.
I have to make an executable that calls that method.
Here's roughly what I have so far:
int[] ids = //...
using (var client = new HttpClient())
{
    var content = // I don't know what goes here.
    var result = cli.PostAsync("/api/Processor/Process", content).Result;
    string resultContent = result.Content.ReadAsStringAsync().Result;
    // Substring(6) because of leading )]}',\n
    var summary = JsonConvert.DeserializeObject<ProcessResultDto>(resultContent.Substring(6));
    return summary;
}

What do I set content to so that I can pass an array of int's to my web api controller
Comment: Maybe `new StringContent(JsonConvert.SerializeObject(new[] { 1, 2, 3 }));` ?
Answer: You could do the following:
int[] ids = new[] {1,2,3,4};
var content = JsonConvert.SerializeObject(new {
   IDs = ids
});

This will create an anonymous object with a property of IDs and convert it to json. The json will look like:
{
    IDs: [1,2,3,4]
}

The web API method will then bind that to your model.
Answer: I use ServiceStack's JSON serializer/deserializer as they're the current .Net performance champ. From the ServiceStack docs

Any List, Queue, Stack, Array, Collection, Enumerables including custom enumerable types are stored in exactly the same way as a JavaScript array literal

Therefore
int[] ids = [1,2,3,4];
var content = TypeSerializer.SerializeToString(new {IDs=ids});


WPF Interoperability: How to get Reference of Host Windows Form in WPF User Control

Question: I've developed an Outlook Addin and UI of the addin is created in WPF. The WPF User controls are hosted in the Windows Forms. All my functionality resides inside the WPF user controls and I've provided a Close form functionality. Can somebody tell me how to get the reference of the Windows Form in the code behind of WPF user control which is hosted in the elementhost available in the Windows Form, so that I can put the frmHost.Hide() code in the WPF user control.
Thanks
Nitin
Answer: I'm not familiar with WPF Outlook addin, but in the control hierarchy, I suppose your WPF control is ultimately the (grand) child of an ElementHost control. Once you have a reference to it, you can get to the Winform host (Parent property, etc.).


Arnol'd's trivium problem 21

Question: Find the derivative of the solution of the equation $\ddot{x} = \dot{x}^2 + x^3$ with initial condition $x(0)=0$, $\dot{x}(0) = A$ with respect to A for A = 0.
I have no idea about how to solve this problem, please help me.
Answer: The general procedure is:

solve the equation with the given the initial conditions. Here the conditions are $x(0)=0$, $\dot x(0)=0$, the solution is $x_0(t)=0$.
linearize the equation around $x_0$. That is: plug $x(t)=x_0(t)+\epsilon y(t)$ to the differential equation, and keep only the part linear in $\epsilon$ (i.e. we compute a derivative). Here we get $\ddot y=0$, with the general solution $y(t)=a+bt$.

Now to compute the derivative of $x(t)$ by $A$ we just need to take the $y$ s.t. $y(0)=0$ and $\dot y(0)=1$; in this case it is
$$y(t)=t.$$
Answer: Let $ w(x) = \dot{x}^2 $, and denote differentiation of $w$ w.r.t. $x$ by $w'$.
$ w'(x) = 2\dot{x} \frac{d \dot{x}}{dx} = 2\dot{x} \frac{d \dot{x}}{dt}(\frac{dx}{dt})^{-1} = 2\dot{x}\space\ddot{x}\space\dot{x}^{-1} = 2\ddot{x} $
With this substitution the ODE in question reduces to the following linear first order equation:
$$ w' - 2w = 2x^3 .$$
Solving for $w$ as a function of $x$ will then give you the autonomous first order equation $ \dot{x}^2 = w(x). $
Comment: David, thanks for your help. However, your method can give me the expression of $\dot{x}(x)$ but I cannot find the derivative of x respect to A for A=0.

Arnol'd's trivium problem 21


Twig Tokens in Views not Rendering Inside an HTML Element

Question: I'm using views to create a custom block of shortcut icons and need the images to link to the corresponding content. Using Rewrite Results I can overwrite the output of the view and have an anchor tag wrap around the image, however when I inspecting the output on the site, the href is blank making the images useless as links. Everything else renders though.
The view uses two fields, all from the same content type (shortcut). It consists of an image and a URL field. The image field is called first and then hidden to get the tokens, and the URL field holds the actual rewrite text. All of the these Twig tokens are listed as available within the Replacement Patterns dialog box.

{{ field_image }}

{{ field_url }}

Does Twig Debug affect the output for content like this? Is there another format I should be using? I tried calling and hiding via CSS the {{field_url}} first, before the rest of the rewrite text to see if it had to do with render inheritance but it still didn't change the blank href output.
Any insight on why the Twig token won't render inside HTML would be GREATLY appreciated. Thank you.
Answer: Problem solved. There were two issue at play; first off when I was messing with the Twig templates to trying and format the view the hard way, I inserted an extra  in one of the templates and failed to remove it. My template was wrapping the empty tag around the properly generated content making it useless.
The second problem was that for some odd reason, the block was calling/using the same custom theme hook twice. I haven't figured out what was causing this error, but deleting the bock and forcing the new one to revert to a more general template hook solved the rendering issue.
However Twig debug still shows that there are two custom theme hooks of the same name available for use. No clue what is causing this behavior.


Why is a characteristic of a sample called statistic and not something else?

Question: Is there any hidden meaning/reason that I'm missing for the word statistic to be used on the above definition? Because as you may know, beginners in Statistics studies can get confused with the term.
Comment: It's not clear what you're seeking here. What kind of answer would suffice? We're presumably discussing Noun meaning 2 [here](https://en.wiktionary.org/wiki/statistic) -- "A quantity calculated from the data in a sample". There's no big secret to naming things -- people call things what they call them because it seemed like a reasonable thing at the time. The term *statistics* was used in a reasonably modern sense in the later half of the 19th century, and *statistic* as a single piece of numerical information was also used then (if rarely). Its modern sense seems to be an invention of Fisher.
Comment: There are two characteristics that make a sample statistic. It is chosen from a **statistical population** which means a set of similar objects for your experiments and another one is  having a **procedure**  for choosing  a sample: http://www.stat.wmich.edu/s216/book/node28.html
Answer: No. It's just a convention. The etymology of the word itself is interesting, being related to "state", because the earliest uses of the word "statistics" were about nations in particular. But this doesn't have much to do with the modern technical meaning of "statistic", which is "measurable function of the data".


Problemas com o file_put_contents()

Question: Tenho um script que roda toda vez que determinada página é carregada.
Basicamente, ele faz uma busca no banco e salva os valores em um arquivo:
$servicos = $db->prepare('SELECT id_servico, UNIX_TIMESTAMP(data) dia, user, cliente, situacao FROM servicos);
$servicos->execute(array());
$servicos_result = $servicos->fetchAll(PDO::FETCH_OBJ);

$out = array();
foreach($servicos_result as $row) {
    $out[] = array(
        'id' => $row->id_servico,
        'user' => $row->loja,
        'cliente' => $row->cliente,
        'situacao' => $row->situacao,
        'start' => $row->dia . '000',
        'end' => $row->dia . '000'
    );
}

$stringData = json_encode(array('success' => 1, 'result' => $out));
file_put_contents ( "events.json.php" , $stringData );

O problema é que tem demorado um pouco para que o arquivo seja atualizado após alguma alteração no banco. Ou seja: ele não é atualizado na primeira vez que a página é reccaregada, mas só após alguns minutos e tentativas.
O arquivo está com cerca de 400kb.
Isso pode ser alguma limitação do servidor?
Comment: Permissão de gravação no diretório?
Comment: @marcelo2605 apaguei meus comments anteriores pra não deixar bagunça embaixo da sua pergunta, como já está resolvido. Qualquer nova dúvida, abra uma pergunta, ou se tiver duvidas sobre esta aqui, deixe um comment na resposta que eu retorno se estiver online.
Comment: @ShutUpMagda. O arquivo tem permissão 666. As informações são salvas, mas demora muito.
Comment: Qual o tempo de conclusão da consulta em si?
Comment: @ismael Pelo Workbench está sendo em 0.078 sec / 0.282 sec
Answer: Caso não precise realmente fazer um cache em disco, é muito mais fácil usar um echo simples, e gravar o próprio arquivo como  events.json.php :
$servicos = $db->prepare('SELECT id_servico, UNIX_TIMESTAMP(data) dia, user, cliente, situacao FROM servicos);
$servicos->execute(array());
$servicos_result = $servicos->fetchAll(PDO::FETCH_OBJ);

$out = array();
foreach($servicos_result as $row) {
    $out[] = array(
        'id' => $row->id_servico,
        'user' => $row->loja,
        'cliente' => $row->cliente,
        'situacao' => $row->situacao,
        'start' => $row->dia . '000',
        'end' => $row->dia . '000'
    );
}

echo json_encode(array('success' => 1, 'result' => $out));

Faria sentido você gravar em arquivo se fosse uma aplicação muitíssimo acessada, e pouco alterada, mas para volumes menores de acesso, ou maiores de alteração, servir o dado diretamente do DB não é um problema.
Mas note que se usar essa estratégia no futuro, de salvar em DB, evite a extensão .php, senão vai passar pelo parser do PHP à toa.
No seu caso, aparentemente a demora estava no cache do browser, e não na gravação do arquivo. Uma solução seria configurar uma pasta no servidor Web com uma regra de cache completamente diferente, mas se a solução acima bastar, é muito mais prático.

Problemas com o file_put_contents()


Finding the solution of a PDE in a specific domain

Question:
My thought: I tried to use polar coordinate to substitute $x,y$ with $r,\theta$ and got $u_{rr}+\frac{1}{r}u_r+\frac{1}{r^2}u_{\theta \theta}=1$
Since solution $u$ depends only on the distance to the origin,
the ODE reduced to:  $u_{rr}+\frac{1}{r}u_r=1$
Let $u_r=p$, then the ODE becomes: $pp'+\frac{1}{r}p=1$, but I do not know how to solve this ODE, although it has been reduced first-order.
Also, I am not sure whether I am on the right track. Is there an easy way to solve this problem? Any help to this problem will be appreciated. Thanks.
Comment: your ODE should be $p' + \frac 1r p = 1$, which can be solved by integration factor
Comment: Indeed it reduces to $(rp)'=r$.
Comment: @ArcticChar Use chain rule, Urr=(dp/dr)=(dp/du)*(du/dr)
Comment: There is no composition of functions here. There are just $u(r), u'(r)$ and $u''(r)$.
Answer: Your ODE can be reduced to $p'(r)+\frac{p(r)}{r}=1$, where $p(r)=u'(r)$. Notice that, as mentioned in the comment section, there is no composition of functions here, this is but a 'change of variables' (or a relabel, if you prefer). Thus there is no need to use chain rule and the original ODE is not the correct one.
Using your notation, write $p=u_r$. Then, considering the integrating factor
$$
T(r)=e^{\int \frac1r \,dr}=r
$$
we multiply it by the equation to get
$$
ry'+y=r\Leftrightarrow(pr)'=r.
$$
Integrating leads to
$$
pr=\frac{r^2}{2}+c
$$
for some $c\in\mathbb{R}$. Hence,
$$
y=\frac{r}{2}+\frac{c}{r}.
$$
Finally, we get
$$
u=\int u_r\,dr=\int p\,dr=\frac{r^2}{4}+c_1\log(r)+c_2
$$
for some $c_1,c_2\in\mathbb{R}$, which are obtained using the boundary conditions $u(a)=u(b)=0$.


Styling input element using only CSS

Question: I want to style the input element as mentioned below.

I did this by removing border property and adding border-bottom alone.
But when I am entering text in that, some border is appearing.

How can I remove the border when the input is focused? Is there any way that we can do it using only CSS (like any pseudo element) without using scripting.

First Name<input type="text" style="
    border: 0px;
    border-bottom: 1px solid black;
">

Answer: In your CSS, set outline: none; for input elements.

input[type="text"] {
    border: none;
    border-bottom: 1px solid black;
    outline: none;
}

input[type="text"]:focus {
    border-color: pink;
}

First Name<input type="text">

Comment: You'll want to use the `:focus` selector.
Comment: thanks.. :) working great.
Any selector that we can use for this scenario..Apart from this I want to change the border-bottom Color when entering text?
Comment: @Jayababu I updated the answer.  I moved the input style to CSS and added an attribute selector to narrow it down to text inputs.  Also, added the `:focus` selector to change the `border-color`.

Styling input element using only CSS


Proof by Contradiction that n is even

Question: Can someone help with this proof?
$$P(n): \forall n \in Z, n^2 + 5 $$ is odd implies that n is even.
I honestly don't even know where to start. I do know that $n=2k$ is even, and $n=2k + 1$ is odd, but I don't know how to use them
Thanks for the help
Comment: Why do you want to do it by contradiction? Proving the contrapositive (if $n$ is odd then $n^2+5$ is even) would be simpler.
Answer: Try expanding the bracket? if $n = 2k$ and $n = 2k+1$ what is $n^2$ in terms of $k$?
Comment: It would be: $n^2 = 4k$ and $4k^2+2$
Comment: Try again? as they are both not correct.
Answer: Suppose $n$ is odd. Can you get a contradiction?
Answer: One way this can be done is by recognizing that all perfect squares are congruent to $0$ or $1$ (mod $4$).

Proof by Contradiction that n is even


Prove null sequence with basic null sequences

Question: {$\frac{3}{4^n} + \frac{2n}{3^n}$}
Here are the basic null sequences
(1) {$\frac{1}{n^p}$} for p>0;
(2) {$c^n$} for $|c| <1$
(3) {$n^pc^n$} for p>0 and $|c| <1$
(4) {$\frac{c^n}{n!}$} for any real c
(5) {$\frac{n^p}{n!}$} for p > 0
Using the second rule - I can see the denominators being null however I know I can't have 0 as a denominator. I can prove it's null using limits. However, the question specifically states to use the basic null sequences
Answer: Hint: Rewriting
$$\frac{3}{4^n}+2\frac{n}{3^n}=3\cdot\left(\frac{1}{4}\right)^n+2\cdot n^1\left(\frac{1}{3}\right)^n$$
it is clear that the rule to be applied is $2$ for the first summand ($c=1/4<1$) and $3$ for the second.


Number of $3 \times 3 \times 3$ magic cubes

Question: A $3 \times 3 \times 3$ magic cube is a three-dimensional array of the consecutive integers $1$ through $27$, with the special property that the sum along any row, any column, any pillar, or any of the four space diagonals is equal to the same number. (Rotations of a certain solution are considered the same solution and therefore not counted.)
How many different $3 \times 3 \times 3$ magic cubes are there?

I got that the sum of each of these should be equal to $\frac19\left(\frac{27\cdot28}{2}\right)=42$, but I have no idea how to proceed after that.
Any help would be appreciated!
Comment: @Servaes your excellent indications should be written as an answer (with for example reference to http://mathworld.wolfram.com/MagicCube.html)
Comment: You've found that each 'line' sums to $42$. The middle number shares a line with every other number. In particular, it shares a line with the number $27$, so it is at most $42-27-1=14$. It also shares a line with the number $1$, so it is at least $42-1-27=14$. Hence the middle number must be $14$. Then the other $26$ numbers are placed in opposing pairs that sum to $42-14=28$.
Comment: @Servaes Oh, thank you, that helped me understand it now :)
Comment: One can take similar reasoning much further, but it becomes a bit too much for a comment. It's a good exercise to see how far you can get in determining all magic cubes with just pen and paper.
Answer: Up to rotation and reflection, there are four.
Comment: Please, if possible, try to put more information. (For example, giving the relevant references that are mentioned in the link you provide would be desirable.)


How to create a redirect to point to the user's id?

Question: I'd like to create a redirect so when the user hits mydrupal.com/my-account its redirected to mydrupal.com/users/3
I'm using Pathauto and I know I can go to admin/config/search/path/add to add the redirect but I can't get it to point to the user id as variable. For instance, in the existing system path option I thought I could add users/[uid] but that didn't work.
Any suggestions?
Comment: Why are you not redirecting /my-account to /user ? It will lead to the user profile page, If he/she is logged in.
Comment: That's exactly what I wanted! Do you want to add as an answer?
Comment: Let me add it so that the question will not be open.
Answer: Instead of redirecting the mydrupal.com/my-account to particular user ID as mydrupal.com/users/3
You should redirect them to mydrupal.com/user which will lead them to thier profile page if the user is logged in.
Answer: As an alternative, you could also use the Rules module for this.
Here is the rule you'd need for it (in Rules export format, just use copy/past to import it in your own setup):
{ "rules_redirect_an_old_path_to_a_new_path" : {
    "LABEL" : "Redirect an old path to a new path",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "the_old_path",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Sorry, the old path (= /the_old_path) is no longer in use, you will be redirected automatically to its corresponding path (= /the_new_path)" } },
      { "redirect" : { "url" : "the_new_path" } }
    ]
  }
}

A few more tweaks to make it fit your exact scenario:

change all occurences of the_old_path to my-account.
change all occurences of the_new_path to user.

Whenever such redirect actually happens, the user will also receive an informational message like so:

Sorry, the old path (= /my-account) is no longer in use, you will be redirected automatically to its corresponding path (= /user)

If you don't want such message to appear, then just delete the line containing drupal_message in the exported rule above.
Note: No Pathauto involved using this approach, just Rules.


Executar função sempre que modificar, criar, excluir post

Question: Galera boa noite, preciso executar uma função no wordpress sempre que um post for incluido, excluido, editado e voltado da lixeira. Alguém pode me ajudar não sei como fazer isso.
Obrigado.
Comment: comece pesquisando por aqui: https://codex.wordpress.org/Function_Reference/do_action
Comment: Poste o código que você já fez.
Comment: @RicardoHenrique acho que ele não conseguiu construir nenhum código, ele diz no post que não sabe como fazer isso.
Answer: Você está procurando por actions. Com eles, você pode atrelar métodos que você define a certos "eventos" que ocorrem no WP. Por exemplo, se você colocar, no seu functions.php o código
add_action( 'admin_init', 'init_admin_custom_css' );
function init_admin_custom_css(){
    add_editor_style( get_stylesheet_directory_uri().'/css/meu_css.css' );
}

o WP vai inserir este .css na tela do editor, toda vez que você entrar no menu de administração (i.e., a action admin_init). No seu caso, para realizar uma ação toda vez que um post é editado, por exemplo, você pode fazer
add_action('edit_post', 'minha_funcao');

e definir
function minha_funcao(){
    .
    . #seu código
    .
}

Veja aqui uma lista com os actions que o WP disponibiliza, e escolha-os de acordo com a sua necessidade. Nesta parte do codex, você pode observar o wp_insert_post, que vai fazer parte do seu código. Leia mais sobre o método add_action, suas peculiaridades e seus parâmetros aqui.
P.S. Todos os 4 links são do codex, o qual recomendo fortemente a leitura.


Is $f:(-1,1)\to \{y\in\mathbb{C}\mid |y| =1\}\setminus\{-1\}:x\mapsto e^{i\pi x} $ a homeomorphism?

Question: Consider $f:(-1,1)\to \{y\in\mathbb{C}\mid |y| =1\}\setminus\{-1\}:x\mapsto e^{i\pi x} $.
I think $f$ is a homeomorphism but I still need to show that the inverse $f^{-1}$ is continuous.
For the inverse I calculated if $0\leq\theta<\pi$ that
$f^{-1}(e^{i\theta})= \frac{\theta}{\pi} $ and if $\pi<\theta<2\pi$ then $\frac{\theta-2\pi}{\pi}$.
How do I go on for the continuity?
Comment: As $f^{-1}$ is linear in the argument $\varphi$, doesn't that show continuity?
Answer: I guess that to do it the way you wanted we could use the identification
$$ \{ y \in \mathbb{C} : \lvert y \rvert = 1 \} \setminus \{ -1 \} = \{ e^{i \theta} \in \mathbb{C} : \theta \in (- \pi , \pi) \}. $$
This way we get simply $f^{-1} (e^{i \theta}) = \frac{\theta}{\pi}$. To prove continuity we can take an open set of the form
$$ U = \{ e^{i \theta} \in \mathbb{C} : \theta \in (a,b) \subset (-\pi,\pi) \}$$
and we get
$$f^{-1}(U) = \left(\frac{a}{\pi},\frac{b}{\pi}\right). $$
Answer: Let $e^{i\theta_n} \to e^{i\theta}$. To show that $\theta_n \to \theta$ it is enough to show that $\theta$ is the only limit point of $(\theta_n)$. [This is because $(\theta_n)$ is a bounded sequence of real numbers]. If $\theta'$ is a limit point of this sequence then  $\pi \leq \theta' \leq 2\pi$ and $e^{i\theta'}=e^{i\theta}$. Can you finish?


How might I show only the first level of an Exposed Taxonomy Filter in Views?

Question: In Drupal 7, I have a exposed filter set at first in its hierarchical fashion

with the following structure:
<code>Adjunct
-Adjunct Lecturer
-Adjunct Professor
Chairperson
Clinician
Container
-Director Advising & Student Affairs
-Managing Director TIC
Deans
-Associate Dean Undergraduate Advising Administration
Department Chair
Emeritus
-Associate Professor Emeritus
-Professor Emeritus
Lecturer
-Senior Lecturer
Professor
-Assistant Professor
-Assistant Professor in Residence
-Associate Professor
-Associate Professor in Residence
-Research Scientist & Professor
Speech Pathologist
Visiting
-Visiting Assistant Professor
-Visiting Associate Professor
</code>
In the exposed filter, is there a way to expose only the parent (first level) items (Adjunct, Deans, Department Chair, etc)?
Update: Grouping the exposed filter in views did not work (ticket).
Comment: have you tried adding " Taxonomy: Term ID (with depth)" and set the depth to "1".
Comment: Hi Bala: I'd suggest moving this down to the answer section below. I've not yet tried but that sounds like something to test today. Thank you.
Comment: Bala: That filter works nicely. First, please put it in the answers! :) Second question is how to only expose parent level taxonomy in the drop down menu?
Comment: I updated my answer and for the second you asked the another question, so I answered there.
Comment: @Richard, I think this duplicate to http://drupal.stackexchange.com/questions/94246/trying-to-remove-options-form-an-exposed-filter
Answer: Add " Taxonomy: Term ID (with depth)" and set the depth to "1" it will show the first level of terms.
For Drupal 6:
Views Taxonomy: limit exposed dropdown by term depth module provides enhanced functionality for the exposed dropdown filter for taxonomy terms in Views.

Exposed term filters can already be limited to display only terms
  selected in the Views interface. But what if content creators add new
  taxonomy terms? They will have to navigate the Views interface and add
  these new terms to the list of terms shown by exposed filters.
Comment: An otherwise excellent answer and worthy of an upvote (which I did). But, I'm using D7. I've just edited my question to jot down that information.
Comment: @Richard did you find answer for D7?


Projection Operator spectrum equation derivation

Question: I am trying to understand how the following left hand side of this spectrum equation becomes the right hand side, no amount of simple algebra manipulations get me to the right hand side.  Can anyone help?
Even accounting for the fact that for Projection Operators $P = P^2$ or that $\lambda^2 = \lambda$.
$$
(\lambda I - P)^{-1} = \frac{1}{\lambda} I + \frac{1}{\lambda(\lambda - 1)}P
$$
This equation is mentioned here on Wikipedia, but no source is mentioned https://en.wikipedia.org/wiki/Projection_(linear_algebra)#Spectrum
I am only interested in the algebraic manipulation that got us from the LHS to the right hand side of the above equation
This question has an answer that makes some hints about the derivation, but its not clear how they got this https://math.stackexchange.com/a/4089303
Answer: If you suspect that an inverse of $\lambda I - P$ may be found (if it exists) among the operators $aI + bP$ (and there are theoretical reasons why you might expect this although you do not need to know them), collecting "like terms" in the expansion of the product
$$
(\lambda I - P)(aI + bP) = \lambda a I + \lambda b P - a P - b P^2 = (\lambda a) I + (\lambda b - a - b) P
$$
and wanting this product to be equal to $I = 1 \cdot I + 0 \cdot P$ shows that $\lambda I - P$ will indeed have an inverse of the form $a I + b P$ as long as the scalars $a,b$ satisfy the scalar equations (1) $\lambda a = 1$ and (2) $\lambda b - a - b = 0$.
The equation (1) forces $a = 1/\lambda$ and solving (2) for $b = a/(\lambda-1)$ and putting in $a = 1/\lambda$ in this expression for $b$ gives the desired formula for $(\lambda I - P)^{-1}$.  And of course the hypotheses needed for these formulas to make sense (that $\lambda \not \in \{0,1\}$) are generally the hypotheses that are also needed for $\lambda I - P$ to be invertible.
More generally, suppose an operator $T$ is known to "be a root of a polynomial," i.e. there is some polynomial $p(x) \in \mathbb{C}[x]$ with $p(T) = 0$, and that $\lambda$ is a complex number.  Performing "polynomial long division" of $p(x)$ by $x - \lambda$ yields a polynomial $q(x)$ (of degree one smaller than $p$) with $p(x) = (x - \lambda) q(x) + p(\lambda)$ (this is sometimes called the "factor theorem" or "remainder theorem" in algebra class).  Evaluating both sides of this polynomial equation at $T$ one obtains
$$
0 = (T - \lambda I) q(T) + p(\lambda) I,
$$
which implies that $(T - \lambda I) q(T) = -p(\lambda) I$.  If $\lambda$ is not a root of $p$, we can divide both sides of this equation by the nonzero complex number $-p(\lambda)$ and deduce that $T - \lambda I$ is invertible with inverse given by
$$
(T - \lambda I)^{-1} = -p(\lambda)^{-1} q(T).
$$
The projection case is the special case $p(x) = x^2 - x$, where if you carry out the polynomial long division you get $p(x) = (x - \lambda)(x + (\lambda - 1)) + \lambda (\lambda - 1)$ so that $q(T) = T + (\lambda - 1) I$ and $-p(\lambda)^{-1} q(T) = \frac{1}{\lambda(\lambda - 1)} T + \frac{1}{\lambda} I$.
Note that an operator on a finite dimensional complex vector space is always the root of some complex polynomial (e.g. its characteristic polynomial), so the argument above generally provides a formula for $(T - \lambda I)^{-1}$ as a polynomial in $T$ in such cases.  Operators on infinite dimensional complex vector spaces are not guaranteed to be roots of polynomials, but when they are, the above argument applies equally well in those cases.
Comment: Sheldon Axler's *Linear Algebra Done Right* has most of the above background material, with its Chapter 4 including enough of the general theory of polynomials and its Chapter 8 introducing e.g. the characteristic polynomial of an operator on a finite dimensional vector space.  I am not sure if it discusses this exact application.
Comment: do you have a textbook or reference you could point me to where this is explained?


product of two distinct squares

Question: Is there any shorter and efficient way to find
if a number can be formed by the product of two distinct square numbers
for example

36=4*9
144=16*9

help me with an algorithm or the logic
Comment: Every perfect square that is not the square of a prime number can be written as the product of two smaller squares.
Comment: ...and those smaller squares can be chosen to be distinct unless the original number is the fourth power of a prime.
Answer: You are looking for a number formed by product of two squares, so you have it written in this form: $n = a^2 b^2$, apply product of powers property, so you have: $n = a^2 b^2 = (ab)^2$, so at the end you have to check if this number is a square. If you want to control if the number is made of two factors you have to find its square root, then check if it's a prime number (as in comment $49 = 7\cdot 7$, $7$ is prime, so you will get only $1 \cdot 49$).
So taking your examples: 36 is a square because $36 = 6 \cdot 6 $, now take factors: $6 = 1 \cdot 2 \cdot 3$, so $36 = 1 \cdot 4 \cdot 9 $, at the end you multiply some of them: $36 = 4 \cdot 9$ or $36 = 1 \cdot 36$.
144 is a square because $144 = 12 \cdot 12 $, now take factors: $12 = 1 \cdot 2 \cdot 2 \cdot 3$, so $144 = 1 \cdot 4 \cdot 4 \cdot 9 $, at the end you multiply some of them: $144 = 1 \cdot 144$ or $144 = 4 \cdot 36$ or $144 = 9 \cdot 16$.
If you try with $15$ you can find any product of squars because $15$ isn't a square.
Comment: I want a and b to be different.
   you said its enough to check if n is a square.
   49=7*7  ( 49 is square,but a and b are not different )
it fails here
Comment: yes, you also has to check if squared number is a prime number: 49 = 7*7 (7 is a prime number), so you will get only 7*7 or 1*49
Comment: yeah.. good one
thanks :)
Answer: As Blex wrote, a number $n$ is the product of two distinct squares $a^2$ and $b^2$ if and only if can be written as $n = a^2 b^2 = (ab)^2$.  Thus, first of all, all such numbers are themselves squares.
Given a square number $n = r^2$, it is the product of two distinct squares if and only if its square root $r$ can be written as the product of two distinct numbers $r = ab$.  If we're allowed to choose $a = 1$ and $b = r$ (or vice versa), then this is always possible for any $r > 1$, but I assume you're only interested in the cases where $a$ and $b$ are strictly between $1$ and $r$.
In that case, there are only two ways in which this factorization can fail: either when $r$ is itself a prime, in which case it has no divisors other than $1$ and itself, or when it is the square of a prime $p$, in which case its only non-trivial factorization is $r = p^2$.
Thus, we get the result:

A number $n > 1$ can be written as the product of two distinct squares (both greater than $1$) if and only if it is the square of a number which is neither a prime nor the square of a prime.

product of two distinct squares


iOS Phonegap push notification shows but no sound or badge

Question: I have a iOS app using PushPlugin for push notifications. So far almost everything works. I can receive the push notification on the device but no sound plays (when on sound) and it doesnt vibrate (when set to vibrate) also no badge appears. Is this something with the registerForRemoteNotificationTypes? I read something saying you need to register for the use of sounds, and badges. this is on iOS 8 using phonegap 3.4
Answer: Some people were reporting this, but only for iOS 7 (so far as I know). I was able to get badge to work using a fork mentioned in that issue, but not sound (yet). It's possible your issue is different, but you might choose to try forking this and giving it a try anyway...
https://github.com/raix/PushPlugin/commits/fix-ios7-badge


I have a list of questions, when I try to get data from it, it gives me a null output

Question: This is the error I got : The body might complete normally, causing
"null" to be returned, but the return type, 'List quiz', is a potentially non-nullable type
Try adding either a return or a throw statement at the end.

List<soal> getsoals() {
  var solayek = soal();
  solayek.soalcode = 1;
  solayek.soaltitle = 'تعداد حلقه های المپیک؟';
  solayek.pasokhlist = ['5عدد', '6عدد', '7عدد', '8عدد'];
  solayek.pasokhdorst = 0;
  solayek.point = 10;
  var solado = soal();
  solado.soalcode = 2;
  solado.soaltitle = 'تعداد اعضای شورای نگهبان؟';
  solado.pasokhlist = ['شش نفر', 'هشت نفر', 'سیزده نفر', 'دوازده نفر'];
  solado.pasokhdorst = 3;
  solado.point = 10;
  var solase = soal();
  solase.soalcode = 3;
  solase.soaltitle = 'ارتفاعات سهند در کدام استان قرار دارد؟';
  solase.pasokhlist = ['آذربایجان شرقی', 'آذربایجان غربی', 'کردستان', 'زنجان'];
  solase.pasokhdorst = 0;

Comment: What's the last line of your function look like.  Are you returning a List or not?
Answer: To resolve this error, you need to add a return statement at the end of the function that returns a List of soal objects. For example:
List<soal> getsoals() {
  var solayek = soal();
  solayek.soalcode = 1;
  solayek.soaltitle = 'تعداد حلقه های المپیک؟';
  solayek.pasokhlist = ['5عدد', '6عدد', '7عدد', '8عدد'];
  solayek.pasokhdorst = 0;
  solayek.point = 10;
  var solado = soal();
  solado.soalcode = 2;
  solado.soaltitle = 'تعداد اعضای شورای نگهبان؟';
  solado.pasokhlist = ['شش نفر', 'هشت نفر', 'سیزده نفر', 'دوازده نفر'];
  solado.pasokhdorst = 3;
  solado.point = 10;
  var solase = soal();
  solase.soalcode = 3;
  solase.soaltitle = 'ارتفاعات سهند در کدام استان قرار دارد؟';
  solase.pasokhlist = ['آذربایجان شرقی', 'آذربایجان غربی', 'کردستان', 'زنجان'];
  solase.pasokhdorst = 0;

  // Create a List containing the objects you've created
  List<soal> soalsList = [solayek, solado, solase];

  // Return the List
  return soalsList;
}


R installation failed

Question: I am trying to install rstudio on my Centos 7 machine, starting with an update of the ecosystem by installing epel-repository which is essential for the installation of R, then proceed to the installation of the R language, except that at the level of
of this phase I am blocked, the packages were not well installed and it brings me back this error :
Error: Package: libicu-devel-50.1.2-17.el7.x86_64 (centos7)
Requires: libicu(x86-64) = 50.1.2-17.el7
Installed: libicu-50.2-4.el7_7.x86_64 (@centos76_repository)
libicu(x86-64) = 50.2-4.el7_7
Available: libicu-50.1.2-17.el7.x86_64 (centos7)
libicu(x86-64) = 50.1.2-17.el7
Error: Package: 1:cups-client-1.6.3-35.el7.x86_64 (centos7)
Requires: cups-libs(x86-64) = 1:1.6.3-35.el7
Installed: 1:cups-libs-1.6.3-51.el7.x86_64 (@ums_centos_7_public_os)
cups-libs(x86-64) = 1:1.6.3-51.el7
Available: 1:cups-libs-1.6.3-35.el7.x86_64 (centos7)
cups-libs(x86-64) = 1:1.6.3-35.el7
Error: Package: 1:java-1.8.0-openjdk-devel-18.104.22.168.b09-2.el7_6.x86_64 (centos7-updates)
Requires: java-1.8.0-openjdk(x86-64) = 1:220.127.116.11.b09-2.el7_6
Installed: 1:java-1.8.0-openjdk-22.214.171.1242.b10-1.el7_9.x86_64 (@ums_centos_7_public_updates)
java-1.8.0-openjdk(x86-64) = 1:126.96.36.1992.b10-1.el7_9
Available: 1:java-1.8.0-openjdk-220.127.116.11-7.b13.el7.x86_64 (centos7)
java-1.8.0-openjdk(x86-64) = 1:188.8.131.52-7.b13.el7
Available: 1:java-1.8.0-openjdk-18.104.22.168.b09-2.el7_6.x86_64 (centos7-updates)
java-1.8.0-openjdk(x86-64) = 1:126.96.36.199.b09-2.el7_6
Available: 1:java-1.8.0-openjdk-184.108.40.206.b12-1.el7_6.i686 (centos7-updates)
~java-1.8.0-openjdk(x86-32) = 1:126.96.36.199.b12-1.el7_6
Error: Package: 1:cups-1.6.3-35.el7.x86_64 (centos7)
Requires: cups-libs(x86-64) = 1:1.6.3-35.el7
Installed: 1:cups-libs-1.6.3-51.el7.x86_64 (@ums_centos_7_public_os)
cups-libs(x86-64) = 1:1.6.3-51.el7
Available: 1:cups-libs-1.6.3-35.el7.x86_64 (centos7)
cups-libs(x86-64) = 1:1.6.3-35.el7
Error: Package: 2:libpng-devel-1.5.13-7.el7_2.x86_64 (centos7)
Requires: libpng(x86-64) = 2:1.5.13-7.el7_2
Installed: 2:libpng-1.5.13-8.el7.x86_64 (@ums_centos_7_public_os)
libpng(x86-64) = 2:1.5.13-8.el7
Available: 2:libpng-1.5.13-7.el7_2.x86_64 (centos7)
libpng(x86-64) = 2:1.5.13-7.el7_2
Error: Package: glibc-2.17-260.el7_6.3.i686 (centos7-updates)
Requires: glibc-common = 2.17-260.el7_6.3
Installed: glibc-common-2.17-324.el7_9.x86_64 (@ums_centos_7_public_updates)
glibc-common = 2.17-324.el7_9
Available: glibc-common-2.17-260.el7.x86_64 (centos7)
glibc-common = 2.17-260.el7
Available: glibc-common-2.17-260.el7_6.3.x86_64 (centos7-updates)
glibc-common = 2.17-260.el7_6.3
You could try using --skip-broken to work around the problem
You could try running: rpm -Va --nofiles --nodigest

Has anyone had the same problem?
Thank you in advance for your feedback
Comment: "ums_centos_7_public_os" could be a local repo? ............ And "centos76_repository" looks like an old version. ..... Suggest : Disable the two "suspects", and try again. ... Note : EPEL and only epel is 100% compatible with the default repo's. ............ Default repo example https://drive.google.com/file/d/1AmA9qe7ov0ue7h7nXG9qePxlaNdOXufy/view?usp=sharing
Answer: The same lines you attach are telling you how to solve it. Check last two lines:
You could try using --skip-broken to work around the problem
You could try running: rpm -Va --nofiles --nodigest

Try using and running this.

R installation failed


Understanding theorem on expected value of a function $E(h(X))$

Question: The theorem states:

Let X, Y be random variables defined over $(\Omega,\Im,P)$ and $h$ a real-valued function such that $h(X)$ is a random variable. If $E(h(X))$ exists, then: $E(h(X))=E(E(h(X))|Y).$

I don't understand the beginning of the proof:
$$E(E(h(X))|Y) = \sum\limits_y E(h(X)|Y=y)P(Y=y)$$
I don't know how to get from the definition of conditional expected value to the last equation. I appreciate your help.
Comment: These are discrete random variables?
Comment: Yes. It's the part of the proof for discrete random variables.
Answer: $$
E[h(X)|Y]
$$
is a random variable: it has the form
$$
E[h(X)|Y] = g(Y)
$$for some deterministic function $g$.
So, the randomness of this random variable does only depend on $Y$:
$$
E[h(X)|Y](\omega) = g(Y(\omega))
$$
and so the expected value is
$$
E[E[h(X)|Y]] =E[g(Y)] = \sum P(Y = y) g(y)
$$
now the strange notation is
$$
E[h(X)|Y=y] = g(y)
$$
and you get
$$
E[E[h(X)|Y]] =\sum P(Y = y) E[h(X)|Y=y]$$
Comment: Hmm I was thinking how could I get to that expression by definition: $E(E(h(X))|Y)=E(\sum\limits_xh(X)P(X=x|Y=y))$ But I can't go further from there.
Comment: did you read my message?
Comment: Yes, and I realised that both of us are wrong: We are beginning with $E(h(X)|Y)$ instead of $E(h(X))|Y$. So that'd give: $$E(E(h(X))|Y)=E\left(\left(\sum\limits_x h(x)P(X=x)\right) | Y\right).$$
Comment: E(h(X)) | Y does not make much sense.
Comment: So probably a print error?
Comment: It was a print error. My teacher (the author of the book) was quite surprised. Thanks mookid.


Path aliases more than one

Question: I could explain everything, but that will take me a while, so, long story short.
I need one node to have 2 path alises (Not re-direction) 2 path aliases, and this is what I need to do, to show some fields in my view or hide them.
The idea is if I access from one view I need to show some fields, or If I join from another one I should hide it
Answer: Its not good idea to have one page or node with 2 different url, what i suggest to you is to override node view page with panel and create 2 variants.
Create the 2 different views panes and drop them each one in variant.
In the link to that node add GET variabile and switch the right variant based on that
Example
/my-url will show the first variat
/my-ulr?show=1
Will show the second variant
You control that with panel visibility rule and use php code to check the $_GET array

Path aliases more than one


How do I relate the std deviation of the step size, to the stdev of the endpoint of a brownian motion, if the step sizes are multiplied by a function

Question: I know that if I take take a brownian motion of, say, 30 steps of standard deviation 1, then the standard deviation of my endpoint will be sqrt(30). But what if the standard deviation of the 30 steps is defined by a function? How do I relate the endpoint standard deviation to that function?
An example in R, first with a standard fixed volatility random walk.
library(xts)
mysd <- 0.1 / sqrt(255) # small sd so that we don't walk too far
genwalk <- function(stepsizes) {i <- 1; for(x in stepsizes) i <- c(i, i[length(i)] * exp(x)); return(i)} # random walk function - geometric
acc <- matrix(0, 1000)
plot(genwalk(rnorm(30, 0, mysd)), type = "l", ylim = c(0.88, 1.12), col = "#0000001A")
for(x in 1:1000) {walk <- genwalk(rnorm(30, 0, mysd)); acc[x] <- last(walk); lines(walk, col = "#0000001A")}
title("1000 30-step random walks with step size 0.1/sqr(255)")

No surprises here:
> sd(acc)
[1] 0.03484051
> mysd * sqrt(30)
[1] 0.03429972
> title("1000 30-step random walks with step size 0.1/sqr(255)")
> library(moments)
> kurtosis(acc)
[1] 3.048236
> mean(acc)
[1] 1.000664

So I know how to get from a standard deviation of x to the standard deviation of a 30-step walk: multiple x by the square root of the number of steps.
But what if x is a function rather than a constant? How do I then relate the function to the endpoint standard deviation? Let's say my function is a decay weighting of length 30 with half life 10:
decay <- exp((-log(2) / 10) * 30:1) # exponential decay, 30 steps

> plot(genwalk(rnorm(30, 0, mysd) * decay), type = "l", ylim = c(0.88, 1.12), col = "#0000001A")
> for(x in 1:1000) {walk <- genwalk(rnorm(30, 0, mysd) * decay); acc[x] <- last(walk); lines(walk, col = "#0000001A")}
> title("Random walks with step size 0.1/sqr(255) * decay weighting")

> sd(acc)
[1] 0.01645629
> mysd
[1] 0.006262243
> kurtosis(acc)
[1] 2.882403
> mean(acc)
[1] 1.000137

So it looks like the endpoints are still nicely normally distributed (mean ~ 0, kurtosis ~ 3), but I have no clue how to relate the standard deviation of the endpoints, that is sd(acc) above = 0.1645629 to mysd which was the step size multiplier for the decay function.
Basically: how do I get from the decay function which was applied to the standard deviation of step sizes, to the standard deviation of the endpoints?
Comment: Can you add a (hopefully) simple phrasing of your question, in mathematical terms? I don't know R and have no desire to read all this code. Just state what is your random variable (as a sum of other RVs, perhaps) etc.
Comment: Although your question does not appear to assume anything about the distribution of the increments, your code appears to use lognormal increments.  Could you clarify this and tell us what *you* mean by a "random walk" and whether you want your question answered in the full generality in which it is asked, or answered only for this special kind of random walk? Also, your code does not execute: what is the function `last` supposed to do?
Comment: @whuber: I am sorry about the last function. This is from the package xts. It returns the last row of an xts matrix, or a the last element of a vector. In this case I have a matrix of 1 column so it's a vector, and last returns the last element each time. I have amended the code.
Comment: My motivation is to model the way that traders think about markets. The recent trading patterns determine their thinking with higher importance than samples going further back in time. My hypothesis is that this weighting scheme in their minds, is decay weighted. Hence the lognormal distribution that I wish to apply to the "random walk" (brownian motion), but I may wish to change the function that is applied so a general answer would be helpful (although I think that Yair Daon has already done so).

Many thanks for helping a non-mathematician (computer scientist here) with formalizing this.
Comment: If you switch to an additive model, as you put in one of your answers, then @YairDaon is telling you exactly what you need for a general case. (In fact, in `mysd * sqrt(sum(decay^2))` just replace your decay weights for the ones you'd prefer and you get to compute the answer).
Answer: If I understand correctly, we seek the std of the following random variable:
$$
S := \sum_i X_i f(i) = \sum a_iX_i,
$$
where $\mathbb{E}[X_i] = 0, \mathbb{E}[X_i^2] = \sigma^2$, where $\{X_i\}_{i=1}^n$ are independent and $a_i$ are non random. Calculate the variance:
$$
var(S) = var(\sum_i a_i X_i) = \sum_i var(a_iXi) = \sum a_i^2 \sigma^2 = \sigma^2\sum a_i^2,
$$
where we've relied on the independence of $X_i$ in the second equality (see this). The standard deviation is thus $\sigma\sqrt{\sum_i a_i^2}$.
Please note that you can make the std of $a_iX_i$ be whatever you want by setting $a_i = \frac{\text{wahtever you want}}{\sigma}$.
Comment: You dropped the square of $a_i$ halfway through and did not recover it later.  I'm sure that was a typo you will want to correct.  You might also want to reformulate your answer without reference to a normal distribution of the $X_i$: it is neither necessary nor explicitly assumed in the question (normality appears to be used there only to generate *examples* in `R`).
Comment: @ThomasBrowne it seems, from what you write, that you are using some variation of an ARCH\GARCH model. See wikipedia. Let me suggest that you change your question. Write **exactly** what you need to find (preferably in latex). This will facilitate answering your question.
Comment: @ThomasBrowne you are welcome! This question could've been answered much more quickly and without a bounty had you removed the code and plots and wrote the problem in "plain" math. You would have got an answer within an hour probably.
Comment: Thank you for responding!  I need to hold off casting any votes, though, until I can figure out what the question really is asking--see my request for clarification in a comment to the question.
Comment: This appears to answer my question. The only subtlety is that I apply the next step by multiplying by 1 * 1+(a2X2) rather than additively, however for small steps, this should  work well, and in the context of my problem, actually it is I who should probably move to an additive version of the problem. I think this is the idea behind the answer from Cristian Atuna.
Comment: @Yair Daon: Thank you for the feedback - I will attempt this so that the question has longevity, even though I already have the answer that I need (from your good self).
Answer: You'll get what you want by typing this formula:
> mysd * sqrt(sum(decay^2))
[1] 0.01611228

Which is basically the answer @YahirDaon gave you.
Let me abuse a little bit of the Brownian Motion definition in this answer.
You should note that this expression only works because, as you put it: "You dont walk too far away". Or, what is the same, your x vector does not differ significantly from zero, since mysd is small.
Because, in this case, your geometric brownian motion can be tought as $e^{\sum_1^nX_i} \approx \sum_1^nX_i$. (Use a Taylor expansion to see this). That is, regular Brownian Motion's formulae are a good approximation. In fact, your formula for variance $\sigma^2 * \sqrt{30}$ is that of a regular Brownian Motion, and only works here because of the same reason: x is a vector with a small norm.
The correct formula (as $\mu = 0$) is: $\sqrt{e^{30\sigma^2}.(e^{30\sigma^2}-1)}$. And you can check that it yields a very similar result:
sqrt(exp(30*mysd^2)*(exp(30*mysd^2)-1))
[1] 0.03433

But if you use a mysd $\gg 0$ both in the iid increments case and the varying ones (which technically isn't even a Brownian Motion because it is defined as having iid increments), then you should check more general Lèvy processes.
btw: Random Walk is not the same as Brownian Motion (the former is a more general concept). You seem to refer to a BM because of the formulae you use, so maybe you should avoid refering to it as Random Walk (which it is, but your formulas are specific to BM, not any RW).
btw2: these notes might help you:
http://www.columbia.edu/~ks20/FE-Notes/4700-07-Notes-GBM.pdf
Comment: That's a good interpretation. To me it says that *for this example,* a random walk with lognormally distributed increments is being generated. However, since I don't see a specific indication of the distribution in the question, I have supposed it is more general than that. I think we will need to ask the OP to clarify the question.
Comment: I have looked for where geometric Brownian motion was mentioned in the question but have been unable to find it. What is the reason you discuss it here?
Comment: I thought this line tried to generate a GBM here: `for(x in stepsizes) i <- c(i, i[length(i)] * exp(x)); return(i)}`, since it does not sum the increments when building his process. I might have misunderstood the question, in that case, my answer is, well, wrong.
Comment: @whuber it is true that the question is much more general than the example, I just went with it w/o considering a more general case.
Comment: I am assuming brownian motion, in a financial markets context. Colloquially we use the term random walk amongst non-mathematicians and I apologise for the lack of rigour.

The use of sqrt(255) is often used to take a daily standard deviation to an annual one, as there are approximately 255 valid trading days in a year, and a circa 10% volatility is common in currency markets.
Comment: Amended from random walk to Brownian motion.
Comment: @Cristian Antuna: these are excellent notes on your btw2 which clarify the difference and the theory very well.
Comment: May I add Cristian, and Yair: although I understand that my question, and your clarifications and answers, are not of the order of deep mathematics (they are mainstream stochastic calculus), it is refreshing, and indeed inspiring, to see the extent to which mathematics is able to purify concepts, discarding the often dirty approximations of statistics, and of financial markets (and other field) practises. Thank you for your academically rigorous efforts. The vast majority of practitioners would benefit from understanding the core principles, and you have educated one of those practitioners.
Comment: If you are interested in mathematical modelling for finance, this book from Schoutens might be useful, as it does not get too formal, but at the same time he reviews many Levy processes that might appear in finance mathematics. The book is "Levy Processes in Finance", by Wim Schoutens: http://www.amazon.com/Levy-Processes-Finance-Financial-Derivatives/dp/0470851562


How to access superclass variables from user input

Question: I am trying to access the super class variable name from user input.
I am not sure how to have the super class variable name point to the user input. Here is the code for it. Any ideas thank you.
    package chapter4;
    import java.util.Scanner;

    public class VetOffice extends Animal {

        public VetOffice(int lifeExpectancy, int weight, String name, Character gender, String type) {
            super(lifeExpectancy, weight, name, gender, type);
            // TODO Auto-generated constructor stub
        }
       public static void main(String[] args) {

        Scanner console = new Scanner(System.in);

                System.out.print("Please enter name of pet");
                //super(name);
                //= console.next();
        //}
        }
    }
    //}

Comment: it may be helpful if you can share the `Animal` super class.
Comment: `VetOffice` **inherits** the property(fields and methods) of its superclass `Animal`. So, if there are `getters` & `setters` methods in the superclass, you can use them in the subclass.
Comment: `VetOffice` extends `Animal`???   That's a red flag right there...
Answer: The thing is you cannot access super class variables in main method. Because it is static method. If you want to access in main() you have to make Animal class name variable to static. Then you can assgin a value directly in main().
Like this:
in Animal class,
static String name;

in VetOffice,
name = console.next();

You can try different ways depending on the thing that you are going to achieve you have to decide,
Is this variable can be declare as static or not? Because static variables common for every object.
Another way you can do this is,
Create getters and setters for Animal class member variables. Then also you cannot access in the main method because also you have to make those methods and variable to static.
As a solution without makinng them static or a new methods even getters and setters in super class you can create default constructor for super class and assign values like below:
If your variable in the super class is private you have to create getters and setters.
public static void main(String[] args) {
   Scanner console = new Scanner(System.in);
   System.out.print("Please enter name of pet");

   VetOffice pet = new VetOffice();
   pet.name = console.next();
   System.out.println(pet.name);
}

Note: create default constructor If it is unnecessary to create object from VetOffice or super class seeing that you have to pass values to constructor.
UPDATE:
According to your comment
If your variable in the super class is private do this:
public static void main(String[] args) {
   Scanner console = new Scanner(System.in);
   System.out.print("Please enter name of pet");

   VetOffice pet = new VetOffice();
   pet.setName(console.next());
   System.out.println(pet.getName());
}

Another way that you asked for in the comment:
Animal class(partialy implemented to show you)
public class Animal {
    int lifeExpectancy;
    static int weight;
    static String name;

    Animal(int lifeExpectancy, int weight, String name, Character gender, String type){
        this.weight = weight;
        this.name = name;
    }

    public static String getName() {
        return name;
    }
    public static void setName(String n) {
        name = n;
    }
}

Then in the main method:
Animal.setName(console.next());
System.out.println(Animal.getName());

Comment: ok it is working thank you. How can I get a hold of you for future questions?
Comment: I have getter and setters in the animal class. So how do i create a VetOffice object. How do I call the setName() in VetOffice.
Comment: Ok I understand that but why would I not call the variable super to access the variable name from the super class.
Comment: @Derrick C `super()` is not a variable. Read this - https://stackoverflow.com/questions/44134360/inheritance-with-constructor-in-java/44135109#44135109
Comment: I tried that but it says to create a VetOffice constructor and when I did that it said. Implicit super constructor animal is undefined must explicitly invoke another constructor. Is there a way I can use setName with the superclass. ie Animal.setName or super(setName).
Comment: if you want `super(setName)` this has to be in constructor
Comment: As I said before `Animal.setName` you can do like that if you make setters, getters and `name` variable to static
Comment: @Derrick C I updated the answer. Look at the bottom of answer in update section.
Comment: I did that but I get a null value  returned when I execute          System.out.println(Animal.getName());
Comment: @DerricC Change `setName(String n)` and `name = n;`
Comment: I think there is no way for that but you can mention me in your question comments - @Blasanka


What hook should I use to alter the File Upload field in Webform 7.x-4.16

Question: In Drupal 7 Webform file field, might there be a way to access the link provided after the a file is uploaded?
The reason is that we have a hot-folder/watch-folder process that runs, cleans a file, converts DOCs to PDFs, checks for accessibility, etc. I'd like to link to converted version of that file.
We want to allow the user submitting everything to ensure their document is converted properly before they click the submit button.
Answer: I believe you could go far with hook_form_alter in drupal 7. Unless you're implying a multiple step webform where some webform hook may apply.
Browse over the webform.api.inc file in the module folder and if none of the hooks sound good for your needs try a simple form alter.


Why do we combine several select statements

Question: This question might be silly , but why do we combine several select statements in SQL. I did not find an answer for this yet.
Example:
<code> select OrderID from (SELECT Customers.CustomerName, Orders.OrderID
 FROM Customers
 INNER JOIN Orders
 ON Customers.CustomerID=Orders.CustomerID
 ORDER BY Customers.CustomerName);
</code>
Comment: Preparing to do something more complex, or stripped down something more complex? As it is now it doesn't make much sense...
Answer: The clue is in the "Relational" part of "Relational database"
A relation is a set of rows, and can therefore be:

The rows in a table
The rows projected from a view
The rows projected from a query
The rows projected from a common table expression

In theory, all of these are the same, and so selecting from a table is logically the same as selecting from a view, or from another query, and joining two tables is logically the same as joining two queries.
As to why it is done, here are three decent reasons:

To avoid having to save a temporary result set into some structure and then read it out again.
Because in some cases it is not possible to place a condition on a query through a WHERE or HAVING clause, and the predicate must be placed on the result set.
Coding convenience.
Answer: Output of this query will be all the orders which are having customer in customer table and it will not give any order which does not having any entry in customer table.  Moreover orders will be come in ascending order of their customerName value.


PHP auto-loading and OS X case insensitivity

Question: So I develop PHP on a Mac, and OS X (HFS+) is case insensitive when it comes to file and folder names. This can cause issues with auto-loading PHP classes, because it uses the class name to search for files.
It becomes an an obnoxious problem when case typos in my code can make it all the way through a development cycle, and only rear their ugly head when I start deploying to our (linux) production server.
Does anyone know a of a solution that will force OS X to obey case sensitivity while developing PHP?
Thanks
Answer: Personally, I think the best solution would be for you to setup a Virtual machine, using whatever you favorite VM tool is, that is as near to identical to your production environment as possible.  Same OS, same packages, same configuration and so on.
You are bound to run into other issues as well like slight differences in php, difference in available modules, and so on.  A VM that is the same as your production environment will help you be sure you have everything tested right.
Anyway, if a VM isn't an option, you should be able to partition the drive, and create a separate partition using the case-sensitive version of HFS+
Answer: You can format your development volume to be HFS case sensitive which will force the behavior you wish. Downside of this is some poorly written OS X applications won't work because developers have made the same mistake you have and mis-capitalized paths.


Regression: Covariance table in spss vs. mplus

Question: I want to use regression output (b, se B and cov of several predictors) as input for a new analysis.
One example: I want to compute:
SE^2(b1) + SE^2(b2) + 2 COV (b1,b2).
If I do a basic regression in Mplus (which I used because I have a choice of estimators, that I don't have in spss), and I look at the covariance table, the values reported there are extremely different from the covariances I get from the bcov command in SPSS regression.
They are so different that I am convinced they do not reflect the same value
(e.g., .484 in mplus, and -.064 in spss).
Can anyone tell me:
- What "estimated sample statistics" -> covariates in Mplus vs. "coefficient correlations" => "covariances"  in spss refer to?
- which one you think might be the cov(b1), referred to in the output? (my instinct says the SPSS one is the one I need)
- How I could obtain this in the other program (i.e., if I need the spss one, how can I get this in MPlus)?
Please note that I did use the same estimator in mplus for my mock data on which I tested this, all other estimates (b, seB etc) are the same.
Model in Mplus:
MODEL:  !Main effects
            leka on S;
            leka on P;
            leka on M;
          !Correlations between predictors
            S with P;
            M with P;
            S with M;
OUTPUT: tech1; tech4; samp; stand; mod(4); Sampstat Mod(3.84);

Model in SPSS:
REGRESSION
/MISSING LISTWISE
/STATISTICS COEFF OUTS BCOV R ANOVA
/CRITERIA=PIN(.05) POUT(.10)
/NOORIGIN
/DEPENDENT Leka_t3
/METHOD=ENTER S P M.

Answer: Estimated sample statistics in Mplus is the covariances of the variables. In SPSS you have asked for the covariances of the parameters.
In Mplus you need to request tech3 on the output line, i.e.
OUTPUT: tech1 tech3 tech4 samp stand mod(4);

The estimators are not the same, you're using ML in Mplus and OLS in SPSS, but the results should be extremely similar, unless your sample is small.
(Also, make sure you have no missing data, or tell Mplus to use listwise deletion , as SPSS is.)
(Another also: I don't think you need to explicitly add the correlations between predictors in Mplus, it will add them by default.)
Comment: Thank you for your response. Some follow-up if I may: (1) Am I correct in assuming I probably need the covariances for the parameter as provided by tech3, rather than the ones I have now? I.e., the spss output (covariances) is what I need in the formula I gave right? {(2) Indeed, I have a large sample so the results are the same, and to rule out the possibility that differences may have been due to missings or anything I ran both on an identical sample with no missings. (3) Regarding your comment on correlations: You are right, but I specify them so I can easily do model test on them later.}


Properties of $\pi_1$ homomorphism induced by inclusion map

Question: I don't understand a few claims made by Rotman in his Algebraic Topology text in the section about $\pi_1$

1. $f \in \pi_1(A, x_0)$ may not be nullhomotopic in A?
Define $H : I \times I \rightarrow X$ by $H(s,t) = f(st)$. This appears to provide the homotopy $H: k \simeq f$, where $k(t) = x_0~\forall t \in I$
2. X can be "taken to be" $CA$?
But $CA = A \times I / A \times \{1\}$, which does not contain A. Can you identify $CA$ with some space that does contain A?
I know that if X is contractible, then any map $ I \rightarrow X$ is nullhomotopic including $jf$.
3. $j_*$ may have a kernel (if $jf$ is nullhomotopic).
This suggests that there may be an $[f], [g] \in \pi_1(A, x_0)$ such that $[f] \neq [g]$ but $j_*([f]) = j_*([g])$. I don't see how this follows from $X$ being a contractible space or $jf$ or $jg$ being nullhomotopic.
Comment: The homotopy you write down in 1. is not a homotopy rel endpoints.
Comment: For 2, there is a copy of $A$ in $CA$ at $0$ i.e the slice $A \times \{ 0 \}$. Of course there are other copies of $A$ but this is the one implied. For any $A$, let $X = CA$ then you have $A$ sits inside an contractible space so the inclusion $j:A \to X$ is nullhomotopic
Answer: In fact Rotman is a bit sloppy when he speaks about nullhomotopic paths.
The concept of "nullhomotopic map" is defined on p.16 for maps $f : X \to Y$ between arbitrary spaces $X,Y$. For paths $f : I \to X$, however, one does not consider the relation of being homotopic, but the relation of being homotopic rel $\dot I$. In Exercise 3.4. Rotman uses the phrase nullhomopotic rel $\dot I$ (which of course only applies to closed paths because a non-closed path cannot be homotopic rel $\dot I$ to a constant map).
This is what he means in the section occurring in your question - but admittedly he does not explicitly say it.

You are right, each path $f: I \to X$ is nullhomotopic. The reason is that $I$ is contractible (your assignment $(s,t) \mapsto st$ describe a contraction).
However, in general there are closed paths which are not nullhomopotic rel $\dot I$.

Again a bit sloppy. One can identify $A$ with $A' = \{[a,0] \mid a \in A\} \subset CA$. This is common practice, nobody cares about that the fact that $A$ is not a genuine subspace of $CA$.

If we have $\pi_1(A,x_0) \ne 0$, then clearly $j_* :  \pi_1(A,x_0) \to \pi_1(CA,x_0)$ has a non-trivial kernel ($\ker j_* = \pi_1(A,x_0)$).
Indeed inclusion-induced $j_* :  \pi_1(A,x_0) \to \pi_1(X_0)$ are in general neither injective nor surjective.
Comment: Thanks for fully answering the question *and* identifying likely points of confusion in the text!


Invalid HTTP_HOST header. The domain name provided is not valid according to RFC 1034/1035

Question: I am getting Invalid HTTP_HOST header error on my server. I don't understand why it's happening and how to fix it. Everytime it happens backend stops working and I have to restart the server.
Any help will be appreciated.
Thanks in advance!
FYI :
Server is aws ec2; frontend is angular and backend is django/drf with gunicorn.
Angular and DRF are both deployed on the same server.
Error 0.
If I don't set the Host variable in nginx.conf, I get below error many times.
Invalid HTTP_HOST header: '/run/gunicorn.sock:'. The domain name provided is not valid according to RFC 1034/1035.
If I set the Host variable in nginx.conf, I get below errors.
Error 1.
proxy_set_header Host $http_host;
Invalid HTTP_HOST header: '127.0.0.1:8000,127.0.0.1:8000'. The domain name provided is not valid according to RFC 1034/1035.
Error 2.
proxy_set_header Host $host;
Invalid HTTP_HOST header: '127.0.0.1:8000,127.0.0.1'. The domain name provided is not valid according to RFC 1034/1035.
Error 3.
proxy_set_header Host $server_name;
Invalid HTTP_HOST header: '126.96.36.199,188.8.131.52:8000'. The domain name provided is not valid according to RFC 1034/1035.
nginx.conf is as below.
server {
    listen 8000;
    server_name 220.127.116.11;

    location / {
        proxy_set_header Host $host;
        include proxy_params;

        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

I found below code on the nginx website. Will it solve this problem?
http://nginx.org/en/docs/http/request_processing.html
server {
    listen      80;
    server_name "";
    return      444;
}

Comment: Regarding $host and $http_host, I speculate that the error might come from a malformed host header in the HTTP request.
Comment: `server_name ` form of directive is wrong. If you need this virtualhost to listen only on single IP, add corresponding `listen` directive. If it needs to be catch-all which responds to any Host value, make it default_server and use `server_name _`.
Comment: The UNIX socket name must be enclosed in colons. Try `http://unix:/run.gunicorn.sock:`.
Comment: Please share the output of `nginx -T`.
Answer: The problem is that you have caused the Host header to be included twice.
        proxy_set_header Host $host;
        include proxy_params;

Looking at the proxy_params file will show you that it was already set there. Setting it again causes the two values to be joined with a comma.
Inside that file you will find preset headers that will be used when you include that file. You do not need to repeat any of those lines in your own configuration.
ubuntu@vmtest-ubuntu2004:~$ cat /etc/nginx/proxy_params
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

You can remove your own additional proxy_set_header Host $host; from the configuration.
Comment: You save me, I spent 36 hours of searching.
Comment: You saved me 16 hours of searching
Answer: I had a similar issue, however, I didn't have proxy_set_header in my Nginx config file and it was simply include proxy_params;.
What happens here is according to Django documentation when your site is behind a proxy server, Django will reject the requests coming from the proxy thinking they are not secure even though the connection between the client and the proxy might be secure. So the solution is to update your Django settings.py file and add the following:
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

You can read further here about this issue here:
https://docs.djangoproject.com/en/3.1/ref/settings/#secure-proxy-ssl-header
Answer: I still get the similar problem, however,
(1)  I didn't have proxy_set_header in my Nginx config file as in the orginal question and it was simply include proxy_params;
(2) I have SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') included in setting.py.
Comment: This does not answer the question. Why did you put it into "Your Answer" box?


Find the number of degree 1 vertices in terms of n and d

Question: Fix an integer $d>1$. Let $G$ be a tree with $n$ vertices, and every vertex can have either degree $1$ or $d$. Find the number of degree $1$ vertices in terms of $d$ and $n$.
I've been working on this problem and I feel like I almost have the answer. I worked out that if $d=2$, the graph will just be a line with vertices and $2$ leaves, so there will be $2$ vertices with $\deg(1)$, no matter how many vertices there actually are. If $d=3$, $n$ starts to matter.
Using the fact that the sum of all the $\deg(v)$ of a graph is $2|E|$ and that in a tree $|E|=|V|-1$ I worked out that the sum of $\deg(v)=2n-1$, and that this sum mod $d$ will be the amount of degree $1$ vertices. ( Since $d+d+d+\dots+1+1+1+1$ mod $d$ will be the sum of the $1$'s unless the sum is greater than $d$, then it will wrap around). I'm having a hard time putting this all together into a simple equation. I don't want just the solution, I want to understand how to find the equation as well.
Comment: Any reason for rolling back the edits?
Comment: @PJK it was accidental, I set it back to the first edit.
Comment: Ah I see. Its okay.
Answer: Let $n_1$ be the number of degree $1$ vertices, and $n_d$ the number of degree $d$ vertices.
Then (the first two lines are the facts as you have already noted):
$$
|E| = \frac12 \sum \mbox{ deg } v_i = \frac12 ( n_1 + d n_d ) \\
|E| = |v| - 1 = (n_1 + n_d) -1 \\
\frac12 ( n_1 + d n_d ) = (n_1 + n_d) -1 \\
n_1 + n_d = n \implies n_d = n - n_1\\
\frac12 ( n_1 + d (n-n_1) ) = n - 1 \\
 n_1 + d (n-n_1)  = 2(n - 1) \\
n_1(1-d) + nd = 2n - 2 \\
n_1 = \frac{(2-d) n - 2}{1-d} = n + \frac{n-2}{d-1}
$$
Comment: **Note:** With your last line, $\frac{(2−d)n−2}{1−d}=\frac{(1−d)n+n−2}{1−d}=n+\frac{n−2}{1−d}$. As such, you should either change the + between the $2$ terms to − or change the second term's denominator to $1−d$. For what it's worth, I think the former is better than the latter.
Answer: Lets say there are $p$ number of degree $1$ vertices. Then sum of the degree of the vertices is $p+d(n-p)$ which is equal to $2(n-1)$ i.e. twice the number of edges of an $n$ vertex tree. This gives the number $p$.


exercicio sobre pointers

Question: Implementa a função void power_ref(int* x, int y) que calcula a potência de x levando a y. O resultado deve ser colocado no endereço indicado no primeiro parâmetro, alterando seu valor inicial.
Tenho algo deste gênero:
#include <stdio.h>

void power_ref(int* x,  int y){

    int result = (int) *x ^ y;
    *x  = result;
    printf("result: %d", result);
}

Comment: Qual é a sua dificuldade no exercício?
Comment: Porque o `x` é um ponteiro e a função é `void`? Não seria mais simples e natural retornar o valor calculado?
Comment: é como pedem no ex , a dificuldade é com o pointer porque nao sei bem como usa-lo
Comment: coloquei o que tenho feito na pergunta em cima
Comment: Você sabe fazer uma função `int power(int x, int y)`? Se sim, poste-a que com base nela fica fácil fazer a `power_ref`.
Comment: O `^` no C não faz exponenciação. O `^` em C é o XOR (ou-exclusivo). Não é isso que você vai precisar usar. Vai precisar de um `for`.
Comment: para que um for?
Comment: Para fazer multiplicações sucessivas.
Answer: Solução #1:
void power_ref( int * x, int y )
{
    int i = 0;
    int n = 1;

    for ( i = 0; i < y; i++ )
        n *= (*x);

    *x = n;
}

Solução #2:
#include <math.h>

void power_ref( int * x, int y )
{
    *x = pow( *x, y );
}

Solução #3:
void power_ref( int * x, int y )
{
    int n = 1;
    int b = *x;

    while(y)
    {
        if(y & 1)
            n *= b;
        y >>= 1;
        b *= b;
    }

    *x = n;
}

Teste:
#include <stdio.h>

int main( void )
{
    int n = 2;

    power_ref( &n, 16 );

    printf( "%d\n",  n );

    return 0;
}

exercicio sobre pointers


AMIs in Amazon EC2

Question: I really like the Amazon EC2 environment, and thought I'll spend a bit of time playing around with various types of public (Windows!) AMI servers. But testing has been a bit, well, questionable. Some of my findings:

It's very difficult to know what exactly a specific public EC2 image is supposed to be doing. Many images come with little to no information.
I can't seem to find the passwords to log onto various windows images. Why are they public if they can't be used!?
Lots of images are based on S3, and not EBS backed. This is very annoying, as S3 takes a lot longer to do pretty much anything (stop, image etc.)  I am only testing images here, so of-course I don't question the value of S3 for other attributes.
The description of what an image does is almost useless and many times confusing.

Have others come across these EC2 issues. Again, my interest was to just play around with public images for testing/experimentation/etc, and therefore these issues may not be too relevant for more normal EC2 deployment uses.
Answer:
I get annoyed by this too; AWS doesn't enforce any kind of description for AMIs, so the content is completely up to the AMI creator.
You have to retrieve the password after your instance is started.  See the "Connect to Your Windows Instance" section in the EC2 Getting Started Guide.
You have the choice to save to either S3 or EBS when you create a new AMI.  the ability to store AMIs on EBS is quite recent, so a lot of older AMIs are S3-backed by default.

See 1.
Answer:
2 You have to retrieve the password after your instance is started. See the "Connect to Your Windows Instance" section in the EC2 Getting Started Guide.

I believe this is only for an initial Windows startup from Amazon's base images. If an image is modified and stored as public then surely Amazon can't retrieve a password (ie it's most likely been changed, and PW retrieval wouldn't work anyway because it's encrypted under a dedicated key). Am I missing something?
Comment: This is correct - if it is a modified version (i.e. not an Amazon provided image) then it is up to the AMI creator to provide the password. Amazon cannot retrieve it for you.
Answer: Honestly not trying to be a troll, but the "windows way" isn't very compatible with "The EC2 way" . Does your application work in Linux? Perhaps you should try using Linux + ec2
Otherwise, perhaps Rackspace's Windows servers might be a better fit for your needs.
Comment: Instead of voting me down, why not just answer the question? This isn't a windows-bashing answer, it's just that the "EC2 way", aka rapid creation and deletion of servers aided by automatic/programmatic configuration isn't currently very compatible with the "windows way" of administering servers- at least that I'm aware of. If I am wrong, then please post another answer with some advice on how to solve this problem.

AMIs in Amazon EC2


Taxonomy term individual occupant

Question: can anyone tell me if there is a way to set the terms under a taxonomy to have only one node?
I am building a system which is based on taxonomies but each term should contain only one one. If any user tries to save a node under an occupied term, I need it to be disallowed.
Can anyone help with some insight?
Answer: you could use a hook_form_alter when a node is saved and check if the selected term has already been used. Then just show an error message.

Taxonomy term individual occupant


how enabled key for show gmap v2 in android

Question: i just wanna show gmap in my project, but when my app running it's showing blank map, like this

and this is my logcat

this is for my developer console

list enable API

and this is my manifest, load more
what's wrong for my code or my setting console dev ??
Answer: Its quite sure from the logcat that the issue is with the API_KEY. Either the key that you have put in the manifest file is from some other project or you have not enabled the Google Maps Android API v2.
Here is what I found out from the images you provided:

The key in the Manifest file and the Key that is generated in your console does not match.
Make sure that you have enabled the Google Maps Android API V2.


jQuery set focus on selected item of a select list

Question: I have a select list that is size="10" - so it always shows 10 of the 100 options available.
When the page loads, the 1st 10 options are always displayed, even if option value 50 is selected.
I have read that adding focus to the selected item of the select list will work so that when the page loads option 50 will be displayed in the select list, instead of the 1st 10 options.
However, after reading many threads and searching google, I am unable to work out how to set the focus to the selected item.
I am wanting to set both the selected and the focus applied to the item of the select list.
Here is what I have tried and does not work:
$('#id_preview_style_select option:selected').prop('selected', true);  //set the selected value.

$('#id_preview_style_select option:selected').prop('focus', true);  //does not work.
$('#id_preview_style_select option:selected').focus();  //does not work

This is what I am seeking to achieve:
<select id="id_preview_style_select" size="10" autofocus>
  <option value="0">Style 0</option>
  <option value="1">Style 1</option>
  <option value="2">Style 2</option>
  <option value="3">Style 3</option>
  ....
  <option value="50" selected focus>Style 50</option>
  ....
  <option value="99">Style 99</option>
  <option value="100">Style 100</option>
</select>

Any assistance would be appreciated.
Comment: `` tag doesn't support most events and can't be hidden either in some browsers. Suggest you look for a plugin that modifies select and is therefore customizable. Numerous ones available since `` is  a difficult tag to work with
Answer: .prop('focus', true); would never work since focus() is a method, not a property (need to be invoked).
Try $('#id_preview_style_select option:selected').focus();
If it doesn't work right away you might need to timeout it with a timeout of 0 milliseconds. Hopefully that will help.
Edit: if none of this works (it might be that browsers would not allow this) I'd just scroll the list of options, so user can see what is selected.
Comment: Pawel, how do i use the timeout with the .focus()?
Comment: `setTimeout( function(){ YOUR_CODE_HERE }, 0);` - 0 is a parameter for time. Basically it's a trick that makes all Javascript run, then run this piece of code. Depending of your implementation there is a small chance this would help. But as @charlietfl mentioned - it might be forbidden to set focus on a option element.


How to solve a TypeError using LeaveOneOut

Question: I have been trying to work through the Vanderplass book and I have been stuck on this cell for days now:
from sklearn.model_selection import cross_val_score
cross_val_score(model, X, y, cv=5)

from sklearn.model_selection import LeaveOneOut
scores = cross_val_score(model, X, y, cv=LeaveOneOut(len(X)))
scores

TypeError                                 Traceback (most recent call last)
<.  ipython-input-78-029fa0c72898> in <module>
  1 from sklearn.model_selection import LeaveOneOut
 ----> 2 scores = cross_val_score(model, X, y, cv=LeaveOneOut(len(X)))
  3 scores

TypeError: LeaveOneOut() takes no arguments

import sklearn
sklearn.__version__
0.22.1'

Thanks in advance for any help!
Cameron
Comment: Please add an explanation of what you are trying to accomplish, and a print out of your expected outcome.
Answer: Welcome to Stack Overflow!
The error says LeaveOneOut() takes no arguments, but when you instantiated LeaveOneOut you passed it len(X) as an argument (in LeaveOneOut(len(X))).
If you change your scores line to the line below it should work:
scores = cross_val_score(model, X, y, cv=LeaveOneOut())

However, note this warning from the scikit-learn documentation:

Note: LeaveOneOut() is equivalent to KFold(n_splits=n)...Due to the
high number of test sets (which is the same as the number of samples)
this cross-validation method can be very costly. For large datasets
one should favor KFold, ShuffleSplit or StratifiedKFold.

In case that's not clear, that's a suggestion to use e.g. KFold with like n=5, which is usually going to serve you better than LeaveOneOut.
Comment: PERFECT! Thank you Max!
Answer: or, can also use
from sklearn.model_selection import cross_val_score
cross_val_score(model, X, y, cv=5)

from sklearn.model_selection import LeaveOneOut
scores = cross_val_score(model, X, y, cv=LeaveOneOut().split(X))
scores


VM migration of SQL Server

Question: We have two SQL Server VMs (SQL 2005 x64 on Windows 2003x64) both have RDM SAN. The SQL Servers are also clustered. My VM admin will be migrating us to different VMs using Cisco UCS solution. Unfortunately we will not be doing failover cluster to the new VMs.
Will it be possible to disable the cluster service and start SQL Server or would you need to uninstall SQL Server from Clustering and reinstall?
Any help would be appreciated.
Answer: I have never tried this but I think you would need to re-install SQL Server. You can have one node in a cluster though, if that helps.

VM migration of SQL Server


Views 3 and HTML5 - how to override output for markup?

Question: I have a view that I've created that selects blog posts based on a specific taxonomy term, creating a sort of "Featured Posts" view that I've embedded on the front page of my site. The issue I keep running into is trying to output the view so that each post is semantically marked up using some of the new HTML. I've tried the built-in "Rewrite this field's output", but it ignores the tags I use (ie, article, header, footer) and wraps everything in divs even when I deselect the placeholder tags.
Should I create a overriding views--view_name.tpl.php to rewrite the output of each post as it appears in the view, or do I need to use preprocess hooks in the template.php to affect the output?
I should state that I have basic experience with writing PHP and preprocess hooks, but I can any resources I need to move me down the linke if I'm pointed in the right direction.
Answer: You'll notice that in your view under the "Style Settings" block there is a link for Theme: Information. It will expose all the theme files that are called for your view. You can use generic to very detailed theme files that will only be use for your views display.
The first file name in Display output is views-view.tpl.php. That will apply to all views and displays. The next one in the list is views-view--[view name].tpl.php. It will only apply to your view. It keeps drilling down until it gets as specific as possible. views-view--[view name]--default.tpl.php is the last one in the list and only applies to the default display of the view. Clicking the Display output: link will expose the template code that views uses. Simply copy and create a new template file with one of the suggested in the list. It's usually best to be as specific as possible. The template file can go anywhere in your theme and views will pick it up as long as you rescan template files in the theming information and save the view. There are view templates, row templates, field templates and field specific templates.
Once you learn how to manipulate view template files it will really open up your design possibilities.
Comment: Fantastic! Thanks for pointing that out; this will definitely allow more design control.
Comment: Extending this a bit, consider the HTML5 Tools module as mentioned in this [guide to Drupal HTML5](http://www.daymuse.com/blogs/drupal-html5-guide-theming-tags-and-templates); it exposes more HTML5 elements within Views.
Answer: Fences looks like a great module (for Drupal 7) to control views output markup:
Project page:
http://drupal.org/project/fences
From the project page:

"Fences is a an easy-to-use tool to specify an HTML element for each
  field. This element choice will propagate everywhere the field is
  used, such as teasers, RSS feeds and Views. You don't have to keep
  re-configuring the same HTML element over and over again every time
  you display the field."

I like this bit particularly (great for debugging output):

"Best of all, Fences provides leaner markup than Drupal 7 core! And
  can get rid of the extraneous classes too!"

This is also nice - reducing repetition of work:

"This kind of tool is needed in order to create semantic HTML5 output
  from Drupal. Without such a tool, you have to create custom field
  templates in your theme for every field. :("

They've considered the popular alternatives too:

Similar projects include Semantic fields, Field Wrappers and a
  tool inside the Display Suite extras. But we think this approach
  is Morefasterbetter™.

Credit to Drupal user rhache for mentioning the Fences Drupal module in their comment on this question Is Semantic Views module obsoleted by Views 3?
Answer: You may try semantic views module.
As it says at this issue, it is useful for html5 output.
Comment: Semantic views is not the instrument for 7, unfortunately


Quickblox 2.6.1 webrtc: missing org.webrtc.videocapturerandroid$nativeobserver

Question: I am getting a missing class error when trying to load libjingle_peerconnection_so.so. I am using Quickblox 2.6.1 video webrtc. Does anyone have any idea whats going on?
##---------------Begin: proguard configuration for Gson  ----------
    # Gson uses generic type information stored in a class file when working with fields. Proguard
    # removes such information by default, so configure it to keep all of it.
    -keepattributes Signature
# For using GSON @Expose annotation
-keepattributes *Annotation*

# Gson specific classes
-keep class sun.misc.Unsafe { *; }
#-keep class com.google.gson.stream.** { *; }

# Application classes that will be serialized/deserialized over Gson
-keep class com.quickblox.core.account.model.** { *; }

##---------------End: proguard configuration for Gson  ----------

##---------------Begin: proguard configuration for quickblox  ----------

#quickblox core module
-keep class com.quickblox.auth.parsers.** { *; }
-keep class com.quickblox.auth.model.** { *; }
-keep class com.quickblox.core.parser.** { *; }
-keep class com.quickblox.core.model.** { *; }
-keep class com.quickblox.core.server.** { *; }
-keep class com.quickblox.core.rest.** { *; }
-keep class com.quickblox.core.error.** { *; }
-keep class com.quickblox.core.Query { *; }

#quickblox users module
-keep class com.quickblox.users.parsers.** { *; }
-keep class com.quickblox.users.model.** { *; }

#quickblox messages module
-keep class com.quickblox.messages.parsers.** { *; }
-keep class com.quickblox.messages.model.** { *; }

#quickblox content module
-keep class com.quickblox.content.parsers.** { *; }
-keep class com.quickblox.content.model.** { *; }

#quickblox chat module
-keep class com.quickblox.chat.parser.** { *; }
-keep class com.quickblox.chat.model.** { *; }
-keep class org.jivesoftware.** { *; }
-dontwarn org.jivesoftware.smackx.**

#quickblox videochat-webrtc module
-keep class org.webrtc.** { *; }

##---------------End: proguard configuration for quickblox  ----------

##---------------End: proguard configuration --------------

Missing class error
Answer: did you put libjingle_peerconnection_so.so for all Jni folders??
like x86,armeabi etc.
Comment: Yes of course i did, that's why this problem is giving me a head ache... could it be the libjingle version, and if so what site would i get the latest version? I am using the version that came with Quickblox webrtc 2.6.1
Comment: @Edison did u got solution?
Answer: I fixed the error. I updated the correct version of libjingle in the right path. thanks for your help.


EditText multiline not expanding when soft input is open

Question: I have seen many answers on this topic, but none of them has solved my problem. My layout file looks like this:
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical"
    android:background="@color/lightGrey"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/chatAppBarLayout"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_alignParentTop="true">

        <android.support.v7.widget.Toolbar
            android:id="@+id/chatToolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:elevation="4dp"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
            app:layout_scrollFlags="scroll|enterAlways" />

    </android.support.design.widget.AppBarLayout>

    <RelativeLayout
        android:id="@+id/chatScreen"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingBottom="16dp"
        android:paddingTop="16dp"
        android:layout_marginTop="?attr/actionBarSize">

        <ListView
            android:id="@+id/chatListView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/sendMessageContainer"
            android:layout_marginBottom="10dp"
            android:scrollbars="none"
            android:stackFromBottom="true"
            android:transcriptMode="normal">
        </ListView>

        <RelativeLayout
            android:id="@+id/sendMessageContainer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="30dp"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="0dp">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBaseline="@+id/sendChatMessage"
                android:layout_toLeftOf="@+id/sendChatMessage"
                android:layout_alignParentLeft="true">

                <EditText
                    android:id="@+id/chatInput"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:inputType="textMultiLine"
                    android:lines="1"
                    android:maxLines="5"
                    android:scrollbars="vertical" />

            </LinearLayout>

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/sendChatMessage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5dp"
                android:layout_marginLeft="15dp"
                android:layout_alignParentRight="true" />
        </RelativeLayout>
    </RelativeLayout>
</android.support.design.widget.CoordinatorLayout>

I want it to initially show 1 line, but expand to a max of 5 lines as text is entered. I cannot figure out why my EditText is not going into multiple lines. I have a feeling it's because it's being anchored to some view but I can't figure it out. Any help would be appreciated.
EDIT: So it seems with the above code, my EditText IS expanding to multiple lines, but NOT when the soft input is open. I open soft input, type 2 lines, the EditText shows one line with a vertical scroll. When I close the soft input, it expands to 2 lines. When I open soft input again, there are 2 lines. If I type in another line, it shows 2 lines with scroll. If I close, it expands to 3 lines. Why is it not expanding when the soft input is open?
Comment: Why have you specified `android:lines="1"` if you want it to be multi line?
Comment: Because I want it to initially show one line, but expand to a max of 5 lines.
Comment: From the documentation of `lines`: **Makes the TextView be exactly this many lines tall.** (http://developer.android.com/intl/in/reference/android/widget/TextView.html#attr_android:lines) So in your case, set `inputType="textMultiLine"` and set `maxLines="5"` and remove `lines`.
Comment: I tried this, but it's initially showing 5 lines.
Comment: That's weird because I just tried and it shows single line initially and as I start pressing the enter key it expands till 5 lines and stops expanding in height and keeps on expanding internally.
Comment: Sorry, it's not showing 5 lines initially. It's showing one, but isn't expanding at all. Did you use the exact same layout?
Comment: Ok I'm sorry, this seems to be a different problem altogether. Please refer updated question.
Answer: You have set lines to 1 that's why it's showing only one lines.
Change android:lines="5"
and add android:minLines="1"
It would be
<EditText
    android:id="@+id/chatInput"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textMultiLine"
    android:lines="5"
    android:minLines="1"
    android:scrollbars="vertical" />

Comment: Please refer edit on the question, I want there to initially be one line but expand to a max of 5.
Comment: Removing `android:lines=1` causes there to initially be 5 lines.
Comment: @VedavyasBhat: Updated my answer.
Comment: Ok I'm sorry, this seems to be a different problem altogether. Please refer updated question.
Answer: Try this
 android:inputType="textMultiLine"
 android:lines="5"

then after its looks like
     <EditText
        android:id="@+id/editTextmessage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="15"
        android:inputType="textMultiLine"
        android:maxLines="5"
        android:scrollbars="vertical"
        android:textSize="@dimen/small_txt_size" />

Comment: @VedavyasBhat new updated answer works perfect for me. try to make height to wrap_content may be its.
Comment: Please refer edit on the question, I want there to initially be one line but expand to a max of 5.
Comment: you mean auto expand line??
Comment: Ok I'm sorry, this seems to be a different problem altogether. Please refer updated question.
Answer: Try this way
               <EditText
                    android:id="@+id/chatInput"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:inputType="textMultiLine"
                    android:minLines="5"
                    android:scrollbars="vertical" />

Comment: Please refer edit on the question, I want there to initially be one line but expand to a max of 5.
Comment: Same problem. One line initially, doesn't expand.
Comment: Ok I'm sorry, this seems to be a different problem altogether. Please refer updated question.
Comment: Remove android:fitsSystemWindows="true"
Answer: you can do this also:
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:context="nasuakza.com.br.nasuakz.activities.AtvProduto">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/descricao" />
    </android.support.v4.widget.NestedScrollView>

Comment: This seems to be a different problem altogether. Please refer updated question.
Answer: Add below line to your source code
editor.setSingleLine(false);