hook_onload() replacement

Question: I want to add JS functions to the body tag's onload and onunload attributes with a custom module. The only hook I found was hook_onload() from Drupal 4.7, but this method has been deprecated. What is the Drupal 7 way of achieving this?
Answer: You don't use PHP hooks to execute Javascript. You would put the Javascript you want to execute into a .js file, and then use PHP to just attach that file to any page where it is needed, for example, using drupal_add_js().
For example if you wanted to attach it to every page with a certain type of form you would put drupal_add_js() inside of a hook_form_FORM_ID_alter).
If you want it on every page all the time, you can add it to your module's .info file like so:
scripts[] 'path/to/js/foo.js
Comment: Shouldn't `files[]` be `scripts[]`?
Comment: Yep it should be `scripts`. Also, the path is relative to the module root file, and no slash prefix. `scripts[] = js/myjs.js`.
Comment: Not to pile it on but you should also use the `#attached` property in a render array (like a form array), rather than `drupal_add_js()`.
Comment: `#attached` is generally preferred, it's true. But I chose `drupal_add_js()` for two reasons: 1. It doesn't require prior knowledge of form API to use, and 2. there are rare cases where `#attached` can't be used and I don't know if the OP's case is one of those. I have fixed the other mistakes.
Comment: So if I need specific functions to run onload and onunload, I would need to write those in an external script using document.ready and document.unload (deprecated in jQuery 1.8, but don't know a better way), and then add that JS to my .info file and that would solve my problem?
Comment: Well it depends on what your problem is, but that's how you attach a script. You can also write javascript directly into the templates but that is less modular and flexible and generally not recommended.
Comment: This is working correctly, but it appears to only be including on JS file. My assumption would be that you can add multiple scripts[] = '' to the .info file to attach additional scripts, but that doesn't seem to be working. (As an aside, it's scripts[] = not scripts[]:. At least that's the only way it'll work for me)
Comment: Actually, this is working now with two scripts. I just had them in the wrong order. Thanks!
Comment: I fixed the rogue colon. Glad it helped you!

hook_onload() replacement


If $f_n$ converges uniformly to $f$, is $|f_n(x)-f(x)|$ bounded above by a function only depending on $n$?

Question: For $n\in\mathbb{N}$, let $f_n\colon X\rightarrow \mathbb{R}$ be a sequence of functions that converges uniformly to $f\colon X\rightarrow \mathbb{R}$. Is it then true that $|f_n(x)−f(x)|$ for all $x\in X$ is bounded above by some function only depending on $n$?
The reason for the question is that if $f_n$ converges uniformly to $f$, then given any $\epsilon>0$, one should be able to find an $N(\epsilon)\in \mathbb{N}$ so that $n>N(\epsilon)$ implies $|f_n(x)−f(x)|<\epsilon$ for all $x\in X$ . By analogy with showing some function is continuous, I would try to find $N(\epsilon)$ by bounding $|f_n(x)−f(x)|$ from above. To satisfy the definition, it seems like this bound can only depend on $n$, so one can in turn bound it from above by $\epsilon$ and solve for $n$.
Answer: Yes the function may be equal to $$\varepsilon (n) =\sup_{x\in X} |f_n (x) - f(x) |$$
Comment: It will always exist as long as you allow $\infty $ to be in the codomain. For uniform converge you need $\epsilon (n) $ to converge to 0 as $n \to \infty $ . Consider the sequence given by $f_n(x)= nx $ for $x \in (0,1/n] $ , $f_n(x)=1 $ for $x \in [1/n, 1] $. This sequence converges pointwise to $f \equiv 1 $ but you see that $\epsilon (n)=1 $.
Comment: Why may this function not exist for a sequence of functions being pointwise convergent?


Continuity of maximum of continuous functions

Question: The problem is from Abbott's Analysis. It is:
Observe that if $a$ and $b$ are real numbers, then
$$
\max\{a,b\}=\frac{1}{2}[(a+b)+|a-b|].
$$
Show that if $f_1,f_2,\dots,f_n$ are continuous functions, then
$$
g(x)=\max\{f_1(x),f_2(x),\dots,f_n(x)\}
$$
is a continuous function.
The base case, when $n=1$ follows because $f_1(x)$ is assumed continuous. Do we need to look at $n=2$ (because when do we incorporate the $\max\{a,b\}$ bit?) And for the induction step, I don't know how to show that $f_{n+1}$ is continuous if I assume the first $n$ are continuous.
Answer: Two observations. It is not hard to show that

If $f_1$ and $f_2$ are continuous, so is $$\frac 12 \left( \, f_1 + f_2 + |f_1 - f_2| \,\right)$$
$\max\{ f_1, f_2, \cdots, f_n \} = \max \{ \max\{ f_1, f_2, \cdots, f_{n-1} \}, f_n \}$

Given those, can you now proceed?
Answer: Denoted $g_n(x)=\max\{f_1(x),...,f_n(x)\}$instead of $g(x)$,by induction $g_n$ has been continuous, and so $g_{n+1}(x)=\max\{g_n(x),f_{n+1}(x)\}$ we can get that $g_{n+1}(x)$ is continuous.
The symbol you use here might be a bit ambiguous.
Comment: how can you just say $f_{n+1}$ is continuous?
Comment: Oh, just use max argument. ok!
Comment: Eh... the continuity of $f_{n+1}$ must be the assumption
Comment: What? How can we assumte the $f_{n+1}$ case? I thought we have to show that and we can do that by looking at $g_{n+1}$, which is continuous.
Comment: If we add a new non-continuous function to the case, their maximum can be also non-continuous, isn't that. Eh


Universal login doesn't work with post-login action in React (Auth0)

Question: we have a React (Typescript) application with Universal Login. The user login works perfectly. But we would like to assign roles to user on first login.
We followed this video: https://www.youtube.com/watch?v=B5pzpPqPbbM
We tried login from Dashboard (like the lady in the video) and it worked. But when we try to login in our React app with the universal login it does not work.
We get back an unauthorized error.
To make Post-Login action to work we had to set "Authentication Method" from "None" to "Client Secret (Post)" and in the Settings → Advanced Settings → Grant Types we checked "Client Credentials" option.
If we switch from "Client Secret (Post)" to "None" then the login works but the action does not (we got the following error: AuthApiError: Grant type 'client_credentials' not allowed for the client.\n at OAuth.parseError (/data/layers/layers-GH-v/GH-vlzQIts7oMVQoMATHHepPqgU7LvJnMmf-9-IHPrA/node_modules/auth0/dist/cjs/auth/base-auth-api.js:43:16)\n at process.processTicksAndR").
So we basically would like to solve that when a user logs-in first time he/she gets his/her roles automatically.
Can you tell the steps we have to make both (login and action) work?
Thank you for help!
Answer: You can achieve that by following the steps

Create two applications
Set the first application Grant Type to "None". This will handle your login.
Set the second application Grant Type to "Client Secret (Post)". That will give access to the Auth0 Management API.

Now you have two APPs but the same API

Auth0 discussion Thread
Blog post authored by myself related to the topic

Universal login doesn’t work with post-login action in React (Auth0)


When does an ACCOUNTDISABLE value in userAccountControl *not* correspond to a disabled mailbox?

Question: We are querying a number (dozens) of LDAP servers (mostly Active Directory, but not exclusively) to determine which mailboxes are active, for the purpose of a mail gateway/forwarding application.
We have come across some instances where userAccountControl has bit 2 set to true (aka ACCOUNTDISABLE), but where the mailbox was still active.
I suppose this would correspond to a Windows login account which was disabled, but for whom the mailbox is still active.
Does this ever really make sense?  Or is this simply a broken configuration?
If it does make sense, is there any way via LDAP to reliably detect this configuration (i.e. that userAccountControl is disabled, but that the mailbox is not disabled)?
We are currently ignoring the userAccountControl disabled attribute, because it seems to sometimes (although a small minority of cases) correspond to an active mailbox. We would like to reliably detect this situation rather than leaving these hundreds of "disabled" mailboxes active.
Answer:
This is a normal behavior. UserAccountControl refers only to the user in the directory.
Exchange add many attributes with which you can determine if a LDAP user has a mailbox.
I'd say that msExchMailboxGuid would be the best, since every active mailbox must have one, and exchange delete the value when the mailbox is disabled (Tested on Exchange 2010 with the latest updates).
As for other mail servers that integrate with LDAP directory, I can't tell because I've never worked with one.
Answer: There are actually two disabled states for an Exchange mailbox.
What many people consider "disabling" occurs when the Disable-Mailbox cmdlet is run.  This actually removes most of the Exchange attributes from the account, and disconnects the mailbox.
There is however an AD attribute msExchUserAccountControl. If this is set to 2, the mailbox is disabled. The enabled/disabled status is typically the same as userAccountControl and is controlled by Exchange.
If msExchUserAccountControl exists and is 0, the mailbox is technically enabled.


What are good metrics to assess the quality of a PCA fit, in order to select the number of components?

Question: What is a good metric for assessing the quality of principal component analysis (PCA)?
I performed this algorithm on a dataset. My objective was to reduce the number of features (the information was very redundant). I know the percentage of variance kept is a good indicator of how much information we keep, be are there other information metrics I can use to make sure I removed redundant information and didn't 'lose' such information?
Comment: Strictly speaking, there is no "redundant" information, unless your initial data were perfectly collinear. One usually sees percentage of variance retained ("we used the first five principal components, which accounted for 90% of the variance"). I'm interested in seeing alternatives.
Comment: Since one of your tags is info theory: An indirect way of assessing whether PCA works is to check the assumptions under which information theory tells us it has low info loss for a given dimension reduction. Wiki says this is so when your data is a sum of gaussian signal plus gaussian noise.
http://en.wikipedia.org/wiki/Principal_component_analysis#PCA_and_information_theory
Answer: I assume part of this question is whether other metric exist besides the cumulative percent variance (CPV) and the similar scree plot approach. The answer to this is, yes, many.
A great paper on some options is Valle 1999:

Selection of the Number of Principal Components:  The Variance of the Reconstruction Error Criterion with a Comparison to Other Methods
Sergio Valle, Weihua Li, and S. Joe Qin, Industrial & Engineering Chemistry Research 1999 38 (11), 4389-4401

It goes over CPV, but also Parallel Analysis, Cross-validation, Variance of the reconstruction error (VRE), information criteria based methods, and more. You might follow the recommendation made by the paper after comparing and use the VRE, but cross-validation based on PRESS also works well in my experience and they get good results with that too. In my experience, CPV is convenient and easy, and does a decent job, but those two methods are usually better.
There are other ways to evaluate how good your PCA model is if you know more about the data. One way is to compare the estimated PCA loadings to the true ones if you know them (which you would in simulations). This can be done by calculating the bias of the estimated loadings to the true ones. The bigger your bias, the worse your model. For how to do that, you can check out this paper where they use this approach to compare methods. It is not usable in real data cases though, where you don't know the true PCA loadings. This speaks less to how many components you removed, than to the bias of your model due to the influence of outlying observations, but it still serves as a model quality metric.
Comment: Link to [Valle, Li and Qin paper](http://distancecovariance.googlecode.com/svn/trunk/References/Selection%20of%20the%20Number%20of%20Principal%20Components.pdf)
Answer: There are also measures based on information-theoretic criteria like
Rissanen's MDL (and variations)
Comment: @user:45382 Yes, that is another one. It is also touched upon in the paper Zhubarb links to.
Comment: @Deathkill14 correct i read the paper, information-theoretic measures are mentioned (in fact as good alternatives)
Comment: An excellent theoretical paper on MDL, MML and Bayesianism: Vitany & Li, Ideal MDL and Its Relation To Bayesianism http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.56.8580 . Also other model selection methods such as AIC and BIC are effectively implementations of MDL.


Converter String Json CSS Inline para um array ou json com PHP

Question: tenho um cadastro no banco de dados em json e dentro do mesmo existe um objeto "style" no qual o mesmo possui um código de css inline, como por exemplo:
"padding: 90px 0px 20px 0px; background: #000000; display: block;"
Digamos que o retorno seria:
{
"style" : "padding: 90px 0px 20px 0px; background: #000000; display: block;"
}

E eu preciso pegar cada parâmetro e transformar em um array onde ficaria algo assim, gerando um array ou Json (não sei qual é a melhor solução), segue um exemplo do que quero:
{
"padding" : "90px 0px 20px 0px",
"background" : "#000000",
"display" : "block"
}

Pois vou pegar esse resultado e regar um input para cada chave, gerando um formulário para que o usuário consiga alterar os valores.
O mais perto que consegui chegar foi com isso:
$wrapStyle = "padding: 90px 0px 20px 0px; background: #000000; display: block;";
$bringStyleString = array_filter(explode(";", json_encode($wrapStyle)));
$bringStyleString = array_filter(explode(";", json_encode($wrapStyle)));
$br = json_decode(json_encode(array_filter(explode(";",$wrapStyle))));
$tks = array();

foreach ($br as $key => $value) {

    $t = explode(":", $value);
    $tk = $t[1];

    $tk1 = array(trim($t[0]));
    $tk2 = array(trim($t[1]));

    $tk = json_decode(json_encode($tk));
    $tks[] = array_combine($tk1, $tk2);

}

$contagem = count($tks);

print_r($tks);

Esta gerando um array e dentro dele outros arrays, gostaria de deixar todos os retornos dentro de um array apenas como por exemplo sendo esse o retorno:
Array ( [padding] => 90px 0px 20px 0px, [background] => #000000, [display] => block )
Seria esse o caminho? Ou melhor seguir outro totalmente diferente?
Answer: Você pode usar array_reduce para gerar ele de uma só vez, segue um exemplo
$wrapStyle = "padding: 90px 0px 20px 0px; background: #000000; display: block;";

$explode = explode(';',$wrapStyle);

$styles = array_reduce($explode,function($carry,$item){
    if(empty($item))return $carry;
    $itemExplode = explode(':',$item);
    if(empty($itemExplode[0]) || empty($itemExplode[1]))return $carry;
    $carry[$itemExplode[0]] = $itemExplode[1];
    return $carry;
},[]);

echo json_encode($styles); //{"padding":" 90px 0px 20px 0px"," background":" #000000"," display":" block"}

Comment: Poxa Antonio, muito obrigado.... pegando o resultado via ajax eu consigo fazer exatamente o que preciso fazer. Confesso que estou faz um tempinho quebrando a cabeça com isso, hoje agradeço pela ajuda.


How to create an else statement with the expect command?

Question: I have the follow expect script which adds a known host if a known host does not exist.
#!/usr/bin/expect
spawn ssh user@domain "cd /home/user"
expect "Are you sure you want to continue connecting (yes/no)?"
send "yes\r"
interact

The script works fine the first time I ssh into a device however if I ssh into a device for a nth + 1 time, it throws an error
send: spawn id exp6 not open
    while executing
"send "yes\r""
    (file "./testing_spawn.sh" line 4)

presumably because it continues to expect the string Are you sure you want to continue connecting (yes/no)?
How can I tell the script to just interact if that message does not show up?
Comment: I'm not familiar with expect, from what I saw [here][1] you can do like that: `expect "Are you sure you want to continue connecting (yes/no)?" { send "yes\r" }`  [1]: http://www.thegeekstuff.com/2010/10/expect-examples/
Answer: Use expect_before to match the "unknown host" question only if it comes before the command prompt:
#!/usr/bin/expect
spawn ssh user@domain
expect_before "*(yes/no)?" {
    send "yes\r"
}
expect "*# "
interact

Answer: try this:
#./test.exp 188.8.131.52

test.exp
#!/usr/bin/expect -f
set ip [lindex $argv 0]

spawn ssh -q $ip
expect {
  timeout { send_user "\nFailed\n"; exit 1 }
  eof { send_user "\nSSH failure for $ip\n"; exit 1 }
  "Password:" {
    send "password\n"
  }
  "*(yes/no)?*" {
    send "yes\n"
    interact
  }
  "*#" {
    interact
  }
}


Solving linear equations using division of matrix determinants

Question:
I did not know that we can use this method to solve linear equations and was wondering what method is called. Thank you so much
Comment: Please use the [mathjax basic tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference), rather than using images, and review the [meta read](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question) and enhance your question. It helps to include context (i.e., your attempts, motivation, etc).
Answer: The method is called Cramer's rule. Namely, let $A\mathbf{x}=\mathbf{b}$ be a system of linear equations such that $A\in \mathbb{R}^{n\times n}$ with $\det(A)\neq 0$. Then we have a unique solution $\mathbf{x}=(x_1,\dots,x_n)^T$ with
$$x_i=\frac{\det(A_i)}{\det(A)},$$
where $A_i$ is the square matrix obtained by replacing the $i$-th column of $A$ by the column vector $\mathbf{b}$.


Jquery - Tooltip

Question: I try to create a tooltip showing when rollover.
I have
HTML

abc

Jquery
$("#Myicon").tooltip({
    content: function() {
        return "Tool Tip Content";
    }
});

CSS
 .ui-tooltip, .arrow:after {
    background: green;
  }
  .ui-tooltip {
    padding: 10px 20px;
    color: white;

    font: 8px "Helvetica Neue", Sans-Serif;
    text-transform: uppercase;
  }

It doesn't show up a tooltip.  Please help.
Sample in jsfiddle
Answer: When you use the content option you also need to set the items option:
$("#Myicon").tooltip({
    content: function() {
        return "Tool Tip Content";
    },
    items: "div"
});

jsFiddle example
From the content options documentation:

When changing this option, you likely need to also change the items
  option.
Answer: In addition to @j08691's answer, you can set the title div attribute:

abc

$("#Myicon").tooltip({
    content: function() {
        return "Tool Tip Content";
    }
});

Fiddle
Comment: @abcidd - if you found the post helpful you can always "upvote" it, even if it's not the accepted answer :) Happy to have helped!

Jquery - Tooltip


Como mostrar uma imagem cujo caminho está no banco de dados?

Question: Estou usando ExtJS 4 e PHP.
Tenho uma imagem salva numa pasta do servidor e o seu caminho está salvo no meu banco de dados. Tentei fazer algo assim:
Código no controller:
onVerImgClick: function(btn, o, e0pts){
    var grid = btn.up('grid');
    var records = grid.getSelectionModel().getSelection();
    var produtoId = records[0].data.id;
    //var image = Ext.create('ExtMVC.view.verImagem');
    Ext.Ajax.request({
        method: 'POST',
        url: 'php/importadorDadosImagem.php',
        success: function(response){
            var array = Ext.decode(response.responseText);
            var cont = 0;
            var caminho;
            while(cont < array.data.length){
                if(produtoId == array.data[cont].idProduto){
                    caminho = array.data[cont].imagem;
                }
                cont++;
            }
            cont = 0;
            if(caminho != null){
                var image = Ext.create('ExtMVC.view.verImagem');
                image.getEl().set({
                    src: caminho
                });
            }
        }
    });
}

verImagem.js
Ext.define('ExtMVC.view.verImagem', {
   extend: 'Ext.window.Window',
   alias: 'widget.verimagem',
   autoShow: true,
   modal: true,
   width: 400,
   height: 400,
   items: [
       {
           xtype: 'component',
           autoEl: {
               tag: 'img',
               src: ' '
           }
       }
   ]
});

importadorDadosImagem.php
<?php
include("connect.php");

$queryString = "SELECT idProduto, imagem FROM imagens";

//consulta sql
$query = mysql_query($queryString) or die(mysql_error());

//faz um looping e cria um array com os campos da consulta
$dados = array();
while($dado = mysql_fetch_assoc($query)) {
    $dados[] = $dado;
}

$total = count($queryString);

echo json_encode(array(
    "success" => mysql_errno() == 0,
    "total" => $total,
    "data" => $dados
));

Desse jeito, nenhum erro é mostrado. Porém, a imagem não aparece.
Answer: bom dia, você já tentou primeiramente se conectar ao banco de dados pelo PHP? você tem que ter no banco de dados a seguinte informação, nome e extensão da imagem, então no php você poe em uma variável, o endereço completo da pasta raiz até a pasta onde a imagem está, então concatena com o nome e extensão da imagem, ai basta inserir em uma variável javascript e atribuir no seu código para exibir a imagem.
exemplo
SQL = nome | ext = imagem.ext
PHP = servidor/pasta/subpasta/imagem.ext
EJS = http://servidor/pasta/subpasta/imagem.ext
Comment: No banco de dados eu tenho salvo o caminho completo da imagem. Por exemplo: ./uploads/Jellyfish.jpg
Então, após escolher o registro que quero ver a imagem, eu recupero o caminho através de uma requisição Ajax e tento setar o src.
Comment: @MarceloAugusto cuidado com este trecho ./ em experiencia própria, vi que isso sempre da erro, no lugar de isso, utilize um request de url completa, e veja se só isso já fará a imagem aparecer, ponha manualmente em uma variável com http e tudo e veja se funciona, se sim, basta criar um request da sua url completa
Comment: Se eu colocar o caminho completo não dá. Se eu colocar ./uploads/Jellyfish.jpg no src do script verImagem.js, deixando-o estático, a imagem aparece.
Comment: @MarceloAugusto então se você poe estático ele aparece com esta formatação, já se busca do banco de dados ele não aparece, então seu erro não está no js e sim no banco de dados, como você está buscando no banco de dados?
Comment: Adicionei o código PHP onde importo os dados da imagem.
Comment: Eu tenho todos os produtos em um grid. Para adicionar uma imagem, eu seleciono o produto e clico num botão. Para ver a imagem, é da mesma forma. No BD, Eu tenho uma tabela para os produtos e outra tabela para as imagens. Então para referenciar uma imagem, eu pego o id do produto selecionado. Na hora de recuperar, eu comparo o id da imagem com o id do produto, se for igual e pego o caminho e tento setar no src. Mas não tá setando.
Comment: @MarceloAugusto experimente utilizar PDO você verá que é muito mais simples e mais seguro, segue um exemplo.

mas, vi que você não adicionou um critério de busca no seu querystring
Comment: Você verificou se o retorno do php está chegando para o ajax? Pois pelo que vi você não definiu o header no php, coloque isto antes do echo:
header('Content-Type: application/json');
Comment: ` setAttribute(PDO :: ATTR_ERRMODE, PDO :: ERRMODE_EXCEPTION);
$a -> exec("set names utf8");
$b = $a -> prepare("SELECT idProduto, imagem FROM imagens WHERE idProduto = :var");
$b -> execute(array(":var" => $var));
$c = $b -> fetchAll();
if(count($c)) {
foreach($c as $d) {
echo $d["imagem"]; } }
$a = null; } catch(PDOException $e) { echo $e -> getMessage(); } ?>`
Comment: Não poste código nos comentários, edite sua resposta e de a sugestão lá.
Comment: @fly flourigh o retorno tá correto sim. Botei para mostrar no console e tá saindo direitinho. O header tá definido no connect.php.
Comment: Sugiro que debug em partes então, defina um string estático para o src invés da variável caminho, se passar vá mudando de nível até chegar onde falha.
Comment: pois é, terá que ver em cada parte onde está o erro, pois pelo que entendi, a variavel de um que é o caminho, não está passando para a variavel de outro para exibir a imagem, ou seja, voce busca com php e insere o caminho em uma variável, este caminho então passa para outra variavel do javascrip e então é exibido, bom, no caso, voce abre um produto, este produto tem um id este id tem várias imagens estas imagens exibem em vários lugares, ou seja, ao requisitar o produto ele cria um array com todas as imagens, caso voce crie um loop, ele exibe as imagens antes de passar para o javascript?
Comment: Consegui carregar as imagens como eu queria. Criei uma outra variável e a fiz receber o componente que tem o xtype = 'image'. A partir daí, consegui fazer o novaVariavel.setSrc(caminho);
O problema agora é a forma como eu salvo o caminho das pastas que o @flyflourigh falou. Eu estou mandando o caminho ./uploads/ ele não salva e mostra o seguinte erro: Warning:  move_uploaded_file(./uploads/Koala.jpg): failed to open stream: No such file or directory in C:\Program Files (x86)\EasyPHP-12.1\www\app\extjs-crud-mvc\php\recebeUpload.php on line 56.
Comment: Se eu colocar ../uploads/ ele salva, mas na hora de ver a imagem ele da um not found, ou seja, não encontra a pasta com a imagem.
Comment: para isso, basta você criar duas variáveis, uma para inserir a imagem no banco de dados que seria a ./uploads/ e uma outra para mover a imagem que é a ../uploads/
Comment: basicamente você irá concatenar um ponto . antes do outro ponto .. na hora de mover apenas
Comment: Pronto! Funcionou. Obrigado, galera!


Beginner to complex integration

Question: Unfortunately I missed one a week of lectures last week due to a family bereavement and my lecturer doesn't put up her notes (I put a request online if someone could share their notes with me but no one will). I missed quiet an important portion of complex integration. I have searched online for videos or examples but just don't understand whats happening with it. I've attempted a question but don't think I've done it correctly any advice would be brilliant.
Evaluate $$\ \int_C (z^2-z+2)\;dz $$
if C is the upper half of the unit circle (in a counter clockwise direction)
$$\ \int_{-1}^1 (z^2-z+2)\;dz = \left[\frac {z^3} {3}-\frac {z^2}{2}+2z\right]_{-1}^1 $$
$$\ \left[\frac {1} {3}-\frac {1}{2}+2\right] - \left[-\frac {1} {3}-\frac {1}{2}-2\right]$$
$$\ =\frac {14} {3} $$
Do I need to use cos and sin or am I right?
Thanks
Comment: Is $C$ a closed path?
Comment: https://www.youtube.com/watch?v=nOFdojRxaSE&list=PLBY4G2o7DhF0TSossUvJ-CTKSLfOhQgb6&index=19 might be helpful. I'm not sure exactly where you are in the course....
Answer: Assuming your description of the path of integration $C$ is right (just an arc, not a closed semicircular loop), then you need to parameterize the path. For example, you could take $z=z(t)=e^{it}$ with $t\in [0,\pi]$. The idea is that as $t$ ranges from $0$ to $\pi$, the point $z=e^{it}$ travels along the upper semicircle from $z=e^{0}=1$ to $z=e^{i\pi}=-1$.
Then you would note that $z^2=(e^{it})^2=e^{2it}$ and $dz = \frac{dz}{dt}\;dt=ie^{it}\;dt$, and so write
$$\int_C(z^2-z+2)\;dz = \int_0^{\pi}(\underbrace{e^{2it}-e^{it}+2}_{z^2-z+2})\underbrace{ie^{it}\; dt}_{dz}$$
Simplifying the integrand,
$$=\int_0^{\pi}(ie^{3it}-ie^{2it}+2ie^{it})\; dt$$
$$=\left[\frac{e^{3it}}{3}-\frac{e^{2it}}{2}+2e^{it}\right]_0^{\pi}$$
$$=\left(-\frac13-\frac12-2\right)-\left(\frac13-\frac12+2\right)$$
$$=-\frac{14}{3}$$
Your solution has two problems: (1) you integrated in the wrong direction, and (2) you didn't parameterize the path correctly (you really used the line segment from $-1$ to $1$). Except for a sign change due to the wrong orientation, your answer matches mine because the integrand is holomorphic so the result of the integral is independent of the path. But even though the answer is (nearly) correct, the technique is wrong as I described.
Comment: Exactly right. You will find that the result in that case is zero for your integrand. Same for any integrand which is holomorphic on the enclosed region. The reason is exactly independence of path together with the fact that integrating in the reverse direction produces the opposite value (a closed loop can be thought of as going from a point $A$ to a point $B$, then back again along another path). $\oint_Cf =0$ if $f$ is holomorphic inside of the closed curve $C$ (I'm omitting some technicalities).
Comment: thanks so much for your explanation it really clears up what I was confused about. How would this be different if it was a closed path? would I find the integral of the line from -1 to 1 and add it?

Beginner to complex integration


Should I learn to read sheet music for playing the guitar?

Question: I would start playing the guitar with the app called Yousician, where it shows the string, and the fret's number. This feels too easy.
Comment: Can you tell us what your goals are as a guitarist? If you want to play in a rock band, being able to read sheet music probably won't help much (although it could in some situations). If you want to play jazz, classical, or be in the pit orchestra for a musical, then you will need to be able to read sheet music.
Answer: Yes, or no, or maybe!
To get started quickly, play a few riffs and chords, there's no great need. And it'll depend a lot on what sort of future your guitar playing holds for you. If you want to play in a pop band, doing covers, blues, etc., there's thousands of guitarists out there doing just that - yes, famous, rich, great players, who never read a note in their lives.
If you start in that fashion, then maybe being able to read proper dots will become attractive later, when you may get asked to play off the charts in different bands - ones who don't waste a lot of time at rehearsals, as they can read what they have to play, and get on with it. Or you want to play in pit bands, or dep., where you just turn up and play from the dots.
Learning to play guitar from music is not an easy option. No doubt about that. One of the problems is that there are several different strings and frets on which any particular note can be played, so it's quite confusing at the start. But believe me, well worth the extra effort eventually - it puts you in a happy position where you can pick up some music and simply play it ! That's got to be good. No need spending ages going over and over trying to learn something. But that's really when your sight reading gets good.
So - get going without it initially - learn some chords - there's no great reason to be able to read the dots making chords yet. Play by ear, learn some riffs and simple tunes. However - try NOT to rely too much on tab - as already stated, it's one man's take on how something should be played. And one man is often a still wet-behind-the-ears kid who thinks he's wonderful. A lot of us realise he's not ! There is good tab out there, but as a beginner, how'll you know?
Answer: Yes.
I believe what your describing is called tabs, which is short for tablature notation. It doesn't teach you how to play guitar; rather, it teaches you how one person thinks a song should be played on guitar. If that's what you're looking for, then you're set. But if you want to learn how you would play a guitar piece, learn to read sheet music and chord symbols.
I Googled guitar chord symbols, and came up with this and this. There are probable better options, but these were the first two search results I saw that looked promising.


Unable to use created element with jquery

Question: I'm new in jquery and I suffer from a problem which is a little strange.
After creating a div in jquery,I can't use it,this example will show you how is the problem!
let's assume that in the get.php page there is just:echo "test test";
the code in my file :

click here

  example

it works here

Can some one help me..
Comment: what exactly is the problem, whats happening? what have you tried to resolve the problem?
Comment: Can you alert(data)..ur able to successful get the data? "after creation a div in jquery,i can't use it" ,by use what you meant? what you wanted to do and that is not getting done?
Answer: What jQuery does with $(".info") is selecting the .info elements at the time you call it - which is only one element since the other one is appended later (through ajax). That other element therefore has no click event attached. So, the .info selector is not actually saved - merely the elements are pulled out of the document and then the selector is discarded.
What you want is that jQuery checks element against a selector when you click. You can do that with event delegation:
// When you click somewhere in the body, jQuery will check whether you
// clicked on a `.info` element and execute the function in that case.
// This also works for elements added later on.

$("body").on("click", ".info", function() { ... });

Comment: I used your solution,but it doesn't work:
"Object doesn't support this property or method"
another question:is it really pratically to use $("body")?
if the page is charged ?
Thank you
Comment: @nabilmenzel: Try `.delegate` if you're using an older version of jQuery. You should bind the event to the closest persistent parent. In your case that closest parent is the body - what would you like to bind the event to instead?
Comment: I use the latest version of jQuery,i tryed to use .delegate but nothing's matter :S
Comment: @nabil menzel: What does `$.fn.jquery` return?
Comment: 1.3.2 !
but i don't what it means
Comment: @nabil menzel: That means you're using jQuery 1.3.2 which is **not** the latest version. It's more than 3 years old in fact. Try using version 1.7.2 instead.
Comment: Sorry,I was confused, i thought i have the latest version !!!
Really very sorry to disturb you.
Answer: as you insert new element to the DOM, you should delegate the event:
$("body").on('click', '.info', function() {
  alert("done");
});

Answer: you bind the click event to info classes at the execution of the script but you add the new div later during the ajax process. you have to reassign the click event to this class
try not binding with .click(), use .on() instead, like mentioned here: http://api.jquery.com/on/
$("body").on('click', '.info', function() {
  alert("done");
});


Direction of a shear confusion

Question: I have this matrix which has a line of invariant points $y=0.5x$ and a line of invariance $y=0.25x$. This matrix is:
\begin{bmatrix}
-3&8\\
-1&3\\
\end{bmatrix}
I am further told that it is a combination of a Shear and a reflection in the line $y=0.5x$. My trouble arises when I am asked to give a geometrical description of the sheer which I calculated to be:
$0.5\begin{bmatrix}
-13&36\\
-9&23
\end{bmatrix}$
The answer states that this is a sheer that is in the direction parallel to the line $y=0.5x$. I am confused as to how this sheer direction is determined? How does the line of invariant points relate to the direction of the shear in a matrix, can anyone convince me?
EDIT: I have made a realization with the aid of a drawing, I realized that given $y=0.5x$ is a line of invariant points, the position of the points after the matrix will lie along that line hence moving parallel to the line $y=0.5x$.
Comment: What's the difference between "line of invariant points" and "line of invariance?"
Comment: i) A line that points lie on that once transformed stay in the same position, ii) a line that points lie on once transformed that may move a scalar distance along.
Answer: A shear in two dimensions leaves points along some line fixed and shifts other points in a direction parallel to this line proportionally to their distance from the fixed line. In this case, the fixed line is the "line of invariant points" $2x=y$, so the shear is indeed parallel to this line.
A pure shear matrix only has the one fixed line, but this transformation also maps the line $4x=y$ to itself, so there's a bit more going on. This line can be represented parametrically as $(4t,t)$ and from $$\begin{bmatrix}-3&8\\-1&3\end{bmatrix}\begin{bmatrix}4t\\t\end{bmatrix}=\begin{bmatrix}-4t\\-t\end{bmatrix}$$ we see that the transformation maps points along this line to their reflections in the origin. I'd hesitate to describe this as a reflection relative to the line $2x=y$, though, because that description usually applies to a transformation that reverses the line perpendicular to $2x=y$. I would instead describe this transformation as decomposing a vector into components in the directions of $(2,1)$ and $(4,1)$ and then reversing the latter component.
Incidentally, the question of which lines are mapped to themselves by a linear transformation is one of the motivations for the idea of eigenvectors and eigenvalues.
Answer: I have made a realization with the aid of a drawing, I realized that given $y=0.5x$ is a line of invariant points, the position of the points after the matrix will lie along that line hence moving parallel to the line $y=0.5x$.

Direction of a shear confusion


NativeScript WebView open url in default browser

Question: I am trying to build app with WebView and click/tap events on URL-s inside WebView. Solution below opens external browser and URL but it loads same url content in webview as well. Is there a way to prevent loading new url inside webview?
Here is my code sample.
function onWebViewLoaded(webargs) {
const page = webargs.object.page;
const vm = page.bindingContext;
const webview = webargs.object;

webview.on(webViewModule.WebView.loadFinishedEvent, (args) => {
   let message = "Loading in progress....";
   if (!args.error) {
    message = `WebView loading finished with url: ${args.url}`;
} else {
    message = `Error received ${args.url} : ${args.error}`;
}

   if (args.url.indexOf('http://') === 0) {
    // Stop the loading url first... but how..

    // Open URL in external default browser
    utilityModule.openUrl(args.url);
}
});
}

I have tried with setting a flag isUserInteractionEnabled="false" added to my xml view but then all interactions are disabled. Does someone knows how to do this?
Answer: Try with loadStartedEvent
    webview.on(webViewModule.WebView.loadStartedEvent, (args) => {
        if(!args.url.includes("whatever.net")){
            webview.stopLoading();
            utilsModule.openUrl(args.url);
        }
    });

This way we catch the loadStartedEvent instead of loadFinishedEvent (where the url is already loaded), we check the url if we want to filter depending on it, and here we can webview.stopLoading() for stop the page load.
Comment: first you should ask that what does he want to do, It looks like a logic game questions, not Nativescript... 1. Why does he need actually?  2. What does he need actually? 3. Why doesn't he open that in Webview? so this app aims only app2app routing? (like a desktop webpage shortcut). If he plans to publish it on stores i think probably AppStoreConnect will reject his app, maybe PlayStore too...
Comment: @DrAchernar I can't see the problem, he wants to open url's in external browser but not in webview, myself have a published app with this behavior without problem.
Comment: @HenryWoody I find the answer self explanatory, we catch the loadStartedEvent instead of loadFinishedEvent (here the url is already loaded), we check the url if we want to filter depending on it, and here we can webview.stopLoading() for stop the page loading proccess.
Comment: @Maka please accept my answer if you think it's ok for your needs.


AD Sites and Services - Adding Subnets

Question: We have various physical sites with servers, workstation, printers, switches, and routers.  Is there a reason to add subnets that do not contain Windows devices? For example printers or switches? We have separate subnets for these devices.
Thank You!
Comment: IMO, it's always bet practice to add all of your sites and subnets to ADS&S.
Comment: Thanks for your suggestion.  I guess its sort of like having a belt and suspenders.
Answer: There isn't a technical reason.  Devices that are not joined to Active Directory and don't use AD for authentication aren't going to leverage AD Sites and Subnets.
One reason for doing it anyway would be thoroughness. Having all your subnets accounted for in AD, even if the subnet has no AD clients in it, is one way of having your environment being self-documenting.
Comment: Couldn't ADSS be used to define a subnet of devices that would provide location based dns responses from a windows DNS server? You might have the same printer in 3 offices and instead of setting up 3 different devices on a laptop you just give it a location based name to reply with the IP that is used in that particular location's printer subnet.
Comment: @ChrisB That is not a function of AD Sites and Services, but rather a function of DNS server subnet mask ordering, which will work regardless of what subnet objects are set up in AD.

AD Sites and Services - Adding Subnets


Completeness proofs for the solutions of Diophantine Equations

Question: In general, what are the strategies for showing the completeness of a solution set for Diophantine Equations?
For example, take the $\textit{Pell-type}$ equation $x^2 - dy^2 = a$. Say, you have a set of solutions $\lbrace (u,v) \rbrace$ and say that $\epsilon$ is the $\textit{fundamental unit}$ of $\mathcal{O}_{\mathbb{Q}(\sqrt{d})}$. Then what is the easiest way to show that all the solutions are generated by $\lbrace\epsilon^n(u+\sqrt{d}v) \rbrace$ and that there are $\textit{no others}$?
As a slightly more intricate example, take the case of Mordell's Equation: $y^2 = x^3 - 13$. Assuming that $y+\sqrt{-13}$ was a cube in $\mathbb{Z}(\sqrt{-13})$ allowed me to find the solutions $(x,y) = (17,\pm 70)$, but in order to show that there were no others, I had to show that the sum and product of ideals:
$(y+\sqrt{-13})+(y-\sqrt{-13}) = \mathbb{Z}(\sqrt{-13})$ and $(y+\sqrt{-13})\cap(y-\sqrt{-13}) = (y+\sqrt{-13})(y-\sqrt{-13}) = (x^3)$
Which I reckon allowed me to justify the assumption using the $CRT$.
Another interesting thing I found useful to keep track of from Keith Conrad's fantastic blurbs is parity. I also found a Theorem (whose proof I do not know) in one of Pete Clark's expositions that could be useful. (Theroem $8$ in http://alpha.math.uga.edu/~pete/4400MordellEquation.pdf)
But besides this, are there any other strategies one can use to learn more about a solution set? For instance, when can we ascertain whether or not it's finite? Are there any applications of the class number of the field here?
Thank you very much.
Comment: your claim on the Pell equation is incorrect. On the other hand, there is a finite set of solutions such that your process generates all solutions.
Comment: @Will My apologies. What I think I really meant was: once you have a finite set of solutions, how do you check that you can now generate all of them?
Comment: I made a CW answer which is just a list of links here that I have answered. Maybe start on the more recent and go backwards.
Answer: The only strategy I know of uses the group structure of the points. On integral points on curves of genus $0$, sch as the Pell equation, you have a group structure coming essentially from the multiplication of algebraic numbers; and on elliptic curves, which are curves of genus $1$, you have a group structure on the set of rational points. There is little you can do in terms of strategies if your variety does not have a group structure.
Now if you have a finite set of points, you can use ascent to produce (in general) infinitely many: given $P$ and $Q$ you can form linear combinations
$aP + bQ$ using the group law. For showing that these are all you use infinite descent: the group law allows you to show that the existence of an additional  solution implies the existence of a point $R$ that is in a very precise sense "smaller" than those you already have (the technical term is called "height"). This reduces the task to a brute force search.
Both for curves of genus $0$ and $1$ there is an associated $L$-function $L(s)$  whose behavior at certain values ($s = 0$, $s = 1$ etc.) allows you to predict whether there are finitely or infinitely many integral (genus $0$) or rational (genus $1$) solutions. In both cases, you can use heavy machinery (cyclotomic units; Heegner points)  to produce a subgroup of finite index if the group in question has rank $1$. This again exploits the underlying group structure.
There are, as you have said, direct methods of obtaining integral points on curves of genus $1$ using algebraic number theory, but these become technical very quickly and reduce to solving sets of Thue equations. This is a completely different idea, since here you do not gain anything from knowing a few solutions. Indeed, the integral points do not have a group structure in this case.
Answer: CW just a list
Another quadratic Diophantine equation: How do I proceed?
How to find solutions of $x^2-3y^2=-2$?
Generate solutions of Quadratic Diophantine Equation
Finding all solutions of the Pell-type equation $x^2-5y^2 = -4$
how to solve binary form $ax^2+bxy+cy^2=m$, for integer and rational $ (x,y)$  ::::  69   55
Find all integer solutions for the equation $|5x^2 - y^2| = 4$
Maps of primitive vectors and Conway's river, has anyone built this in SAGE?
Infinitely many systems of $23$ consecutive integers
Solve the following equation for x and y:  <1,-1,-1>
Finding integers of the form $3x^2 + xy - 5y^2$ where $x$ and $y$ are integers, using diagram via arithmetic progression
Small integral representation as $x^2-2y^2$ in Pell's equation
Solving the equation $ x^2-7y^2=-3 $ over integers
Solutions to Diophantine Equations
How to prove that the roots of this equation are integers?
Does the Pell-like equation $X^2-dY^2=k$ have a simple recursion like $X^2-dY^2=1$?
If $d>1$ is a squarefree integer, show that $x^2 - dy^2 = c$ gives some bounds in terms of a fundamental solution.


How to figure out a tone center in an ambiguous/chromatic situations?

Question: This question bugs me since I started writing music. I'm asking in general, but I'll show an example so it would be more clear. Keep in mind the notation is arbitrary, as I don't quite know what I'm doing.

This is an 8-bar excerpt from the piece I'm working on currently. Judging by the notes that fall on the strong beats I would guess this is somewhat E-minor-ish. The chromatic rundown skips A natural even though it is present in the first bar. So the question is does this have a chord progression, or is it just Em throughout? I can't tell. But there is another voice.

This one is much simpler. It reinforces A natural, but it also has Bb (or should it be A#). Which would imply a flat fifth in the scale. But it still fits into the E-minor-ish sound. But there is a third voice.

Here you have F# and G which are again notes of E-minor, the problem arises when the upper F# becomes natural. With another voice playing E at the same time this would make it a cluster of 4 semitones in a row (E F F# G). And if this is indeed E-minor that would make it so it has both natural and flattened second degree playing at the same time. But with this third voice added I feel like there appears an implication of a chord change when F# becomes natural.
Now the problem is that I have to write a bass line and without knowing what kind of harmony I'm dealing with it became an impossible task. I tried treating this as E-minor and it didn't work well. Sometimes I felt like this is centered in A-minor, but nothing came out of that too. So unless someone opens my eyes I feel like I'm stuck. So if you have any ideas I would love to hear them.
Comment: Maybe it's become an impossible task due to you resorting to *theory*. It's a very simplistic view, but whatever *sounds* best probably *is* best. The technicality of what key comes later.
Comment: I suspect your piece is in A minor from the looks of it (and the repeated E is treated as a dominant), but I also suspect that your piece sounds rather like a chromatic mess because E, F, F#, G, and A are playing simultaneously at points, and one of your parts has a chord consisting of F, F#, and G. I'd need to listen to an audio clip to make sure, but it's quite possible that your piece sounds atonal in practice.
Comment: There aren't any rules, just things that fit with expectations or challenge expectations. If composing were like drawing, then I would suggest the melody is like the outlines of shapes and the chords and harmony are the colors. You might draw an outline of a ball that has stitches on it so that it looks like a baseball, and then the natural colors would be white and red. Similarly, a melody might have a "natural" harmonization for it (or several). On the other hand, if you just draw a circle to represent a ball, it could be any color you like. or you could make your baseball strange colors.
Comment: When you write an unusual melody, you might have to come up with an unusual harmony if you want it to sound a certain way. Unless you know a lot of theory to be able to just "see" a harmonization that sounds how you want it to sound, you might just have to pick at it and experiment until you find what you're looking for (or listening for).
Comment: You're asking for a 'right answer' to how to harmonise this piece.   There isn't one.   There isn't even an obvious one, with less conventional alternatives.   Sorry!
Comment: What instrument do you play this music on?
Comment: Also, why do you "have to" write a bass line?
Answer: The general answer
To start, it's worth making a distinction between a tone center and a pitch center. I infer from your use of "tone center" that you're looking for a "tonic" pitch — that is, "what key/mode am I in?"
One way to attempt to figure out the key and mode is simply to take each unique pitch in your piece, place them in pitch-ascending order starting from what you perceive to the the "primary" pitch, and see what you get. Of course, if you have too few pitches you might get nothing, and if you have too many, you just get a chromatic scale.
By definition, an ambiguous or sufficiently chromatic musical passage doesn't have a tonal center. It might have a "pitch center" — that is, a pitch that the listener perceives as a stable point or point of focus -- but not be in a key.
For example, Ligeti's Musica Ricercata, no. 1, has a clear pitch center — A — but it cannot be said to be "in the key of" anything.
But you can force a tonal center on otherwise ambiguous situation.
The melody of Samuel Barber's "Nocturne", op. 13 no. 4 is built on a twelve-tone row, so has no pitch center. However, by embedding the twelve-tone melody in a tonal-sounding harmony, the whole piece winds up sounding like Ab Major. The piece stands up to a twelve-tone interpretation in a very clear and logical way, but woe to the person attempting a tonal analysis without stretching the rules to meaninglessness.
Toward a specific answer
I think your composition is sufficiently ambiguous so as to say it doesn't have a tonal center, but certainly E and A are candidates for pitch center.
You've built (this part of) your piece around two musical ideas:

a "chord" (maybe better to call it a "simultaneity") consisting of the pitches F#, G, and A, plus E and/or Bb, and
a three-note chromatic cell, always descending, sometimes transposed.

I hear your piece with E as the pitch center. But I like the sound of Bb in the bass against the chord-centric moments, "resolving" to an A in the bass against the chromatic moments. To my ear, that gives the E a sort of "dominant" feel, and the A a "tonic" feel. If placed in rhythmically interesting places, I think those two pitches alone would give a pretty cool sound, maybe like a funky A minor. Now that I think about it, let's apply the suggestion above of ordering the pitches. The scale would look something like A Bb [C D] E F# G, which, ta-da!, is second mode of G melodic minor. (C and D are in brackets, because you don't use those pitches in a significant way.)
You might consider making the piece even more rhythmically ambiguous, to go with the tonal ambiguity. You can do that by having the bass play at irregular intervals. That would still be compatible with the Bb - A suggestion if you like it.
Etc., etc., etc. ...


Primefaces p:commandButton: disabled only working before f:setPropertyActionListener

Question: I'm using
 and in a
 I have a
 that must be disabled in one condition that is specified in the bean.
Here's the form:

                        <f:setPropertyActionListener value="#{flusso}"
                            target="#{invioFlussiTUManagedBean.selectedFlusso}" />
                        <f:setPropertyActionListener value="#{false}"
                            target="#{invioFlussiTUManagedBean.modoInvioTutti}" />

In my ManagedBean:
public boolean isDettaglio() {
    return flussiTURepository.isDettaglio(selectedFlusso);
}

This method queries the database and returns true or false depending if selectedFlusso responds to a condition.
The issue is this: in the method isDettaglio(), selectedFlusso is initialized in the f:setPropertyActionListener. When the method is called, selectedFlusso is null.
How do I set selectedFlusso so that in the disabled attribute of
 is not null?
Comment: Your question is confusing. The code snippets and the description in the question does not seem to match each other. Do you actually mean the one and the same thing with `isDettaglio` and `disableDettaglio`? If so, why don't you have just a `disabled="#{flusso.dettaglio}"`?
Comment: You're right, sorry! I did some tests and I have not restored the original. disableDettaglio in reality is dettaglio like this:

disabled="#{!invioFlussiTUManagedBean.dettaglio}">
Answer: The <f:setPropertyActionListener> is not invoked when the HTML representation of the button is rendered, as you seem to expect. Instead, it is only invoked when the form is submitted via the button in question and its action is been queued.
If you want to continue using this strange design — I'd have just used
disabled="#{!flusso.dettaglio}"

instead —, then your best bet is to programmatically evaluate #{flusso} inside the getter.
public boolean isDettaglio() {
    FacesContext context = FacesContext.getCurrentInstance();
    Flusso currentFlusso = context.getApplication().evaluateExpressionGet(context, "#{flusso}", Flusso.class);
    return flussiTURepository.isDettaglio(currentFlusso);
}

Note that if your environment would support the new EL 2.2 feature of invoking methods with arguments, then you could just use
disabled="#{!invioFlussiTUManagedBean.isDettaglio(flusso)}"

See also How to call a method with a parameter in JSF.
Regardless of the solution based on the current design, this design is "strange", because it's potentially very expensive. See also Why JSF calls getters multiple times.
Comment: Thanks for your answer. Can you tell me how can I allow my environment to support the new EL 2.2?
Comment: Click the "See also" link. It isn't included for decoration purposes :)
Comment: Great answer @BalusC !! I always end up adding managed beans inside another managed bean just to get a hold of a single variable or expression , evaluateExpression is a wonderful alternative for some scenarios.
Comment: @Avinash: if you happen to use OmniFaces; it's also available via the easier-to-use `Faces.evaluateExpressionGet("#{flusso}")` utility. See also [showcase](http://showcase.omnifaces.org/utils/Faces).
Comment: @BalusC : Omnifaces is my go-to util library for JSF. I especially use it for validators . I wonder if there is any harm in adding name as Faces.getManagedBean() . It makes code look simpler , some of my team doesn't understand  'evaluateExpression'.
Comment: Interpret it as: "evaluate the given EL expression in the current EL scope and return the result". E.g. `Faces.evaluateExpressionGet("#{1 + 1}")` would return 2. It's just reusable for more purposes than just returning a bean by name.
Answer: You could use something like that
<p:commandButton disabled=#{!invioFlussiTUManagedBean.isDettaglio(flusso)}

and in your bean:
public boolean isDettaglio(Flusso selectedFlusso) {
    return flussiTURepository.isDettaglio(selectedFlusso);
}

Comment: Noted should be that this works in Servlet 3.0 / EL 2.2 only and it's not clear from OP's question if he is using that. JSF 2.x is namely backwards compatible with Servlet 2.5 and EL 2.1. You should never assume EL 2.2 to be always present in JSF 2.x, unless otherwise indicated by the question or the code snippets (which does not seem to be the case anywhere in this particular case).
Comment: according to your suggestion, I have the following exception:

18.03.2013 18:01:52 *ERROR* DefaultExceptionHandler: handleUnexpected - An unexpected internal error has occurred - (DefaultExceptionHandler.java, line 119)
javax.faces.view.facelets.TagAttributeException: /tu/invio-flussi-tu.xhtml @77,68 disabled="#{!invioFlussiTUManagedBean.isDettaglio(flusso)}" Error Parsing: #{!invioFlussiTUManagedBean.isDettaglio(flusso)}
Comment: Your environment doesn't support EL 2.2, as predicted by my comment, and this answer is therefore useless/unhelpful to you :)
Comment: Thanks. I'll wait for other answers!
Comment: Even more, 5 minutes before you posted your comment, I've already posted an answer.


Firestore permissions

Question: How do I configure permissions so that a user can only read and write documents where they are the owner?
my documents have a top level attribute called owner.
I read these docs
https://firebase.google.com/docs/firestore/security/secure-data?authuser=0#the_resource_variable
and it seems like this should work?
service cloud.firestore {
  match /databases/{database}/documents {
    match /analysis/{analysis} {
      allow read, write: if request.auth.email == resource.data.owner
    }
  }
}

however this doesn't seem to work. i continuously get insufficient permission error.
What do i need to change?

Update:
After reading the docs @Doug Stevenson linked I decided to go with
service cloud.firestore {
  match /databases/{database}/documents {
    match /analysis/{analysis} {
      allow read, write: if request.auth.uid == resource.data.owner_uid;
    }
  }
}

So my original intent was that when we do a list operation:
a. only those documents belonging to a user are returned
b. only documents a user owns can be read or written by that user.
With the above configuration b. is accomplished.
how do I do accomplish a. ?
Answer: According to the documentation, you should use request.auth.token.email (not request.auth.email).
Comment: Good catch! That `token` in there messes me up every time. :-/
Comment: Thanks @doug stevenson. I've udpated my question above. let me know if you think it's better suited to a new question.
Answer: To answer your update question part (a):
I has a similar issue - I had my rules set correctly to allow that user to read and write. However, Firestore needs us to have our queries match the firestore database rules. So the query on the front should match what that user has access to. So my issue was I was asking for all products in the collection. What I needed to change it to was asking for all products in the collection where the "owner" of the product matched the logged in user, like this:
db.collection('products').where('owner', '==', firebase.auth().currentUser.uid).get()

Hope this helps
Comment: thanks. i re asked my question seperately here https://stackoverflow.com/questions/47472230/firestore-permissions/47685677#47685677 and got the same answer

Firestore permissions


Imagem de fundo não é replicada nas demais páginas ao usar funcão onChange

Question: Pessoal estou tentando selecionar uma imagem de fundo de acordo com opção selecionada em uma função onChange, mas acontece que ela (a imagem) só é aplicada na primeira página, se eu NÃO usar a função onChange para o endereço da imagem mostra em todas as páginas normalmente, o problema se dá ao implementar a opção de select e função onChange, segue codigo e imagens com e sem a função que estou usando:

SEM a função:

COM a função:

Inspecionando os elementos verifiquei o seguinte:

Meu código:

script da função

CSS


What is the deal with $p$-value when generating Pearson's $r$ correlation coefficient?

Question: I know how to generate Pearson's $r$ correlation values in Excel and in R.
I understand the meaning of the value as it ranges from $-1<r<1$
I also understand hypothesis tests, confidence intervals, and $p$-value.  ($p$ = the probability that this outcome was due to random chance or natural variation, and null hypothesis is true)
However, I am having trouble making the connection between Pearson's $r$ correlation and $p$-value.  In a hypothesis test, there is some element of chance of the variation of outcomes (like coin flips).  But, in a regression, it is based on actual data points.  So what does p-value mean in this context?  The odds that the data points are just clustered due to random chance?  Is this directly based on sample size? I ask because I wonder how would a formula know anything about the variability of discrete data points (such as selling price and mileage of a car).
So, for an r value, the p-value is based on sample size?
What I don't understand is that p-value seems to answer a binary question: Is there an effect or not?
But for a correlation coefficient, there isn't a yes/no question being asked.
If I get an r = .8, and p-value of .20, what does that mean?
It means there is a 20% chance that the correlation of .8 is not true?
But, then what IS true? r=.7 ? r=.6?
Or is the rule of thumb that you can only use the r value, regardless of number, if p < .05 ?
If I get an r = .1, and p-value of .0001, what does that mean?
We are very confident there is a very weak correlation? (How ironic?)
If I get an r = .5, and p-value of .0001, what does that mean?
We are very confident there is a moderate correlation?
If I get an r = .5, and p-value of .3, what does that mean?
It means there is a 30% chance that there is a moderate correlation of .5 ?
Comment: Also, you should start accepting and upvoting aswers to your question. This encourages answers.
Comment: Im afraid , your understanding of the p value is not generally correct, which may be where the question originates. For the actual question, what null hypothesis about the correlation for which you need to understand p do you have in mind? The  usual $\rho=0$? Or any other?
Comment: So, for an r value, the p-value is based on sample size?
What I don't understand is that p-value seems to answer a binary question: Is there an effect or not?
But for a correlation coefficient, there isn't a yes/no question being asked.

If I get an r = .8, and p-value of .20, what does that mean?
It means there is a 20% chance that the correlation of .8 is not true?
But, then what IS true? r=.7 ? r=.6?

Or is the rule of thumb that you can only use the r value, regardless of number, if p < .05 ?
Comment: If I get an r = .1, and p-value of .0001, what does that mean?
We are very confident there is a very weak correlation? (How ironic?)

If I get an r = .5, and p-value of .0001, what does that mean?
We are very confident there is a moderate correlation?

If I get an r = .5, and p-value of .3, what does that mean?
It means there is a 30% chance that there is a moderate correlation of .5 ?
Answer: [Fixed/improved, based on the feedback from @Momo and @whuber]
I believe that in the context of regression the relationship between $p$-value and Pearson's correlation coefficient is the following: $p$-value can be interpreted as probability that correlation (coefficient), determined in a random sampling-based experiment, is the same or larger than the one, determined from the observed data, provided that the null hypothesis is true. In other words, I think that $p$-value in this context is related to hypothesis testing, where hypotheses themselves are correlation-based, as follows:
\begin{multline}
\shoveleft{H_0: \text{correlation (of the underlying data-generation process) is zero;}}\\
\shoveleft{H_A: \text{the correlation is not zero.}}
\end{multline}
Then, the situation IMHO boils down to the following traditional hypothesis testing interpretation. If $p$-value is small (less than arbitrarily selected significance level $\alpha$, usually equal to 0.05), then you can reject the null hypothesis ("determined correlation is statistically significant"), and, if $p$-value is greater than $\alpha$, than you fail to reject the null ("the correlation is not statistically significant").
In regard to a relationship between $p$-value and sample size $N$, the following formulae present the relationship in question in a mathematical form.
Fisher transformed test statistic of $r$ (aka $z$) is defined as $T(r) = artanh(r)$.
For a bivariate normal distribution, $z$'s standard error depends on sample size $N$, as follows:
\begin{align}
SE(T(r)) \approx \frac{1}{\sqrt{N - 3}}
\end{align}
Moreover, since the test statistic is approximately normal,
\begin{align}
\frac{T(r)}{SE(T(r))} \approx N(0,1) \text{ and } \lim_{N\to\infty} SE(T(r)) = 0
\end{align}
so the standard error in the denominator is getting increasingly smaller for increasingly larger $N$.
P.S. You may also find the following two answers relevant and useful: this and this.
Comment: The hypotheses as currently written are not valid hypotheses in a standard testing setting.  I would therefore like to suggest they should be formulated differently.  The null is that the correlation coefficient (of the underlying data-generation process) is zero, *not* "due to random chance"; the alternative is that it is not zero.
Comment: @aleksander Great, I'm sure it will become a good answer.
Comment: @Momo & whuber: Thank you for your suggestions and corrections. As I work on learning/improving my knowledge of statistics, your feedback is very valuable not only to the OP, but to me as well. I will try to read a bit more and then consolidate the feedback from both of you and update my answer to the best of my (current) knowledge. I appreciate your comments!
Comment: You write that the p-value is the "probability that correlation (coefficient), determined in a random sampling-based experiment, is the same or larger than the one". Please re-read and amend this obvious falsehood.
Comment: @DWin: Please feel free to fix whatever the erroneous information this (or any other answer) contains. Just make sure to provide relevant references. I will be more than happy to learn from you.


Como adicionar varios dicionarios usando o pickle para salvar em txt

Question: Estou com o problema na hora de salvar um arquivo utilizando o modulo pickle, toda vez que faço a execução do programa ele reescreve sobre o dicionario ja existente. Ja tentei usar o shelve para subistituir mas não obtive exite.
Segue abaixo parte do algoritomo para melhor entedimento.
aluno = {'nome': str (nome), 'nota1':float(nota1), 'nota2':float(nota2), 'media': float(media), 'resultado': str(resultado)}
escola[aluno['nome']] = aluno
bancodd = open('escola_banco.txt', 'wb') #abrindo arquivo para modo de edicao
pickle.dump(escola,bancodd) #salvando arquivos
bancodd.close()
print ('Dados do aluno',nome,'salvos',)

Answer: Você está copiando apenas uma referência do seu dicionário.
Para fazer uma duplicata idêntica do seu dicionário utilize a função deepcopy() do módulo copy:
import copy
...
escola[aluno['nome']] = copy.deepcopy(aluno)
...

Comment: Tentei usar esta maneira com o copy mas mesmo assim ele escreve em cima do arquivo ja salvo em txt.
Answer: Se você não lê o arquivo original, ele sempre vai escrever um dicionário novo.
Você tem que, no começo da execução do seu programa, ler o arquivo que está no disco para um dicionário em memória, trabalhar com ele, atualizar, etc...e na hora de encerrar o programa, gravar o dicionário no disco.
Esse dicionário no disco sempre será um novo dicionário criado a partir do zero.  Tem formas de não re-escrever tudo? Tem - mas absolutamnte não vale a pena. Um dicionário com 10000 nomes será escrito em um tempo em torno de 1 segundo no disco, e as complicações para manter tudo sincronizado seriam várias.
A alternativa a esse fluxo de ler tudo pra memória, trablahar e gravar de volta é usar um banco de dados - seja SQL tradicional (e Python vem com o sqlite, não precisa instalar nem configurar nada), seja um banco NoSQL mais simples como o redis - que funciona quase como um dicionário "vivo".
Agora, uma coisa que você vai precisar fazer é agrupar seu código em funções . Você provavelmente já aprendeu sobre elas, então é hora de começar a exercitar o que aprendeu. Tendo uma função que lê o dicionário e uma que escreve o dicionário no arquivo, você pode fazer isso a todo momento que desejar, com apenas uma linha de código.  Da'i o restante da aplicação pode crescer para ter menus de inclusão de aluno, alteração de notas, etc.... e você só precisa chamar a função que grava o dicionário, com o código todo num lugar só.


Why did Queen use cross-handed technique to play the piano part of Bohemian Rhapsody?

Question: I tried to find some explanation for this based on watching this YouTube video
I found a similar question on here, but I'm not sure it addresses my specific situation.
If anyone here can elaborate that would be excellent, since I think it would be rather pointless to do this as it's easy to reach the F3 and G4 if you are not playing them together.
Comment: Yeah, but how good does it look?!? Freddie was more of a showman than PT Barnum.
Answer:
If anyone here can elaborate that would be excellent, since I think it would be rather pointless to do this as it's easy to reach the F3 and G4 if you are not playing them together.

It is octaves. You can not easily reach those octaves with the right hand. Doing it the way he does with cross-handed technique is just a simple way that makes sense.
You could play the lower notes of the octaves with the right hand, but you would still need to cross over with the left hand to play the upper notes of the octaves.
If you want to avoid cross-handed technique completely you would need to shift your right hand position one octave up and then back to reach the low F and and then one octave up again. That is ackward to say the least.
Doing it the way he does means that the right hand plays the accompaniment and sticks to that while the left hand crosses over and plays that little motive. Thus you can easily play the right hand without disturbance in the accompaniment and play the motive with the left hand with a clear seperate sound quality.
Anyway, play it the way that works for you.
Comment: Mozart's piano sonatas are full of this.  One hand is noodling accompaniment, while the other occasionally crosses over to echo a melodic phrase as if it were, say, bassoon answering flute.
Answer: Lines and phrasing.  Nothing more. Freddie approached this song as a singer also playing the piano, not a piano player playing both the melody and piano part.
Think orchestrally or as if you are singing.  The RH plays the melody notes of A Bb Bb and, how the music is written, the final Bb is a whole note.  Now sure, you can use the sustain pedal and sustain the Bb and it dies away or even just let it go as you play the octave notes with the same hand but, if you were singing or playing that melody on a wind instrument, you would be trapped there holding the Bb for four or eight beats. You couldn't stop (or lift your hand) to play the broken chord and octave notes because it would break your phrasing.  I know, it doesn't matter to the ear of the listener but musically, linear wise, breath wise, you are breaking the line by switching up the hands. It has little to do with technique and more to do with what is going on inside your heart and soul.
So since the LH is already playing arpeggiated chords and has its own counter melody of those octave notes, it is best to musically cross the hands over to continue the lines each hand started.  Each hand has its own line even though the right hand's note is a whole note.
To break the invisible line with your hands, sure, the average musician won't notice but, someone who is listening to the piece as if it were being played by individual instruments would immediately hear the disconnect even if you don't.  There are a lot of things we think we get away with by using the sustain pedal but we don't.  Not to real musicians with ears that hear.
Listen to a four part fugue played by four distinct wind instruments then listen to the same fugue played by a pianist.  The instruments will proffer four distinct lines with their own phrasing as they flutter together like four butterflies doing a fugal mating dance in the air.  Chances are the pianist is just playing a bunch of notes.  The sustain pedal then becomes a crutch which just amalgamates "stuff" and creates additional multi timbrel'd notes that should not be there.   I would compare it to putting on glasses that are not your own and everything looks blurry.  Breaking the lines makes it aurally blurry. Again, the average person never notices this.  They just hear the whole. Like looking at those Magic Eye books.  Some people see billions of dots, others see the hidden image they create. Hey, a bunny . . .
Listen to this guy play Bach's Little Fugue in G Minor on the piano.  It is nice.  You can clearly hear the subject each time it enters. Bravo for him. The digital reverb is a, uhm, like, you know, a nice touch, shall we say.

Now listen to four distinct instruments playing their own lines.  Pick one of the instruments and listen to how it weaves in and out of the whole. Listen how they answer one another, like Freddie's LH octave notes.

This is what we should strive for. Not to play a bunch of notes, be a slave to the notation, or mash it all together with the sustain pedal.  Other than harps and guitars, no other instrument can do that.
Go find an organ and play Freddy's BR. Your RH will be forced to be anchored to the Bb, your foot would be stuck on a pedal tone Bb and that forces the LH to play those counter 6ths and 5ths.  Just like Freddy originally played it on the piano.
What is wrong with Freddie?  Iguessnoonetaughthimthathecouldjustsmooshallthosenotestogetherwiththesustainpedal.
This is why pianists should sing.  It teaches them phrasing.  Or, at least, dabble in a wind instrument or organ so they don't learn to just throw notes away or cheat.


Multiplicative spectral sequence

Question: I have a simple question regarding the definition of a multiplicative spectral sequence, which I couldn't answer myself by looking at the definitions in various texts:

Is the product assumed to be associative?
Is it assumed that there is a multiplicative unit? It should live in bidegree $(0,0)$ on each page.
Is it usually assumed that the product is graded-commutative?
Answer: I'm basing myself on McCleary's book A user's guide to spectral sequences, sections 1.3 and 2.4. He actually calls them "spectral sequences of algebras", not "multiplicative spectral sequences". But it's probable that other sources give similar definitions (in the end, it all depends on what your applications are, I guess).

Yes, the product is almost* always required to be associative.
No, it's not always the case that there's a unit. (Indeed if there's one it should live in bidegree $(0,0)$, because if the unit $1$ is in bidegree $(p,q)$, then $1 \cdot 1 = 1 \implies (2p,2q) = (p,q)$.) It's extra structure.
No, it's not usually assumed. The most common example of a multiplicative spectral sequence is the Serre one, which is graded commutative, but it need not be the case. For example, the Adams spectral sequence is multiplicative, but it's not graded commutative if I'm not mistaken.

By the way you might be interested in this article of Bauer and Scull (I haven't read it yet). They say they have identified conditions on an operad such that if some page of your spectral sequence is an algebra over the operad, then so are the next pages. In general if your operad has trivial differential I believe the structure should pass through without any problem; there is nothing special about $\mathtt{Ass}$ (or $\mathtt{Ass}_+$, or $\mathtt{Com}$) here, and I think you could very well consider spectral sequences of Lie algebras, Poisson algebras...

* I write almost because I don't want to make an absolute statement in case someone comes up with a counterexample, but I think I could drop it. Of course I'm sure you can also consider spectral sequences where some page is an $A_\infty$-algebra if you wanted to, which aren't strictly associative, but the spirit is the same (and the next page would be strictly associative anyway). For example the $E_1$ page of the Serre spectral sequence is something that looks like $C^*(B; C^*(F))$ which is only homotopy associative and commutative.
Comment: Thank you. Can you give an example of a multiplicative spectral sequence which appears in practice and which has no unit?
Comment: I can't think of a "standard" example off the top of my head (Serre's, Adams's... are all unital), but whenever you want to know the homology of a filtered nonunital algebra through spectral sequences you will have an example.

Multiplicative spectral sequence


How to validate AWS Service belonging to an arn during terraform plan using Open Policy Agent?

Question: resource "aws_cloudwatch_event_target" "sns" {
  rule      = aws_cloudwatch_event_rule.console.name
  target_id = "SendToSNS"
  arn       = aws_sns_topic.aws_logins.arn
}

I would like to use Open Policy Agent to ensure the arn of the target above belongs to an allowed list of AWS services (like Lambda, SQS, SNS etc).
How can i verify this using OPA?
I can check if arn starts with aws::sns:: but the arn would be generated only at runtime during terraform apply and at plan time during terraform plan.
So how can i verify the arn during plan?
Answer: The common way of working with OPA and Terraform is to write policy that is run against the JSON represenation of terraform plan (and not the .tf files themselves), so that should not be a problem:
terraform plan -out tfplan.binary
terraform show -json tfplan.binary > tfplan.json

You'll now have a tfplan.json that will represent the planned changes in JSON format, and will include any values resolved at the time the plan was made. You can now run e.g.
opa eval --input tfplan.json --data policy.rego data.policy.allow

To run the policy stored in the policy.rego file against the input provided in the Terraform plan, querying the allow rule in the policy package (as a simple example).
I wrote an introduction to using OPA for Terraform policy some time back, covering this topic and a few others useful for getting started.
Comment: How so? Your question was "How can i verify this using OPA?", which is what I answered.
Comment: Appreciate the answer but this quite doesn't answer my question.


Can't load library path files

Question: I have added a library to the libraries folder. I have the Libraries API module installed and I wrote this code:

function my_module_libraries_info() {
  $libraries['google-api-php-client'] = array(
    'name' => 'Google Api PHP Client',
    'path' => 'src/Google',
    'vendor_url' => 'https://github.com/google/google-api-php-client',
    'download_url'=> 'https://github.com/google/google-api-php-client',
    'files' => array(
      'php' => array(
        'Client.php',
        'Service.php',
      ),
    ),
  );
  return $libraries;
}

and the code to call it

$library =libraries_load('google-api-php-client');
dpm($library);

This dpm did give me a library array, so it looked like it was ok. But then I tried
$client = new Google_Client();
and I got an error:
PHP Fatal error:  require(): Failed opening required 'http://[site-name-here]/sites/all/libraries/google-api-php-client/src/Google/Client.php'
When I tried this

 global $base_root;
  require $base_root . '/'. libraries_get_path('google-api-php-client') . '/src/Google/Client.php';

I got the same error message. I checked and saw tat the files were still there. What is going wrong?
Answer: Clearing the cache might help. I had tried to use libraries_flush_caches but that didn't seem to work. General CC did though - that will ensure libraries_load detects and loads the files you put in your files array.
Also, for this library (at least composer version "google/apiclient": "1.0.*@beta") , you want to put 'autoload.php' in your files array - it'll do what it sounds like, auto-load all the classes you want to use instead of you manually having to do it.

Can't load library path files


Looking for suggestions with a program that doesn't allow multiple sessions

Question: We are running a Windows Server 2012 R2 machine with Remote Desktop Services.  The idea is that everybody can log in and run company software that requires extensive configuration, that way we only have to configure it once and delegate the settings to everybody on that PC.
We have RemoteApps deployed as well and it works for the majority of programs.
However, there's one particular program, Lutron RadioRA, that refuses to work in this type of environment.  If it's opened by anybody on the computer, and another user tries to open it in their own RDP session, it complains that the program is already running and won't start.
My first thought was to try Sandboxie, as I know that's what it's designed for.  It didn't work at all... .NET crashed immediately and I got tons of "file too large for sandbox" errors and various other crashes until I forceclosed Sandboxie.
My next thought was to try "runas", since it's built into Windows.  I created a user called runastest with a simple password, and tried launching runas pointed to the program's EXE file.  Put in the password and it started up as expected.  Switched to another user, did the same thing using that same runastest user... same error about it already running.
I'm not sure what else to try, really.  We need a way to start the program without it checking what other programs are running on the computer, essentially - as I can't imagine why it would actually be problematic to have multiple copies open at once.  Everything's stored in the active user's session anyway, AppData and whatnot.
Comment: You should really open a support ticket with the app vendor about this. It may be against your license agreement to run it in this fashion even if it did work.
Comment: Yes, it's home automation software. Our business creates home theater setups for people, and we use the software to configure their lighting for them when setting it up.
We used to give our installers laptops with the software installed locally. But the idea going forward is that all the software will be on RemoteApps, and they'll just launch it from their laptops, but it's actually running on our server.

So it's not as if several people are trying to control the same lighting at the same time. We'd be using it in different contexts, if that makes any sense.
Comment: I think someone else at the company has tried to talk to them and not gotten anywhere.
Comment: Is that some type of home automation software? If so, it seems weird that you'd be running that in a business environment. What do you use it for, out of curiosity?
Comment: Why did you try app-v?
Comment: I'm guessing the Lutron RadioRA application is controlling the environmentals at your location (lighting, temperature, etc). What happens if you load up the software on two separate systems (virtual or physical)?  Are they both able to control the same environmental system at the same time?  If not then there's nothing you can do, aside from seeing if that application offers a web interface that can be accessed from a browser.
Comment: @DannyForche man I feel for you. I did IT in the same industry, and every application used in home theater and automation is crap. Oh what's that? It's 2015 and you're telling me the guy who designs motorized shades need to be a local administrator and I need to disable UAC?
Answer: The program is intended to run as a single instances.
On Windows developing, it's called "Global Mutex". I don't know how you can by-pass it. And even if you can, it's a bad idea. Since the program was developed with single instance in mind, and bypassing that, would leave you with a unpredictable behavior of the software.
IMHO, you should install an VNC server on the remote host, and share the instance, everybody will access the same desktop instance, allowing then to use the software at the same time. Yes! At the same time, it's means people will start to fight to move the mouse.
Edit:
With some research I found this solution for Lync. Maybe it's work for you. It's use a "IsolatedSynchronizationObjects" option for ThinApp, that will ensure a "Global Mutex" will be isolated. In the same link, it's show how you can detect if the application is using a global mutex or not with the Process Explorer.
Comment: These applications are often designed with restrictions or oversights like this that have nothing to do with the application's needs. Like it still writes it's configuration in the program files directory, so they'll tell you that you need to be an administrator when in reality you could just change the permissions on that one directory to allow Users to write/modify and everything works fine (or they could fix the damn thing by storing files the correct place). I could be wrong but I doubt there is good reason for Lutron software to be single instance on a given machine.
Comment: Yeah, it's often lazy programming. QuickBooks does the same thing, and it was a nightmare to fix, we had to go messing with permissions on drive C because it wouldn't store its stuff in AppData like every other program.
Comment: Yep, in general, it's a over designed solution. I think the developers who made this software is worried with two user changing the same resource at same time. Like @RyanBolger said, you need to open a support ticket and explain your use case.

If the developer used a global mutex, it's impossible to open the second instance without exploiting the application or the windows kernel. And from your problem description, I bet that's the case.


To mix sounds using OpenAl

Question: Anybody have any idea about how to mix sounds in iphone.We can use OpenAl that i know but need some sample application or code which would be easier for me to understand this concept As i have seen some apples demo application which uses openGl along with openAl and is too confusing for me to understand this as i am new to this openGl environment
Thanks All in advance.
Answer: I would suggest you visit here
http://connect.creativelabs.com/openal/Documentation/OpenAL_Programmers_Guide.pdf
and download the guide. There are plenty of code snippets in the guide that can help you build the code base that you need. Works on the iPhone too, I built a mixer once myself :)
Good luck!
EDIT
http://www.devmaster.net/articles/openal-tutorials/lesson1.php
http://kcat.strangesoft.net/openal-tutorial.html
Comment: Hi! openal is not an iPhone specific api, it is plain c, the code provided in the tutorials works on the iPhone too.
Comment: Thanks for the links but none of them are iphone tutorials some use C,C++And java but i need for iphone or ipad (objective c) the PDF book is helpful.

To mix sounds using OpenAl


Differentiate exponential/logarithm function

Question: Given the function, $e^{2x+1}\ln3x$,
I can differentiate the two separately but how do I combine them?
$\dfrac{d}{dx} e^{2x+1}$ = $2e^{2x+1}$
$\dfrac{d}{dx}\ln3x$ = $\ln3$
Answer: The Product Rule for Differentiation states that if two functions $f$ and $g$ are differentiable, then their product $fg$ is differentiable and
$$\bbox[5px,border:2px solid #C0A000]{\frac{d(fg)}{dx}=f\frac{dg}{dx}+g\frac{df}{dx}}$$
Here, we have $f=e^{2x+1}$ and $g=\log 3x$.  Thus,
$$\frac{df}{dx}=\frac{de^{2x+1}}{dx}=2e^{2x+1}$$
and
$$\frac{dg}{dx}=\frac{d\log 3x}{dx}=\frac{1}{x}$$
The derivative of the product is
$$\begin{align}
\frac{d(fg)}{dx}&=f\frac{dg}{dx}+g\frac{df}{dx}\\\\
&=\frac{d\left(e^{2x+1}\log 3x\right)}{dx}\\\\
&=\left(e^{2x+1}\right)\times\left(\frac{1}{x}\right)+\left(\log 3x\right)\times \left(2e^{2x+1}\right)
\end{align}$$
Answer: Using the chain rule, you differentiate each function in turn:
$$\frac{d}{dx}uv = u\frac{d}{dx}v + v\frac{d}{dx}u$$
$$\frac{d}{dx}e^{2x+1}\ln3x = 2e^{2x+1}\ln3x + \frac{1}{x}e^{2x+1}$$
$$\frac{d}{dx}e^{2x+1}\ln3x = e^{2x+1}\left(2\ln3x + \frac{1}{x}\right)$$
Note that the derivate of $\ln3x \neq \ln3 $ becaue $\ln3x = \ln3 + \ln x$ and since $\ln3 $ is just a constant, it becomes zero when its defferentiated leaving you with $\frac{d}{dx}\ln x =\frac{1}{x}$


Why doesn't smart-cast handle this situation?

Question: I have some code with a similar structure to this:
<code>private fun test() : Double {
    val a : Double? = 15.0
    val b : Double? = 20.0
    return if (a == null && b == null) {
        0
    } else if (a != null && b == null) {
        a
    } else if (a == null && b != null) {
        b
    } else {
        a+b
    }
}
</code>
From my understanding, smart casting should infer that in the final 'else' statement, neither a nor b can be null, yet it doesn't seem to infer this which results in an error.
Is there a legitimate reason that smartcasting isn't working in the way I expect here, or is it just not as smart as I think it is?
Comment: Please report this as a bug to the Kotlin issue tracker if you do not find an existing bug that matches.  https://youtrack.jetbrains.com  ... you can then note the bug you created here so others can find it.  Your bug report can be added as an answer to your own question or you can update the question to note the link to the bug.
Answer: It just isn't as smart as you think it is.
There are a slew of smart cast related issues in IntelliJ IDEA's issue tracking system. e.g. https://youtrack.jetbrains.com/issue/KT-6822 which is a subtask of https://youtrack.jetbrains.com/issue/KT-2454 which lists other possibly related issues. I would go through those and see if your issue is already tracked or not and, if not, creating one for this and see what comes of it.


Views Escaping Special Characters in URL

Question: I am creating a view with a list of titles that link to the relevant full article that is also displayed via a view.
The view that contains the article has a contextual filter which contains the Title and the of the views is "mysite.com/%"
So the article that is named "hello world" will be found at "mysite.com/hello-world"
However if the article has the ' special character in it for example "Children's Book" the link that I create to point at the article will be "mysite.com/Children%26#039;s-Books" which brings back an empty result.
Answer: With the Pathauto module you can strip the special Chars. Here is a quote about it (from the module's project page):

... automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.
Comment: Thanks but I'm sill confused, I am talking about arguments in views rather than the actual alias of the node...unless I am missing something.
Answer: You can configure under Contextual Filter > More  setting. There are some transform settings.
Comment: @gilzeroI don't find any option related remove special characters in setting.
Answer: You can try to override the template for your view, and there escape the string that is sent with urlencode(); assuming that you have the necessary Drupal experience to do that.


Configurar Firewal Servidor SQL

Question: Como configura a regra do firewal para não ficar pedindo atualização de um novo IP ?
Criei uma conta no azure e tenho um sistema que esta em teste e o servidor sql server de tempos em tempos pedi para atualizar o IP e quando acontece isso o sistema não acessa o banco de dados e tenho que sempre adicionar um novo range de IP.
Comment: Poderia esclarecer melhor o seu problema?
Answer: A solução mais directa (se for possível) é colocar a maior gama possível:
0.0.0.0 - 255.255.255.255
Comment: @Renato Afonso vou tentar e assim que possível eu retorno, obrigado!

Configurar Firewal Servidor SQL


Given two sequences of positive numbers with $\sum_{n\ge1}\frac{x_n}{y_n}$ and $\sum_{n\ge1}y_n$ convergent, is $\sum_{n\ge1}\sqrt{x_n}$ convergent?

Question: Consider two sequences of positive numbers $(x_n)$ and $(y_n)$. Suppose that the series
$$\sum_{n \ge 1} \frac{x_n}{y_n}$$
and the series
$$\sum_{n \ge 1} y_n$$
are both convergent. Is the series
$$\sum_{n \ge 1} \sqrt{x_n}$$
also convergent?
This is what I tried:
We know that the series:
$$\sum_{n \ge 1} \frac{x_n}{y_n} \hspace{4cm} \sum_{n \ge 1} y_n$$
are both convergent. By the $n^{th}$ Term Test, we can conclude that:
$$\lim_{n\to\infty} \frac{x_n}{y_n} = 0$$
and
$$\lim_{n\to\infty} y_n = 0$$
Now, since we know that the series $\sum_{n \to \infty} y_n$ is convergent and that
$$\lim_{n \to \infty} \frac{x_n}{y_n} = 0 \in [0, \infty) \cup \{\infty \}$$
we can conclude by the Second Comparison Test that the series
$$\sum_{n \to \infty} x_n$$
is convergent.
Now, using the $n^{th}$ Term Test again, we get that
$$\lim_{n \to \infty} x_n = 0$$
But this is about as far as I got. I don't really see how to draw any conclusion about the series $\sum_{n \to \infty} \sqrt{x_n}$. I don't know how to take into consideration that square root.
Comment: $\sqrt {x_n} =\sqrt {\frac  {x_n} {y_n}} \sqrt {y_n}$. Apply Cauchy-Schwarz.
Answer: Hint: $$\sqrt{x_n}\leqslant\frac12\left(\frac{x_n}{y_n}+y_n\right).$$
Comment: I see. I can apply the First Comparison Test on that inequality and then get that the series is convergent, right? Is what I did above completely useless? I don't see that it helps in any kind of way.
Comment: @user1502: Right. And I often continue the attempts given, when I can (and it isn't done by someone else). This time, I see no way.
Answer: By Cauchy–Schwarz inequality we have
$$\sum_{n \ge 1} \sqrt{x_n}=\sum_{n\ge1}\left(\frac{ \sqrt{x_n} }{ \sqrt{y_n}}\cdot \sqrt{y_n}\right)\le \left(\sum_{n\ge1}\frac{x_n}{y_n}\right)^2 \cdot \left(\sum_{n\ge1}y_n\right)^2 $$