Condições em JavaScript não funcionando

Question: Estou fazendo um cálculo com as seguintes informações:
Estilo, experiência, altura e peso.
Com a altura e peso, eu pego o IMC do usuário e comparo com sua experiência.
Com o estilo, eu defino o tipo de prancha.
Primeiro, eu pego o estilo de prancha. Com o estilo de prancha "em mãos", eu comparo o IMC e a Experiência do usuário e exibo o resultado.
O problema é que, somente a opção "SURF" está funcionando. Quando eu escolho a opção "StandUP Paddle", ele não funciona.
Como resolver isso?

function calcularIMC(){
var estilo = document.getElementById("estilo").value;
var experiencia = document.getElementById("experiencia").value;
var altura = document.getElementById("altura").value;
var peso = document.getElementById("peso").value;
var imc = 0;

   if(altura >0 && peso >0){
     imc = peso / (altura * altura);
    }

    if(estilo == "StandUp Paddle"){

      if((experiencia>=3) && (imc<=29)){
        alert("SUP SURF");
      }
       else if((experiencia<=3)&&(imc>29)){
          alert("FUNBOARD");
        }

     }
      else if(estilo == "Surf"){
         if(imc<=25){
          alert("PRANCHINHA");
      }
      else{
          alert("LONGBOARD");
          }
     }
}
Estilo

<select name="estilo" id="estilo" value="estilo" required>
   <option disabled selected hidden>Escolha seu estilo</option>
   <option>StandUp Paddle</option>
   <option>Surf</option>
</select>

Experiência

  <select name="experiencia" id="experiencia" required>
  <option disabled selected hidden>Escolha sua experiência</option>
  <option value="0">sem experiência</option>
  <option value="1">menos de 1 mês</option>
  <option value="2">até 3 meses</option>
  <option value="3">até 6 meses</option>
  <option value="4">1 ano ou mais</option>
</select>

Altura

<select name="altura" id="altura" required>
  <option disabled selected hidden>Escolha sua altura</option>
  <option>1.60</option>
  <option>1.61</option>
  <option>1.62</option>
  <option>1.63</option>
  <option>1.64</option>
  <option>1.65</option>
  <option>1.66</option>
  <option>1.67</option>
  <option>1.68</option>
  <option>1.69</option>
  <option>1.70</option>
  <option>1.71</option>
  <option>1.72</option>
  <option>1.73</option>
  <option>1.74</option>
  <option>1.75</option>
  <option>1.76</option>
  <option>1.77</option>
  <option>1.78</option>
  <option>1.79</option>
  <option>1.80</option>
  <option>1.81</option>
  <option>1.82</option>
  <option>1.83</option>
  <option>1.84</option>
  <option>1.85</option>
  <option>1.86</option>
  <option>1.87</option>
  <option>1.88</option>
  <option>1.89</option>
  <option>1.90</option>
  <option>1.91</option>
  <option>1.92</option>
  <option>1.93</option>
  <option>1.94</option>
  <option>1.95</option>
  <option>1.96</option>
  <option>1.97</option>
  <option>1.98</option>
  <option>1.99</option>
  <option>2.00</option>
</select>

Peso

<select name="peso" id="peso" required>
  <option disabled selected hidden>Escolha seu peso</option>
  <option>50</option>
  <option>51</option>
  <option>52</option>
  <option>53</option>
  <option>54</option>
  <option>55</option>
  <option>56</option>
  <option>57</option>
  <option>58</option>
  <option>59</option>
  <option>60</option>
  <option>61</option>
  <option>62</option>
  <option>63</option>
  <option>64</option>
  <option>65</option>
  <option>66</option>
  <option>67</option>
  <option>68</option>
  <option>69</option>
  <option>70</option>
  <option>71</option>
  <option>72</option>
  <option>73</option>
  <option>74</option>
  <option>75</option>
  <option>76</option>
  <option>77</option>
  <option>78</option>
  <option>79</option>
  <option>80</option>
  <option>81</option>
  <option>82</option>
  <option>83</option>
  <option>84</option>
  <option>85</option>
  <option>86</option>
  <option>87</option>
  <option>88</option>
  <option>89</option>
  <option>90</option>
  <option>91</option>
  <option>92</option>
  <option>93</option>
  <option>94</option>
  <option>95</option>
  <option>96</option>
  <option>97</option>
  <option>98</option>
  <option>99</option>
  <option>100</option>
</select>

 <button id="Enviar" onclick="calcularIMC();">Send</button>

Consegui através desta maneira:
if(estilo == "Surf"){
   if((imc<=25) && (resultado == 5)){
    alert("PRANCHINHA");
}
else{
    alert("LONGBOARD");
    }
}
else if(estilo == "SUP"){
  if((experiencia >= 3) && (imc <=29)){
    alert("Sup Surf");
  } else{
    alert("FUNBOARD")
  }
}

Comment: Não entendi qual é o problema.
Comment: Ainda não entendi qual é o problema. Se não explicar, vou continuar sem saber.
Comment: Não funciona é muito genérico, você tem que explicar o que deveria acontecer.
Comment: Dentro do `if(estilo == "StandUp Paddle")` você só testa `experiencia>=3` (até 6 meses). E se o usuário escolher uma experiência menor do que 3?
Comment: Rode o Snippet escolhendo o estilo "StandUp Paddle"
Comment: @bigown Atualizei a pergunta. Dá uma olhada pf
Comment: Pra mim está funcionando. Só não sei se está do jeito que deseja, não temos como adivinhar o jeito que quer.
Comment: @abfurlan Verdade. Inverti o simbolo.
Comment: @bigown Quando eu escolho a opção `StandUp Paddle` o alert não dispara. Este é o problema
Comment: Respondi o que consegui, senão for isso, aguardo a explicação do que o código deveria fazer. Ficar repetindo a mesma coisa sem explicar o que deveria fazer, não vai ajudar ninguém ajudar.
Comment: O objetivo do código é definir um tipo de prancha ideal para o usuário. De acordo com suas informações (estilo de prancha, tempo de experiência, altura e peso). Com a altura e o peso dele, eu calculo o IMC - Índice de Massa Corporal, assim eu tenho noção do estado de saúde do usuário. Com essa informação "em mãos", eu comparo com o tempo de experiência e estilo de prancha e dou o resultado
Comment: Eu votei pra fechar porque a última edição deixou claro que a pergunta não pode ser respondida por ninguém a não ser o próprio autor dela. Mesma a resposta colocada não funciona corretamente em qualquer definição a não ser que volte ter comportamento semelhante ao que o autor diz ser problema, ou seja, há situações em que nada é feito.
Comment: @LuizSantos A resposta resolveu o seu problema? Acha que pode aceitá-la? Se não souber como faz, veja o [tour]. Isso ajudaria muito indicar que a solução foi útil para você e dar uma indicação que houve uma solução satisfatória. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Esta é uma forma que poderia resolver o problema, mas não posso garantir porque a pergunta não explica qual é o resultado desejado. Até houve uma edição que muda completamente o que deveria fazer. Tudo leva a crer que a edição deixou o código mais errado ainda, mas não tem como garantir. Depois houve outra edição colocando uma solução que certamente está errada e mesmo que fosse a certa ainda concluiríamos que só o AP poderia responder a pergunta.
Note que organizar o código ajuda entendê-lo.

function calcularIMC() {
    var estilo = document.getElementById("estilo").value;
    var experiencia = document.getElementById("experiencia").value;
    var altura = document.getElementById("altura").value;
    var peso = document.getElementById("peso").value;
    var imc = 0;
    if (altura > 0 && peso > 0) {
        imc = peso / (altura * altura);
    }
    if (estilo == "StandUp Paddle") {
        if (experiencia >=3) {
            if (imc<=29) {
                alert("SUP SURF");
            } else {
                alert("FUNBOARD");
            }
        } else {
            alert("Alguma mensagem pra quem não tem experiência suficiente");
        }
    } else if (estilo == "Surf") {
         if (imc <= 25) {
             alert("PRANCHINHA");
         } else {
             alert("LONGBOARD");
         }
    }
}
Estilo

<select name="estilo" id="estilo" value="estilo" required>
   <option disabled selected hidden>Escolha seu estilo</option>
   <option>StandUp Paddle</option>
   <option>Surf</option>
</select>

Experiência

  <select name="experiencia" id="experiencia" required>
  <option disabled selected hidden>Escolha sua experiência</option>
  <option value="0">sem experiência</option>
  <option value="1">menos de 1 mês</option>
  <option value="2">até 3 meses</option>
  <option value="3">até 6 meses</option>
  <option value="4">1 ano ou mais</option>
</select>

Altura

<select name="altura" id="altura" required>
  <option disabled selected hidden>Escolha sua altura</option>
  <option>1.60</option>
  <option>1.61</option>
  <option>1.62</option>
  <option>1.63</option>
  <option>1.64</option>
  <option>1.65</option>
  <option>1.66</option>
  <option>1.67</option>
  <option>1.68</option>
  <option>1.69</option>
  <option>1.70</option>
  <option>1.71</option>
  <option>1.72</option>
  <option>1.73</option>
  <option>1.74</option>
  <option>1.75</option>
  <option>1.76</option>
  <option>1.77</option>
  <option>1.78</option>
  <option>1.79</option>
  <option>1.80</option>
  <option>1.81</option>
  <option>1.82</option>
  <option>1.83</option>
  <option>1.84</option>
  <option>1.85</option>
  <option>1.86</option>
  <option>1.87</option>
  <option>1.88</option>
  <option>1.89</option>
  <option>1.90</option>
  <option>1.91</option>
  <option>1.92</option>
  <option>1.93</option>
  <option>1.94</option>
  <option>1.95</option>
  <option>1.96</option>
  <option>1.97</option>
  <option>1.98</option>
  <option>1.99</option>
  <option>2.00</option>
</select>

Peso

<select name="peso" id="peso" required>
  <option disabled selected hidden>Escolha seu peso</option>
  <option>50</option>
  <option>51</option>
  <option>52</option>
  <option>53</option>
  <option>54</option>
  <option>55</option>
  <option>56</option>
  <option>57</option>
  <option>58</option>
  <option>59</option>
  <option>60</option>
  <option>61</option>
  <option>62</option>
  <option>63</option>
  <option>64</option>
  <option>65</option>
  <option>66</option>
  <option>67</option>
  <option>68</option>
  <option>69</option>
  <option>70</option>
  <option>71</option>
  <option>72</option>
  <option>73</option>
  <option>74</option>
  <option>75</option>
  <option>76</option>
  <option>77</option>
  <option>78</option>
  <option>79</option>
  <option>80</option>
  <option>81</option>
  <option>82</option>
  <option>83</option>
  <option>84</option>
  <option>85</option>
  <option>86</option>
  <option>87</option>
  <option>88</option>
  <option>89</option>
  <option>90</option>
  <option>91</option>
  <option>92</option>
  <option>93</option>
  <option>94</option>
  <option>95</option>
  <option>96</option>
  <option>97</option>
  <option>98</option>
  <option>99</option>
  <option>100</option>
</select>

 <button id="Enviar" onclick="calcularIMC();">Send</button>

Coloquei no GitHub para referência futura.
Comment: Ínves destes três `if`. Eu não poderia fazer de uma forma direta `if((experiencia>= 3) && (imc<= 29))` ?
Comment: Depende, você ainda não disse o que você deseja. Tem caso que pode, tem caso que não pode.
Comment: O objetivo do código é definir um tipo de prancha ideal para o usuário. De acordo com suas informações (estilo de prancha, tempo de experiência, altura e peso). Com a altura e o peso dele, eu calculo o IMC - Índice de Massa Corporal, assim eu tenho noção do estado de saúde do usuário. Com essa informação "em mãos", eu comparo com o tempo de experiência e estilo de prancha e dou o resultado
Comment: `SE` o estilo de prancha for `STANDUP PADDLE`... A `experiencia` for maior ou igual a `6 meses` e o IMC dele for `<=29`, `alert("SUP SURF");
Comment: Estou fazendo isso de uma forma direta `if((experiencia>= 3) && (imc<= 29))` e não está pegando. Este é meu problema
Comment: Não tenho como ajudar mais que isso sem dar mais detalhes. Você pode testar na resposta e ver que funciona. Se não funciona do jeito que deseja eu não tenho o que fazer, você não explica de uma forma que dê para ajudar. Seu problema provavelmente não é código, é não saber o que deseja fazer, e aí ninguém consegue te ajudar.
Comment: Eu fiz de uma forma diferente, mas consegui o que queria. Obrigado pela disposição em ajudar! Coloquei o código na pergunta.

Condições em JavaScript não funcionando


Getting web site addresses in squid logs

Question: Is there a way to get all website addresses that have not been blocked by firewall for the last week sorting by IP address using squid logs?
Here's an example of the log file
1250388539.781    388 10.0.44.22 TCP_MISS/200 1931 GET http://safebrowsing-cache.google.com/safebrowsing/rd/goog-phish-shavar_s_45871-45875.45871-45875.: - DIRECT/220.127.116.11 application/vnd.google.safebrowsing-chunk
1250388540.180    382 10.0.44.22 TCP_MISS/200 923 GET http://safebrowsing-cache.google.com/safebrowsing/rd/goog-phish-shavar_a_63716-63720.63716-63717.63718-63720: - DIRECT/220.127.116.11 application/vnd.google.safebrowsing-chunk
1250388549.554    657 10.0.12.101 TCP_MISS/200 430 GET http://tracker.openbittorrent.com/announce? - DIRECT/18.104.22.168 text/plain
1250388583.580    675 10.0.12.101 TCP_MISS/200 1579 GET http://tracker.prq.to/announce? - DIRECT/220.127.116.11 text/plain
1250388588.951    702 10.0.12.13 TCP_MISS/405 1368 LOCK http://www.portforward.com/images/spacer.gif - DIRECT/18.104.22.168 text/html
1250388595.574    674 10.0.12.101 TCP_MISS/200 1579 GET http://denis.stalker.h3q.com/announce? - DIRECT/184.108.40.206 text/plain
1250388703.596    667 10.0.12.101 TCP_MISS/200 1579 GET http://open.tracker.thepiratebay.org/announce? - DIRECT/188.8.131.52 text/plain
1250388746.959    699 10.0.12.13 TCP_MISS/405 1368 LOCK http://www.portforward.com/images/spacer.gif - DIRECT/18.104.22.168 text/html
1250388761.595    676 10.0.12.101 TCP_MISS/200 1578 GET http://tpb.tracker.prq.to/announce? - DIRECT/22.214.171.124 text/plain
1250388772.590    678 10.0.12.101 TCP_MISS/200 1580 GET http://open.tracker.thepiratebay.org/announce? - DIRECT/18.104.22.168 text/plain
1250388803.588    663 10.0.12.101 TCP_MISS/200 620 GET http://tracker.openbittorrent.com/announce? - DIRECT/22.214.171.124 text/plain
1250388835.578    665 10.0.12.101 TCP_MISS/200 430 GET http://tracker.thepiratebay.org/announce? - DIRECT/22.214.171.124 text/plain
1250388835.910    678 10.0.12.101 TCP_MISS/200 1578 GET http://tracker4.finalgear.com/announce? - DIRECT/126.96.36.199 text/plain
1250388848.523    408 10.0.8.155 TCP_MISS/200 663 POST http://safebrowsing.clients.google.com/safebrowsing/downloads? - DIRECT/22.214.171.124 application/vnd.google.safebrowsing-update

System Specs: Centos5
I need to determine who visited which site for a week.
Is this possible?
Comment: You'll need to provide a little more detail of your setup for someone to answer this.
Answer: Yes, you can put this together with basic unix commands like awk, grep and sort. Or you could hack something together in perl. Or you could load it into a database and do all sorts of mining and reporting.
cat log | grep "TCP_MISS/200" | awk '{ print $3, $7 }' | sort | uniq

Note that matching physical people with proxy or web access logs is illegal in many countries and may require a court order. Your profile suggests you are in South Africa, in which case there is a constitutional right to not have "the privacy of their communications infringed". (South African Constitution of 1996, Section 14)
Comment: You don't need grep command when awk is there: sudo cat /var/log/squid/access.log | awk '/TCP_MISS\/200/{ print $3, $7 }' | sort | uniq
Answer: You can use this command to browse connectivity in real time, methods and bytes:

sudo tail -f /var/log/squid/access.log |awk '{printf(" %-20s | %-15s |  %-28s | %-6s | %-5s |%-s\n",strftime("%c",$1),$3,$4,$5,$6,substr($7,0,50))}'

Also, for some kind of report i use sarg, and sometimes a python script named sqview


How to center image in 300px by 300px div? (Image dimensions not known)

Question: I have a div that is absolutely positioned from the top left corner of the browser that is 300px by 300px. I plan to show an image in the div but unfortunately I do not know the size of the image although I do know that the image will be 300px by 300px or smaller.
How can I create a div that has a set width and height of 300px that centers images of the same size or smaller horizontally and vertically?
Answer:
#container { width: 300px; height: 300px; line-height: 300px; text-align: center; }
#container img { vertical-align: middle; display: inline-block; }

jsFiddle Demo
Comment: FYI : I had down voted his old answer because he didn't have the `line-height: 300px` - he deleted before I could comment.
Comment: I didn't vote down but I got 2 down votes on the exact same answer 2 minutes ago :) Some people just like to be douches
Comment: Just beware IE with inline-block if you want [IE7 support](http://quirksmode.org/css/display.html#inlineblock).
Comment: @RobertK The `img` should be inline-block by default, and if you use a different element, there is still [the good old IE7 hack](http://stackoverflow.com/questions/6544852/ie7-problem-with-display-inline-block/6545033#6545033).
Comment: @ZoltanToth Yeah I see your deleted answer now. It is missing the `line-height`, but still, downvoting without a comment is not understable.
Answer: Use the following CSS on the div:
CSS
div {
    width: 300px;
    height: 300px;
    position: absolute;
    top: 0;
    left: 0;
    background: #fff center center no-repeat;
}

HTML / PHP
<div style="background-image: url('<?php echo $image_url; ?>');">

Comment: @acidic - See the second example. I would put the static CSS properties in the style sheet and only define the dynamic style property inline.
Comment: I would like to do that except that the image location is being created by PHP. Is there any way to do this while using PHP to generate the image link?
Comment: @iambriansreed What's bad practice about the solution I posted? In my opinion [`img` vs. `background-image`](http://stackoverflow.com/questions/4335957/using-sprites-with-img-tag/4336431#4336431) should be decided on whether the image is considered content or decoration, not on which one is more practical to style. Btw I upvoted your solution.
Comment: My previous comment was a reply to a now removed comment, but I decided to leave it here because it might help future visitors to decide which technique to use in their situation.


Existence and Uniqueness of Solutions to First-Order Non-Linear Recurrence Relations

Question: How do I go about proving the uniqueness of an existing solution to a recurrence equation of the form
$$
a_{n+1} - f(n)a_n = 0
$$
?
Is there a theorem related to questions of uniqueness and existence for recurrence relations of a certain type as is the case for ordinary differential equations?
Comment: Solving a recurrence relation is very similar (if not equivalent) to solving a differential equation.  I would also tag differential equations and see if anyone can help you there.
Comment: What is the uniqueness proof for ordinary differential equations?  I think it should be applicable to recurrence relations (as per my previous comment).
Comment: This is a (very simple) homogeneous linear recurrence of the first order, just not with constant coefficients.
Answer: Hint
If the recurrence equation is of the form $$a_{n+1} - f(n)a_n = 0$$ you could easily show that the solution is simply given by $$a_n=c \prod _{i=1}^{n-1} f(i)$$
Comment: Oh! Well that's simple enough to make me feel kind of sheepish :P. Thank you! How, then, now, do I prove that that is the ONLY solution?
Comment: Just write the first terms and substitute. This is how I arrived to this formula. I do not see how, from the definition itself, another solution could exist.


Set up probability question.

Question: Can someone show me how to set this up? Asking for help on how to work this, not asking for the answer.
Question:
Assume that P(A) = 0.5, P(A∩C) = 0.18, P(C) = 0.4, P(B) = 0.4, P(A∩B∩C) = 0.08, P(B∩C) = 0.16, and P(A∩B) = 0.21. Calculate the following probabilities:
b. P(A'∩(B∪C))
Comment: rolled back to original question
Comment: Your newly edited version removed the original question and replaced it with something vague and incorrect. I suggest rolling it back to the previous version. I've deleted my answer as it no longer applies.
Comment: Sorry I'm new to the site about 15min worth of using it. I was trying to follow suggestions in the FAQs about asking a question to help me understand my homework without asking the actual question.
Answer: Observe that
$$P(A' \cap (B \cup C)) = P(A' \cap B) + P(A' \cap C) - P(A' \cap B \cap C)$$
The three terms on the RHS can be computed as follows:
$$P(A' \cap B) = P(B) - P(A \cap B)$$
$$P(A' \cap C) = P(C) - P(A \cap C)$$
$$P(A' \cap B \cap C) = P(B \cap C) - P(A \cap B \cap C)$$

Set up probability question.


Is there a closed-form expression for the inverse of $f \left( x \right) = \sum_{i = 1}^{n} \mu_i \left( 1 - x \right)^{i - 1}$?

Question: I am trying to find the inverse of $f$, knowing that
\begin{equation}
  f \left( x \right) = \sum_{i = 1}^{n} \mu_i \left( 1 - x \right)^{i - 1}
\end{equation}
where $\sum_{i = 1}^n \mu_i = 1$, $x \in \left[ 0 , 1 \right]$.
It seems that $f$ is a bijection of $\left[ 0, 1 \right]$, so $f$ has an inverse. For example, it is easy to check that $f \left( x \right) = \frac{1 - \left( 1 - x \right)^n}{nx}$ is stricly monotonous, where $\mu_i = \frac{1}{n}$. However, even in this case, I am unsure of the existence of a closed-form solution for the inverse.
And I am just wondering if a closed-form exists in general.
Thank you!
Answer: I do not think that you could find a closed form for the general case.
However, letting $t=1-x$, you could consider that
$$y= \sum_{i = 1}^{n} \mu_i\,t^{i - 1}$$ is a Taylor expansion built around $t=0$ to $O(t^{n+1})$ and use series reversion for an approximate solution. This would give quite nasty things such as
$$t=z-\frac{\mu_3 }{\mu_2}z^2+\frac{2 \mu_3^2-\mu_2 \mu_4
  }{\mu_2^2} z^3+\frac{-5 \mu_3^3+5 \mu_2 \mu_4 \mu_3-\mu_2^2 \mu_5 }{\mu_2^3}z^4+
   \frac{14 \mu_3^4-21 \mu_2 \mu_4 \mu_3^2+6 \mu_2^2 \mu_5 \mu_3+3 \mu_2^2 \mu_4^2 }{\mu_2^4}z^5+\cdots \qquad\text{where} \qquad z=\frac{y-\mu_1}{\mu_2}$$
The case where $\mu_i = \frac{1}{n}\,\,\forall i$,  it seems that
$$t=z \sum_{i=0}^n (-1)^i z^i=\frac{z}{z+1}\left(1+(-1)^n z^{n+1} \right) \qquad\text{where} \qquad z=n y-1$$


Can I make an HTML form perform two actions?

Question: Can I use my HTML form to perform multiple actions?

Post the information to another destination.
Navigate a user to another page once they submit the form.

At the moment I can post the filled form to the destination but cant navigate the user to another page using HTML specifically. Is there any method in HTML to do this?
Any suggestions?
Comment: You could use AJAX to submit the form, then JS to navigate to a different page.  You could also submit the form outright, then on the server side redirect the user.
Comment: thank you for your reply. actually i am working on goolge sites that have very limited compatibility. i cant use javescript js or any other programming language with the form..the form is on the google site..once the user is submitting the form it is moving to the blank page.. i want to rediect it to the page that i can design..google site is not working properly if i put any script in it.. any suggestions if i can do the actions with the submit button or if form can do multipe actions
Answer: You can use redirect after you perform whatever you are going to do on the first page (the one from form action)
Comment: Thank you boris for your reply. actually i am working on goolge sites that have very limited compatibility. i cant use javescript js or any other programming language with the form..the form is on the google site..once the user is submitting the form it is moving to the blank page.. i want to rediect it to the page that i can design..google site is not working properly if i put any script in it.. any suggestions if i can do the actions with the submit button or if form can do multipe actions
Comment: Can you change the HTML? Can you change the FORM action page?
Comment: yes i can change the html but as soon as i put any script in it..t will stop working..everything has t be done in html itself..google says that they accept javascript with html but its not working.. i have searche the new and got to know that we can only perform one action with one form??? any sugesstions
Answer: Things are easy if you control the server and/or are on the same domain, then you can do a server side redirect. But since you are using salesforce surely you don't control that. Nevertheless, double check their documentation for a redirect option you can put in the form.
If that fails, one thing I'd try is to submit it to an iframe: add  somewhere to your html (you can hide it too if you want) and add target="foo" to your form. Then, also add an onsubmit javascript handler to the form that redirects after a delay to allow the form to be processed. The timing of the delay is likely to be a source of bugs btw, checking for errors in the submitted form can't be easily done across domains, you'd be guessing. Maybe an onload handler on the iframe can do the redirect though, I'm not sure, but worth a try.
This isn't guaranteed to work either, some sites don't like being in iframes. If that fails, you might try setting target="_BLANK" to submit the form to a popup window then redirect your main window using javascript or something. This will require you to give an instruction to the user to close the window.
Lastly, if you can submit the data via a server side API call to salesforce, that would be good too because then the plain redirect option is back under your control.
Comment: thank you adam for your reply. actually i am working on goolge sites that have very limited compatibility. i cant use javescript js or any other programming language with the form..the form is on the google site..once the user is submitting the form it is moving to the blank page.. i want to rediect it to the page that i can design..google site is not working properly if i put any script in it.. any suggestions if i can do the actions with the submit button or if form can do multipe actionsl


Pandas, How to subtract first row value from all values in a Series?

Question: I have a Series object in Pandas and I would like to subtract a number equal to the first value of the Series from all values of the Series.
For example:
This:
2015-10-01: 5000
2015-10-02: 5005
2015-10-03: 5012

becomes this:
2015-10-01: 0
2015-10-02: 5
2015-10-03: 12

Is this possible with a native Pandas method? Or should I loop through all values and subtract?
Comment: just do `s - s.iloc[0]`
Answer: You can access the first row value using iloc[0] and then just subtract from the rest of the series:
In [5]:
import io
import pandas as pd
t="""2015-10-01 5000
2015-10-02 5005
2015-10-03 5012"""
s = pd.read_csv(io.StringIO(t), index_col=[0], parse_dates=[0], header=None, delim_whitespace=True, squeeze=True)
s

Out[5]:
0
2015-10-01    5000
2015-10-02    5005
2015-10-03    5012
Name: 1, dtype: int64

In [6]:
s - s.iloc[0]

Out[6]:
0
2015-10-01     0
2015-10-02     5
2015-10-03    12
Name: 1, dtype: int64

It's possible to use head(1) but you need to index the array in order to get the scalar value otherwise you get NaN for the 2nd row onwards due to index alignment:
In [9]:
s - s.head(1)[0]

Out[9]:
0
2015-10-01     0
2015-10-02     5
2015-10-03    12
Name: 1, dtype: int64

compare with:
In [10]:
s - s.head(1)

Out[10]:
0
2015-10-01     0
2015-10-02   NaN
2015-10-03   NaN
Name: 1, dtype: float64


Question in Hatcher proposition 1.26 proof

Question:
(a) If $Y$ is obtained from $X$ by attaching 2-cells as described above, then the inclusion $X\hookrightarrow Y$ induces a surjection $\pi_1(X,x_0)\to\pi_1(Y,x_0)$ whose kernel is $N$.

Rather than writing down the meaning 'describe above' and '$N$' in the statement, I think it's better to look p.49 of Hatcher's algebraic topology here.

The question is I can't understand the red line in the image. I understand why they're trying to choose such $\delta_\alpha$, but why such an element exists in $\pi_1(A\cap B,z_0)$? The map $\pi_1(A\cap B)\to \pi_1(A)$ is not surjective. Could you explain this?
Answer: To describe the desired loop $\delta_\alpha$ in detail, let's look at the parts of the path $\gamma_\alpha \phi_\alpha \bar\gamma_\alpha$, and describe corresponding new parts which will be concatenated together to define $\delta_\alpha$.
The path $\gamma_\alpha$ goes along the bottom of the strip labelled $S_\alpha$ in that picture, starting from its initial point $x_0$. Define a correponding new path $\gamma'_\alpha$ which instead goes along the top of the strip, starting from its initial point $z_0$.
The closed path $\phi_\alpha$ goes around the boundary circle of the disc $e^2_\alpha$, which is where that disc is attached to $X$, and the base point of $\phi_\alpha$ coincides with the terminal endpoint of $\gamma_\alpha$.  Define a corresponding new path $\phi'_\alpha$ which instead goes around a circle in the disc $e^2_\alpha$ that is concentric to the outer circle, and such that the base point of $\phi'_\alpha$ meets the terminal endpoint of $\gamma'_\alpha$.
Thus the concatenation $\delta_\alpha = \gamma'_\alpha \, \phi'_\alpha \, \bar\gamma'_\alpha$ is a closed loop based at $z_0$, and $\delta_\alpha$ is entirely contained in $A \cap B$.
Furthermore, letting $h$ be "the line segment connecting $z_0$ to $x_0$ in the intersection of the $S_\alpha$'s", the concatenation
$$\bar h \, \delta_\alpha \, h = \bar h \, \gamma'_\alpha \, \phi'_\alpha \, \bar\gamma'_\alpha \, h
$$
is a closed loop in $A$ based at $x_0$ that is path homotopic to $\gamma_\alpha \, \phi_\alpha \, \bar\gamma_\alpha$. That path homotopy may be seen geometrically as moving through the strip $S_\alpha$ and through the annulus joining the outer circle $\phi_\alpha$ of $e^2_\alpha$ to the concentric circle $\phi'_\alpha$.
It follows that $\delta_\alpha$ is a loop "in $A \cap B$ based at $z_0$ representing the element of $\pi_1(A,z_0)$ corresponding to $[\gamma_\alpha\, \phi_\alpha\, \bar\gamma_\alpha]$ under the base-point change homomorphism $\beta_h$".


link_to() generates route successfully, but clicking on that link results in a 404

Question: I've set a website up. If I try and click on a link such as register I get the following error:
404 | Not Found | sfError404Exception
Empty module and/or action after parsing the URL
    "/trevelyan.alumni/register" (/).

The links are generated using
<?php
    print link_to( 'Register', 'register/index' );
?>

And I have a 'register' module in apps/frontend/modules/register.
I'm quite new to Symfony, any help is appreciated!

routing.yml:
# default rules
homepage:
  url:   /
  param: { module: home, action: index }

default_index:
  url:   /:module
  param: { action: index }

default:
  url:   /trevelyan.alumni/:module/:action/*

Comment: Can you show us what you have in your routing.yml?
Comment: # default rules
homepage:
  url:   /
  param: { module: home, action: index }

default_index:
  url:   /:module
  param: { action: index }

default:
  url:   /trevelyan.alumni/:module/:action/*
Comment: do you have a method in the class in apps/frontend/modules/register/actions/actions.class.php called executeIndex?
Answer: I managed to fix this by editing the symfony controller files to use the $_SERVER variables to pick a module from, if one was not found.
Answer: I think that your problem is that you're running symfony out of a "sub-site" instead of directly off of the "root" url (http://www.dur.ac.uk/trevelyan.alumni instead of http://www.dur.ac.uk/).  I think the easiest solution would be to add trevelyan.alumni to the front of all your urls in routing.yml.
For example, for the default route, instead of
default:
  url: /:module/:action/*

use
default:
  url: /trevelyan.alumni/:module/:action/*

Comment: The problem seems to be that I'm using a 'virtualdocuments' handler (no .htaccess allowed) so any requests that are not to a file that exists (e.g. /register/) get sent to virtualdocuments/index.php. I've made this just require /index.php but it still doesn't seem to work - same error as above.
Comment: # default rules homepage: url: / param: { module: home, action: index } default_index: url: /:module param: { action: index } default: url: /trevelyan.alumni/:module/:action/*
Comment: so wait - virtualdocuments/index.php requires symfony's index.php?  Maybe symfony is not parsing the route correctly because it is not what you're actually seeing in the browser.  It might be useful to try to find out exactly what route symfony is getting.
Answer: Read Steven Oxley, but try this as well :
Check you have at least an action class in your module dir with the proper name (symfony is case sensitive, and this is very tricky).
If you do, check that the default action (in the module config files) is one of the action class in your module.
Don't forget to clear cache every time you change a config file.
Answer: at the end of your routing.yml file:
homepage:
  url:
  param: { module: main, action: index }

default:
  url:   /:module/:action/*

and don´t forget to clear the cache afterwards ;)
Answer: you should remove a dot from your matching url for route because of default routing rules
change your default route to:
default:
  url: /trevelyan_alumni/:module/:action/*

and that should work. note that dot(.) is replaced with _
Answer: Just a quick note, for the routing change(s) to take effect, you must run symfony clear cache:
./symfony clear-cache

Answer: I had upgraded from symfony 1.2 to 1.4, and was having this problem. At the end of the day, basically the config files have all changed enough to the point that routing somehow broke. Going through the app config files and comparing / updating them against the "new app" templates found in lib/vendor/symfony/lib/config/config (or where ever you are keeping symfony) fixed this issue.


Registering a DLL from a TFS Build using a CodeActivity

Question: I'm attempting to create a CodeActivity object that will register a DLL on a remote system during a TFS build. I am successfully impersonating my own user account, which has administrator rights to my machine. (I am trying to register the DLLs on my machine for now.) Note that all the attempts have worked if I run the workflow locally, but not from the build server. Also, if I manually run regsvr32, the DLL will register and unregister correctly.
This is the highly stripped-down code I'm using:
Private DllType As Type 'Type of the DLL being registered is handled elsewhere'
Dim Result As Integer
Result = CInt(DllType.InvokeMember("DllUnregisterServer", BindingFlags.InvokeMethod, Nothing, Activator.CreateInstance(DllType), Nothing))

When I run it, I get this message, the most relevant probably being the inner exception, "Unable to find an entry point named 'DllUnregisterServer' in DLL 'RptBarcodeLabel.dll"

Error = Exception has been thrown by the target of an invocation., stack =    at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
     at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
     at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
     at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
     at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
     at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args)
     at TfsCopyFile.DllRegServer.InternalRegServer(Boolean fUnreg)
     at TfsCopyFile.DllRegServer.UnRegister()
     at TfsCopyFile.TfsRegisterDLL.Execute(CodeActivityContext context), inner exception = Unable to find an entry point named 'DllUnregisterServer' in DLL 'RptBarcodeLabel.dll'.

Another method of remotely registering DLLs might work, too - I'm open to suggestions, as long as the process can be fire off during a build from TFS.
Answer: This is the approach I have taken for a similar requirement:
In the TFSBuild.proj, use Exec action to create a .bat file on the fly on the deployment server; the batch file is remotely executed by PsExec. This example creates a batch file to run msiexec, but you can easily change it to register a dll use regsvr32.
<Exec Condition="'$(DeploymentServer)'!=''" Command='echo @echo off >"\\$(DeploymentServer)\C$\Temp\Install.bat"' ContinueOnError="true" />
<Exec Condition="'$(DeploymentServer)'!=''" Command='echo start /wait msiexec /uninstall "{98056358-8984-4554-b0c3-9f2af248a029}" /passive /log "C:\Temp\Uninstall.log" >>"\\$(DeploymentServer)\C$\Temp\Install.bat"' ContinueOnError="true" />

<Exec Condition="'$(DeploymentServer)'!=''" Command='echo taskkill /IM PSEXESVC.EXE >>"\\$(DeploymentServer)\C$\Temp\Install.bat"' ContinueOnError="true" />
<Exec Condition="'$(DeploymentServer)'!=''" Command='"C:\Program Files\Sysinternals\psexec" -accepteula \\$(DeploymentServer) -u myuser -p mypassword -w "C:\Temp" "C:\Temp\Install.bat"' ContinueOnError="true" />

If you don't use something like psexec, you can run into problems with permissions etc when trying to execute commands on the remote server.
Comment: Thank you - I checked into psexec and that, combined with a CodeActivty item, did the trick.


What does "Race to X" mean?

Question: A local pool hall features weekly 8-ball and 9-ball double-elimination tournaments, and the different tournaments are described as:

Race to 4
Race to 4/3
Race to 2

What do these terms mean?
Answer: According to Wikipedia, the term race in billiards means:

A predetermined, fixed number of games players must win to win a match; "a race to seven" means whomever wins seven games first wins the match.

Here is a file with some more examples:

First competitor to win 3 matches (race to 3)
  First competitor to win 4 matches (race to 4)
  First competitor to win 5 matches (race to 5)
  First competitor to win 6 matches (race to 6)

As for your "race to 4/3" example, I believe that is specific to double-elimination tournaments in which you play a different number of games depending on whether you are in the winner's bracket or the loser's bracket.  So "race to 4/3" means it's a "race to 4" in the winner's bracket and a "race to 3" in the loser's bracket.  Here's a page where it mentions a different "race" for the winner's and loser's brackets in one tournament:

Race to 3 winner's side. Race to 2 on the loser's side.

If a double-elimination tournament has the same number of games for both the winner's and loser's brackets, then you could call it a "race to N/N".  An example of that can be found here:

race to 3/3 double elimination

But instead of calling it a "race to 3/3", you could just call it a "race to 3".  An example of that can be found here:

Double Elimination – Race to 3
Comment: That's a very complicated way of saying "Win x racks to win the match".
Comment: The usual sporting idiom is "first to X" as a shortening of "first to get score X wins the match". The change to using "race to X" instead is not complicated at all.

What does "Race to X" mean?


PHP regex with quotes

Question: I want to match all href values in my page content. I wrote regex for that and tested it on regex101
href[ ]*=[ ]*("|')(.+?)\1

This finds all my href values properly. If I use
href[ ]*=[ ]*(?:"|')(.+?)(?:"|')

its even better since I do not have to use certain group later.
With " and ' in regex string I cannot run the regex properly with
$matches = array();
$pattern = "/href[ ]*=[ ]*("|')(.+?)\1/"; // syntax error
$numOfMatches = preg_match_all($pattern, $pattern, $matches);
print_r($matches);

If I "escape" double quote and thus repair the syntax error I get no matches.
So - what is the correct way to apply the given regex in PHP?
Thanks for any help
Notes:

addslashes or preg_quote won't help since I need to pass legit string first
escaping all the special chars   \ + * ? [ ^ ] $ ( ) { } = ! < > | : - didn't help either

EDIT: Ok, I see I really shouldn't be doing this with regex. Could you please provide some helpful DOM parsers or any other tool I 'should' use with PHP for instance ?
Comment: For finding all href links regex is not the right tool.
Comment: Don't use regexes. This'd be far easier with DOM+XPath: `//*[@href]` and done. And just because you ARE defining a regex doesn't excuse you from PHP's string syntax rules. If your string contains the same quote that delimits the string, that internal quote must be escaped.
Comment: Are you trying to [parse HTML with regular expressions](http://stackoverflow.com/a/1732454/53114)? Why not using a proper parser?
Comment: To escape chars just use the backslash like: `\"` (quotes) or `\(` (brace) or \\ (backslash)
Comment: Haha, this escaping thing doesn't let me highlight \\ as code ^^
Comment: [Don't use regex to parse HTML!](http://stackoverflow.com/a/1732454/2812842) Read a **basic** XPath tutorial and you'll see that returning all href attributes in a document is easy. Regex will kill you one day.
Comment: Thanks guys, I see I really shouldn't use regex here. Please see my edited question
Answer: For your case, the following should work:
/]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>/siU

Given the nature of the WWW there are always going to be cases where the regular expression breaks down. Small changes to the patterns can fix these.
spaces around the = after href:
/]*href\s*=\s*(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>/siU

matching only links starting with http:
/]*href=(\"??)(http[^\" >]*?)\\1[^>]*>(.*)<\/a>/siU

single quotes around the link address:
/]*href=([\"\']??)([^\" >]*?)\\1[^>]*>(.*)<\/a>/siU

Source
Answer: I had to use this regex to make it work. Next time I will definitely try with DOM parser :)
$regexForHREF = "/href[ ]*=[ ]*(?:\"|')(.+?)(?:\"|')/";

PHP regex with quotes


Como transformar uma lista que vai ser dada na entrada em uma matriz?

Question: Estou tentando transformar essa lista que foi me dada na entrada em uma matriz
u l i o a

e a p b e

a r y l s

j i t u a

e e h u b

e u o r r

c t n e p

b i o s b

Esse é um dos exemplos de entrada, minha
Mas o máximo que consegui até agora foi isso, que lê somente a primeira linha
l = input().split()

diagrama_entrada = []

diagrama_entrada.append(l)

Comment: Já estudou laços de repetição?
Answer: É possível realizar isso usando compreensão de listas no python.
Vou fazer uso de um exemplo hipotético por acreditar que facilitará sua compreensão:
imaginemos a seguinte lista:
lista = [1,2,3,4,5,6,7,8,9]

E imaginemos agora que buscamos o seguinte resultado:
lista_2 = [[1,2,3],[4,5,6],[7,8,9]]

A lista_2, uma lista de listas, representa também uma matriz, já que:
lista_2[0][0] = 1
lista_2[1][0] = 4
lista_2[2][2] = 9

E assim por diante...
Existem ótimos materiais na internet que destrincham esse assunto, mas para simplificar seu trabalho, observe o código abaixo:
# Definimos aqui a lista de entrada
lista = [1,2,3,4,5,6,7,8,9]

# Definimos aqui o tamanho das linhas da matriz
size = 3

# Geramos a lista_2
lista_2 = [x[i:i+size] for i in range(0, len(lista), size)]

Sendo que na ultima linha acontece o seguinte:
O range(0, len(lista), size) nos cria uma lista que irá iniciar no zero, terminar no 9 (comprimento de nossa lista), mas sua contagem irá ser de 3 e 3 (nosso size).
O x[i:i+size] está fazendo um slice de nossa lista, ou seja, cortando ela do i até o i+size. Se i for 0, ela iá cortar do 0 ao três, se i for 1, ela irá cortar do 1 ao 4 e assim por consequência.
No meio disso tudo tempo um for loop, que irá gerar um i (a sua direita) para cada termo na lista passada(o range, a sua esquerda).
Logo, nosso for loop irá correr todos os termos de [0, 3, 6] (lista gerada pelo range)e para cada um dos termos irá fatiar nossa lista de entrada, ficando com [i[0:3], i[3:6], i[6:9]], que por sua sequência são:
i[0:3] = [1, 2, 3]
i[3:6] = [4, 5, 6]
i[6:9] = [7, 8, 9]

Se desejar ir mais afundo sugiro que leia sobre como trabalhar com listas e depois sobre compreensão de contêineres.


Is this note in Chopin's Nocturne Op. 9, No. 1, a Bb or an Ab?

Question: In the original edition of Chopin's Nocturne Op. 9, No. 1, there is an Ab in bar 5 (6 if the anacrusis is counted) as the 4th note of the left hand:

However, somebody6's transcription on MuseScore shows a Bb in that place:

Is it correct to play the Ab or the Bb? If I open up the piano keyboard on that bar, I see that the 4th note lines up with a Bb key:

Rubinstein's recording plays the Ab:

Is this a mutated note? Is it correct to play the Ab or the Bb?
Comment: Why would you assume an random edition by some random person on MuseScore.com to be in any way a reliable source? ☺
Answer:
The correct note is Ab. This can be checked by looking at the editions on IMSLP or the Chopin Variorum.
Anacruses are not counted in the measure numbering.
Never trust any edition found on MuseScore.
Comment: Short and sweet.  I checked OCVE at the Chopin Variorum manuscript digitalization project archive, in all 3 first editions ([Paris 1832](https://chopinonline.ac.uk/ocve/browse/pageview/77137/), [Leipzig 1833](https://chopinonline.ac.uk/ocve/browse/pageview/67736/), and [London 1840](https://chopinonline.ac.uk/ocve/browse/pageview/67766/)), **the note is Ab**.  The MuseScore transcriber must have made a mistake.
Answer: It's certainly possible for a professionally produced score to have an error where an amateur score does not, but it's far more likely to be the other way around. Absent any other information, you should generally give more weight to the professional score.
But really, whenever you find a discrepancy between two scores, the more careful approach is to look at more scores. (See Andy Bonner's comments along these lines.) See if you can determine why the discrepancy exists: it might be a simple error; the authoritative source might be unclear; there could be multiple authoritative sources that do not agree with each other; it could be a deliberate "correction" of an authoritative source by some editor, and you might decide to agree with that editor or to disagree.
Now, for the most part, people who post their own editions on MuseScore or similar sites (including https://imslp.org and https://cpdl.org) do not invest adequate time and effort in proofreading. Small errors are common. But some people's care in proofreading falls farther short of adequate than others'!
I would therefore refine Aaron's advice somewhat.  Rather than saying "Never trust any edition found on MuseScore," I would say "approach every edition on MuseScore with skepticism" -- but after you've spent time with individual pieces from MuseScore or indeed with several pieces from a given editor, you can form an opinion about the care with which the edition was prepared, and sometimes you will find that some are trustworthy.


Function Problem

Question: If $f(x)$ is a function satisfying $ \displaystyle f(x+y) = f(x) \cdot f(y)  \text { for all } x,y \in \mathbb{N} \text{ such that } f(1) = 3 \text { and } $ $ \sum_{x=1}^{n} f(x) = 120 $, then find the value of $n$.
How to approach this one?
Answer: Hint: Knowing the value of $f(1)$, you can get the value of $f(2)=f(1+1)$ from the defining equation. Knowing these two, you can get value of $f(3)=f(1+2)$ and so on.
Comment: +1,thanks.Using your hint, $f(x) = \left[f(1)\right]^x = 3^x$; Then in the summation which is in geometric progression, $3^n = 3^4$;which gives $n = 4$.
Comment: @Debanjan: Indeed.

Function Problem


Atualizar uma tabela usando javascript e arrays

Question: O que preciso fazer é simples, mas como sou iniciante na arte do PHP e Javascript, estou me batendo um pouco.
O que preciso fazer é o seguinte. Tenho uma tela de pedidos, onde vou cadastrar os dados do pedido, até aí, tudo bem. Logo mais abaixo, vou inserir os produtos no pedido, e eles serão mostrados logo abaixo para serem salvos assim que o pedido for salvo.
O que desejo fazer, é selecionar um produto num combobox, clicar no botão de adicionar produto, adicionar este produto num array ou algo que valha e exibir este array em uma tabela logo abaixo. Mas gostaria de fazer isto, sem atualizar a página.
Alguém tem alguma idéia ou exemplo de como fazer isto?
Comment: Ariel, só para esclarecer: quando você fala em tabela quer dizer tabela em base de dados certo? sabe o que é AJAX? Tem alguma framework de javascript (jQuery, Mootools, etc) ou quer fazer com JS puro? Responda/explique melhor essas 3 perguntas, junte o código que já tem e vai ter uma resposta bem esplicada prometo :)
Comment: Na verdade é um table em HTML. O que estou fazendo é uma tela de pedidos. Eu seleciono o produto numa combo, clicar no botão "Inserir no Pedido", e o produto vai aparecer numa tabela logo abaixo. Quando eu salvar o pedido, vou varrer essa tabela, cujos dados estarão num array (ou algo que o valha) e inserir no banco de dados.
Answer: Você realmente precisa mandar cada novo produto imediatamente pro servidor? Se sim, você vai precisar usar algum tipo de AJAX para se comunicar com o servidor sem recarregar a página.
Mas se você puder "esperar" para mandar tudo de uma vez, seu problema passa a ser apenas de javascript: basta ler os campos e inserir uma linha em uma tabela ou um elemento em um div. Isso é extremamente facilitado por bibliotecas como jquery, por exemplo:
<!DOCTYPE html>

    <title>Test</title>

<form>

Inserir Novo Telefone

    Nome: <input id="nome" type="text"/>

    Telefone: <input id="telefone" type="text"/>

    <input type="button" onclick="$('#telefones').append('
Nome: '+$('#nome').val()+' - Telefone: '+$('#telefone').val()+'
')" value="Adicionar" />
</form>

Telefones

Este código "cadastra" telefones em javascript, colocando dentro do div chamado "telefones". Para enviar ao servidor ainda precisaríamos pôr estes valores em forms, mas você pode gerar estes campos mudando a string dentro do .append() para gerar novos inputs. Eu aconselho a estudar um pouco esta biblioteca, ela inclusive facilita o uso de AJAX.
Answer: Em uma resposta a outra pergunta, fiz um exemplo de como popular uma tabela a partir de um array em javascript.
Código funcional no Jsfiddle.
Sugiro usar este exemplo como base. Basta atualizar o array e chamar o método de paginação para incluir o produto.
Se não quiser paginação, basta fazer alguns pequenos ajustes no loop para remover os limites relacionados à página atual, isto é, incluindo todos os itens.
Answer: Aqui fica uma sugestão com jQUery. Não sei se você usa javascript puro, jQuery, Mootools ou outra biblioteca de Javascript...
$('#adicionarFruta').on('click', function () {
    var $fruta = $('#frutas option:selected');

    // ignorar se fôr a primeira opção do select
    if ($fruta.val() == '0') return false;

    // verificar se o produto já está na tabela
    if ($('#carrinhoCompras input[name^=' + $fruta.val() + ']').length) return false;

    var novaLinha = '\

 \
    ' + $fruta.text() + '	 \
    <input name="' + $fruta.val() + '" value="1" />	 \
    <button>-</button>	 \

 ';

    // adicionar nova linha à tabela
    $('#carrinhoCompras ').append($(novaLinha));
});

// codigo para o botão que remove linhas da tabela
$('#carrinhoCompras').on('click', 'button', function () {
    $(this).closest('tr').remove();
});

Exemplo


How to play strange Emadd9 and Am6 chords in this song?

Question: I'm trying to play this song: https://musescore.com/user/26991134/scores/5554268
I have downloaded, pasted into a new score sheet in musescore and added a Guitar Tab Starve.
But, for the two first chords: Emadd9 and Am6, the auto generated Tab indications are very strange:

Emadd9: String1 - Fret 2, Open String2, Open String3, String6 - Fret3

How can I play this without playing strings 4th and 5th?

Am6: String1 - Fret 2, String2 - Fret 1, String3 - Fret 2, Open String 5

How can I play this without playing string 4th?
NOTE: I have been doing some research and it seems like in this tab the bass notes are 'second voice' notes. That's means that are supposed to play with another instrument like a piano or a bass.
Thank you.
Answer: I think this is meant to be played finger style, like on classical guitar.
Then the bass would be played with the thumb and the top notes with fingers 1, 2, and 3, also called, i, m, a, of the plucking hand.
If you are using a pick you might want to use a hybrid technique where you use the 2, 3, ad 4 fingers of the plucking hand to grab the top notes and the pick to act as a thumb.
Yet another option, if the song is not too fast, is to play the bass note first then the top chord.  The wavy line would indicate they want the chord arpeggiated, meaning to have the notes played with a slight separation in time, like on a harp.
Comment: Not exactly. The three notes are arpeggiated, but the bass note needs to be played at  the same time as the arpeggio starts - on the 3rd string. So bass and 3rd string together. The squiggly line says so. And what's the treble clef sign doing on TAB..?
Comment: I agree but I'm giving other options for he OP to try if they are hell bent on using a pick only.  It will require some reinterpretation.
Answer: You have used the classical-guitar tag
This is a classical guitar piece. Therefore you do not strike all the strings as you would with a pick/plectrum. You use the right hand fingertips (or fingernails) to pluck only the strings that you need.
The right-hand fingers are labelled as pima**
Notice that you can pluck all the strings together or, in this case, one at a time in quick succession.
There are lots of tutorials online if you search for pima guitar, e.g.

**
P = pulgar (thumb)
I = indice (index finger)
M = medio (middle finger)
A = anular (ring finger)
Comment: Thank you very much. Not sure if this technique it's applicable here, but it's a good technique to learn! Thank you for the information.
Answer: Maybe you are not supposed to strum the chord, you just pluck those strings one by one/in a fingerstyle picking pattern.


Can a batsman be out hit wicket on a no ball, and do runs scored count?

Question: A no ball is bowled. The striker hits the ball, but in doing so accidentally puts down their wicket. Will the runs be considered or not? And will be the striker be out hit wicket or not?
Comment: I've voted to reopen. [The community consensus is that low-effort is not a reason for closing](https://sports.meta.stackexchange.com/questions/661/rules-questions-with-little-effort-do-we-close-these-questions-as-off-topic-o/697#697).
Comment: There were three upvoted answers saying "keep them open" and one downvoted answer saying "close". That's as close as we ever get to a consensus on meta here.
Comment: @Nij - I could say the same about 90% of the association football (soccer) questions on here. I had no idea this was the case in cricket - what is obvious to you may not well be obvious to others.
Comment: I'm not a huge follower of cricket, so I may have minced some of the terminology in re-wording this question. However, as it stands, it seems like the close vote / downvotes are no longer unnecessary, since it is entirely clear what is being asked.
Comment: I'm voting to close this question as off-topic because the laws are trivially clear on a no ball, hit wicket.
Comment: A lot of football law application requires knowledge of the game in a real context, or implications not actually stated. This is like asking "if an IFK goes straight into the goal, can the team keep playing? Is it a goal?" - to which the only reasonable response is "that's explicitly stated in very simple terms in the laws of the game".
Comment: And no, there isn't a community consensus on low-effort questions. A moderator stated their view and it has total score of 3. That's not at all close to a consensus.
Answer: A batsman cannot be out hit wicket from a no ball. See Law 24.16:

When No ball has been called, neither batsman shall be out under any of the Laws except 33 (Handled the ball), 34 (Hit the ball twice), 37 (Obstructing the field) or 38 (Run out).

As such, if a batsman does break his own wicket after a no ball, nothing in particular happens: the ball is not dead because no wicket has fallen, so any runs scored count as normal.
(This assumes that breaking the wicket was accidental; if it was deliberate, the fielding side may have a case for the batsman being out obstructing the field).


What is this training device used by Vasyl Lomachenko called?

Question: Video from a Vasyl Lomachenko twitter account.

What is the name of this device or similar type of device?
Answer: It is a Sports Vision Trainer (SVT):

The SVTs come in different sizes and Lomachenko uses the smaller one with 32 lights.
They also have the picture of him using it on their website.
Answer: While I can't provide the specific name to the device you show, I can tell you that it has many uses, one of which is improving hand to eye coordination.  A company called Dynavision makes a very similar product called D2(Dynavsion Dynamic Motor) that is used in sports training and rehabilitation.
Listed benefits of it are:

Incorporates gross motor skills
Progresses neuro-cognitive abilities
Expands peripheral awareness
Trains reaction time
Improves functional mobility
Develops enhanced balance

It's easy to see why a boxer would seek out this type of training device, as it can be used to improve his boxing abilities.


ANCOVA with "Day number" of my study as covariate

Question: I've got some problems with selecting right model/method in my analysis.
Two groups of animals (differ by "Treatment") were measured from 1-st to 42-nd day, one common value for each group was measured by each day (food consumption per day).
I need to compare this groups and I want to use ANCOVA with "Treatment" as fixed effect and "Day number" as covariate in the model.
There are many examples which contain covariates with some sort of randomness in their distribution (like weight, age, IQ, etc., where we can't directly control this variable).
But in our experiment we eliminate this variation by measuring groups day by day. Is it correct to use "Day number" as continious covariate?
Maybe the whole model is incorrect and you can suggest right one?
To be more concrete I would like to present the scatter plot of my data:

(source: fastpic.ru)
Best regards!
Answer: The scatterplot shows clear temporal auto-correlation in the data, which would certainly invalidate some of the statistical assumptions for an ANCOVA. You would be much better off using a general or generalized linear model with an appropriate residual autocorrelation structure to deal with this, otherwise you will not be able to trust the results from your model.
This is a reasonably large topic, and assuming it's not something you know about you would be best spending some time reading and understanding as much of the details as possible before trying anything. It sounds like you are in ecology or a related area, and as an ecologist I would really recommend the book by Zuur et al. 2009 - Mixed Effects Models and Extensions in Ecology with R. This covers exactly these issues, provides great step-by-step ecology-related examples, and is arguably 'easy' to understand, going into some of the maths if you want it, but not being essential.
Comment: Hi @JupiterM104! thanks for recomendation, what the difference between my data and data from [here](http://www.theanalysisfactor.com/ancova-assumptions-when-slopes-are-unequal/)? Could you specify more precisely what of the statistical assumptions for an ANCOVA are not suitable here?
Comment: This is the study where I measured food consumption per day for chickens. So there is study for 42 days only, we can't talk about seasons here, I don't thing that we have autocorrelated data... Maybe I'm wrong. How can we check this?
Comment: The usual assumptions for an ANCOVA or similar general linear models are that the residuals are normally distributed and homoscedastic, and that each observation is independent. Although not the residuals, the clear, curvy shape of your scatterplot indicates almost certain temporal autocorrelation, and therefore non-independence of observations. I don't mean to be rude, but checking model assumptions is quite a basic issue, and will be covered in any decent stats book/many places online, so I would suggest doing some ground work reading and then asking more specific questions if necessary.
Comment: Ok, thanks, I'll try to go deeper and to read more about autocorrelation and more complex models.


No connection to wcf service with oob except when fiddler is running

Question: I have a silverlight application and the application connects with wcf (SSL/https) to a public service hosted on iis. Everything works fine if I start the application in Browser. As soon as I start the application in "Out of Browser Mode" it doesn't work anymore. I tried to figure out the Problem with fiddler but as long as fiddler is running, everything works fine. I found many posts in Internet about this but nothing worked. Are there any idea? What does fiddler do exactly and making it running in oob?
Summary:
1. Everything ok "In Browser"
2. No Connection to public Service when running "Out of Browser"
3. It's runinng "Out of Browser" as long Fiddler is running
Below are some info how I do the connects.
Thank you very very much for a help.
Best regards.
Marc
Here are some info how I do everything:
Is it possible that the self signed certificate has something to do with all?
The connect on Client side to the public service looks like this:
<code> PublicServiceClient proxy;
    BinaryMessageEncodingBindingElement binaryMessageEncodingBindingElement = new     BinaryMessageEncodingBindingElement();
    HttpsTransportBindingElement httpsTransportBindingElement = new HttpsTransportBindingElement();
    httpsTransportBindingElement.MaxBufferSize = int.MaxValue;
    httpsTransportBindingElement.MaxReceivedMessageSize = int.MaxValue;
    httpsTransportBindingElement.TransferMode = TransferMode.Buffered;
    Binding binding = new CustomBinding(binaryMessageEncodingBindingElement,     httpsTransportBindingElement);
    binding.SendTimeout = new TimeSpan(0, 0, _WcfTimeout);
    binding.ReceiveTimeout = new TimeSpan(0, 0, _WcfTimeout);
    binding.OpenTimeout = new TimeSpan(0, 0, _WcfTimeout);
    binding.CloseTimeout = new TimeSpan(0, 0, _WcfTimeout);
    proxy = new PublicServiceClient(binding, new EndpointAddress("https://" +     App.CurrentParameter.WcfDomain + "/PublicService.svc"));
</code>
Binding Server side (web.config):
<code>   <binding name="Web.PublicService.customBinding0" sendTimeout="00:01:00" receiveTimeout="00:01:00" openTimeout="00:01:00" closeTimeout="00:01:00">
    <binaryMessageEncoding maxReadPoolSize="2147483647" maxWritePoolSize="2147483647">
    <readerQuotas maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxDepth="2147483647" maxNameTableCharCount="2147483647" maxStringContentLength="2147483647"/>
    </binaryMessageEncoding>
    <httpsTransport maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" keepAliveEnabled="false"/>
    </binding>
</code>
Service Server side (web.config):
<code>  <service name="Web.PublicService">
    <endpoint address="" binding="customBinding"    bindingConfiguration="Web.PublicService.customBinding0" contract="Web.PublicService"/>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    </service>
</code>
Comment: What's the behavior when running OOB without fiddler, but the connection isn't SSL? Can you test such a scenario?
Comment: The connection is always SSL. If it's running in OOB the following error occurs: Während des Vorgangs ist eine Ausnahme aufgetreten, sodass das Ergebnis ungültig ist. Weitere Ausnahmedetails finden Sie in InnerException. | 0 | 0 | Void RaiseExceptionIfNecessary()
at Void RaiseExceptionIfNecessary() line 0 column 0
at SL.PublicServiceReference.CustomerData get_Result() line 0 column 0
at Void OnGetCustomerDataCompleted(System.Object, SL.PublicServiceReference.GetCustomerDataCompletedEventArgs) line 0 column 0
at Void OnGetCustomerDataCompleted(System.Object) line 0 column 0
Comment: Well, and what says the inner exception? ;)
Did you already activate [tracing](http://msdn.microsoft.com/en-us/library/ms733025.aspx) to get more details about the error?
Comment: I tried the tracing but in OOB there is nothing logged. I suppose that the call from OOB never get to the Server, so nothing will be logged. The innerexception looks like: InnerException {System.ServiceModel.CommunicationException: Der Remoteserver hat einen Fehler zurückgegeben: NotFound. System.Net.WebException: ...: NotFound. System.Net.WebException: ...: NotFound. bei System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) bei System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClassa.b__9(Object sendState) bei System.Net.Browser.Asy...
Answer: If you disable HTTPS Decryption in Fiddler (and restart it) and the app stops working through Fiddler, that means that the self-signed certificate in use on the server is the problem, and you need to fix it by trusting that certificate.
If disabling HTTPS decryption in Fiddler doesn't make a difference, the problem is likely related to the security zone settings. See http://blogs.msdn.com/b/fiddler/archive/2010/11/22/fiddler-and-silverlight-cross-zone-cross-domain-requests.aspx for details on why that might be.


What is the purpose of the "Views: views_view" component?

Question: Using the Features module, I notice there is a "Views: views_view" component, when creating a feature, but I don't see any setting for that component.

I thought it would be list the views enabled in the site, but that doesn't happen, even if I have two views enabled.
What is the purpose of that component? Why isn't showing any settings?
I have tried with both the latest release candidate, and the lastest development snapshot, but the result doesn't change.
Answer:
What is the purpose of [the "Views: views_view"] component?

As you suspected, to allow views to be exported into a features module.

Why isn't showing any settings?

I do not know. One possible explanation is, that all the enabled views are provided by other modules via an implementation of hook_views_default_views(). The Features module itself exports views by writing an implementation of hook_views_default_views(), so the Views module cannot distinguish between the two versions of the view. That's why the Features module does not allow views to be exported, that are provided by other modules.


Acessar itens de uma tupla no Django

Question: Estou tentando acessar um item de uma tupla no meu template para imprimir o nome da tecnologia e não o numero correspondente.
Meu model onde a tupla esta:
TECHNOLOGY = (
  (0, "JavaScript"),
  (1, "Java"),
  (2, "Python"),
  (4, "Android"),
  (5, "Apple"),
  (6, "Other")
)

class Project(models.Model):
  project_id = models.BigAutoField(primary_key=True)
  slug = models.SlugField(max_length=200, unique=True)
  title = models.CharField(max_length=200, unique=True)
  github = models.CharField(max_length=500)
  technology = models.IntegerField(choices=TECHNOLOGY, default=6)
  summary = models.TextField(max_length=200)
  description = HTMLField()
  date_created = models.DateTimeField(default=now)
  project_image = models.ImageField(blank=True)

  class Meta:
      ordering = ['technology']

  def __str__(self):
      return self.title

Meu template onde preciso acessar:

              {% for project in project_list %}
                  {% for id, name in project.technology %}

{{ name }} Projects

Projects made for programming studies or for college
                          assignments

                  {% endfor %}
              {% endfor %}

Answer: Quando você faz o for e acessa o atributo technology retorna o primeiro elemento das tuplas. Para não ocorrer isso, você precisa executar uma função no template html {{project.get_technology_display }} ou criar uma função no models para retornar os nomes das tecnologias invés dos IDs. Detalhe, mesmo você fazendo isso vai retornar um erro no seu segundo for, com a seguinte mensagem 'int' object is not iterable, isso deve pelo fator que o seu objeto não é interável
Solução
Nesse caso vou criar uma função chamada technology_verbose dentro do models, assim tirando a necessidade de executar a função no template, através do {{project.get_technology_display }} (boa prática). E não irei utilizar o for id name pelo motivo que não é um ManyToMany e sim um IntegerField com apenas um valor do choice
models.py
from django.db import models
from datetime import datetime

class Project(models.Model):
    TECHNOLOGY = (
        (0, "JavaScript"),
        (1, "Java"),
        (2, "Python"),
        (4, "Android"),
        (5, "Apple"),
        (6, "Other"),
    )

    now = datetime.now()

    project_id = models.BigAutoField(primary_key=True)
    slug = models.SlugField(max_length=200, unique=True)
    title = models.CharField(max_length=200, unique=True)
    github = models.CharField(max_length=500)
    technology = models.IntegerField(choices=TECHNOLOGY, default=6)
    summary = models.TextField(max_length=200)
    #description = HTMLField()
    date_created = models.DateTimeField(default=now)
    project_image = models.ImageField(blank=True)

    class Meta:
        ordering = ["technology"]

    def __str__(self):
        return self.title

    ## Função para retornar os nomes das tecnologias
    def technology_verbose(self):
        return dict(Project.TECHNOLOGY)[self.technology]

html
<link  rel="stylesheet"  href="https://firstname.lastname@example.com/dist/css/bootstrap.min.css"  integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"  crossorigin="anonymous">

    {% for project in project_list %}

{{ project.technology_verbose }} Projects

Projects made for programming studies or for college
                assignments

    {% endfor %}

Visualização do HTML

GitHub
O Django possui a arquitetura MTV (Model, Template, View), sendo assim depende de vários fatores para funcionar. Vou deixar o GitHub e com o passo a passo de como rodar o projeto no README.
https://github.com/Kaiquenakao/stack-question/tree/master
Comment: Muito obrigado funcionou :)
Comment: Fico feliz em saber ;)))

Acessar itens de uma tupla no Django


Fantasie Impromptu and hand flexibility

Question: I am thinking of perhaps learning Fantasie Impromptu soon. I have played a 4:3 polyrhythm before but not for longer than a measure. The piece in which I have encountered this polyrhythm is Nocturne Op. 9 no. 2. I am perfecting that nocturne(I commonly lose my place in the rallentando when I start at tempo and go up to trill speed).
I noticed that my hands, even though my right hand is the same width and depth and is only longer by a millimeter or 2(that slight asymmetry in the hands I found is due to handedness, my longer hand is my dominant hand), my right hand is more flexible(don't get me wrong, my left hand is pretty flexible too). This shows up clearly when I play arpeggios that have a 10th as the interval between the lowest and highest notes.
Take the first 2 arpeggios in Fantasie Impromptu for example. They stretch up to a 10th. I can't reach a 10th with static intervals at all in my left hand and I can rarely reach a 10th in my right hand as a static interval.
I can use a 1-2-4-5 fingering in my right hand for G#-D#-G#-B but for that same arpeggio in the left hand I have to use a 5-3-2-1 fingering(Both of these are with some rotation to reach the 10th without overstretching the ligaments). Only when the interval is a 9th or smaller can I use a 5-4-2-1 fingering in my left hand.
I don't know if I am going to get a growth spurt in my 20s or not(I know some people do get a growth spurt in their 20s). But I was wondering, would practicing Fantasie Impromptu, particularly those triplet arpeggios, increase my left hand flexibility, particularly between my 5th and 4th fingers?
Comment: If you *really* want to break out of the trap you have got into, practice the left hand *using only your 3rd finger, for* ***every*** *note.* When you can do that accurately and evenly (but not necessarily at full speed!) then go back to using a more sensible fingering, but don't "forget about" the wrist and arm movements you have just learned.
Comment: To repeat what I have said in answers to several of your other questions: you don't want "hand flexibility", you want *wrist* and *arm* freedom of movement. Waiting to see if you "might get a growth spurt" is just fantasy. Either you stop trying to play the piano like a harpsichord, or you stop trying to play 19th-century piano music - it's your call!
Answer: Streching one's hand in order to play the arpeggios you are reffering to would be higly detrimental.
A streched hand build up tension, and you want to be as relaxed as possible while playing.
You wont be able to sustain such a stress for the duration of this piece, at best your musicality will suffer a great deal from it, and at worst you will injure yourself.
As alphazero pointed out in the comments, you should use arm and wrist movement instead, to maintain the hand as closed as possible when playing. So just use the fingering which is the most confortable for you.
To answer your question, yes I think repeatedly streching your hand will make it more flexible, but you dont need to be actualy playing the piano to do that. Stretching your hand in the air would to it too, i just don't think there is any point in doing that.

Fantasie Impromptu and hand flexibility


SQL to filter out some data?

Question: I have a database table: mydata
id    content   name
1     1         a
2     2         b
3     2         c
4     13        hhh
5     13        yyyy
6     7         wwww
7     13        iiii
8     7         nnnn
9     8         oooo

It will look at "content" field. If the same value inside "content" show up more than one time, it will display out. Here is final result
id    content   name
2     2         b
3     2         c
6     7         wwww
8     7         nnnn
4     13        hhh
5     13        yyyy
7     13        iiii

Thus how to write this SQL?
Answer: select *
from myData
where content in (
  select content
  from myData
  group by content
  having count(*) > 1)

Comment: LOL. Exactly the same answer at exactly the same time :)  I'll let you have it since you have less rep.
Comment: It doesn't work. It displays following error message: #1241 - Operand should contain 1 column(s)
Comment: @andy: What sql database engine are you using?  You should always include that in your tags because it makes a difference.
Comment: I use MySQL with MyISAM. It shows an error message when I use your sql statement.

SQL to filter out some data?


What does mean $df/dg$ (derivative of a function with relation to another)?

Question: I have on a textbook a system of two ODEs as follow
$$\dfrac{df}{dx}=af(x)g(x)\\
\dfrac{dg}{dx}=-bg(x)$$
So, the author studies $df/dg$ writing $\dfrac{df}{dg}=-\dfrac{a}{b}f(x)$.
I understand the arithmetic, but I am not sure of mathemathical/geometric meaning.
Thank you in advance for light and maybe some lemmas or theorems of reference that it is valuable (are when is valuable).
Answer: I have ranted numerous times on this site about that horrendous notation. It really means nothing and can be very misleading. I would suggest you write
$$\frac{df}{dx} = af(x)g(x) = -\frac ab f(x)\frac{dg}{dx},$$
and then divide by $f(x)$ to get
$$\frac1{f(x)}\frac{df}{dx} = -\frac ab \frac{dg}{dx}.$$
Now integrate both sides (with respect to $x$) and you get
$$\ln |f(x)| = -\frac ab g(x) + c.$$
[You could write the previous equation as $\frac{df}f = -\frac ab dg$, and then you get where your textbook should end up.]
Comment: For better or for worse, this is a very common notational abuse. For example, the chain rule is often written as $$\frac{dy}{dx}=\frac{dy}{du} \cdot \frac{du}{dx} \, ,$$ where you are differentiating $y$ with respect to the function (!?) $u$.
Comment: @Joe: No, when we write the chain rule, we really have $y=f(u)$ where then we substitute $u=g(x)$, so $u$ is the independent variable for $f$, not a function. I did teach calculus for mire than 45 years, and it can be done in a way that makes sense.
Comment: @TedShifrin That's what I meant—the usual formula is an abuse of notation because it makes it seem *as if* you are differentiating a function with respect to a function. If $y=f(g(x))$, and $u=g(x)$, then $$\frac{dy}{du} = \frac{df(g(x))}{dg(x)} \, .$$ However, the RHS is 'overloading' the function $g(x)$. It is being used both as a dummy variable to illustrate that we are talking about $f'$, and also as the point at which $f'$ is being evaluated. Hence, we could write this is more clearly as $$\frac{df(u)}{du}\Biggr|_{u=g(x)} \, .$$
Comment: @MathDoctor That's fine, although basically no one does it. I personally prefer the non-Leibniz notation $f'(x)$ because it makes it explicit where you're evaluating the function $f'$. The sorts of things we write like $$\frac{dx}{dy} = \frac1{\frac{dy}{dx}}$$ are horrendous, because we completely suppress where the derivatives are evaluated (so kudos to you for wanting to make it explicit).
Comment: @TedShifrin Yes, although I have changed my profile, I was one of the person that you bicker about this confused notation (rs). However, this time, I take the notation in a very consecrated article (two very consecrated articles in fact, that I just rewrote to post as question). As Joe said, this is a very common notational abuse, but I'd like to thank you so much for show an alternative way that avoid it! Thank once again, Prof. Shifrin.
Comment: I discovered the question was being discussed here https://math.stackexchange.com/questions/291376/differentiate-with-respect-to-a-function and here https://math.stackexchange.com/questions/954073/derivative-of-a-function-with-respect-to-another-function
Comment: @TedShifrin - Hi Dr. Shifren, I have a quick question pertaining to the portion of your answer regarding *notation*: what are your thoughts on writing $\frac{df}{dx}(x)$ for the derivative of a function $f$ evaluated at a point $x$ (example using this notation: given $f(x)=x^{2}$, then  $\frac{df}{dx}(x) = 2x$)?
Answer: This notation is often difficult to make sense of. What, for instance, would it mean to differentiate $\sin(x)$ with respect to $\cos(x)$? To begin with, we must write $\sin(x)$ in terms of $\cos(x)$:
$$
\sin(x)=\sqrt{1-\cos(x)^2} \, ,
$$
ignoring the $\pm$ signs that should be on the square root for now. This means that
$$
\frac{d\sin(x)}{d\cos(x)}=\frac{d\sqrt{1-\cos(x)^2}}{d\cos(x)} \, .
$$
But this is the same as
$$
\frac{d}{du}\left(\sqrt{1-u^2}\right)\Biggr|_{u=\cos(x)} \, .
$$
So every time you see
$$
\frac{df(x)}{dg(x)} \, ,
$$
note that $f(x)=h(g(x))$ for some function $h$, and write
$$
\frac{dh(g(x))}{dg(x)}=\frac{dh(u)}{du}\Biggr|_{u=g(x)} \, .
$$
The $u$ is a dummy variable that can then be replaced by whatever function you are 'differentiating with respect to'. You can use $g(x)$ as a dummy variable, but it often leads to confusion, and is considered by many people to be poor style.

To give another example, let's consider the chain rule,
$$
\frac{dy}{dx}=\frac{dy}{du} \cdot \frac{du}{dx}
$$
Say $y=\sin(u)$, where $u=x^2$. Then, the chain rule appears to say
$$
\frac{d}{dx}(\sin(x^2))=\frac{d}{dx^2}\left(\sin(x^2)\right) \cdot \frac{d}{dx}(2x) \, .
$$
It seems difficult to parse the first term on the RHS. The easiest way to do this is to write it instead as
$$
\frac{d}{du}(\sin(u)) \Biggr|_{u=x^2} \, .
$$
However, we can also treat $x^2$ just as we would any other variable, and make sense of the term that way, too.
Comment: @Quiet_waters I wouldn't worry too much about it—I think your comment has demonstrated how imprecise Leibnizian notation can be. If I can find a way to make sense of $df/dg$, then I'll edit my post.
Comment: @Quiet_waters: My feelings won't be hurt if you accept Joe's answer instead. There are really two issues going on here. One is the Leibniz notation and its abuse; the other (which was more what I cared about here) is the usual separation of variables game for differential equations (which has been discussed numerous times on here, too), where I have argued before that it's really just an application of the chain rule to justify it.
Comment: Joe, I accepted Prof. Shifrin's answer and would like to bount your answer as well as soon as system liberate. But I'd like to confess you a confusion that hurt my mind. And if the function $g(x)$ is not one-to-one, this "variable" could lead to some mathematical confusion maybe?! Thank you. @TedShifrin
Comment: Yes Thank you @Joe
Comment: I discovered the question was being discussed here https://math.stackexchange.com/questions/291376/differentiate-with-respect-to-a-function and here https://math.stackexchange.com/questions/954073/derivative-of-a-function-with-respect-to-another-function
Comment: Not at all @TedShifrin. I did not make the comment in this regard. My only intention was to accept both answers (but it is impossible). So I will accept you (because I think it got to the heart of my dissatisfaction with the notation) but also evaluate Joe's (because it in some way gives sense to the  notation). The question in fact was about the care of the notation abuse as you pointed out. Thank you all


Android 6.0.1 application auto start after boot

Question: I want to start my MainActivity right after device boot. I tried multiple solutions but no one works. Currently, I have this.
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<receiver android:name="installer.common.InstallerBroadcastReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.QUICKBOOT_POWERON" />
    </intent-filter>
</receiver>

InstallerBroadcastReceiver.kt
class InstallerBroadcastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val i = Intent(context, MainActivity::class.java)
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        i.putExtra("test", 1)
        context.startActivity(i)
    }
}

MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.main)
    if (intent.hasExtra("test")) {
        someMethodHere()
    }
}

Any suggestion on what can be wrong?
Answer: Seems like there is some problem with device (zkteco), i get this error I/BackgroundManagerService: prevent from boot complete broadcast: com.mypackagename
On other devices i tried, it was working.
Answer: try to split your intent-filter
    <intent-filter>
        <action android:name="android.intent.action.QUICKBOOT_POWERON" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>

Comment: hi, unfortunatelly it did not help still not working


Fatal error: Uncaught Error: Class in php loop

Question: How do i loop through the object bank to get the amount of the specified id?
`
<?php

$user_id = 2;

$banks_data = [
    ['id' => 1, 'amount' => '22000', 'name' => 'ken'],
    ['id' => 2, 'amount' => '24000', 'name' => 'ken'],
    ['id' => 3, 'amount' => '26000', 'name' => 'ken'],
];

foreach($banks_data as $item){
    $balance = $item['amount']::where(id, $user_id);

return $balance;
}
?>

`
suppose the user_id is 3 i want the returned figure to be 26000
Comment: You code is not valid, amount is a string you can't call it like that, balance can be found at `$item['balance']` like you do for amount.
Comment: Err, bank_data is an array of arrays, so what is an object bank?
Comment: I thought over and found a  even more PHP-way one-liner. See my answer update.
Answer: You need a custom search method for that.
$banks_data = [
    ['id' => 1, 'amount' => '22000', 'name' => 'ken'],
    ['id' => 2, 'amount' => '24000', 'name' => 'ken'],
    ['id' => 3, 'amount' => '26000', 'name' => 'ken'],
];

$getBalance = function (array $data, int $userId): int {
    foreach ($data as $bank) {
        if ($bank['id'] === $userId) {
            return (int) $bank['amount'];
        }
    }
    throw new Exception('User not found');
};

echo $getBalance($banks_data, 2);

or a even more PHP-way one-liner
echo false !== ($index = array_search(2, array_column($banks_data, 'id'))) ? $banks_data[$index]['amount'] : 'not found';

Output
24000


Exiting python program using evdev InputDevice results in a error

Question: I'm experimenting with a controller as an input device using evdev. When I exit the program, I get an error message stating that the delete method (super) requires at least one argument. I have looked, but wer not able to find a solution to handle this properly.
The program:
# import evdev
from evdev import InputDevice, categorize, ecodes

# creates object 'gamepad' to store the data
# you can call it whatever you like
gamepad = InputDevice('/dev/input/event5')

# prints out device info at start
print(gamepad)

# evdev takes care of polling the controller in a loop
for event in gamepad.read_loop():
    # filters by event type
    if event.type == ecodes.EV_KEY and event.code == 308:
        break
    if event.type == ecodes.EV_ABS and event.code == 1:
        print(event.code, event.value)
    if event.type == ecodes.EV_ABS and event.code == 0:
        print(event.code, event.value)
    # print(categorize(event))
    if event.type == ecodes.EV_KEY:
        print(event.code, event.value)

When I use a specific key I break out the loop, resulting in this error message:
Exception TypeError: TypeError('super() takes at least 1 argument (0 given)',) in <bound method InputDevice.__del__ of InputDevice('/dev/input/event5')> ignored

The same happens when I exit using ^C.
Any ideas how to handle the exit properly?
Answer: Simply, evdev is waiting for an event to occur while suddenly you interrupt the cycle.
In order to exit from the execution properly, remove the break statement, close the device and end your script.
[...]
for event in gamepad.read_loop():
    if event.type == ecodes.EV_KEY and event.code == 308:
        gamepad.close()   #method of ..yourpythonlib/evdev/device.py
        quit()
[...]

For exiting sharply with ^C without having errors, you still need to close the evdev input device, using a "try-except block".
for event in gamepad.read_loop():
   try:
       [...] if event [...]
   except KeyboardInterrupt:
       gamepad.close()
       raise


How do I append to end of a file, without deleting its previous content, in eiffel

Question: i am programming with eiffel and every time i open a file and start writing into it, it deletes its content and starts writing into it like it's an empty file, is there a way to do it without deleting the previouse content?
Here is a example of code
local
    f: PLAIN_TEXT_FILE
do
    create f.make_open_write("C://myName/desktop//myfile.txt")
    f.put_integer(3)

and now the file will contain 3 and all the previouse data will be lost!
Answer: Creation procedure make_open_append should be used in this case:
create f.make_open_append ("C:/myName/desktop/myfile.txt")
f.put_integer(3)

Answer: If you want to append text at the end of the file, use make_open_append like that:
f.make_open_append("C://myName/desktop//myfile.txt")

If you want to rewrite from the beginning of the file (like in your example, replacing the first character of the file with 3), you can open in read write mode and write to it like this:
f.make_open_read_write("C://myName/desktop//myfile.txt")
f.put_integer(3)

Comment: Calling `make_open_read_write' will still shrink the file. To overwrite the content, you need to map the file to memory which can be done using platform specific APIs.


How to use Remote Desktop for administration when a policy is set to start a program automatically?

Question: On a Windows 2008 R2 server with the Remote Desktop Services role installed, I have used a local group policy to start a program automatically. How do I log into the console session to manage the server using Remote Desktop in this scenario? In other words, how do I log in to manage the server without having the program start? The /admin switch doesn't work. It did when connecting to Windows 2003 Terminal Service servers.
Comment: What program, what group policy? It would help if we knew how it would start? Is it in the Start>Startup, or is it running via the \run key in the registry.
Comment: The program is a medical practice management software that supports Terminal Services. As stated in the question, we used a local group policy Remote Desktop Services setting to start the application automatically upon a remote desktop connection. This setting starts the application using a path to the executable. It does not start the application when logging on locally, at the console.
Comment: Group policy does not start anything directly. It makes changes to a local computer or user profile so it starts. Now that you said that, I get it. Is the policy set to run against user profiles or that entire computer?
Comment: I think you are on to something! I set the policy in the "Computer" section of the local group policy. Having some of these settings available in the "user" section is new in Server 2008 (I believe). I'll try changing the setting to start the program automatically into the user section and then I'll try connecting to with the /admin switch again.
Comment: Unfortunately, this made no difference. The program still started automatically so I could not get a desktop.
Answer: Starting the program with Local Group Policy isn't, probably, the best way to do what you're looking for.
In Terminal Services environments generally one uses Loopback Group Policy processing (in either Merge or Replace mode) to apply a set of user policy settings to users logging-on to the Terminal Server computer. For "Administrators", typically one would "Deny" the "Apply Group Policy" right to the GPO containing the settings that aren't appropriate for "Administrator" users (like starting a program automatically on logon).
The Multiple Local Group Policy object (MLGPO) functionality can accomodate what you want, as well, but I discourage people from using it in Domain environments. Generally it's better to put your GPOs in the Directory because, in the future, you may have a different (or multiple) server computers in the Terminal Server role. Using GPOs in the Directory means that you need only put new Terminal Server computers into the correct OU to have them "do the right thing", as opposed to having to manually replicate MLGPO settings "by hand" between machines. (In general, you should only want to do a given thing once...)
Comment: This makes sense. It's a simple environment but I see your point and if setup the way you describe, it appears like I'll be able to log into the console (physical) session and get a desktop rather than have the application start automatically. I'll give this a try.
Comment: What if the domain controllers are Windows Server 2003 (only the Terminal Service/Remote Desktop Service server is 2008 R2)? In order for this to work, would I have to install/turn on RSAT on the 2008 R2 box to configure this as you suggest?
Comment: I installed the GPMC feature on the R2 server and configured the GP settings in the directory but I still have the same problem, even when denying the policy for administrative accounts and the administrative groups.
Comment: @BoogieKnight: Without seeing more detail about where your user accounts, server computer account, GPO contents, and GPlinks are in your Directory I can't say much about why you're not getting the expected performance. I use this type of security group filtering in production at several Customer sites so I know it *can* work fine.
Comment: @Evan: If it helps, here's how this directory is setup: An OU for Domain Controllers (2 Win 2K3 servers), an OU for Terminal Servers (1 Win 2K8 R2 server), an OU for "Computers" at the main office, an OU for "Computers" at the branch office, an OU containing all "users" and an OU consisting of a Security Group of users at the branch office. The Group Policy I set to control Terminal Services is linked to the Terminal Servers OU and has "Computer Configuration" policies. I tried "User Configuration" policies but it didn't help (I did not try using Loopback on this policy).
Comment: @Evan: Well...you were right. Once I created a Directory based "user" policy, turned on Loopback processing, denied the policy from administrators, it worked! Thank you for your insight.
Answer:
I think you are on to something! I set
  the policy in the "Computer" section
  of the local group policy. Having some
  of these settings available in the
  "user" section is new in Server 2008
  (I believe). I'll try changing the
  setting to start the program
  automatically into the user section
  and then I'll try connecting to with
  the /admin switch again

Sorry it took so long to understand, but when you see it, you just soak in all the details, but to me, it was just not coming across.
Yes, now that I had enough information to even understand the problem, I was getting to that. I would make it a user policy, and just move the users, administrator for example, to a different OU, so it is not affected by the policy that starts the program. If you already create a separate OU for your users (I highly recommend this anyway), at least administrator in the default users OU won't have to be touched. Any other users you want to exempt, you should move out too.
I will keep the rest of the answer for reference.
2008 Server no longer supports connecting to the console:
http://support.microsoft.com/kb/947723
http://www.techrepublic.com/blog/datacenter/windows-server-2008-drops-rdp-console-option/434
Comment: Actually, to expand on this, we can no longer connect to "Session 0", but we can connect to the session that is physically logged onto at the server (see the 2nd bullet point in the "Why the /console switch is no longer needed" section of the link you provided. Previously, it didn't matter whether we already had the console session (session 0 in that case) open or not.
Comment: So then the real question is how do you stop a specific program from running, but you have not told us anything about the program.
Comment: See my comment above for an answer to your question about the program.
Comment: In my comment above, the reference to "we can connect to the session that is physically logged onto at the server" refers to what we "should" be able to do, but that's not happening in my case.
Comment: Keep in mind, the policies I'm changing are "local" policies on the 2008 R2 server, not "domain" policies; thus I don't think there's a way to separate the administrator users from domain users.
Comment: I did not realize that. If not, you would have to apply that to each user profile. Are you not running a domain?
Comment: Yes, a Windows Server 2003 based domain.
Comment: Then have you considered just ditching the local policy, and move it to an OU that encompasses the users you want to have that start for?
Comment: I'm actually trying that now; per your suggestion and another persons suggested answer.
Comment: This doesn't work either. If the policy is set under "User Configuration" and linked to an OU that contains the server and/or an OU that contains users, the policy is not applied because the application doesn't start upon logon. If I change the policy and set the setting in the "Computer Configuration", I have the same problem as the original question: can't remote in and receive a desktop for administration purposes. I also tried blocking the policy from applying to administrators but this made no difference.
Comment: @KCotreau: Thank you for your help and suggestions. Between you and Evan (below), I got this to work!
Answer: Which version of RDP uses the client you are connecting from? Try to use the /console switch.
Comment: The switches changed in W2k8 and Vista SP1. I thought the /console switch will still work if you have an older version on the client but after digging around I found this: http://blogs.msdn.com/b/nickmac/archive/2007/11/28/mstsc-console-switch-in-windows-server-2008-and-windows-vista-sp1.aspx
Comment: Ya, the /console switch is only for older versions of Remote Desktop. I should be able to use the /admin but with the application set to start automatically, the /admin switch is not taking me into administration mode.
Comment: Tried 6.0 and 6.1.7600 (both from an XP workstation). Version 6.1 supports Remote Desktop Protocol 7.0, if that matters.


How to decide the Jordan normal form of a matrix?

Question: I have the following matrix:
\begin{bmatrix}1&1&0\\-1&3&0\\-1&1&2\end{bmatrix}
My matrix has characteristic polynomial $(X-2)^3$ and minimal polynomial $(X-2)^2$. How do I decide between the two following Jordan normal forms of this matrix?
\begin{bmatrix}2&1&0\\0&2&0\\0&0&2\end{bmatrix}
or
\begin{bmatrix}2&0&0\\0&2&1\\0&0&2\end{bmatrix}
Comment: Jordan normal forms are unique *up to permutation of the Jordan blocks*
Comment: they are the same
Answer: They are equivalent Jordan normal form as also the following
$$\begin{bmatrix}2&0&0\\1&2&0\\0&0&2\end{bmatrix} \quad \begin{bmatrix}2&0&0\\0&2&0\\0&1&2\end{bmatrix}$$
which are sometimes also used.
Indeed the Jordan normal form is unique up to a permutation of the blocks.
Answer: Both of them will do. That is, both of them are a Jordan normal form of your matrix.
Comment: Oh book uses only one of them without saying anything. Thank you :)
Comment: This depends on the convention that the Jordan basis of each generalised eigenspace begins or ends with eigenvectors.
Comment: @Bernard no, that would yield the one in the other answer. The difference in the question is how one orders the cyclic subspaces. By increasing or decreasing dimension. [That is assuming matrcies operate on the left.]