Verificar se os valores de uma array são todos iguais ou todos diferentes

Question:   Queria alguma função que retornasse TRUE quando todos os valores dentro de uma array fosse igual ou se todos fossem diferentes, e retornasse FALSE se não fossem todas iguais e nem todas diferentes. Caso não tenha entendido, explicarei com exemplos:
Ex:
 Caso eu tenha a(s) seguinte(s) array(s) para verificação:
var arr = ['xx','xx','xx']; //(todos iguais)
     //ou
var arr = ['xx','yy','zz']; //(todos diferentes)

A função retornaria TRUE, porém se fosse uma array na qual os valores não são todos iguais nem todos diferentes retornaria FALSE, como na seguinte situação:
var arr = ['xx','xx','zz']; //(Os valores não todos iguais, e nem todos diferentes)

Eai? Alguém tem alguma ideia de como posso fazer isso?
Comment: O que você já tentou?
Answer: Filtrei o array removendo os duplicados. Se só sobrou um elemento, todos são iguais. Se o tamanho do array for o mesmo, todos são diferentes.
function todosIguaisOuDiferentes(array) {
    var filtrado = array.filter(function(elem, pos, arr) {
        return arr.indexOf(elem) == pos;
    });

    return filtrado.length === 1 || filtrado.length === array.length;
}

Comment: +1 ... Código legível, curto e inteligente.
Comment: Vlw, funcionou aqui! : )
Answer:

Array.prototype.allValuesSame = function() {
  for (var i = 1; i < this.length; i++) {
    if (this[i] !== this[0])
      return false;
  }
  return true;
}

var arr = ['xx', 'xx', 'xx']; //(todos iguais)
var arr2 = ['xx', 'yy', 'zz']; //(todos diferentes)

console.log(arr.allValuesSame()); // true
console.log(arr2.allValuesSame()); // false
Comment: Deve retornar true se todos forem iguais ou todos diferentes. Essa resposta está incorreta.
Comment: Quando são todos diferentes tem que retornar true também, pelo o que entendi.
Comment: Entendi, esqueci esse detalhe,  vou editar esta resposta.
Answer: function CheckArray (a) {
    if (a.length == 1)
        return true;

    var result = false;

    // Verifica se são todos iguais
    for(var i = a.length - 1; i >= 0; i--) {
        if (!(a[0] === a[i])) {
            result = false;
            break;
        } else {
            result = true;
        }
    }
    if (result)
        return true;

    // Verifica se são todos diferentes
    result = true;
    for (var i = a.length - 1; i >= 0; i--) {
        // Caso o indexOf e o lastIndexOf sejam diferentes, isso indica que há duas ocorrências e portanto não são todos diferentes.
        if (a.indexOf(a[i]) != a.lastIndexOf(a[i])) {
            result = false;
            break;
        }
    }

    return result;
}

Não está exatamente um código elegante, mas pelo o que testei funciona.


Como faço um botão switch para alternar css?

Question: Tenho dois arquivos CSS para o mesmo HTML e gostaria de  utilizar uma botão switch para alternar os estilos. A idéia é montar um chaveamento "layout padrão" "layout novo".
Tentei com isso, mas não obtive sucesso.

    <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>

e também
$('#novo').click(function (){
  $('link[href="theme_4_1.css"]').attr('href','theme_4_1.css');
});
$('#original').click(function (){
   $('link[href="theme_4_0.css"]').attr('href','theme_4_0.css');
});

Comment: você chegou a ver se o `href` esta sendo alterado?
Comment: Você está atribuindo o mesmo valor que já está presente no `href`, ou seja, nunca iria alterar o valor. Não deveria ser invertido? Onde está o tema `4_1` receber `4_0` e vice versa?
Comment: Não teve sucesso em q? Não pára no evento ou não carrega o css?
Comment: Era isso mesmo Anderson! funcionou.
Comment: creio que o problema pode ter sido por causa dos eventos dentro dos elementos no label, ambos talvez sejam disparados ou não propagam, ou talvez seja por que os seletores dentro de `$(...)` estejam errados, veja a resposta: http://pt.stackoverflow.com/a/189186/3635
Answer: Creio que isto ocorre porque href é convertido para o endereço absoluto, então você pode fazer o seletor assim href$="theme_4_0.css", fora que acredito que você tenha invertido os seletores, creio que o correto seja assim:
$('#novo').click(function (){
  $('link[href$="theme_4_0.css"]').attr('href', 'theme_4_1.css');
});
$('#original').click(function (){
   $('link[href$="theme_4_1.css"]').attr('href', 'theme_4_0.css');
});

Ou pode ser que você aplicou o evento nos SPAN mas ambos são disparados por estarem dentro do switch, então mude para isto:
$('#myonoffswitch').change(function () {
     if (this.checked) { //Se ON aplica o novo tema
         $('link[href$="theme_4_0.css"]').attr('href', 'theme_4_1.css');
     } else { //Se OFF aplica o tema antigo
         $('link[href$="theme_4_1.css"]').attr('href', 'theme_4_0.css');
     }
});

Usando o disabled com link
Você pode também criar 2 elementos link diretamente no HTML (creio que você esteja usando este script https://proto.io/freebies/onoff/):

$(function() {
    var tema1 = $("#theme-4.0");
    var tema2 = $("#theme-4.1");

    $('#TROCAR-TEMA').change(function () {
        if (this.checked) {
            console.log("Tema novo");
            tema1.prop("disabled", true);
            tema2.prop("disabled", false);
        } else {
            console.log("Tema antigo");
            tema1.prop("disabled", false);
            tema2.prop("disabled", true);
        }
    });
});
.onoffswitch {
    position: relative; width: 90px;
    -webkit-user-select:none; -moz-user-select:none; -ms-user-select: none;
}
.onoffswitch-checkbox {
    display: none;
}
.onoffswitch-label {
    display: block; overflow: hidden; cursor: pointer;
    border: 2px solid #999999; border-radius: 20px;
}
.onoffswitch-inner {
    display: block; width: 200%; margin-left: -100%;
    transition: margin 0.3s ease-in 0s;
}
.onoffswitch-inner:before, .onoffswitch-inner:after {
    display: block; float: left; width: 50%; height: 30px; padding: 0; line-height: 30px;
    font-size: 14px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold;
    box-sizing: border-box;
}
.onoffswitch-inner:before {
    content: "ON";
    padding-left: 10px;
    background-color: #34A7C1; color: #FFFFFF;
}
.onoffswitch-inner:after {
    content: "OFF";
    padding-right: 10px;
    background-color: #EEEEEE; color: #999999;
    text-align: right;
}
.onoffswitch-switch {
    display: block; width: 18px; margin: 6px;
    background: #FFFFFF;
    position: absolute; top: 0; bottom: 0;
    right: 56px;
    border: 2px solid #999999; border-radius: 20px;
    transition: all 0.3s ease-in 0s;
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner {
    margin-left: 0;
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch {
    right: 0px;
}

<link id="theme-4.0" rel="stylesheet" href="tema1.css">
<link id="theme-4.1" rel="stylesheet" href="tema2.css" disabled>

      <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="TROCAR-TEMA" checked>

Answer: Nos meus projetos eu utilizo o seguinte código e funciona bem:
Html:
<link id="theme" href="dark.css" rel="stylesheet">
<button id="whiteTheme" data-theme="white.css">White Theme</button>

Script:
$("button[data-theme]").click(function() {
    $("link#theme").attr("href", $(this).data("theme"));
});

Espero que ajude.
Answer: Resolvido o problema invertendo a ordem do href.
$('#novo').click(function (){
    $('link[href="theme_4_1.css"]').attr('href','theme_4_0.css');
});
$('#original').click(function (){
    $('link[href="theme_4_0.css"]').attr('href','theme_4_1.css');
});


Is my proof correct? I want to show if $V \subset H$ is dense, then $L^2(0,T;V) \subset L^2(0,T;H)$ is dense too.

Question: I want to show that if $V \subset H$ is a dense embedding then $L^2(0,T;V) \subset L^2(0,T;H)$ is dense too. Everything is a Hilbert space.
Let $h \in L^2(0,T;H)$. Then $h(t) \in H$ for each $t$. By density of $V$, there is a $v(t) \in V$ such that
$$\lVert v(t) - h(t) \rVert_H \leq \epsilon.$$
So
$$\lVert v - h \rVert^2_{L^2(0,T;H)} = \int_0^T\lVert v(t) - h(t) \rVert_H^2\;dt \leq T\epsilon^2$$
which is what we wanted.
Is this a correct proof? I am not sure how to show that $v$ is integrable..
Comment: By definition $a_i \in H$. Now take $b_i \in V$ close to $a_i$ and define $v = \sum_{i=1}^{M_n} b_i \chi_{A_i}$. With a little care you can ensure that $\lVert v - h\rVert \lt 2 \varepsilon$. (Meanwhile, +1 for your effort.)
Comment: @maximumtag I knew, but thanks. Your write-up would be clearer if you simply approximated the $a_i$'s. Oh, you've done it in between. Nicely done.
Comment: @maximumtag You could write it as an answer instead of putting it in the body of the question.
Comment: Why is $v(t)$ measurable? Try doing it in two steps: approximate $h$ by a simple function and then use density of $V$ to find a function with values in $V$ close to $h$.
Comment: @julien please see edit.
Comment: @Martin Can you give me another hint? I edited in your suggestions
Comment: @Martin thank you, I think I got it now.
Comment: @julien Thanks, I believe I understand the proof now.
Comment: @julien Done. Thanks.
Answer: Thanks to Martin's suggestion:
By definition of Bochner space, there is a simple function
$$h_n(t) = \sum_{i=1}^{M_n}a_{i}\chi_{A_i}(t) \in H$$
where $a_i \in H$ and $A_i$ is disjoint subset of $[0,T]$ such that
$$\lVert h_n - h \rVert_{L^2(0,T;H)} \leq \epsilon.$$
Since $a_i \in H$ and $V$ is dense in $H$, there exist $b_i \in V$ such that $\lVert b_i - a_i \rVert_H \leq \frac{\epsilon}{M_n\sqrt{T}}$. Then define $$v(t) = \sum_{i}b_i\chi_{A_i}(t)$$
which is measurable (in the sense that its norm in $L^2(0,T;H)$ exists).
$$\lVert v - h \rVert_{L^2(0,T;H)} = \lVert v(t) - h_n + h_n - h(t) \rVert_{L^2(0,T;H)} \leq \sum_i \lVert (a_i - b_i)\chi_{A_i}\rVert_{L^2(0,T;H)} + \epsilon \leq 2\epsilon$$
Comment: That's almost it. I would choose $b_i \in V$ such that $\lVert b_i - a_i\rVert_H \lt \varepsilon/(M_n \cdot T)$ or something like that, in order to ensure that $\lVert v - h\rVert_H \lt 2 \varepsilon$. (Otherwise the product $M_n \cdot \varepsilon$ need not go to zero when you let $\varepsilon \to 0$.)
Comment: For short: that's dense by transitivity of density. Simple $V$ valued functions are dense in simple $H$ valued functions. And the latter are dense in $L^2$.
Comment: @julien Nice point.


Binomial Distribution and Random Variable

Question: John is blindfolded and shoots the ball towards the goal. You can assume that each time he
shoots there is a probability of 0.2 to score and that shots are independent of each other.
Every time he hits the target, John receives 2 points, and everytime he misses he loses 1 point. Compute the probability that after the four shots John will have  more than two points .
My approach:
The Sample space of getting more than two points are the following ways
Let $S$ be the event of scoring and Let $S'$ be the event of missing
${SSSS,SSSS',SSS'S,SS'SS,S'SSS}$
Independently calculated the probability of each event
$P(SSSS)=1/625$
$P(SSSS')=4/625$
$P(SSS'S)=4/625$
$P(SS'SS)=4/625$
$P(S'SSS)=4/625$
Hence the probability of getting more than 2 points is
$P(X>2)=17/625$
Is this correct way to get the solution and i know its the topic binomial distribution but can't figure out a way to draw the table
Answer: He is only shooting $(4)$ times, and his point total will be greater than $(2)$ if and only if he hits the target either all $(4)$ times, or $(3)$ out of $(4)$ times.
That is, hitting the target $(2)$ out of $(4)$ times results in a point total of $(2 \times 2) - (2 \times 1) = 2,$ which is to be regarded as not greater than $(2)$, and thus insufficient.
See Binomial Distribution,
specifically $\displaystyle \binom{n}{k}p^kq^{(n-k)}.$
Based on the discussion, and the cited article, the desired computation is
$$\left[\binom{4}{4}(0.2)^4 (0.8)^0\right] + \left[\binom{4}{3}(0.2)^3 (0.8)^1\right].$$


Auto cc addresses on inbound emails from certain addresses in Exchange 2010

Question: I am wanting to automatically add a cc address to any inbound emails that come from a specific address (which is external to the company).
I've had a quick look into Transport rules however I am unable to figure out how to do this.
Is anybody able to provide me with some assistance on this?
Answer: Transport rules are you only option, but adding in a CC isn't possible. The only options you have are to include a BCC or copy the message to another recipient.


Proof of proposition 5.3.1 of Ravi Vakil's notes on algebraic geometry

Question: I am reading the proof of proposition 5.3.1 of Ravi Vakil's notes on algebraic geometry, and I have a problem with the last sentence : "If $g' = g''/f^n$ ($g''\in A$) then $\textrm{Spec}((A_f)_{g'}) = \textrm{Spec} (A_{fg''})$, and we're done."
Noting $V = \textrm{Spec} (B)$ and $V' = \textrm{Spec} (B_g)$, and noting $D_Z (h)$ the distinguished affine open subset of an affine scheme $Z$ associated to a section $h\in\Gamma(Z,\mathcal{O}_Z)$, I understand perfectly that if we note $U' = \textrm{Spec} (A_f)$ then the inclusion $U'\subset V$ induces a morphism $f : \Gamma(V',\mathcal{O}_X)\to \Gamma(U',\mathcal{O}_X)$ and that if we note $\varphi$ the associated morphism of affine schemes then $\varphi^{-1}(V') = D_{U'}(g')$ where $g'$ is the image of $g$ by $f$, but as $\varphi$ is the the inclusion $V'\subset U'$, we have $\varphi^{-1}(V') = V'$ because $V'\subset U'$ so finally $V' = D_{U'}(g')$ and $V'$ is distinguished in $U'$. I guess that the last sentence of the proof is supposed to show that this $V'$ is also distinguished in $U$, but I don't understand why.
Answer: A first look on math.stackexchange could make think that this question has already various answers, but it is false : the most "complete" answer is this one :
Intersection of open affines can be covered by open sets distinguished in *both*affines
which nevertheless does not show the last bit, simply saying "hence in $U$" instead.
Lemma. (Transitivity of distinction.) Let $X$ be an affine scheme. If $U$ is a distinguished affine open subset of $X$ and if $V$ is a distinguished affine open subset of $V$ then $V$ is a distinguished affine open subset of $X$.
Proof. Note $ U = D_X (f)$ for some $f\in\Gamma(X,\mathscr{O}_X)$ and $V = D_U(g)$ for some $g\in\Gamma(U,\mathscr{O}_X)$. The inclusion $D_X (f)\subseteq X$ induces a morphism $\sigma : \Gamma(X,\mathcal{O}_X)\to\Gamma(D_X (f),\mathcal{O}_X)$ and as $\mathcal{O}_X$ is a sheaf, the image of $f$ by this morphism is invertible, so that the morphism induces a morphism $\varphi:\Gamma(X,\mathcal{O}_X)_{(f)}\to\Gamma(D_X (f),\mathcal{O}_X)$ which is in fact an isomorphism (see EGA I, chapitre I, proof of théeorème (1.3.7).) By the inverse of this isomorphism the element $g\in\Gamma(D_X (f),\mathcal{O}_X)$ corresponds to an element $h\in\Gamma(X,\mathcal{O}_X)_{(f)}$ that can be written $\frac{g''}{f^n}$ for some $g''\in\Gamma(X,\mathcal{O}_X)$ and some $n\in\mathbf{N}$. Note that this is equivalent to the equality $$(\ast) \;\;\sigma(f)^n g = \sigma(g'')$$ taking place in $\Gamma(D_X (f),\mathscr{O}_X)$. Now, we have $D_{U}(g) = D_{X}(g''f)$. Indeed, take $x\in D_{X}(g''f)$ so that $(g''f)(x)\not=0$, that is, $g''(x)f(x)\not=0$, which implies (as after all $x$ corresponds to a prime ideal of $\Gamma(X,\mathcal{O}_X)$) that $f(x)\not=0$ so that $x\in U$, and that $g''(x)\not=0$. Now localizing $(\ast)$ at $x$ gives $\sigma(f)(x)^n g(x) = \sigma(g'')(x)$ which is the same as $f(x)^n g(x) = g''(x)$ which implies that $g(x)\not=0$ which implies that $x\in D_{U}(g)$, and $D_{U}(g''f)\subseteq D_{U}(g)$. Using $(\ast)$ allows also to show the opposite inclusion, and concludes the proof. $\square$
Proposition. Let $X$ be a scheme, and $U,V$ be affine open subsets of $X$. Then $U\cap V$ is union of affine open subsets of $X$ that are distinguished affine open subsets of $U$ and of $V$ simultaneously.
Proof. If $U\cap V=\varnothing$ we have $U\cap V = D_U (1) = D_V(1)$ so we may assume $U\cap V \not=\varnothing$. To conclude it suffices to prove that each point of $U\cap V$ has a neighbourhood in $U\cap V$ which is a distinguished affine open of $U$ and $V$ simultaneously. Take $x\in U\cap V$. As $U\cap V$ is open in $U$ and as distinguished affine open subset of $U$ form a basis of $U$'s topology one can find an $f\in\Gamma(U,\mathscr{O}_X)$ such that $x\in U' := D_U (f) \subseteq U\cap V$. As $U\cap V$ is open in $V$ the set $U'$ is open in $V$ and as distinguished affine open subset of $V$ form a basis of $V$'s topology one can find a $g\in\Gamma(V,\mathscr{O}_X)$ such that $x\in V' := D_V (g) \subseteq U'$. By construction $V'$ is a distinguished affine open subset of $V$, so to conclude it suffices to show that it is a distinguished affine open subset of $U$. The inclusion $V'\subseteq U'$ induces a morphism of rings $\rho : \Gamma(U',\mathscr{O}_X)\to\Gamma(V',\mathscr{O}_X)$. Noting $g'$ the image of $g$ by $\rho$, EGA I, (126.96.36.199) ensures that $({}^a \rho)^{-1}(V') = D_{U'} (g')$ where ${}^a \rho$ is the (affine) schemes morphism associated to $\rho$ , that is, that $V' = U'\cap V' = D_{U'} (g')$, as ${}^a \rho$ is but the inclusion $V'\subseteq U'$, and the lemma concludes the proof. $\square$
Remark. Of course, building up intuition about such arguments allows to understand more easily the proof you are quoting, and allows to write less verbose proofs.


404 Not found: Could not find the controller

Question: I am creating a resource for service module
function noteresource_services_resources() {
  return array(
    'note' => array(
      'retrieve' => array(
        'help' => 'Retrieves a note',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_retrieve',
        'access callback' => '_noteresource_access',
        'access arguments' => array('view'),
        'access arguments append' => TRUE,
        'args' => array(
          array(
            'name' => 'id',
            'type' => 'int',
            'description' => 'The id of the note to get',
            'source' => array('path' => '0'),
            'optional' => FALSE,
          ),
        ),
      ),
      'create' => array(
        'help' => 'Creates a note',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_create',
        'access arguments' => array('note resource create'),
        'access arguments append' => FALSE,
        'args' => array(
          array(
            'name' => 'data',
            'type' => 'struct',
            'description' => 'The note object',
            'source' => 'data',
            'optional' => FALSE,
          ),
        ),
      ),
      'update' => array(
        'help' => 'Updates a note',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_update',
        'access callback' => '_noteresource_access',
        'access arguments' => array('update'),
        'access arguments append' => TRUE,
        'args' => array(
          array(
            'name' => 'id',
            'type' => 'int',
            'description' => 'The id of the node to update',
            'source' => array('path' => '0'),
            'optional' => FALSE,
          ),
          array(
            'name' => 'data',
            'type' => 'struct',
            'description' => 'The note data object',
            'source' => 'data',
            'optional' => FALSE,
          ),
        ),
      ),
      'delete' => array(
        'help' => 'Deletes a note',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_delete',
        'access callback' => '_noteresource_access',
        'access arguments' => array('delete'),
        'access arguments append' => TRUE,
        'args' => array(
          array(
            'name' => 'nid',
            'type' => 'int',
            'description' => 'The id of the note to delete',
            'source' => array('path' => '0'),
            'optional' => FALSE,
          ),
        ),
      ),
      'index' => array(
        'help' => 'Retrieves a listing of notes',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_index',
        'access callback' => 'user_access',
        'access arguments' => array('access content'),
        'access arguments append' => FALSE,
        'args' => array(
          array(
            'name' => 'page',
            'type' => 'int',
            'description' => '',
            'source' => array(
              'param' => 'page',
            ),
            'optional' => TRUE,
            'default value' => 0,
          ),
          array(
           'name' => 'parameters',
           'type' => 'array',
           'description' => '',
           'source' => 'param',
           'optional' => TRUE,
           'default value' => array(),
          ),
        ),
      ),
    ),
  );
}

Which is created sucessfully.
Now I have also created a function _noteresource_create($data) { echo "hello"; exit;} under inc file.
Now when I am accesing resouce as websitename/endpoint/resource/create
and via Post and passing variable it gives me error:
Response does not contain any data.
And:

Under Status 404 Not found: Could not find the controller.

Does anybody can tell me how to fix this issue?
Comment: On the endpoint settings, what is the path that is on the "Path to endpoint" field?
Answer: Added actions in create resource where POST method is using. I hope it would work for you.
function noteresource_services_resources() {
  return array(
    'note' => array(
      'retrieve' => array(
        'help' => 'Retrieves a note',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_retrieve',
        'access callback' => '_noteresource_access',
        'access arguments' => array('view'),
        'access arguments append' => TRUE,
        'args' => array(
          array(
            'name' => 'id',
            'type' => 'int',
            'description' => 'The id of the note to get',
            'source' => array('path' => '0'),
            'optional' => FALSE,
          ),
        ),
      ),
      'actions' => array(
          'create' => array(
            'help' => 'Creates a note',
            'file' => array('file' => 'inc', 'module' => 'noteresource'),
            'callback' => '_noteresource_create',
            'access arguments' => array('note resource create'),
            'access arguments append' => FALSE,
            'args' => array(
              array(
                'name' => 'data',
                'type' => 'struct',
                'description' => 'The note object',
                'source' => 'data',
                'optional' => FALSE,
              ),
            ),
          ),
      ),
      'update' => array(
        'help' => 'Updates a note',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_update',
        'access callback' => '_noteresource_access',
        'access arguments' => array('update'),
        'access arguments append' => TRUE,
        'args' => array(
          array(
            'name' => 'id',
            'type' => 'int',
            'description' => 'The id of the node to update',
            'source' => array('path' => '0'),
            'optional' => FALSE,
          ),
          array(
            'name' => 'data',
            'type' => 'struct',
            'description' => 'The note data object',
            'source' => 'data',
            'optional' => FALSE,
          ),
        ),
      ),
      'delete' => array(
        'help' => 'Deletes a note',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_delete',
        'access callback' => '_noteresource_access',
        'access arguments' => array('delete'),
        'access arguments append' => TRUE,
        'args' => array(
          array(
            'name' => 'nid',
            'type' => 'int',
            'description' => 'The id of the note to delete',
            'source' => array('path' => '0'),
            'optional' => FALSE,
          ),
        ),
      ),
      'index' => array(
        'help' => 'Retrieves a listing of notes',
        'file' => array('file' => 'inc', 'module' => 'noteresource'),
        'callback' => '_noteresource_index',
        'access callback' => 'user_access',
        'access arguments' => array('access content'),
        'access arguments append' => FALSE,
        'args' => array(
          array(
            'name' => 'page',
            'type' => 'int',
            'description' => '',
            'source' => array(
              'param' => 'page',
            ),
            'optional' => TRUE,
            'default value' => 0,
          ),
          array(
           'name' => 'parameters',
           'type' => 'array',
           'description' => '',
           'source' => 'param',
           'optional' => TRUE,
           'default value' => array(),
          ),
        ),
      ),
    ),
  );
}


Como exibir dados de um arquivo serializado em Java?

Question: Estou iniciando em Java e preciso fazer um sistema que cadastra alunos e salva os dados desses alunos em um arquivo serializado.
Eu até consigo criar e salvar os dados no arquivo serializado (acho rsrs) mas não sei como exibir todos esses dados na tela (posteriormente precisarei deletar e editar esses dados salvos mas no momento quero focar só em exibi-los).
Alguém poderia me ajudar com esse problema?
Irei exibir os dados em uma JTable.
Classe Estudante onde ele adiciona
public class Estudante implements Serializable {

    private String id;
    private String nome;
    private String sexo;
    private String dataNasc;
    private String rg;
    private String cpf;
    private String celular;
    private String telefone;
    private String email;
    private String end;
    private String bairro;
    private String cidade;
    private String cep;
    private String uf;
    private String num;

    public String getId() { //retorna o id
        return id;
    }

    public void setId(String id) { //recebe o id
        this.id = id;
    }

    public String getNome() { //retorna o nome
        return nome;
    }

    public void setNome(String nome) { //recebe o nome
        this.nome = nome;
    }

    public String getSexo() { //retorna o sexo
        return sexo;
    }

    public void setSexo(String sexo) { //recebe o sexo
        this.sexo = sexo;
    }

    public String getDataNasc() { //retorna a data de nascimento
        return dataNasc;
    }

    public void setDataNasc(String dataNasc) { //recebe a data de nascimento
        this.dataNasc = dataNasc;
    }

    public String getRg() { //retorna o rg
        return rg;
    }

    public void setRg(String rg) { //recebe o rg
        this.rg = rg;
    }

    public String getCpf() { //retorna o cpf
        return cpf;
    }

    public void setCpf(String cpf) { //recebe o cpf
        this.cpf = cpf;
    }

    public String getCelular() { //retorna o celular
        return celular;
    }

    public void setCelular(String celular) { //recebe o celular
        this.celular = celular;
    }

    public String getTelefone() { //retorna o telefone
        return telefone;
    }

    public void setTelefone(String telefone) { //recebe o telefone
        this.telefone = telefone;
    }

    public String getEmail() { //retorna o email
        return email;
    }

    public void setEmail(String email) { //recebe o email
        this.email = email;
    }

    public String getEnd() { //retorna o endereço
        return end;
    }

    public void setEnd(String end) { //recebe o endereço
        this.end = end;
    }

    public String getBairro() { //retorna o bairro
        return bairro;
    }

    public void setBairro(String bairro) { //recebe o bairro
        this.bairro = bairro;
    }

    public String getCidade() { //retorna a cidade
        return cidade;
    }

    public void setCidade(String cidade) { //recebe a cidade
        this.cidade = cidade;
    }

    public String getCep() { //retorna o cep
        return cep;
    }

    public void setCep(String cep) { //recebe o cep
        this.cep = cep;
    }

    public String getUf() { //retorna o uf
        return uf;
    }

    public void setUf(String uf) { //recebe o uf
        this.uf = uf;
    }

    public String getNum() { //retorna o numero
        return num;
    }

    public void setNum(String num) { //recebe o numero
        this.num = num;
    }
}

Classe Clientes onde adiciona e exibe os estudantes
public class Clientes implements Serializable {

    public boolean adiciona(Estudante estudante) {
         try {
             FileOutputStream saveFile = new FileOutputStream("estudantes.txt", true);
             ObjectOutputStream stream = new ObjectOutputStream(saveFile);

              // salva o objeto
             stream.writeObject(estudante);
             stream.writeObject(System.getProperty ("line.separator"));

             saveFile.close();
             stream.close();

             return true;
           } catch (Exception exc) {
             exc.printStackTrace();
           }

         return false;
    }

    public void exibe(){
        Estudante estudantes = null;

        try{
            FileInputStream fin = new FileInputStream("estudantes.txt");
            ObjectInputStream ois = new ObjectInputStream(fin);

            estudantes = (Estudante) ois.readObject();

            //System.out.println(estudantes.getNome());

            ois.close();

       }catch(Exception ex){
        ex.printStackTrace();
       }
   }
}

Tela principal que recebe os dados
  String nome = edtNome.getText(); //variavel 'nome' recebe o que estiver no campo de texto Edit
  String sexo = (String) edtSexo.getSelectedItem(); //variavel 'sexo' recebe o que estiver no campo de texto Edit
  String dataNasc = edtdataNasc.getText(); //variavel 'dataNasc' recebe o que estiver no campo de texto Edit
  String cpf = edtCpf.getText(); //variavel 'cpf' recebe o que estiver no campo de texto Edit
  String rg = edtRg.getText(); //variavel 'rg' recebe o que estiver no campo de texto Edit
  String celular = edtCelular.getText(); //variavel 'celular' recebe o que estiver no campo de texto Edit
  String telefone = edtTelefone.getText(); //variavel 'telefone' recebe o que estiver no campo de texto Edit
  String email = edtEmail.getText(); //variavel 'email' recebe o que estiver no campo de texto Edit
  String end = edtEnd.getText(); //variavel 'end' recebe o que estiver no campo de texto Edit
  String bairro = edtBairro.getText(); //variavel 'bairro' recebe o que estiver no campo de texto Edit
  String cidade = edtCidade.getText(); //variavel 'cidade' recebe o que estiver no campo de texto Edit
  String cep = edtCep.getText(); //variavel 'cep' recebe o que estiver no campo de texto Edit
  String uf = (String) edtUf.getSelectedItem(); //variavel 'uf' recebe o que estiver no campo de texto Edit
  String num = edtNum.getText(); //variavel 'num' recebe o que estiver no campo de texto Edit

  estudante.setId(id);
  estudante.setBairro(bairro); //envia a variavel 'bairro' para o respectivo set da classe Estudante
  estudante.setCelular(celular); //envia a variavel 'celular' para o respectivo set da classe Estudante
  estudante.setCep(cep); //envia a variavel 'cep' para o respectivo set da classe Estudante
  estudante.setNome(nome); //envia a variavel 'nome' para o respectivo set da classe Estudante
  estudante.setSexo(sexo); //envia a variavel 'sexo' para o respectivo set da classe Estudante
  estudante.setCidade(cidade); //envia a variavel 'cidade' para o respectivo set da classe Estudante
  estudante.setDataNasc(dataNasc); //envia a variavel 'dataNasc' para o respectivo set da classe Estudante
  estudante.setCpf(cpf); //envia a variavel 'cpf' para o respectivo set da classe Estudante
  estudante.setEmail(email); //envia a variavel 'email' para o respectivo set da classe Estudante
  estudante.setRg(rg); //envia a variavel 'rg' para o respectivo set da classe Estudante
  estudante.setEnd(end); //envia a variavel 'end' para o respectivo set da classe Estudante
  estudante.setUf(uf); //envia a variavel 'uf' para o respectivo set da classe Estudante
  estudante.setTelefone(telefone); //envia a variavel 'telefone' para o respectivo set da classe Estudante
  estudante.setNum(num); //envia a variavel 'nm' para o respectivo set da classe Estudante

  Clientes cliente = new Clientes();

  if(cliente.adiciona(estudante)==true){ //chama o método addEstudante da classe Estudante
    JOptionPane.showMessageDialog(null,"Estudante cadastrado com sucesso!");
  }
} catch (Exception ex){
  JOptionPane.showMessageDialog(null,"Erro ao cadastrar o estudante!");
  Logger.getLogger(cadEstudante.class.getName()).log(Level.SEVERE, null, ex); //retorna erro
}

Answer: Olá Amigo se voce serializou o objeto e o persistiu em um arquivo ou em um banco de dados em um array de bytes, o correto que para que ele seja visualizado precisa ser desserializado. A abaixo vou colocar a forma que utilizo para realizar esta duas tarefas e eu recomendo que use o try-resources para que os recursos sejam devidamente fechados sem dor de cabeça nem preocupação.
Serialização:
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(baos)){

         oos.writeObject(instancia);
         byte [] arquivoSerializado = baos.toByteArray();

    } catch (IOException ex) {
        ex.printStackTrace();
    }

Diferente do seu o meu eu persisto em um banco de dados por isso o transformo em um array de bytes.
Desserialização:
    try (ByteArrayInputStream bais = new ByteArrayInputStream(registro_logs.getObjeto().getObjeto());
            ObjectInputStream ois = new ObjectInputStream(bais)) {

        TransportadoraContainer container = (TransportadoraContainer) ois.readObject();

    } catch (IOException | ClassNotFoundException | Relatorio_Exception ex) {
        LOG.error(ex);
    } catch (NullPointerException exception) {
        Utils.painelDeMensagens("Não Existe Arquivo para este log", JOptionPane.WARNING_MESSAGE);
    }

Depois que o objeto foi desserializado eu o atribuo a variavel container e a partir daqui e so usar o objeto como eu precisar.


Campo de busca com php e mysql. Como não diferenciar caracteres especiais?

Question: Estou tendo um problema com um campo de busca em um site em php com banco MySql.
Tenho um registro no banco como "SIFÃO" e quando faço a busca como sifão, sifao ou SIFAO não retorna esse registro. Eu gostaria que não fizesse diferenciação de maiúsculas/minúsculas e caracteres especiais.
A tabela e os registros já estão convertidos para latin1 e estou usando essa colação na query, como podem ver no código abaixo. Nem assim está dando certo.
Segue o código:
  $texto = mysqli_real_escape_string($conn, $_POST['texto']);
  $result = mysqli_query($conn, "SELECT DISTINCT
  produtos.id as id,
  produtos.nome as nome,
  produtos.descricao as descricao,
  produtos.tags as tags,
  produtos.url as url,
  ambientes.url as AmbienteUrl,
  categorias.url as CategoriaUrl,
  imagens.arquivo as ImagemArquivo
  FROM produtos
      INNER JOIN prod_amb ON prod_amb.produto_id = produtos.id
      INNER JOIN ambientes ON ambientes.id = prod_amb.ambiente_id
      INNER JOIN categorias ON categorias.id = produtos.categoria_id
      INNER JOIN imagens ON imagens.produto_id = produtos.id
  WHERE (produtos.nome LIKE '%".$texto."%' collate latin1_swedish_ci
  OR produtos.descricao LIKE '%".$texto."%' collate latin1_swedish_ci
  OR produtos.tags LIKE '%".$texto."%' collate latin1_swedish_ci)
  AND produtos.situacao = 1
  AND imagens.principal = 1
  GROUP BY produtos.id");

  while ($row = mysqli_fetch_assoc($result)) {
     echo $row['nome'];
  }

Answer: Cara, uma solução seria na query você converter tudo pra maiúsculo, ou pra minusculo, por exemplo:
SELECT * FROM produto WHERE nome = UPPER('nomeProduto')
a função UPPER() transforma o argumento passado pra maiúsculo, a função LOWER() transforma em manúsculo. No seu caso acho que daria pra fazer assim:
...WHERE (produtos.nome LIKE UPPER('%".$texto."%')...
Quanto aos acentos (ã, à, á) eu só vejo uma forma que seria fazendo uma função que removesse esses acentos dos caracteres, quando eu mechia com PHP não conhecia nada que fizesse isso automático, hoje pode ser que já exista.
Answer: Complementando a resposta do @Victor Hartur de Carvalho
uma função simples para remover os caracteres especiais:
function cleanStr($str)
{
    return preg_replace("/[^a-zA -Z0-9_.]/", "", strtr($str, "ÁÍÓÚÉÄÏÖÜËÀÌÒÙÈÃÕÂÎÔÛÊáíóúéäïöüëàìòùèãõâîôûêÇç",
                                                             "AIOUEAIOUEAIOUEAOAIOUEaioueaioueaioueaoaioueCc"));
}

Answer: É preciso converter em minúsculas (ou maiúsculas), os dados do banco e as variáveis, antes de fazer a comparação:
WHERE (LOWER(produtos.nome) LIKE LOWER('%".$texto."%') collate latin1_swedish_ci
OR LOWER(produtos.descricao) LIKE LOWER('%".$texto."%') collate latin1_swedish_ci
OR LOWER(produtos.tags) LIKE LOWER('%".$texto."%') collate latin1_swedish_ci)

Comment: Por favor, colabore com a qualidade do conteúdo da comunidade elaborando melhor sua resposta. Respostas muito curtas dificilmente serão suficientemente claras para acrescentar algo à discussão. Se sua resposta é baseada em alguma função ou característica da linguagem/ferramenta, faça a ligação com a documentação oficial ou material confiável que sustente sua resposta. Buscar perguntas semelhantes na comunidade também pode ser interessante para indicar outras abordagens do problema.


flex cannot open file in sh script

Question: I use flex on cygwin package for Windows to build lexical analyzer.
I created file test.lex with rules
When i use this commands in command line
flex -i test.lex
cc lex.yy.c -lfl
./a

It works fine. But when i tried to make sh file (compile_flex.sh) with this commands and run file
./compile_flex.sh

I received error
flex: can't open test.lex

I tried to put different paths to my file
~/test.lex
/home/user/test.lex
c:\\cygwin64\\home\\user\\test.lex

But it doesn't work! I always receive message that file not found.
When I put command
vi test.lex

In my .sh file it works good and file is opened in vim
Answer: I figured out with my problem. I use windows editor (notepad++) for create .sh file. When I changed line separator from \n\r to \n in preferences, it was working fine

flex cannot open file in sh script


Divide a space equally for each element

Question: Is there any way to divide a space (or div) equally for each element without specify a an absolute value for width. JUST to make the CSS code flexible.
For example if you put these element into a div:

The CSS will automatically give each .child element width=50%
And in this example:

The CSS will also automatically give each .child element width=25%
Is it possible?
Comment: heh... probably not the answer you're looking for, but yeah. tables.
Comment: You want all `.child` to be in the same line?
Comment: @KaiQing You gave me an idea. I'll try to prove it first. Thanks.
Answer: You have to use tables I'm afraid and add a wrap for the child divs, you can do it like so:
#parent{
width: 1000px; /* Example width */
height: 100px; /* Example height */
display: table;
table-layout: fixed;
}
.childwrap {
display:table-row;
}
.child{
display: table-cell;
}

Example: http://cssdesk.com/rZKRW
Answer: You can use jQuery code below:
var childs = $('#parent .child')
    ,width = Math.floor(100/childs.length);
childs.css('width',width+'%');

Comment: Thank you, but I would prefer if I found a way in CSS.
Answer: You sure can. Just apply a value with the required percent to the width property and be sure to apply a defined with to their parents. Thas all.
.child {
with:50%;
}

or for your 4 children...
.child {
 width:25%;
}

For this to work among other details the ancestor width must be specified. If the ancestor width depends on the children contents then there is a chance to hava an uncomputed width.
If your ancestor div itself hava a porcentual value, then it will be required that its ancestor to have a defined with and so on..
Comment: The question was if there is a way to have the child percent automatically derived from the number of children.
Comment: Thanks for your try, but I don't wanna specify an exact value.

Divide a space equally for each element


Query cannot be parsed, please check the syntax of your query

Question: I have an error in my SQL syntax "Query cannot be parsed, please check the syntax of your query. (ORA-00904: "RENTED": invalid identifier)". How to solve this problem??
SELECT area,
       status,
       price_le,
       location

from stores
WHERE status = rented
ORDER BY location;

Answer: Unless you have an actual table field called rented that you want to compare to, you'll need to single quote it to have it be a string;
SELECT area, status, price_le, location
FROM stores WHERE status = 'rented' ORDER BY location;

Comment: @user3609435 - please remember to [up-vote useful answers and accept the best solution](http://stackoverflow.com/help/someone-answers). Read more [on meta](http://meta.stackoverflow.com/q/251078/266304). Of course all three current answers say much the same thing so you'd need to pick one to be the 'best', which is entirely up to you; but this one was right first...
Answer: Without knowing more about your database schema - I assume you intended to test status against the string 'rented' in your where clause. To do that you need to surround rented in single quotes.
SELECT area, status, price_le, location
FROM stores WHERE status = 'rented'
ORDER BY location;

Comment: Single quotes for a string literal; you're trying to compare it to a (mixed-case, quoted) identifier, not a string value. This will get the same error.
Answer: Try this
SELECT area, status, price_le, location
FROM stores WHERE status = 'rented' ORDER BY location;


Two partial fraction approaches, one is wrong, the other is right, why?

Question: I want to do a partial fraction on
\begin{equation}
\frac{z}{(z-4)(z+\frac{1}{2})}
\end{equation}
Method one, which apparently is wrong:
\begin{equation}
\frac{z}{(z-4)(z+\frac{1}{2})}=\frac{A}{z-4}+\frac{B}{z+\frac{1}{2}}
\end{equation}
\begin{array}
f A(z+\frac{1}{2})+B(z-4)=Az+\frac{1}{2}A+Bz-4B ;\\
Az+Bz=z \rightarrow A=1-B\\
\frac{1}{2}A-4B=0 \rightarrow A-8B=0 \\
A=\frac{8}{9}, B=\frac{1}{9}
\end{array}
which gives
\begin{equation}
\frac{8}{9}\frac{1}{z-4}+\frac{1}{9}\frac{1}{z+\frac{1}{2}}
\end{equation}
Then , the second method which is a reference from an exam correction, which is deemed right, disregards for the existence of z in the numerator at first:
\begin{equation}
\frac{1}{(z-4)(z+\frac{1}{2})}=\frac{A}{z-4}+\frac{B}{z+\frac{1}{2}}
\end{equation}
\begin{array}
f A(z+\frac{1}{2})+B(z-4)=Az+\frac{1}{2}A+Bz-4B ;\\
Az+Bz=0 \rightarrow A=-B\\
\frac{1}{2}A-4B=1 \rightarrow B=-1/4 + A/8 \\
A=\frac{2}{9}, B=-\frac{2}{9}
\end{array}
Then at the end, the author inserts z back in the numerator, obtaining:
\begin{equation}
\frac{2}{9}\frac{z}{z-4}-\frac{2}{9}\frac{z}{z+\frac{1}{2}}
\end{equation}
So why was the former wrong, when it follows all the rules of partial fractions? And why is the second right, when z is not included in the partial fraction decomposition?
Thanks
Comment: Why do you say the first method is wrong? It is right!
Comment: What does "apparently right" mean? Do you have a citation?
Comment: Note the correction at the end, regarding importing z back in the numerator. This is a Professors method at a University.
Comment: Thanks! I will check this up with the reference.
Comment: Whoever did the second method missed the boat completely. If you want to integrate $\dfrac z{z-4}$, you must now write $$\frac z{z-4} = \frac{z-4+4}{z-4} = 1 + \frac 4{z-4},$$ etc. Note this will give *your* correct answer when you do it all.
Comment: I checked with the Prof, and it was done as such, because the aim of this is to findthe z transforms of the original function.
Answer: Both methods are algebraically correct. That is, both methods yield new functions that are the same as the original function.
Your method is the correct way to carry out the partial fraction decomposition algorithm. Moreover, your method results in the outcome desired from the partial fraction algorithm—a sum of rational functions, each of which has a denominator with a single distinct irreducible factor, and a numerator whose degree is less than the degree of the irreducible factor in its denominator. The professor's method yields a result without this last property.
(The reason we want this last property, in a calculus context at least, is that there are standard and often immediate methods for integrating that type of rational function, whereas a function like $\frac z{z-4}$ still requires further algebraic preprocessing to be integrated.)
Comment: Understood. I will use the method I used, and multiply  the z to the fraction at the end to find the right z transform from the table.


Summing cotangent pairs

Question: I've stumbled across an identity that I think holds, but can't prove it. The identity is:
$$
\sum_{i=1}^{N} \cot(\phi_i - \phi_{i+1}) \cot(\phi_i - \phi_{i-1}) = -1
$$
The angles $\phi_i$ are some arbitrary set of angles, with the only constraint being that $\phi_i - \phi_{i+1}$ does not equal $0$ or $\pi$. Addition of the indices is modular, so that $\phi_{N+1} = \phi_{1}$.
The formula comes from some normalisation conditions in quantum mechanics, and it arose while checking a result that I've derived otherwise, which is my reason for believing it stands. It can be shown straightforwardly using Hermite's cotangent identity if $N=3$, but I'm unable to generalise further.
Any ideas? Thanks for your help.
Comment: It doesn't hold for $N\neq 3$.
Comment: Did you check this in Mathematica? I'll check the origin calculation where this came up and maybe see what the result is for N=4
Comment: Did *you* check it? For $N=4$ and $\phi_i=i\pi/4$, the sum is equal to $\color{red}{-4}$.
Comment: Sorry, I phrased badly. I meant to say "did you get the result that it doesn't hold in general using mathematica". I looked at the original calculation and there's an assumption in jumping to the N>3 case that maybe doesn't hold, but I still think the LHS series will be needed at some point... I'll investigate. Thanks for your help.
Comment: Have you tried to see what you get for $N=2$ yet? Both terms of the sum on the left side are equal.
Answer: https://en.wikipedia.org/wiki/Hermite%27s_cotangent_identity
Does this Wikipedia article answer your question?
Comment: I can use that for N=3, but not for higher N

Summing cotangent pairs


Should I be concerned about wires showing at the side of one of my pickups?

Question: My new guitar arrived today. It's a Squier Classic Vibe 70s HSS. I noticed some wires are showing at the side of one of the pickups. Is this something I should be concerned about?
Not sure I want to go through the hassle of getting it replaced as it seems it's out of stock now, and I've been waiting to get this guitar for a long time. I ordered it online.
I'd love some advice. I was thinking about using a pointy blunt object to push the wires in, but I don't want to ruin the guitar.
Comment: I wouldn't use a pouty blunt object to push the wires. If it was me I'd leave it as long as it is working and the wires aren't in the way or in danger of being damaged. If they are in the way or in danger take it to a guitar shop to have them look at it, preferable the shop you bought it at.
Comment: @b3ko - it's by design. You can see the solder tags.
Answer: This is absolutely not a problem, unless you object to the cosmetic appearance.
Some pickups have that extra loop there to add extra relief to lower the risk of snapping the wires when removing/replacing pickups. If you pop the back off or remove strings and pop the pickup out, you may be able to reroute the wires if you want to.
Or you could get some black paint or a black marker pen and colour them :-)
Answer: Leave it alone - you'll probably break something.
They're meant to be like that.
Basically, that's where the coil wires are tagged onto the thicker wires needed to carry the signal off to the volume & tone pots. The short loops you can see are where the thicker wires are dropped through the pickup base to provide a stronger structure, strain relief when the pickups are handled.
Strat pickups, at their most basic, are… basic.
Sometimes they have covers, sometimes not. Yours don't, they're an open design.
On 'standard' single coil designs the tags are usually at the side, not the end, and are hidden by the scratch plate. On a covered humbucker design, they would be hidden by the cover. On an open design you can see them - though amusingly they always seem to be out of sight, round the corner, on advertising photos.
See this Guitar Centre page for just how many different variants there are.
Answer: Personally, seeing the wires wouldn't particularly concern me - other pics I can find online of similar models (1,2) seem to also show a cheeky bit of wire peeping out.

I was thinking about using a pointy blunt object to push the wires in

I wouldn't do that. If it's something that you find particularly offputting in terms of presentation, you might want to reconsider whether this is the guitar for you! Not all pickups have the wires visible in this way.


Aurelia @children with dynamic data

Question: Suppose I have a custom element in which I iterate over an array of data and render custom subelements.
<my-list action-handler.bind="actionHandler">
  <my-element item.bind="element" repeat.for="element of data"></my-element>
</my-list>

In my-list.html I render the contents with <contents></contents> and in general the real code is a bit more complex and has replaceable template parts, but that's not the problem.
I want the actionHandler that I bind to MyList to be available in all of the children. For the sake of elegancy, we did this in my-list.js:
@children('*:not(div)') listItems;

//...
attached(){
    this.listItems.forEach((e) => {
        e.actionHandler = this.actionHandler;
    });
}

And everything worked just fine until we started to load data dynamically. In this case listItems is empty since the element is initialized before the child elements re-rendered.
So, the question is:
How would I make @children be re-calculated?
I understand that we could bind the actionHandler to all children when we were repeating over them, but this would start to look really ugly when we add some more logic like
Thanks!
Answer: If <my-element> has a dependency on it's parent <my-list> element's actionHandler, you can express that declaratively and let Aurelia's dependency injection system do the rest.  Here's a couple of ways to do that...
If <my-element> will always be within a <my-list> (doesn't necessarily need to be directly within):
import {inject} from 'aurelia-dependency-injection';

@inject(MyList)
export class MyElement {
  constructor(list) {
    this.actionHandler = list.actionHandler;
  }
}

If you need access <my-element>'s closest parent custom element, regardless of what it is:
import {inject, Parent} from 'aurelia-dependency-injection';

@inject(Parent.of(Element))
export class MyElement {
  constructor(parent) {
    this.actionHandler = parent.actionHandler;
  }
}

I know this wasn't exactly what you were asking but I'm proposing this in case it's a simpler way to meet your requirements.
Answer: The Aurelia Cheat Sheet is telling that:

@children(selector) - Decorates a property to create an array on your class that has its items automatically synchronized based on a query selector against the element's immediate child content.

so i guess it is not possible to use @children with dynamic data.
You might should go with the Parent approach, like the previous answer is suggesting.

Aurelia @children with dynamic data


Como exibir elementos HTML em um TextView do Android?

Question: Estou desenvolvendo uma Api que retorna alguns textos, porém esses textos tem tag HTML, seja negrito  ou linha
 gostaria de saber qual seria a melhor forma de imprimir isso em um TextView, ou se eu devo arrumar o texto antes de enviar para a API.
Lembrando que eu tenho o controle da API e do cliente
Comment: Veja se lhe ajuda: http://pt.stackoverflow.com/questions/191586/como-colocar-quebra-de-linha-no-textview-direto-do-xml/191595#191595
Comment: Relacionado: [Como formatar o texto num TextView](http://pt.stackoverflow.com/q/166114/2541)
Answer:
[...]gostaria de saber qual seria a melhor forma de imprimir isso[...]

Quanto a melhor forma, isso vai de sua necessidade. Não tem nenhum problema em definir um texto HTML dentro do seu TextView. Seria basicamente desta forma:
String htmlJsonText = "
Titulo

Descrição here
";
textViewHTML.setText(Html.fromHtml(htmlJsonText));

Veja mais detalhes na documentação sobre a classe HTML.


What is the sum of a geometric series indexed from $m>0$?

Question: I know how to calculate the sum of the geometric series given the base is $|x|<1.$
But how would I calculate something like $$\sum_{n=m}^{\infty}(1/2)^n$$
If it was from zero to infinity, the answer would be $2$ because $1/(1-0.5)=2$.
Answer: Note that $$\sum _{ n=m }^{ \infty  } (1/2)^{ n }=\frac { 1 }{ { 2 }^{ m } } +\frac { 1 }{ { 2 }^{ m+1 } } +...=\frac { 1 }{ { 2 }^{ m } } \left( 1+\frac { 1 }{ 2 } +... \right) =\frac { 1 }{ { 2 }^{ m } } \frac { 1 }{ 1-\frac { 1 }{ 2 }  } =\frac { 1 }{ { 2 }^{ m-1 } } $$
Comment: so obvious. I can't believe I missed that
Answer: A slightly different approach is to split up your sum into known sums.  First notice the sum you're interested in is:
$$ \sum_{n=m}^\infty \frac{1}{2^n} = \sum_{n=0}^\infty \frac{1}{2^n}-\sum_{n=0}^m \frac{1}{2^n}$$  The first sum is just a geometric series, the other is just a finite geometric series which is also well know see here:
http://mathworld.wolfram.com/GeometricSeries.html
So we have $$\sum_{n=m}^\infty \frac{1}{2^n} = 2-\frac{1-(\frac{1}{2})^m}{1-\frac{1}{2}}=2^{1-m}$$  which is precisely what @Battani got as well.
Answer: It may be worthwhile to think of the geometric series formula without the indices:  If $|r|<1$, then $$a+ar+ar^2+\cdots=\dfrac{a}{1-r}=\frac{\text{first term}}{1-\text{ratio}}.$$
You can recognize a geometric series whenever you multiply by the same number to go from one term to the next, and that is your "$r$" (the ratio of successive terms).  Regardless of how you are indexing, the "$a$" is just the first term.  In your case, $a=\dfrac{1}{2^m}$.


Log into my MediaWiki site when specific users are logged into my website on a different server

Question: I have a ASP.NET/C# website using IIS that when a user logs in successfully (Using login control and checking oracle table for user info) I create a session variable that lets the site know the user is authenticated.  I have also created a Wiki site using Media Wiki which I have hosted on a different web server.  I'm going to link to the Wiki from my main website where the user logged in.
What I need to do is when a specific users log into my main site I want them to be logged into my Wiki site as well when they navigate to that page.  I want them to be able to edit the Wiki without having to log in again.
This will only be for a handful of people that will be flagged in my user table on my main site and already have user accounts on my Wiki site.  What would be the best approach?
I did read the information on the Media Wiki website and it wasn't helpful for IIS and how to set it up.  For MediaWiki to know what user I want to have be logged in to I have to manually set the remote_user enviroment variable or can I tell MediaWiki to look for my session variable value?
Comment: Looks like you're looking for a "single sign-on" mechanism. There's a whole bunch of ways you could implement this which would be beyond the scope of an answer on StackOverflow. Here's some implementations that might help: https://en.wikipedia.org/wiki/List_of_single_sign-on_implementations. You could bodge a mechanism into MediaWiki kinda along the lines of what I did once before with a product called "ScrewTurn" wiki: https://stackoverflow.com/a/6088373
Comment: These MediaWiki extensions might also help: https://www.mediawiki.org/wiki/Category%3aUser_identity_extensions
Comment: Thank you, Kev I will look into everything you posted.  I have to find a way to take some indicator that the user is validated on my site and tell my Wiki site that they are validated.  The Remote_User seems to be the windows login.  Thanks again.
Comment: I'm sorry if I'm missing the obvious, but I still can't find a good way to do this.  Can I pass something in a page header when the user clicks the link to the wiki?
Answer: The internal MediaWiki mechanism for this is the SessionProvider (somewhat complex and the documentation is highly technical). A simple implementation that just pushes the burden of authentication to the web server software is the Auth remoteuser extension.
Otherwise, if you share a domain, you could set cookies in your primary application in some kind of verifiable fashion (e.g. digitally signed) and verify them on your wiki. If you don't, the wiki will have to trigger a web request to the primary application, which would check the cookie and respond with an authentication status, and the wiki would set its cookies based on that.
Comment: Thank you so much Tgr for your help.  I will look into everything you mentioned and report back.


Do all domains on the same shared hosting server have the same IP or ID

Question: Here's what I've got:

siteA.com and siteB.com are hosted on hostgator. They're hosted on the same account of a shared hosting server (not VPS or dedicated).
script.php is an external site that each of these 2 sites are accessing.

I noticed that when siteA.com or siteB.com access the outside script.php, the script identifies them both as 1a.12.12ab.static.theplanet.com (apparently because hostgator uses theplanet.com servers). The fact that they're identified as the same value isn't surprising because after all they're hosted on the same account /home/user123/public_html.
What I'm wondering about is how about other websites that are hosted on the same shared hosting server, but under other accounts. Basically other websites that are under another developer's control, but just happen to share the same hardware (hosting server). Do they also have the exact same identifier 1a.12.12ab.static.theplanet.com or that changes by account?
Answer: Low-end shared hosts are always going to share IP addresses. That doesn't mean every app on the same server has the same IP address though. On my dreamhost account I have several domains with different IPs but they all run on the same server. There is really no reason for you to pay any attention to the address they assign you. Just use the DNS record they create and make CNAME entries for other aliases - the last thing you want to do is create your own DNS records based on the IP you have right now; that IP should be expected to change.
Answer: One machine can have multiple IP addresses, each of which can resolve to a unique DNS entry.
For example, if you're currently on a Windows PC that has IIS running, you could access the default web page from http://127.0.0.1/ and http://nnn.nnn.nnn.nnn, where nnn.nnn.nnn.nnn is the IP address that the machine has either been provided with statically or via DHCP (which can be obtained by running ipconfig from a command prompt). Yes, 127.0.0.1 is a special case, but it still fits the general case of one machine can have multiple IP addresses (Note: I've used Windows/IIS purely for the purposes of the example, the same would apply equally to Linux/Apache).
Comment: @silow - that's ultimately going to be entirely dependent on (a) the hosting provider and (b) how much you pay them. The answer is almost always going to be "no" due to the fact that IP addresses are a finite resource that have a cost associated with them.
Comment: +1 That's great info for starters, but do you know what host providers usually do? Do they usually give a separate IP for each new account on the server?


jquery ajax, array and json

Question: I am trying to log some input values into an array via jquery and then use those to run a method server side and get the data returned as JSON.
The HTML looks like this,

                Choose region:

                            <input type="checkbox" class="radio" value="Y" name="area[Nationwide]" id="inp_Nationwide">

                            Nationwide

                            <input type="checkbox" class="radio" value="Y" name="area[Lancashire]" id="inp_Lancashire">

                            Lancashire

                            <input type="checkbox" class="radio" value="Y" name="area[West_Yorkshire]" id="inp_West_Yorkshire">

                            West Yorkshire

I have this javascript the detect whether the items are checked are not
if($('input.radio:checked')){

}

What I dont know is how to get the values of the input into an array so I can then send the information through AJAX to my controller. Can anyone help me?
Answer: You need to serialize your input with - serialize()
var data = $('#MYFORM').serialize();

Answer: You can use jQuery's each() function.
$('input.radio:checked').each(function() {
  //put each of the selected check boxes into an array
});

jquery ajax, array and json


How to get Google Ads Keywords and Ad Contents via Google Analytics API

Question: I need AdWords data from Goole Analytics API.
Please tell me what is collect queries for dimensions and filter.
For example;
Traffic > Acquisition > Adwords > Campaigns
I could get data using the following queries.
Dimensions
ga:campaign,ga:adwordsCampaignID
Filters
ga:adwordsCampaignID!=(not set)
How about below?
Traffic > Acquisition > Adwords > Keywords  Primary Dimension: Keyword
Traffic > Acquisition > Adwords > Keywords  Primary Dimension: Ad Content
How can I get these data from GA API?
Referrer
https://developers.google.com/analytics/devguides/reporting/core/dimsmets#view=detail&group=adwords
Comment: how much did you try so far?
Answer: Both the Ad content and Keyword dimensions are derived from utm_ parameters, so you will find them under the traffic sources section (note: these utm_ parameters are auto-tagged by AdWords):

Ad Content: ga:adContent (derived from utm_content)
Ad Keyword: ga:keyword (derived from utm_term)
Comment: I have tried using ga:adContent and ga:keyword on Query Explorer,
but the data does not match between GA UI and Query Explorer.

Does it need to add some filter?
Comment: the UI and API should display the same results as long as the queries are identical.


Does Task.WhenAny prioritize some tasks over others?

Question: When passing multiple completed tasks to Task.WhenAny does Task.WhenAny give a preference to which task completed Task will be returned?
Comment: why are you sending completed tasks to `Task.WhenAny`?
Comment: No. If you're adding completed tasks, the first completed task it comes across in the collection (iterating in a natural order, nothing crazy) will be returned. I highly doubt the order is specified anywhere, so behavior *could* change, not likely though. If no tasks are completed then it'll return the first task which *does* run to completion. [Relevant source code](http://referencesource.microsoft.com#mscorlib/system/threading/Tasks/TaskFactory.cs,db51a91904616672)
Answer: When you want to know the exact behavior, you can often check the reference source.  For instance, WhenAny can be found here.
When looking through the source, note that the returned task is not one of your tasks, but an internally-created task (either a CompleteOnInvokePromise instance or continuation of it), whose Result will be one of your tasks.  In the case where you are passing completed tasks into WhenAny, the Result is immediately set to the first completed task it encounters.
Comment: Of course, there's also a race here, assuming the non-completed tasks are hot - if you have `{t1,t2,ct1,ct2}` where the `ct` items are already completed and the `t` ones weren't at the start of the call, one of `t1` and `t2` may complete *whilst* `WhenAny` is still looping through and setting things up. In short - if you pass a mixture of incomplete and complete tasks, you're certainly not guaranteed that one of the already completed tasks will be what you get handed back.


uniform convergence and model selection question

Question: I am working on the Question 1(c) of problem set 3 from cs229. A screenshot of the question is

I am not sure how this formula came to be
\begin{align*}
\left|\epsilon(\hat h_j) - \hat \epsilon_{S_{train}}(h_j^*) \right| \le \sqrt{\frac{2}{(1 - \beta) m} \log {\frac{4 \left|\mathcal{H}_j \right|}{\delta}}}
\end{align*}
A solution is written at https://see.stanford.edu/materials/aimlcs229/ps3_solution.pdf, but I still don't quite get the (c) part. There seems to be also a typo as it confuses $\beta$ with $\gamma$.
The corresponding class note is https://see.stanford.edu/materials/aimlcs229/cs229-notes4.pdf
Answer: OK, you have a few different questions:

I am not sure how this formula came to be.

It's given in the question. It looks like they derived it by applying the bound on the top of pp. 7 of the notes.

I still don't quite get the (c) part.

There are 2 bounds (found in part a, and given for part c), each guaranteed with probability of $\geq 1-\frac{\delta}{2}$. If both bounds apply at the same time (i.e probability of "x" AND "y" in this case) then the joint probability is $\geq (1-\frac{\delta}{2})(1-\frac{\delta}{2}) > 1-\delta$.
And they do apply them at the same time, giving the bound they want to show.

There seems to be also a typo as it confuses $\beta$ with $\gamma$.

I agree with you there.
Comment: Thanks! As for the 1st question. I am aware that it's given in the question, but I don't see how it's derived obviously. Do you mind posting your derivation?


ASP.NET MVC Helper Methods Throwing Null Reference Exception

Question: I have been working on a project for about 9 months now using .NET Framework ASP.NET MVC. I have a view with many forms each with its own model. I use a ViewModel that contains all the individual models that I am using for the forms. I use the Html Helpers to create input boxes such as TextBoxFor and TextAreaFor in the forms as shown below.
@Html.TextAreaFor(d => d.Foo.Property, new { @class = "form-control" })

This has worked since starting the project many months ago and continues to work in production, however as of yesterday when trying to run locally it has stopped working. When loading the page each of my helper inputs throws a null reference exception. I have tried using earlier versions of the project and it is throwing the same exception. I have been unable to find anyone with the same problem online and I am at a loss on how to fix this. My only inclination at this point is to reinstall Visual Studio which I would prefer not to do.
EDIT:
To clarify exactly what my issue is I have included the flow I am using below. These are from a dummy project I created so my problem is not specific to any project.
I have a class here that I would like to input values as part of a form.
public class Foo
{
    public int TestProp1 { get; set; }
    public string TestProp2 { get; set; }
}

I have many forms on one page so I must use a ViewModel to contain each of the multiple models.
public class IndexViewModel
{
    public Foo Foo { get; set; }
    public Bar Bar { get; set; }
}

Using Html helpers I create inputs to bind to the model on form submission.
@model TestMvc2.Models.IndexViewModel

@{
    ViewBag.Title = "Home Page";
}

    @using (Html.BeginForm("PostForm", "Home", FormMethod.Post))
    {

            @Html.Label("Foo Test Prop 1")
            @Html.TextBoxFor(c => c.Foo.TestProp1)

            @Html.Label("Foo Test Prop 2")
            @Html.TextBoxFor(c => c.Foo.TestProp2)

    }

When the page is loaded I get the following exceptions highlighted on the TextBoxFor extension:
Exception thrown: 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' in Microsoft.CSharp.dll
Exception thrown: 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' in Microsoft.CSharp.dll
Exception thrown: 'System.NullReferenceException' in System.Web.Mvc.dll
Object reference not set to an instance of an object.
I am confused as to why this is the case because this is the flow I have used since beginning the project and it continues to work properly in production. It is only when trying to debug locally that this is a problem
Comment: Are you the only person working on this project? There might be a change in the models that isn't reviewed thoroughly.
Comment: I am the only person working on the project and I am facing this issue on a dummy project as well so it is not project specific. I have made an edit that will hopefully clarify my problem.
Comment: I can't find the one I'm looking for-- will you include your controller action that creates the viewmodel and displays the view? thanks.
Comment: So I did some more tests and it seems that it is a problem with the debugger. If I run without debugging then it runs perfectly fine. I am not sure where to begin with solving this now. It is thrown when passing over the Html Helper methods so my inclination is that there may be a broken dll somewhere but I am unfamiliar with dlls.
Answer: I had the same problema and I repared visual studio instalation and the problem desapear.
Comment: This worked for me too, but it had the effect of removing all the settings I'd applied and the arrangement of windows. Very annoying.
Answer: What worked for me was activating Just My Code after restarting the PC:


Functoriality and inverse images of sheaves

Question: I'm now learning sheaf theory from Gortz and Wedhorn's Algbraic Geometry 1 - Schemes and trying to understand the direct image and the inverse image of sheaves.
In the book, the authors said that

...... Again the construction of $f^{+}\mathcal{G}$ and hence of $f^{-1} \mathcal{G}$ is functorial in $\mathcal{G}$. Therefore we obtain a functor $f^{-1}$ from the category of presheaves on $Y$ to the category of sheaves on $X$.......

Now let me clarify the notations. In the quoted sentences, $f: X \rightarrow Y$ is a continuous map and $\mathcal{G}$ is a presheaf of $Y$. A presheaf on $X$ is defined by
$$
U \mapsto \mathrm{colim}_{V \supset f(U), V \subset Y \,  \text{open}}  \mathcal{G}(V)
$$
and the restriction maps are induced by the restriction maps of $\mathcal{G}$. We denote this presheaf by $f^{+}\mathcal{G}$, and the sheafification of it by $f^{-1}\mathcal{G}$. This is the inverse image of $\mathcal{G}$ under $f$.
My question is: What does the word "functorial" mean in the quoted sentences?
I have looked up the book Categories for the Working Mathematician by Mac Lane, and only find the definition of natural when discussing natural transformations. It seems that this is the same as the word functorial? Actually I'm lost in checking from the definition and finding what I need to verify (to show that $f^{-1} \mathcal{G}$ is functorial in $\mathcal{G}$).
I've read the question and answers on What exactly is functoriality? but still feeling hard to find out what to check.
Thank you for your helps!
Comment: Once you get comfortable with the notion of categories, you will see that an assignment is "functorial" if it also induces morphisms in a consistent way. In you case, the inverse image of a sheaf gives a new sheaf, but that is only the first part of being a functor. The other part is that, given a morphism of sheaves, there is a morphism between the respective direct images of the sheaves (in one or the other direction). This is the (or a) meaning of being functorial.
Comment: Thank you for your comments!
Answer: Since you already know what a presheaf is, it may be convenient for you to see why a presheaf is a functor. Basically it amounts to the existence of restriction maps and certain conditions on them.
Take a presheaf of sets $F$ on your topological space $X$.
The condition of being a presheaf is that:

For any open set $U$ you get a set $FU$.
Given open sets $U\subseteq V$ you obtain a restriction function $\rho^V_U:FV\to FU$.
For any open $U$, the restriction map $\rho^U_U$ is the identity function on $FU$.
For open sets $U\subseteq V\subseteq W$ you have $\rho^W_U=\rho^V_U\circ\rho^W_V$.

These four conditions are exactly the conditions that "$FU$ is functorial on the open sets $U$".
Writing $i^U_V:U\to V$ for the inclusion of $U$ into $V$, one could denote the corresponding restriction function as $\rho^V_U=F(i^U_V)$.
Denoting the category of open sets of $X$ by $\text{Top}_X$ and the category of sets by $\text{Set}$, then $F$ is a functor $F:\text{Top}_X^{\text{op}}\to\text{Set}$. ($\text{op}$ because $\rho^V_U=F(i^U_V)$ goes "in the opposite direction" as $i^U_V$).
If you denote the categories of sheaves on $X$ and $Y$ by $\text{Sh}X$ and $\text{Sh}Y$, respectively, then for any continuous function $f:X\to Y$ you obtain a functor $f^{-1}:\text{Sh}Y\to\text{Sh}X$. Explicitly, this means that

For any sheaf $G$ on $Y$ you get a sheaf $f^{-1}G$ on $X$.
Given a morphism $\alpha:F\to G$ of sheaves on $Y$, you obtain a morphism $f^{-1}\alpha:f^{-1}F\to f^{-1}G$ of sheaves on $X$. (Note that here $f^{-1}\alpha$ goes "in the same direction" as $\alpha$).
For any sheaf $G$ on $Y$, the morphism $f^{-1}(\text{id}_G):f^{-1}G\to f^{-1}G$ is the identity morphism on $f^{-1}G$.
For morphisms $F\xrightarrow{\alpha} G\xrightarrow{\beta} H$ of sheaves on $Y$ you have $f^{-1}(\beta\circ\alpha)=(f^{-1}\beta)\circ(f^{-1}\alpha)$.

So you need to check the last 3 conditions on $f^{-1}$.
Comment: A good answer. Two small typos: "Explicitely" should be "Explicitly", and "For any sheaf $G$ on $Y$ you get a set $f^{-1}G$ on $X$" should be "For any sheaf ... you get a **sheaf**...".
Comment: @HetongXu You're welcome. Do you know the definition of a morphism of sheaves? It's a collection of morphisms satisfying a commutative diagram for every inclusion of open sets. The commutativity of those diagrams is the naturality condition.
Comment: @KReiser The first one is not a typo, I just learned that I've been writing it wrong all the time haha. I'll edit my answer. Thanks for the feedback, and I suppose the upvote is yours as well. Cheers.
Comment: Thank you so much! It seems that I have misunderstood the notions of **naturality** and **functorality**. Is this right that actually the two notions have nothing to do with each other?
Comment: Aha, I got it! I have mixed up all these stuffs before. Thank you a lot!!
Comment: Good to be helpful. Cheers.


Django oscar search return same results when paginate

Question: The problem is when I make a search for the products and results count more than 20, pagination to the next page shows products from the first page. Results count is correct, but filtered products are not.
I use haystack simple backend for search.
In products catalog pagination works correct. I made some changes in oscar code and thought that it may effects to the search, but I checked clean installation of django-oscar with my database and get the same result.
Answer: After research I solved this problem with switching on solr search.
A little bit strange that I have to use old versions of solr and pysolr.
Solr 4.7.2 & pysolr 2.1.0
Newer versions give some errors but this two versions work as described in documentation.


Counting no. of ways to make a necklace

Question: Claudia wants to use 8 indistinguishable red beads and 32 indistinguishable blue beads to make a necklace such that there are at least 2 blue beads between any red beads. In how many ways can she do this?
This is one of the unsolved problem in the book 'A Path to Combinatorics for Undergraduates' by Titu Andreescu and Zuming Feng.
My approach: Denote blue by b, red by r. Then we create elements of the form 'brb'(8 elements), and 16'b's. We place the 16 'b's arounds a circle with a space in between them and we choose from those 16 available places 8 for the 'brb' and divide the whole be 2 to account for rotational symmetry.
I am not sure whether I am fully accounting for the rotational symmetry and the fact that the beads are indistinguishable.
Not Homework. Trying to learn.
Thank you.
Comment: Look up Polyá Counting or Burnsides Lemma.
Comment: Okay I will but I was looking for something simple. I am only in high school.
Comment: Sorry - irrelevant - but I laughed a little. The book's called "A Path to Combinatorics for *Undergraduates*," it's natural that you'll receive undergraduate tools here, regardless of what level of schooling you're actually at. :)
Answer: This problem can indeed be solved by Polya counting. First place the eight red beads along a circle, leaving some kind of space between them for the blue beads. Now place two blue beads between each adjacent pair of red beads as well as an empty slot that will be filled later. That leaves $32-2*8 = 16$ blue beads. Now the empty slots may be filled by any number of blue beads as long as there are $16$ blue beads in total. This means that the blue beads going into the eight slots have generating function $$ f(z) = \frac{1}{1-z}.$$ What we have in fact is that the generating function is $$g(z) = 1 + z + z^2 + z^3 + \cdots z^{15} + z^{16}$$ but we shall see that we can use $f(z)$ in place of $g(z)$ with no overcounting.
Now the eight slots are being permuted by $C_8$, the cylic group of order $8.$ The cycle index of the cyclic group $C_n$ is
$$ Z(C_n) = \frac{1}{n} \sum_{d|n} \varphi(d) a_d^{n/d}$$
so that $Z(C_8)$ is
$$ Z(C_8) = \frac{1}{8}
\left(a_1^8 + a_2^4 + 2 a_4^2 + 4 a_8 \right).$$
It follows that the number of orbits or necklace configurations is given by
$$ [z^{16}] Z(C_8)_{a_1=f(z); a_2=f(z^2); a_4=f(z^4); a_8=f(z^8)}$$
which is
$$ [z^{16}] \frac{1}{8}
\left(\frac{1}{(1-z)^8} + \frac{1}{(1-z^2)^4} + 2 \frac{1}{(1-z^4)^2} + 4 \frac{1}{(1-z^8)} \right).$$
Finally recall that
$$ [z^n] \frac{1}{(1-z)^q} = \binom{n+q-1}{q-1}$$
so that the value of the coefficient of $z^{16}$ is
$$\frac{1}{8}
\left( \binom{16+7}{7} +\binom{8+3}{3} +2\binom{4+1}{1} +4\binom{2+0}{0}\right) =
30667.$$
In the case where instead of the cyclic group $C_n$ the dihedral group $D_n$ is acting on the slots on the necklace (i.e., the symmetry includes reflections) the cycle index is given by
$$ Z(D_n) = \frac{1}{2} Z(C_n) +
\frac{1}{4} \left( a_1^2 a_2^{(n-2)/2} + a_2^{n/2}\right)$$
so that the answer becomes
$$  \frac{1}{2} 30667 +
\frac{1}{4}  [z^{16}] \left( \frac{1}{(1-z)^2}\frac{1}{(1-z^2)^3} +
\frac{1}{(1-z^2)^4}\right) = 15581.$$
Comment: I am sure your solution to the problem is correct, but frankly I was looking for something much simpler.
The problem is from a chapter on 'Combinations', in fact there is no mention  of Polya counting anywhere in the book.
It would also be very helpful if you could point out where I went wrong with my answer of (16 Choose 2)/2.
Comment: @Noel I think his solution is correct, but you are looking for an elemental proof. Without algebra. I will try to add one later this day. Still working on  this one.

Counting no. of ways to make a necklace


Azure function v1 PowerShell - how to access request headers?

Question: In Azure functions the http request is parsed from a $req JSON object like so
# POST method: $req
$requestBody = Get-Content $req -Raw | ConvertFrom-Json
I am finding it very difficult (coming from powershell ISE as a sys admin) to get the exact structure of this variable, for example, this is the default run.ps1 whenever a PowerShell function is created
# POST method: $req
$requestBody = Get-Content $req -Raw | ConvertFrom-Json
$name = $requestBody.name

# GET method: each querystring parameter is its own variable
if ($req_query_name)
{
    $name = $req_query_name
}

Out-File -Encoding Ascii -FilePath $res -inputObject "Hello $name"

so if the http method is POST $name = $requestBody.name
if it's GET $name = $req_query_name
how to I access the rest of the request such as the http headers, user agent timestamps etc?
for example this is not well documented and would have been nice to know, especially if dealing with a large amount of query params
if ($req_method -eq 'GET'){
something with GET
}
if ($req_method -eq 'POST'){
something with POST
}

this led me on a guessing game, $req_headers? - nope $req_context? nope
My question is how can I find out everything about the incoming request?
why are variable names $req_something or  $req_something_something - what is this structure?
Comment: You can use `Get-Variable` to get a list of all variables in the session, and `$var | Get-Member` to see all properties on a variable.
Comment: that is how I would normally inspect variables in the ISE - but in Azure functions console is DOS and in kudu, while there is a powershell console it doesn't seem to be in the runspace e.g. it's only for administering the web service environment
Comment: You can save the output of the commands in a variable, as a string (`$var | Out-String`). Make that part of the function code itself, and return it as the function's response, or log it, or store it to a file, etc.
Comment: yes, so the only documented variable is $req for the request body and I want the headers - $req is read (get-content) from a file, outputing the value of $req is not helping - the result for the example given is `{"name":"Azure"}`
Answer: You should get the headers as $req_headers_<HeaderName>.
Comment: Thanks ketan, this is the correct answer, however if the header contains non alphanumeric characters like 'Content-Type' we get error 500


powerbi.embed() not returning Report type

Question: I have succesfully embedded a report using a powerbi service:
const report = powerbi.embed(...)

Now report is of type Embed and not Report as expected. Thus, no Report-specific functions are available (at least typescript-wise). What am i missing?
EDIT: The report object is indeed an instance of the Report class, but the type is still Embed. Do i need to install additional typings for powerbi-client?
Answer: No need to install any additional typings. Just return the powerbi.embed as Report and it will works.
const report = powerbi.embed(.....) as Report


How musicians are chosen to accompany on stage?

Question: I had a question about music concerts. When solo artists do concerts, in the backstage different unknown musicians are accompanying them. So how are these musicians chosen to accompany?
Comment: What do you mean by "backstage"? Do you mean upstage (on stage but farther from the audience) or off stage (not visible to the audience)?
Answer: There are several things that come into play, the skill of the musicians, the courtesy of the individuals involved, the personal attraction of one person to another, how their playing blends, how much they're are willing to work for, whether their appearance is deemed appropriate to the act. The list just goes on and on, and every point has its validity. It's usually referred to as "chemistry".
Answer: They are professional musicians who got the job through personal contact, through an agent or by responding to an advertisement.  The same way as for any worker in a skilled, specialised field.  As it's an on-stage job, personal appearance and 'style' as well as musical ability will be a consideration.
On tour, or in concert, they will be playing their instruments.  It's too expensive to tour musicians who are just window-dressing.  But on a TV performance they will very likely be miming to a pre-recorded track, particularly when the gig is a one-song spot on a chat show.  Young, attractive female violin players do well in this particular market! And the 'uniform' for male 'rock' musicians seems to invariably include a hat.
I could tell a story of a band who were booked for a foreign TV appearance, miming to tracks. As their regular pianist was unavailable they took a 'ringer', someone who played piano well enough to LOOK right...    Then the agent called.  'While you're over there, I've got you a couple of live gigs too.'
Answer: This is a very broad question. Assume everyone involved is relatively competent musically (not really necessary with electronic effects or three others playing that instrument, one could just fake it)
100 performers/bands could have 100 different reasons for choosing people, and each musician they use might be chosen for a different reason.

Here's a list of common factors that come into play when such choices are made:

Regulars they often play with;
Ambitious musicians that will pay for camera/stage time;
'House band' players that play with and help out with any act that
plays that venue.
People that a high profile act wants to promote, for example rising
stars they may want to boost by giving them a place on stage.
People who look good/right for the atmosphere the performers want to
create for their music.
Financial considerations - some musicians might charge more than
others for their services.
Musicians who are 'well connected' (or their agents are), so they get
a spot on stage.
A union rotation: Often a venue has an agreement with a musicians'
union - when they need musicians, the union provides them based on
whoever's turn it is to get a job in the union's rotation.
Buddies - good friends - sometimes they'll put a buddy up there, good or
not so good, just to give him "a charge" - a good feeling.

The list goes on....


Conditional Operator in SQL Where Clause

Question: I'm wishing I could do something like the following in SQl Server 2005 (which I know isnt valid) for my where clause.  Sometimes @teamID (passed into a stored procedure) will be the value of an existing teamID, otherwise it will always be zero and I want all rows from the Team table.
I researched using Case and the operator needs to come before or after the entire statement which prevents me from having a different operator based on the value of @teamid.  Any suggestions other than duplicating my select statements.
    declare @teamid int
    set @teamid = 0

    Select Team.teamID From Team
      case @teamid
         when 0 then
            WHERE Team.teamID > 0
         else
            WHERE Team.teamID = @teamid
      end

Answer: You can do that without a case:
SELECT  Team.teamID
FROM    Team
WHERE   (@teamid = 0 AND Team.teamID > 0)
        OR (@teamid <> 0 AND Team.teamID = @teamid)

Answer: Without using dynamic SQL, the most performant option is:
IF @teamid = 0
  BEGIN

    SELECT t.teamid
      FROM TEAM t
     WHERE t.teamid > 0

  END
ELSE
  BEGIN

    SELECT t.teamid
      FROM TEAM t
     WHERE t.teamid = @teamid

  END

Using Dynamic SQL:
DECLARE @SQL NVARCHAR(4000)
   SET @SQL = 'SELECT t.teamid
                 FROM TEAM t
                WHERE 1 = 1 '

   SET @SQL = @SQL + CASE @teamid
                       WHEN 0 THEN ' AND t.teamid > 0 '
                       ELSE ' AND t.teamid = @teamid '
                     END

BEGIN

  EXEC sp_EXECUTESQL @SQL N'@teamid INT', @teamid

END

Beware that sp_EXECUTESQL caches the query plan, while EXEC will not.  Read this: http://www.sommarskog.se/dynamic_sql.html
Comment: Wouldn't t think the added complexity of dynamic SQL or two IF blocks is worth it, unless you're querying the National Sport Association of China database ;-)
Comment: But is the performance gain worth the complexity and maintainance cost loss?
Comment: All three options have their pros & cons - miss a bracket in Andomar's suggestion, and things won't work as intended.
Answer: What about:
Select Team.teamID From Team Where (@teamid=0 and team.teamID>0) or (@teamid<>0 and team.teamid=@teamid)

Answer: Even simpler than Andomar's answer, and assuming that id is never 0 (as for most auto-increment ids) is
SELECT  Team.teamID
FROM    Team
WHERE   @teamid = 0 or Team.teamID = @teamid;

That predicate is always true when @teamid is zero, and otherwise only true when it matches a particular row's teamId.
Note however: this works pretty efficiently on Sybase 11 or above; it worked pretty inefficiently on MS SQL server 2003; I don't know how it works on the current version of MS SQL Server.
Also, you can use case; you just have to put the case in where clause, not the where clause in the case. So your original query would be:
Select Team.teamID
From Team
where
   case when @teamid = 0 then 0 else Team.teamID end = @teamId;

Note that this is likely to be less efficient, however, as it must be evaluated per row and will also likely result in a full table scan.
The form I gave above is more likely to be rewritten by a smart query optimizer (your mileage depends on your RDBMS) to use an index when @teamid is not zero.
Comment: +1 Your first answer is awesome.  Even simpler might be `@teamid in (0, TeamID)` !
Comment: Thanks! But using an inlist will probably not result in optimization.
Comment: An in list is just syntactic sugar.  I think `a in (b,c)` is expanded to `a=b or a=c` before the optimizer gets to see it
Answer: If you could treat Null as all records:
WHERE Team.teamID = ISNULL(@teamid, Team.teamID)


Feed hexdump to sed

Question: I have a file called samples.txt with 374371 lines that was created like this:
hexdump -e '8/1 "%02x " "\n"' samples.bin > samples.txt

and it looks like this (deprecated):
1a 03 1a 03 4a 03 57 03
4b 03 44 03 1e 03 09 04
10 03 19 03 40 03 ae 03
1e 03 26 03 33 03 ad 03
10 03 84 03 43 03 62 03
e0 03 16 03 34 03 c4 03
f8 02 3b 03 53 03 61 03
10 03 15 03 42 03 58 03
23 03 1f 03 57 03 62 03
17 03 73 03 31 03 33 03
14 03 ff 02 30 03 51 03
5f 03 42 03 47 03 7e 03
ba 03 26 03 35 03 a0 03
08 03 33 03 36 03 c8 03
0c 03 38 03 97 03 44 03

and the following sed command:
echo "                ch0    ch1    ch2    ch3"; cat -n samples.txt | sed 's/\s*\([0-9]*\)\s*\([0-9a-f]*\) \([0-9a-f]*\) \([0-9a-f]*\) \([0-9a-f]*\) \([0-9a-f]*\) \([0-9a-f]*\) \([0-9a-f]*\) \([0-9a-f]*\)/Sample \1:\t0x\2\3 0x\4\5 0x\6\7 0x\8\9/' | head -n 15

gives me output that looks like this:
                ch0    ch1    ch2    ch3
Sample 1:       0x1a03 0x1a03 0x4a03 0x5703
Sample 2:       0x4b03 0x4403 0x1e03 0x0904
Sample 3:       0x1003 0x1903 0x4003 0xae03
Sample 4:       0x1e03 0x2603 0x3303 0xad03
Sample 5:       0x1003 0x8403 0x4303 0x6203
Sample 6:       0xe003 0x1603 0x3403 0xc403
Sample 7:       0xf802 0x3b03 0x5303 0x6103
Sample 8:       0x1003 0x1503 0x4203 0x5803
Sample 9:       0x2303 0x1f03 0x5703 0x6203
Sample 10:      0x1703 0x7303 0x3103 0x3303
Sample 11:      0x1403 0xff02 0x3003 0x5103
Sample 12:      0x5f03 0x4203 0x4703 0x7e03
Sample 13:      0xba03 0x2603 0x3503 0xa003
Sample 14:      0x0803 0x3303 0x3603 0xc803
Sample 15:      0x0c03 0x3803 0x9703 0x4403

It would seem to me, redirecting the output of hexdump to a temporary samples.txt file is inefficient, because for one you have to delete it at the end, and for two, perhaps using sed on the data in memory is faster than it would be on disk. How can I skip the samples.txt file and get the same results?
Comment: I have a vague idea why you cannot used direct piping, but to make your question clearer you might want to explain explicitly. I mean, I assume you did try that and did not like the result. Maybe discuss the difference of the result of what you tried and what you want.
Comment: Hi @Yunnosch, I modified my original question.
Answer: I think the following should work, if I understand your intentions correctly.
hexdump -e '8/1 "%02x " "\n"' samples.bin | cat -n | sed '....

Comment: This works`echo "          ch0     ch1     ch2     ch3"; hexdump -e '8/1 "%02x " "\n"' samples.bin | cat -n | sed 's/\s*\([0-9]*\)\s*\([0-9a-f]*\) \([0-9a-f]*\) \([0-9a-f]*\) \([0-9a-f]*\) \([0-9a-f]*\) \([0-9a-f]*\) \([0-9a-f]*\) \([0-9a-f]*\)/Sample \1:\t0x\2\3\t0x\4\5\t0x\6\7\t0x\8\9/'` Thanks @Dino Dini
Comment: Hi @Dino Dini, I was actually going to try that, but I didn't think it would work. Thank you.
Answer: Alternative with xxd and coreutils:
{
  # Print header
  printf "\t\tCh0    Ch1    Ch2    Ch3\n"

  # Create hexdump of data
  xxd -p samples.bin       |

  # Use 16 bit samples
  fold -w4                 |

  # Add hex indicator
  sed 's/^/0x/'            |

  # Data contains 4 interleaved channels
  xargs -n4                |

  # Number each sample
  nl -n ln                 |
  sed 's/ /:/; s/^/Sample /'
} > samples.out

Content of samples.out:
                Ch0    Ch1    Ch2    Ch3
Sample 1:       0x1a03 0x1a03 0x4a03 0x5703
Sample 2:       0x4b03 0x4403 0x1e03 0x0904
Sample 3:       0x1003 0x1903 0x4003 0xae03
Sample 4:       0x1e03 0x2603 0x3303 0xad03
Sample 5:       0x1003 0x8403 0x4303 0x6203
Sample 6:       0xe003 0x1603 0x3403 0xc403
Sample 7:       0xf802 0x3b03 0x5303 0x6103
Sample 8:       0x1003 0x1503 0x4203 0x5803
Sample 9:       0x2303 0x1f03 0x5703 0x6203
Sample 10:      0x1703 0x7303 0x3103 0x3303
Sample 11:      0x1403 0xff02 0x3003 0x5103
Sample 12:      0x5f03 0x4203 0x4703 0x7e03
Sample 13:      0xba03 0x2603 0x3503 0xa003
Sample 14:      0x0803 0x3303 0x3603 0xc803
Sample 15:      0x0c0a 0x3803 0x9703 0x4403

Comment: Hi @Thor, love your comments and use of `\t` for tab, fold was a nice solution too. I suppose we could even do like so `printf "\t\tCh0\tCh1\tCh2\tCh3\n"`. I changed your script like `nl -v 0 -n ln` to start the first line at 0. The only issue is that this script runs slowly. I have discovered the use of mawk and I got the whole thing to run in 4 seconds. I forgot to mention that the samples.bin file contains 374371 lines.

Feed hexdump to sed


Como fazer left join com multiplas condições usando a classe DBIx

Question: Tenho a seguinte consulta:
SELECT *
FROM endereco e
LEFT JOIN favorite f ON f.end_id = e.end_id AND f.user_id = '123'
ORDER BY
  CASE WHEN f.end_id IS NOT NULL THEN 0 ELSE 1 END, -- ordena por favoritos primeiro
  e.name -- ordena pelo nome

Nessa consulta ele possui um left join com a condição do user. Preciso fazer a mesma coisa usando o DBIx no Perl.
No Model de Endereco possuo:
__PACKAGE__->has_many(
  "favorite",
  "Models::Result::Favorite",
  sub {
    my $args = shift;
    return {
      "$args->{foreign_alias}.end_id" => { -ident => "$args->{self_alias}.end_id" },
      "$args->{foreign_alias}.user_id" => { '=',  "$args->{self_alias}.user_id" },
    };
  },
  { cascade_copy => 0, cascade_delete => 0 },
);

E pra fazer a query ja tentei usar o prefetch só e nao funcionou, exemplo:
  prefetch => ['favorite'],

A condição de user não é aplicada. Como posso fazer?
Answer: Para adicionar a condição do usuário na cláusula LEFT JOIN usando o DBIx no Perl, você precisa usar a opção join_type do método has_many. Esta opção permite que você especifique o tipo de junção que será usada na cláusula JOIN gerada pelo DBIx.
Você pode atualizar o código do Model de Endereco para adicionar a opção join_type e especificar a condição do usuário como uma cláusula AND na junção. Por exemplo:
__PACKAGE__->has_many(
  "favorite",
  "Models::Result::Favorite",
  sub {
    my $args = shift;
    return {
      "$args->{foreign_alias}.end_id" => { -ident => "$args->{self_alias}.end_id" },
    };
  },
  {
    cascade_copy => 0,
    cascade_delete => 0,
    join_type => 'LEFT JOIN',
    on => sub {
      my $on = shift;
      $on->and(
        { 'favorite.user_id' => { '=', \'123' } },
        { 'favorite.end_id' => { '=', \"me.end_id" } },
      );
    },
  },
);

Neste exemplo, adicionamos a opção join_type com o valor 'LEFT JOIN' para especificar o tipo de junção. Também adicionamos a opção on com uma subrotina que adiciona a condição do usuário como uma cláusula AND na junção. A condição do usuário é definida usando uma referência a uma string literal, '123', para evitar que o valor seja citado incorretamente na consulta gerada.
Com essas atualizações, o DBIx deve gerar uma cláusula LEFT JOIN com a condição do usuário na sua consulta. Note que neste exemplo, estamos especificando um valor fixo para o usuário ('123'). Se você quiser usar um valor dinâmico para o usuário, pode modificar a subrotina on para aceitar um parâmetro que contenha o valor do usuário a ser usado na consulta.
Answer: Eu penso que esta forma pode ajudar. Eu usei a cláusula de junção condicional 'ON'
para adicionar a condição do usuário à consulta como nesta discusão.
Para traduzir para DBIx::Class, especifiquei a tabela ('favorite') e a condição de junção com join e -and. A cláusula join para especificar a tabela e a -and para especificar as condições da junção. como explicado aqui
Além disso, a cláusula order_by que usei para especificar a ordem de classificação, que é a mesma da consulta que mostraste. A expressão (CASE WHEN favorite.end_id IS NOT NULL THEN 0 ELSE 1 END) na cláusula order_by é equivalente à cláusula CASE da consulta que mostraste.
Por fim, o método search que cabulei aqui para executar a consulta.
my $endereco_rs = $schema->resultset('Endereco')->search(
  undef,
  {
    join => {
      'favorite' => {
        '-and' => [
          { 'favorite.end_id' => { -ident => 'me.end_id' } },
          { 'favorite.user_id' => '123' },
        ],
      },
    },
    order_by => [
      { '-asc' => 'CASE WHEN favorite.end_id IS NOT NULL THEN 0 ELSE 1 END' },
      { '-asc' => 'me.name' },
    ],
  }
);

Comment: Não funcionou, ele retornou o erro: No such relationship '-and' on Favorite
Comment: Eu editei o codigo. Poderia verificar agora? Eu usei o método 'search_related' e vi o erro que tinha cometido no -and.


Implemented BasicAuth, says its missing BasicAuth?

Question: I've implemented... or rather copy pasted code from http://www.asp.net/web-api/overview/security/authentication-and-authorization/basic-authentication but when I try to run the website i get this error:
<code>Could not load file or assembly 'BasicAuth' or one of its dependencies. The system cannot find the file specified.
</code>
I'm working on the example so I have very little knowledge about what this is, why isn't it working?
Answer: BasicAuth is the name of your application assembly, usually it is the name of your test application. You can check it in the project properties.