Como salvar o caminho de uma imagem no Banco de Dados?

Question: Estou utilizando JDBC e pegando uma imagem para guardar no banco de dados. Porém eu quero guardar a imagem no HD e salvar no banco apenas o caminho (path) dela.
Eu queria saber qual é o melhor tipo que eu uso para manipular e salvar a imagem (Image ou File). Já que a maioria das funções do File são relativas à String;
A imagem é selecionada pelo form do html e passada como se fosse um servlet, porem, eu a uso numa de Controller para que fique um código mais simples e coeso.
Comment: Se for inserir apenas o caminho, porque não uma String ? File.getAbsolutePath() ?
Comment: A imagem é selecionada pelo form do html. Como se fosse um servlet
Answer: Não é possível por questões de segurança.
De forma bem simples: Nenhum site precisa saber qualquer coisa sobre sistema de arquivos do usuário. Quando um arquivo é enviado para um servidor somente os dados do mesmo são importantes.
No Firefox você ainda consegue visualizar o mozFullPath que mostra o absolute path de um arquivo utilizando Javascript, mas se tentar pegar/usar esse valor ele retornará uma string vazia.

/* CTRL+SHIFT+J para ver a mensagem no console. */

document.getElementById('file').onchange = function(){
    console.dir(this.files[0]);
    console.log("mozFullPath: " + this.files[0]['mozFullPath']); // vai retornar ""
};
<input id='file' type='file'/>

Você verá algo assim:
Comment: Entendi. Mas eu quero é primeiro salvar o arquivo no meu HD. Para depois pegar o Caminho, e assim guarda o caminho no banco de dados.O meu problema maior e saber qual tipo de variavel eu uso para manipular a imagem. Porque se eu uso o `Image` eu não consigo salva-lo no sistema, e se eu uso o tipo `File` eu não consigo coloca a imagem dentro do tipo File.
Answer: Salvando o caminho completo
Para salvar em um banco de dados você deve salvar o caminho como uma String.
Obviamente o seu código que lê e grava os registros pode encapsular essa String em um File  por exemplo, recuperando a String banco e criando um File ou recuperando o caminho do arquivo como String e gravando no banco de dados.
Nessa situação, faça o que for mais conveniente.
Organizando os arquivos
Porém, a não ser que seja um requisito absolutamente necessário do seu sistema, eu não salvaria o caminho completo dos arquivos.
Em geral, seria mais adequado definir um diretório na configuração do programa e salvar todos os arquivos selecionados naquele diretório.
Então você pode salvar apenas os nomes das imagens no banco e, quando precisar salvar o arquivo, basta fazer algo como:
new File(configuracao.getPastaArquivos(), nomeArquivo)

Aliás, nem o nome do arquivo é necessário. Se você tiver, por exemplo, uma tabela no banco de dados onde salva as informações do arquivo, pode simplesmente salvar o arquivo na pasta usando o ID como nome.
Então o caminho no disco seria algo assim:
new File(configuracao.getPastaArquivos(), arquivo.getId())

Dessa forma, os dados do arquivo (como o seu nome) ficam no banco de dados e você tem tudo organizado em uma pasta pelo ID.
É mais fácil fazer backup, mover os arquivos para outro local se necessário e também evita problemas com caracteres especiais nos nomes, espaços e acentuação. Também permite situações onde dois usuários do sistema enviam um arquivo com mesmo nome.


preg_match do not allow the last character to be underscore or dash

Question: I have a regex which works nicely for usernames.
I want to tweak it somewhat to stop -_ characters from being used as the first/last character of a username. But, allow them elsewhere in the username.
This is what I have so far.
if(!preg_match('/^[a-zA-Z0-9_-]{3,16}+$/', $user)){
    echo 'not valid';
} else {
    echo "is valid username";
}

Answer: That + at the end of your regex should actually throw an error. Just remove it.
Use this, plain and simple:
^[a-zA-Z0-9][a-zA-Z0-9_-]{1,14}[a-zA-Z0-9]$

Answer: Use lookarounds.
^(?![_-])[a-zA-Z0-9_-]{3,16}(?<![_-])$

Also you dont need + after {1,16}


Multiple Context block order / weight

Question: I have 2 Contexts set up that each place a block in the same region.
There are times when both these contexts will happen at the same time and as such both blocks appear together.
Currently when both appear they are not in the order I require, is there a way of weighting these across contexts?  I know the weighting works within a context however this is not what I need at this point.
Currently using:
Drupal 6.22,
Context 6.x-3.0
UPDATE:
Hi All,
This post appears to get quite of interest but I'm afraid I don't use Drupal anymore or have any time (or sites) to check these answers.  If any answer gets enough interest and appear to be right then I'll happily mark it correct but I can't actually verify anything.
Answer: This patch worked for me. Enable the patch at admin/build/context/settings.
There is a lot that gets discussed after that comment and one contributor even created a module. I haven't read much of the other comments, implemented the module nor any of the patches posted after the one I referred to above.
Answer: There's still no definitive solution for this problem, you might have a look at Block weights when multiple contexts are set or maybe context_respect. You can also have a look at Way to Weight Blocks that Show From Multiple Contexts for some background information.
One work-around is to export all your context to code (using features) and edit the weight inside the created code files, the only problem is that if you re-export your feature, your manual changes will be reverted. We use this approach for the moment because it fits in our workflow.
Answer: I just fixed this for myself (while using version 7.x-3.x), using hook_context_load_alter().  Basically, you can implement this in your own misc module, print out what you're getting with dpm(), and then adjust as needed.  Here's what I ended up doing:
/**
 * Implements hook_context_load_alter().
 */
function example_misc_context_load_alter(&$context) {
  // We need to make sure that the mobile section menu is printed before these menus,
  // so we set the weights to -9 here so they appear after it.
  if ($context->name == 'about') {
    $context->reactions['block']['blocks']['menu_block-15']['weight'] = -9;
  }
  if ($context->name == 'traveler') {
    $context->reactions['block']['blocks']['menu_block-1']['weight'] = -9;
  }
}

Comment: There is more then one way to fix this. John's solution is the most correct and certainly the cleanest. Documentation on hook_context_load_alter is here: http://drupalcontrib.org/api/drupal/contributions%21context%21context.api.php/function/hook_context_load_alter/7
Answer: The weight context assign to a block is a number, that will effect the position of all the blocks that any context will add to any region. There isn't an UI to tweak these weights to mix blocks from several contexts, but there is a way around it.
The easiest solution I could find, was to run some custom JavaScript in a browser console:
 $(".form-item").show()

This will show all the weights that control the sorting. Tweaking these would allow you to sort the blocks like you want.
Answer: You can edit (carefully) the serialised values in the context table through phpMyAdmin.  This has to be done again every time the context is edited through the UI.  But it's not a bad solution which avoids the overhead of installing extra modules to solve this.
Comment: The reason I suggested this was a failure to get anywhere with some of the suggestions above:

(1) I didn't like the idea of patching Context, as that opens up a maintenance liability.
(2) context_respect seemed not to affect weights - only block visibility.
(3) Implementing Features is a much more admin-intensive solution than the occasional phpMyAdmin tweak - if Features is **not** currently part of the workflow.

So I felt that my solution, while clearly not perfect, may be worth considering alongside the other options.

Multiple Context block order / weight


The request failed with HTTP status 417: Expectation Failed - Using Web Services

Question: some minutes ago i was working on a project in visual studio 2010 and suddenly my pc was restarted.
after rebooting i got the error below when browsing that web site in local machine:

The request failed with HTTP status 417: Expectation Failed.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Net.WebException: The request failed with
HTTP status 417: Expectation Failed.

my web site's name is : MyWebSite
i have a web service on a remote server (a vps) that MyWebSite is using it and that error is in relationship with it.
Line 172:        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/MyWebSiteEnable", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
Line 173:        public bool MyWebSiteEnable() {
Line 174:            object[] results = this.Invoke("MyWebSiteEnable", new object[0]);
Line 175:            return ((bool)(results[0]));
Line 176:        }

every thing is ok about that web service.
so what is this error and how can i fix it?
there is just a simple bool method inside that web service that returns true.
and i am using that web servive in code-behind like below :
private void CheckForPageExpiration()
{
    MyService service = new MyService();
    if (service.MyWebSiteEnable())
    {
    }
    else
    {
        Response.Redirect("~/blank.aspx");
    }
}

i removed that web service and add it again, but still have that error!
what is wrong about that?
thanks in advance
Comment: i think that is for my ADSL internet. i test that web site with another wifi internet and every thing was ok. so what should i tell to that isp?
Answer: This suggests that the problem is a proxy server that does not support a 100-continue response from the server, and shows code for resolving it. This would explain why it works on another network.
Since you are unlikely to convince your ISP to change their practice (no harm in a request though), you should turn off the behavior of sending a 100-Continue as the link suggests by either:
Putting this code before an web request:
System.Net.ServicePointManager.Expect100Continue = false;

Or, adding the following lines to the applications configuration file as a child of the <configuration> tag:
<system.net>
    <settings>
        <servicePointManager expect100Continue="false" />
    </settings>
</system.net>

Comment: i test it and that was the problem. i know this problem is for my isp. but what should i tell them to fix?
Comment: thanks for the answer / i read that / but is disabling expect 100 continue the right solution? / i do n't think so and that is why i asked this Q again here! i have no problem in my web server, and only local machine (adsl internet) is the problem. so there should be another way to fix that exception.
Comment: But at least if you try disabling 100-continue you can see if it fixes the problem. If nothing else it will help you understand what the problem is, and perhaps provide more options for a solution.
Comment: I going through the same issue but worst part is when had this issue i wrote a test application to test my webservice call but it is working fine. any idea?
Answer: Add below line of code in your config file.
<system.net>
    <defaultProxy useDefaultCredentials="true" >
    </defaultProxy>
</system.net>


Spectral radius of a complete bipartite graph

Question: Let $p, q > 0$ be integers and let $K_{p,q}$ be a complete bipartite graph. Let $A(K)$ denote the adjacency matrix of $K_{p,q}$ according to a convenient labeling of vertices , which is the $2 \times 2$ block matrix
$$\begin{bmatrix}
0_{p \times p} & 1_{p \times q}\\
1_{q \times p} & 0_{q \times q}
\end{bmatrix}$$
I know that the spectral radius of $A(K)$ is $\sqrt{pq}$ but couldn't prove it. I tried to find the determinant of the characteristic polynomial in order to find the spectrum but also couldn't. Any help would be appreciated.
Answer: The spectral radius of $A(K)$ is the square root of the spectral radius of $A(K)^2$. Note that
$$
A(K)^2 =
\begin{pmatrix}
q\mathbf{1}_{p \times p} & 0\\
0 & p\mathbf{1}_{q \times q}
\end{pmatrix}.
$$
Hence
$$
\det(xI - A(K)^2) = \det(xI - q\mathbf{1}_{p \times p})\det(xI - p\mathbf{1}_{q \times q}) = (x - pq)^2x^{p + q - 2}.
$$
Comment: $pq$ is clearly is an eigenvalue of $q\mathbf{1}_{p \times p}$ (take $\mathbf{1}_{p \times 1}$ as an eigenvector) and this matrix has rank 1, so $0$ is an eigenvalue with multiplicity $p - 1$, which implies that $pq$ has multiplicity $1$ and there can be no other eigenvalues.
Comment: Define $X$ please.
Comment: @sal.f Sorry, I meant $K$. Edited.
Comment: No worries, thank you.
Comment: Sorry, but how did you find $\det(xI - q\mathbf{1}_{p \times p})$ ?
Comment: Okay , thank you
Comment: One could use the [matrix determinant lemma](https://en.wikipedia.org/wiki/Matrix_determinant_lemma) to compute the characteristic polynomial of each block.


É possível simplificar o comando Runnable numa função do Android?

Question: Criei uma classe para facilitar a utilização de Dialogs, e gostaria de saber se é possível simplificar ainda mais.
Minha Classe está assim:
public class FVRDialog {
    private Activity act;
    private Context context;
    private AlertDialog dialog;

    public FVRDialog(Activity act) {
        this.act = act;
    }

    public boolean Confirm(int icon, String Title, String ConfirmText,
                       String OkBtn, String CancelBtn, final Runnable OkBtnPress, final Runnable CancelBtnPress) {

    dialog = new AlertDialog.Builder(act).create();
    dialog.setTitle(Title);
    dialog.setMessage(ConfirmText);
    dialog.setCancelable(false);
    if (icon != 0) { dialog.setIcon(icon); }
    dialog.setButton(DialogInterface.BUTTON_POSITIVE, OkBtn,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int buttonId) {
                    OkBtnPress.run();
                }
            });
    dialog.setButton(DialogInterface.BUTTON_NEGATIVE, CancelBtn,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int buttonId) {
                    CancelBtnPress.run();
                }
            });
    dialog.show();
    return true;
   }

    public void dismiss() {
        dialog.dismiss();
    }
}

E para executar eu estou fazendo assim:
final FVRDialogs fvrdialog = new FVRDialogs(this);
       fvrdialog.Confirm(@drawable/ic_pergunta, "Titulo", "Descrição", "Sim","Não",
           new Runnable() { public void run() { executarBtnSim(); } },
           new Runnable() { public void run() { executarBtnNao(); } });

Eu gostaria de simplificar sem precisar usar o runnable, deixar se possível, mais ou menos assim:
FVRDialogs fvrdialog = new FVRDialogs(this);
 fvrdialog.Confirm(@drawable/ic_pergunta, "Titulo", "Descrição", "Sim","Não", executarBtnSim(), executarBtnNao());

Ou se tiver algum outro jeito mais interessante de fazer istso, estou aberto a sugestões.
Answer: O Android Studio 3 dá suporte à algumas funcionalidades do Java 8. Você pode habilitar isso adicionando as seguintes linhas no build.gradle:
android {
  ...
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

Desta forma você pode passar um lambda como parâmetro:
fvrdialog.confirm(@drawable/ic_pergunta, "Titulo", "Descrição",
    "Sim","Não", () -> executarBtnSim(), () -> executarBtnNao());

Ou uma referência de método:
fvrdialog.confirm(@drawable/ic_pergunta, "Titulo", "Descrição",
    "Sim","Não", this::executarBtnSim, this::executarBtnNao);

Comment: Eu diminuiria ainda mais a chamada à função. `this::executarBtnSim` eu acho mais digno de lambda do que `() -> this.executarBtnSim()`.
Comment: @JeffersonQuesado bem observado. Adicionei na resposta
Comment: Obrigado amigos, funcionou bem para mim. Só tenho mais uma dúvida, na documentação mencionada ele explica algo sobre compatibilidade com `Jack`, o que seria isso? Será q posso ter problemas futuros de compatibilidade utilizando Java 8??
Comment: O que acontece é que na verdade o Android não dá suporte nativo ao Java 8 antes da versão 24. Eles usam uma ferramenta que traduz o seu código para uma versão compatível com o Java 7, um processo que eles chamam de  _desugaring_. A equipe do Google tinha desenvolvido o _Jack toolchain_ pra isso, mas eles resolveram abandoná-lo por uma solução melhor. Esta nova solução é suportada oficialmente pelo Google e você pode usá-la sem medo de problemas de compatibilidade.


Prove $\vec i^i = \vec i_i$ in rectangular coordinates

Question: Prove $\vec i^i = \vec i_i$ where $\vec i_i$ is a basis vector and $\vec i^i$ is a dual basis vector in rectangular cartesian coordinates.
My attempt:
$\vec i^i \cdot \vec i_j = \delta_j^i$$\delta_j^i = 1$ if $i=j$$\vec i^i \cdot \vec i_i = 1$
Since the bases in rectangular coordinate systems are orthonormal...
$\vec i_i = 1$
Given that $\vec i^i \cdot \vec i_i = 1$...
$\vec i_i = \vec i^i = 1$
Thanks!
Comment: Letter $i$ to denote tensor, letter $i$ to denote index... now all you need is the letter $i$ to denote the complex scalar and you'll have a truly unholy trinity.
Comment: Haha yes, the notation is pretty redundant.
Answer: I see this from a geometric perspective, but there may be a more general way to see it!
You see, Euclidean space is actually a Riemannian space with $g=I$ or $g_{ij}=\delta_{ij}$ in Cartesian coordinates.
What you seem to be asking is about the musical isomorphism and raising and lowering indices. Here we are talking about vectors and covectors, but more generally one can talk about contravariant and covariant tensors. In any case, when a metric is available, one can lower an index by contracting with the metric.
So, in this case: $$ v_j = g_{ij}{v}^i = \delta_{ij}v^i $$
where notice that the RHS is just the $j$th component of the vector.
Or, in matrix-vector notation: $$ v = Iu = u $$ where $v$ is the dual of $u$.
See also here and here.


How to pass text value to MFMailcomposeView Controller

Question: Hi guys faily newbie here tons to learn in IOS
I am using messageUI  and I want to pass a text value to MFmailComposeviewController
this is why I have try so far
  var userdata = String(txtUserEmail.Text)

  let mail = MFMailComposeViewController()

  mail.setToRecipients([" \(userdata)"])

for somereason  when I enter a email address it does not show in the composer of course there are other parts to the code that I have not included on here. As the main problem is i am unable to pass this value to the setToRecipients([])
any support would be most welcome here
Answer: Is txtUserEmail a UITextField?
If so declare your userdata like this:
let userdata = txtUserEmail.text
mail.setToRecipients(userdata!)

A UITextField.text (not "Text") already returns a string.
Comment: something so simple, yet not obvious at the time of coding God I feel so mmm, thanks, Alex,
Comment: You're welcome. If it fixed the problem could you please select my answer? Thank you


Method that checks if one word is a rotation of another

Question: Working on the Cracking The Coding Interview problem that asks for a method that checks if one string is a rotation of another. The one caveat to the problem is that it must be solved with a single call to isSubstring(s1, s2).
I fully understand the author's solution that says-- if s2 is a rotation of s1, then you can break s1 into two parts x and y such that s1 = xy and s2 = yx. The author continues to say, therefore, that s2 must be a substring of s1s1 (yx is a part of xyxy).
I'm writing this question to make sure I'm understanding thoroughly. Isn't it equivalent to say that s1 must be a substring of s2s2 (that is, xy must be a substring of yxyx) for s2 to be a rotation? And in that way, both approaches are equivalent? Not sure if I'm missing something..
Comment: The question is only two sentences in the book that it came from, so there's really not a lot more to add to it.
Comment: A reference to a problem on an external site that is not even linked and only described in such a vague way as you did isn't helpful. Please edit with a description of the actual problem (link is optional and should only be provided in addition to a description of the problem).
Answer: Yes, those two are equivalent. If s1 is a rotation of s2, then s2 is also a rotation of s1, so it doesn't matter which direction you approach the problem from. s1 will be a substring of s2s2 and s2 will be a substring of s1s1 if the two strings are rotations of each other.


Could not load HiveConf in Sqoop workflow in Oozie

Question: I created a Sqoop workflow in Oozie to sqoop data from MySQL into Hive table.
If I run Sqoop job in terminal, it run fine and data were successfully inserted into Hive table, but if I put the job inside Oozie and run it, it gives me an error:
Could not load org.apache.hadoop.hive.conf.HiveConf. Make sure HIVE_CONF_DIR is set correctly.

Encountered IOException running import job: java.io.IOException: java.lang.ClassNotFoundException: org.apache.hadoop.hive.conf.HiveConf

Can anyone help me with this?
I'm using HDP 2.5 here.
Below is my properties file for Oozie:
nameNode=hdfs://master.nodes:8020
jobTracker=master.nodes:8050
queueName=default
examplesRoot=jas-oozie

oozie.use.system.libpath=true
oozie.libpath=${nameNode}/user/oozie/share/lib
oozie.action.sharelib.for.pig=hive,pig,hcatalog
oozie.action.sharelib.for.hive=pig,hcatalog,atlas,hive

oozie.wf.application.path=${nameNode}/user/${user.name}/${examplesRoot}/jas-oozie-workflow.xml
outputDir=jas

and below is the xml file for Oozie:
<?xml version="1.0" encoding="UTF-8"?>

<workflow-app xmlns="uri:oozie:workflow:0.2" name="jas-import-wf">
    <start to="sqoop-import-air-quality-node"/>

    <action name="sqoop-import-air-quality-node">
        <sqoop xmlns="uri:oozie:sqoop-action:0.2">
            <job-tracker>${jobTracker}</job-tracker>
            <name-node>${nameNode}</name-node>
            <prepare>
                <delete path="${nameNode}/user/${wf:user()}/${examplesRoot}/output-data"/>

            </prepare>
            <configuration>
                <property>
                    <name>mapred.job.queue.name</name>
                    <value>${queueName}</value>
                </property>
            </configuration>
            <arg>import</arg>
            <arg>--connect</arg>
            <arg>jdbc:mysql://xx.xx.xx.xx:3306/xxxx?dontTrackOpenResources=true&defaultFetchSize=1000&useCursorFetch=true&zeroDateTimeBehavior=convertToNull</arg>
            <arg>--driver</arg>
            <arg>com.mysql.jdbc.Driver</arg>
            <arg>--username</arg>
            <arg>xx</arg>
            <arg>--password</arg>
            <arg>xx</arg>
            <arg>--query</arg>
            <arg>
                select <fields> from
 where $CONDITIONS
            </arg>
            <arg>--hive-import</arg>
            <arg>--hive-drop-import-delims</arg>
            <arg>--hive-overwrite</arg>
            <arg>--hive-table</arg>
            <arg>table</arg>
            <arg>--target-dir</arg>
            <arg>/user/${wf:user()}/${examplesRoot}/output-data/sqoop-import</arg>
            <arg>-m</arg>
            <arg>1</arg>
        </sqoop>
        <ok to="end"/>
        <error to="import-air-quality-fail"/>
    </action>

    <kill name="import-air-quality-fail">
        <message>Sqoop from ICP failed, error message[${wf:errorMessage(wf:lastErrorNode())}]</message>
    </kill>

    <end name="end"/>
</workflow-app>

Thank you.
Comment: You need to configure oozie share lib--https://docs.hortonworks.com/HDPDocuments/HDP2/HDP-2.4.2/bk_installing_manually_book/content/setting_up_sharelib.html
Comment: There is already a share/lib folder in my HDFS /user/oozie folder.

In fact if I run this command:

oozie admin -shareliblist

I will get all the lib list
Comment: is hive-exec jar in the list?
Comment: Yes, is in the hive folder in oozie share lib
Answer: 1) create a directory lib in path ${nameNode}/user/${user.name}/${examplesRoot}/
2) add hive-exec jar in ${nameNode}/user/${user.name}/${examplesRoot}/lib/ path and try again


How to set image dimensions to parentNode as atrribute with javasript?

Question: I need to add image dimensions to parentNode as atrribute with javasript. But I am getting Uncaught TypeError: Cannot read property 'setAttribute' of undefined, result in html is  data-size="undefinedxundefined". What am I doing wrong? Thanks you
My JS code:
var imgs = document.getElementsByClassName("wp-post-image");

for (i in imgs){
       var x = imgs.naturalWidth;
       var y = imgs.naturalHeight;
       var sizevalue = x+'x'+y;

       imgs[i].parentNode.setAttribute("data-size", sizevalue);
}

Html:

<img width="1000" height="750" src="http://www.example.cs/wp-content/uploads/2020/04/Job_10458_2500px.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="Fotografie parfem" srcset="http://www.kasparstudio.cs/wp-content/uploads/2020/04/Job_10458_2500px.jpg 1000w, http://www.kasparstudio.cs/wp-content/uploads/2020/04/Job_10458_2500px-300x225.jpg 300w, http://www.kasparstudio.cs/wp-content/uploads/2020/04/hob_10458_2500px-768x576.jpg 768w" sizes="(max-width: 1000px) 100vw, 1000px" title="hob_10458_2500px" itemprop="thumbnail">

Answer: There were several problems:

for in is not recommended for looping over an array.
You were trying to get the naturalWidth/naturalHeight for the array of images, and not for a single image, and it returned undefined.
You should use the dataset property instead of setting a data-* attribute.

var imgs = document.getElementsByClassName("wp-post-image");

for (const img of imgs){
       var x = img.naturalWidth;
       var y = img.naturalHeight;
       var sizevalue = x+'x'+y;

       img.parentNode.dataset.size = sizevalue;
}

console.log(document.getElementById("link").getAttribute("data-size"))

As you can see, the data-size attribute of the hyperlink has the expected value.


Multicollinearity when adding a confounding variable

Question: When you run a regression on ice cream sales with predictor shark attacks, you find a significant coefficient. But that is because there is a confounding variable temperature.
But how do you correct for this confounder? In case you also add temperature to the model, you have two correlated predictors and the multicollinearity problem. So in case you found the confounder temperature, is the only option to leave the shark attacks out of the model?
Answer: First, just because two variables are fairly highly correlated does not mean they are colinear to a problematic degree.  Problematic collinearity is best examined with condition indices. See the work of David Belsley or see my dissertation Collinearity Diagnostics in Multiple Regression: A Monte Carlo Study.
Second, if you did find high collinearity, you could solve it with methods such as ridge regression, which are biased but have better variance when there is collinearity.
Third, the effects of collinearity are seen in the variances of the parameter estimates, not in the parameter estimates themselves. So, when you see that the parameter estimate for shark attacks is greatly reduced, that is a sign of confounding.
Comment: I am still confused about the concepts. On one hand, adding a confounding variable improves your model. A textbook example is adding a gender dummie. On the other hand, wikipedia says a confounder is typically correlated with both the independent and the dependent variable, and thus increasing the confidence intervals of the coefficient estimates (multicollinearity).
Comment: Adding a confounding variable ought to make it clear that the original independent variable is not needed. e.g. that you ought to model ice cream sales by temperature, not shark attack.
Comment: Ok and in the case of adding the gender dummie, that isn't really a confounding variable, just another significant predictor?
Comment: Indeed, in most cases anyway.
Comment: Ok. And why is it than exactly that confounding variable and multicollinearity al rarely mentioned in the same chapter (i.e. on the wikipedia page of confounding, multicollinearity is not mentioned).
Comment: I can't say why people don't mention something; you'd have to ask the authors :-). Perhaps because the reason for confounding is clear in this case, as is the remedy?
Answer: If you cannot use a linear regression with a controlling variable, or related, the partial correlation, another option is to stratify on the temperature variable.
To do so, categorize temperature into multiple, say five, categories. Then you run five conditional regression models, i.e. for the units in each category of temperature one model of shark attacks and sales. Use the quintiles of temperature as thresholds for categorization.
The net effect of shark attacks is found by taking the weighted average of the regression parameter across the categories of temperature (i.e. weighted for the category frequency of temperature).
I believe there is an argument by Cochran that says that stratifications of this type can remove 90% of the bias due to confounding.


How to get JSON Object by variable?

Question: My json code:
var jsontest = {
    "testlang": "no no testlang dziala lol"
}

i want get "testlang" by variable, eg:
var variabletest = "testlang";
jsontest.variabletest

can anyone help plz?
Comment: Duplicate of https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable
Answer: In this case the below would work
const jsontest = {
    "testlang": "no no testlang dziala lol"
}
const variabletest = "testlang";
console.log(jsontest[variabletest])

How to get JSON Object by variable?


What is the gradient of $\frac{1}{|x|}$?

Question: Given a function $V(x)$:
$$\displaystyle V(x) =  \frac {1}{||x||}$$
What is the gradient, $\nabla V$, of $V$?
The result I saw is: $\displaystyle -\frac {x}{||x||^3}$.
How do I get this?
Comment: You should complete the question showing what you have tried.
Comment: More explicitly, $V(x_1,\dots, x_n)=\frac{1}{\sqrt{(x_1)^2+\cdots +(x_n)^2}}$. I'm sure using the quotient rule and standard rules of differentiation, you can calculate $\frac{\partial V}{\partial x_i}$
Comment: Hint, how do you calculate the magnitude of a vector given it's coordinates?
Answer: Using the definition of vector norm $||x||=\sqrt{\sum\limits_{i}{x_i^2}}$, we have, $\frac{\partial V}{\partial x_i}=-\frac{1}{||x||^2}.\frac{1}{2||x||}.2x_i$, by chain rule. Hence, $\nabla V=\left[-\frac{x_1}{||x||^3}, -\frac{x_2}{||x||^3}, \ldots\right]^T=-\frac{x}{||x||^3}$.
Answer: Let's first rename your function like so:
$$
f(\vec{\bf{v}})=\frac{1}{||\vec{\bf{v}}||}
$$
We can then name each component of your vector $\vec{\bf{v}}_x$ and $\vec{\bf{v}}_y$, and have them as the individual parameters of the function and given that $||\vec{\bf{v}}||=\sqrt{\left(\vec{\bf{v}}_x\right)^2+\left(\vec{\bf{v}}_y\right)^2}$:
$$
\begin{align}
& f(\vec{\bf{v}}_x,\vec{\bf{v}}_y)=\frac{1}{||\vec{\bf{v}}||} \\
\implies & f(\vec{\bf{v}}_x,\vec{\bf{v}}_y)=\frac{1}{\sqrt{\left(\vec{\bf{v}}_x\right)^2+\left(\vec{\bf{v}}_y\right)^2}}
\end{align}
$$
Now we can differentiate this with respect to $\vec{\bf{v}}_x$ or $\vec{\bf{v}}_y$ like so:
$$
\begin{align}
&f(\vec{\bf{v}}_x,\vec{\bf{v}}_y)=\left(\left(\vec{\bf{v}}_x\right)^2+\left(\vec{\bf{v}}_y\right)^2\right)^\frac{-1}{2} \\
&\frac{\partial f}{\partial \vec{\bf{v}}_x} = \frac{-1}{2}\left(\left(\vec{\bf{v}}_x\right)^2+\left(\vec{\bf{v}}_y\right)^2\right)^\frac{-3}{2}\cdot\frac{\partial \left(\left(\vec{\bf{v}}_x\right)^2+\left(\vec{\bf{v}}_y\right)^2\right)}{\partial \vec{\bf{v}}_x} \\
&\frac{\partial f}{\partial \vec{\bf{v}}_x} = \frac{-1}{2}\left(\left(\vec{\bf{v}}_x\right)^2+\left(\vec{\bf{v}}_y\right)^2\right)^\frac{-3}{2}\cdot 2 \vec{\bf{v}}_x \\
&\frac{\partial f}{\partial \vec{\bf{v}}_x} = \frac{-2\vec{\bf{v}}_x}{2}\frac{1}{\left(\sqrt{\left(\vec{\bf{v}}_x\right)^2+\left(\vec{\bf{v}}_y\right)^2}\right)^3} \\
&\frac{\partial f}{\partial \vec{\bf{v}}_x} = \boxed{\frac{-\vec{\bf{v}}_x}{\left(\sqrt{\left(\vec{\bf{v}}_x\right)^2+\left(\vec{\bf{v}}_y\right)^2}\right)^3}}
\end{align}
$$
Which simplifies to:
$$
\frac{\partial f}{\partial \vec{\bf{v}}_x} = \boxed{\frac{-\vec{\bf{v}}_x}{||\vec{\bf{v}}||^3}}
$$
And the same for differentiating with respect to $\vec{\bf{v}}_y$. So the gradient of your function is:
$$
\begin{align}
\nabla f &=
\begin{bmatrix}
\frac{-\vec{\bf{v}}_x}{||\vec{\bf{v}}||^3} \\
\frac{-\vec{\bf{v}}_y}{||\vec{\bf{v}}||^3}
\end{bmatrix} \\
&=\frac{-1}{||\vec{\bf{v}}||^3}\begin{bmatrix}
\vec{\bf{v}}_x \\
\vec{\bf{v}}_y
\end{bmatrix} \\
&=\frac{-1}{||\vec{\bf{v}}||^3}\vec{\bf{v}} \\
&=\boxed{-\frac{\vec{\bf{v}}}{||\vec{\bf{v}}||^3}}
\end{align}
$$
I hope this helped!


PHP Adding database result to multidimensional array

Question: I'm trying to generate a multidimensional array like this in PHP :
$books =  array(

    "8" => array(   "my girl" => 2.5,
                    "the god delusion" => 3.5,
                    "tweak" => 3, "the shack" => 4,
                    "the birds in my life" => 2.5,
                    "new moon" => 3.5),

    "14" => array(    "the last lecture" => 2.5,
                      "the god delusion" => 3.5,
                      "the noble wilds" => 3, "the shack" => 3.5,
                      "the birds in my life" => 2.5, "new moon" => 1)
     );

from a database table which is like this :
ID  value   title
------------------------------------------------------------------
8   5   Clara Callan
8   5   Where You'll Find Me: And Other Stories
8   5   The Middle Stories
8   5   Jane Doe
8   6   The Witchfinder (Amos Walker Mystery Series)
8   6   More Cunning Than Man: A Social History of Rats an...
8   7   Goodbye to the Buttermilk Sky
9   6   Beloved (Plume Contemporary Fiction)
12  10  If I'd Known Then What I Know Now: Why Not Learn f...
14  5   Mary-Kate & Ashley Switching Goals (Mary-Kate ...
14  5   Tell Me This Isn't Happening
14  6   Flood : Mississippi 1927
16  9   Airframe
17  7   Death in the Clouds
17  5   Bant/Spec.Last of the Breed
17  6   Piercing the Darkness
17  3   Prophet
19  7   Prague : A Novel

I'm already tried several ways but I still can't figure out how to do exactly like that. I've been searching numerous threads in here but still no one discussing about this. I'm a newbie in PHP, so I don't understand too much array concept in PHP. Currently my PHP code is like this :
        $result = mysql_query($mySelectQuery) or die("

".mysql_error());
        $books = array();
        while ($row = mysql_fetch_array($result))
        {
            $userID = $row{'User-ID'};
            $books[$userID] = array($row{'Book-Title'} => $row{'Book-Rating'},);
        }

That code already produce similar result with "what I want", but it's still replace the existing book records, so in the end every user only have one book record in their array. My question is:
How could I populate a multidimensional array formatted like mine with the result of my query?
Thanks a million in advance for your answers. And sorry for bad English.
Answer: Try:
$result = mysql_query($mySelectQuery) or die("

".mysql_error());
    $books = array();
    while ($row = mysql_fetch_array($result))
    {
        $userID = $row{'User-ID'};
        $books[$userID][$row{'Book-Title'}] = $row{'Book-Rating'};
    }

This will assign your book title as a array key/index, and set the rating as it's value.
Answer: Before the loop add:
$books[$userID] = array();
Inside the loop use:
$books[$userID][] = array($row{'Book-Title'} => $row{'Book-Rating'},);
Answer: Try with this :
$books[$userID][] = array($row{'Book-Title'} => $row{'Book-Rating'},);


rsync/scp extremely slow transfer rate (<30kB/s) over fast connection

Question: I am attempting to perform a backup using rsync of some files on a Digital Ocean VPS running Ubuntu 14.04.4 LTS.
rsync is extremely slow, ranging from 20-50 kB/s, only 1% of what it should be. It is equally slow when using scp or when using rsync in daemon mode, so this does not seem to be a problem particular to rsync or ssh.
I also have access to another VPS (Linode), I get the expected transfer speeds of 2-3MB/s when transferring files using rsync from that VPS.
Also, when I transfer files using rsync directly from the Digital Ocean VPS to the Linode VPS I get normal inter-server transfer rates of 15MB/s. These factors combined indicate that ssh and rsync are working fine on all the machines.
For now I've circumvented the problem by tunneling the ssh connection via the Linode VPS, but I'm curious about what might be causing the very low transfer rates.
Comment: Perhaps your ISP sees it as some form of peer 2 peer downloading and throttles it. Try running it within a VPN tunnel.
Comment: @JayMcTee It wouldn't seem to be an ISP issue as I have no problems when rsyncing to the other server, also for what it's worth my p2p rates are top-notch and often as high as 6MB/s
Comment: It could still be an ISP issue if their filtering/throttling varies per host/network in some way. Perhaps they try to differentiate between home nodes (from where encrypted traffic is likely to be P2P traffic), known P2P friendly hosts, and other commercial data centres, and they are classifying DO as one of the former but Linode as one of the latter. Do you get similar performance using HTTPS, copying a file over SSH without rsync (SCP, SFTP, cat-via-ssh-to-cat, ...), and so on?
Comment: @DavidSpillett it is the most plausible explanation so far. The idea that the IP or IP range is blacklisted (brownlisted?) by my ISP and being throttled would fit the evidence, which is impaired performance with rsync, scp, and rsync daemon. I realized that the HTTP download speed was bogus because it was going via Cloudflare servers and not a direct connection to the server.
Comment: @JayMcTee at the moment I've resorted to using an SSH tunnel via the Linode VPS which provides a decent 2-3MB/s.
Comment: As the HTTP result turns out to have been false it may also be a routing and capacity issue: your ISP will (directly or indirectly) have better peering links with some locations than they have with others. I too have seen faster results data through another DC than a direct transfer because the routes from DC1 to DC2 and from DC2 to DC3 are better than the more direct route packets generally take from DC1 to DC3. You almost always take a latency hit with such tricks of course, but occasionally the extra bulk throughput is worth it.
Comment: @DavidSpillett a speed of 30kb/s can't be explained by routing to VPS on major internet trunklines, maybe for a few minutes, but not sustained. The number is suspiciously close to typical throttling numbers though.
Comment: Probably, though I'd still be included to test other protocols, a correct HTTP test, and so forth, to confirm. You never know (even less likely, but stranger things have happened) it could be due to a routing error such as the high-ish profile BGP problems last year (http://research.dyn.com/2015/03/uk-traffic-diverted-ukraine/ for one).
Answer: When you say "mainly 15Mb tarballs", how many smaller files are there? Do you see the slow rate constantly or does it look faster on the larger files? rsync (and almost any other filesystem operation) is slower at processing many small files rather than fewer large ones due to the filesystem overhead of opening and closing each file (and any directory read/modify operations needed too). This can be exacerbated by VPS providers enforcing fair(er) IO use by throttling IO operations per second for each VM to a fixed maximum value.
To illustrate this:

Create a large (say ~100Mb) file with something like:
dd if=/dev/urandom of=/tmp/test.file bs=1024 count=102400
and pushing just that file over rsync
then repeat with many small files, for example 10240 10Kb files created with:
for i inseq 1 10240; do dd if=/dev/urandom of=test.file.$i bs=1024 count=10; done
repeat with even smaller files, 102400x 1Kb files created with:
for i inseq 1 102400; do dd if=/dev/urandom of=test.file.$i bs=1024 count=1; done

You should see the process being far slower for the smaller files even though the cumulated contents are the same size. This will be the case even if you do everything locally rather then over the network at all (though obviously the network will magnify the effect somewhat). On a little old machine here time rsync * /location/on/another/local/drive/ gives real 0m0.683s, user 0m0.596s, sys 0m0.220s for the 1*100MB case and
real 0m38.793s, user 0m4.664s, sys 0m15.657s for 102,400*1Kb - a difference of ~57x.
Comment: You should include that detail in the question text, otherwise others may not see it down here in the comments section.
Comment: A 15MB file takes about 10 minutes at 30kB/s. I'm aware that rsync is a little slower with tiny files, but that's completely different to taking 10 minutes to transfer a 15MB file. During those 10 minutes, the progress displayed by --progress is 20-50Kb/s. It's not an average over many files, and it transfers small files at a comparable average speed.


Calculate which day of the week a date falls in using modular arithmetic

Question: In Summer Wars the main character (he is a mathematician) calculates the day of the week of someone's birthday (19/07/1992 is Sunday). I know (very) basic modular arithmetic but I can't figure out how to do it. Can someone point me to the right direction? It seems fun to do.
Comment: http://en.wikipedia.org/wiki/Doomsday_rule
Comment: I actually teach this algorithm in my algorithms class; it's useful in real life to be able to do this!
Comment: [Dershowitz/Reingold](http://books.google.com/books?id=DPbx0-qgXu0C) is the go-to book for topics like these.
Comment: I wonder if O'Beirne's algorithm (http://www.sixthform.info/maths/?p=155) to find the date of Easter Sunday is based (at least partialy) on this one.
Comment: Ah, Conway… "I'm sorry, I'm used to saying "naught". I'll try to say "zero". (pause) No, I won't try. You can all just learn to be naughty."
Answer: Before the Doomsday method (see link in Theo Buehler's comment), there was a formula due to Gauss. A good write-up is Berndt Schwerdtfeger, Gauss' calendar formula for the day of the week, available at http://berndt-schwerdtfeger.de/cal/cal.pdf
Answer: The Zeller congruence is yet another method for reckoning the day of the week of a given date. Kim Larsen presents an implementation of a variant of the Zeller congruence in this article. (There is additional discussion of Larsen's formulation here.)
Comment: The link for Zeller's congruence seems to be dead. Maybe it could be replaced by link to the [Wikipedia article](https://en.wikipedia.org/wiki/Zeller's_congruence) or by a snapshot from [Wayback Machine](http://web.archive.org/web/%2a/http://www.merlyn.demon.co.uk/zeller-c.htm).
Answer: Zeller's Congruence, modified for modern computing conventions, provides a simple algorithm for determining day of the week for any day of the Gregorian Calendar, which came into use in 1582. The simplest variation of the formula is this:
h = (d + ((m+1)*26)/10 + y + y/4 + 6 * (y/100) + y/400 + 5) % 7 + 1;
where d is the day of the month, m is the month, y is the four-digit year, and the result uses ISO day-of-week conventions: 1=Monday to 7=Sunday.
All division operations must use integer (truncating) division. This variant uses only positive coefficients, so it avoids problem with negative results that show up in other variants.
Month and year must be handled differently for the first two months of the year. January and February must be treated as months 13 and 14 of the previous year. So the first month becomes March, with a value of 3. A Java implementation might look like this:
<code>/**
 * Calculate the day of the week for a given date of the Gregorian Calendar.
 * @param year The four-digit year
 * @param month The month, from 1 (January) to 12 (December)
 * @param dayOfMonth The day of the month.
 * @return An ISO-compliant day of the week, where 1 = Monday and 7 = Sunday.
 */
public final int dayOfWeek(int year, int month, int dayOfMonth) {
  assert year > 1582 : "Four digit year required: " + year;
  int y = year;
  if (month < 3) {
    month += 12;
    y--;
  }

  return (dayOfMonth + ((month+1)*26)/10 + y + y/4 + 6 * (y/100) + y/400 + 5) % 7 + 1;
}
</code>
A thorough article about the formula may be found in Wikipedia's Zeller's Congruence article
Answer: It's easy without invoking any special formulas by not only doing arithmetic modulo 7, but in that same spirit also use the same logic for the months. E.g. why let August end on 31st of August? it's convenient to extend August into September and define 32 August as being equivalent to 1st of September.
To compute how many days have passed modulo 7 since the 19th of July 2015 (today is Wednesday 9th of August 2015), I can consider today to be the 40th of August, so it's 40 + 12 days, modulo 7 this is 3. Then we know that 365 = 1 mod 7, so if we forget about leap years the 23 years that have passed would make this 3 + 23 Mod 7 =  5  weekdays earlier. Each leap year makes an additional contribution of 1 day. In a time span of 4 years there is one leap year with the exception of years divisible by 100, but not years divisible by 400. So, we don't need to worry about the year 2000, this was the exception to the exception. To count the number of leap years, we can then simply consider the first one that falls in the time interval we're considering and that's the year 1996. One can then divide the time interval since 29th of February 1996 and divide that by 4 years and round and round it to the next integer. But it's simpler to just consider that the last leap year in the interval was 2012 and that therefore you had 16/4+1 = 5 leap years.
So, we add 5 to the 5 days without leap years and take mod 7 to obtain 10 Mod 7 = 3. Now 3 weekdays days before Wednesday is indeed a Sunday.


Should an IEnumerable iterator on a Queue dequeue an item

Question: I have created a custom generic queue which implements a generic IQueue interface, which uses the generic Queue from the System.Collections.Generic namespace as a private inner queue. Example has been cleaned of irrelevant code.
public interface IQueue<TQueueItem>
{
    void Enqueue(TQueueItem queueItem);
    TQueueItem Dequeue();
}

public class CustomQueue<TQueueItem> : IQueue<TQueueItem>
{
    private readonly Queue<TQueueItem> queue = new Queue<TQueueItem>();
    ...
    public void Enqueue(TQueueItem queueItem)
    {
        ...
        queue.Enqueue( queueItem );
        ...
    }

    public TQueueItem Dequeue()
    {
        ...
        return queue.Dequeue();
        ...
    }
}

I want to keep things consistent with the core implementations and have noticed that the core Queue implements IEnumerable so I will do the same either by explicitly implementing IEnumerable on the class or inheriting it with the IQueue interface.
What I want to know is when enumerating over the queue should each move next dequeue the next item? I have used reflector to see how Microsoft has done it and all they do is step through the queues private array but Microsoft is far from infallible so I wanted to get a general opinion.
public class CustomQueue<TQueueItem> : IQueue<TQueueItem>, IEnumerable<TQueueItem>
{
    ...

    public IEnumerator<TQueueItem> GetEnumerator()
    {
        while (queue.Count > 0)
        {
            yield return Dequeue();
        }
    }

    //Or

    public IEnumerator<TQueueItem> GetEnumerator()
    {
        return queue.GetEnumerator();
    }

    ...
}

I am in two minds, on one hand I feel that iterating through a collection should not changed the collections state but on the other hand and especially with my particular implementation it would make the usage look clean.
EDIT
To put things into context. The class that I am implementing does a Monitor.Wait when Dequeuing and there are no items in the queue. When an item is put onto the queue there is a Monitor.Pulse. This allows for one thread to push stuff onto the queue and the other to essentially "watch" the queue.
From a coding point of view I am trying to decide which it looks cleaner:
foreach(QueueItem item in queue)
{
    DoSomethingWithThe(item);
}

//Or

while(systemIsRunning)
{
    DoSomethingWithThe(queue.Dequeue());
}

For my particular implementation it wouldn't matter if there were multiple process dequeuing items. Because it is a queue they can both pick of an item as no item should be processed more than once, hence the use of a queue.
EDIT
Interestingly enough I have found a blog post where someone has done exactly this.
Link
EDIT
One last stab at this before I close this off. How do people feel about the class not implement IEnumerable but having an IEnumerator GetEnumerator() method that dequeues items? The .net language supports duck typing, foreach being one of the uses. Perhaps this deserves it's own question?
EDIT
Have raised the question of implementing a GetEnumerator method without implementing IEnumerable in another question.
Comment: I agree what I was considering doing was an abuse hence the reason for posting, I just needed to be told 10 or 11 times. I think the real question I have to ask myself is why do I need to implement IEnumerable? Am I doing it because the core implementation does as I have no real requirements for my queue to be iteratated over.
Comment: Unfortunately I cannot mark you all as correct so I will give you all a day to clean up your answers and mark the highest voted as correct.
Answer: Iterators should always be idempotent, that is, don't modify the queue as you iterate over it.
There are no guarantees that there won't be two concurrent iterations...

Edit to address your new comments:
When another programmer (such as your future self ;) ) comes along to add features to the code, they may not assume that the iterators are single-use. They might add a log statement that lists what's in the queue just before using it (oops).
Another thing I just thought of is that the visual studio debugger will often enumerate your classes for display. That would cause some extremely confusing bugs :)
If you're implementing a sub-interface of IEnumerable, and don't want to support IEnumerable, you should throw a NotSupportedException. Although this will not give you any compile time warnings, the run time error will be very clear, while a strange IEnumerable implementation could waste future you hours.
Comment: @Keith in general that's an excellent point, but in the OP's code, the enumerator implementation doesn't exhibit that particular problem.
Comment: It's even simpler than a concurrency problem. IEnumerables are forward-only, read-only. Modifying the underlying concrete collection can cause IEnumerable implementations to get "lost", and so most of them don't allow it. Take a List, for example. Plug it into a foreach that removes each element. On the first go-round, index 0 disappears and index 1 becomes index 0. When the enumerator calls MoveNext, it will attempt to move from index 0 to index 1, which is now actually index 2. This will result in undesired behavior.
Comment: I agree that Iterators should be idempotent, I am just wondering if a queue is where you can break the mould. In my case (see edit) it wouldn't matter if there were multiple process iterating over the queue and in fact there probably will be.
Comment: Additionally, one thing that I had not thought of till now is that I don't have to implement the IEnumerable inerface, all I have to do is provide a IEnumerator GetEnumerator() method as the .net language supports duck typing, foreach being one or the places. Now the question is this still an abuse?
Comment: You might be interested to see some of the responses to my other question http://stackoverflow.com/questions/4194900/should-a-class-that-has-a-getenumerator-method-but-does-not-implement-ienumerable
Comment: I am leery of any iterator that modifies the collection which it iterates over.  I consider that to be the wrong way to do it, and will generally only accept it as valid when it is there is no choice but to do so.  Jon Skeet gives examples where it might be necessary in his answer to your other question, though even in those situations my first instinct would be to try either avoid `IEnumerable` in favor of a `Stream` or to cache the response.  But there are probably cases where using an iterator that modifies the collection could be superior.
Comment: To avoid debugger/designer issues you could implement the necessary attributes that would hide that member from the debugger/designer. At least this would some issues if you wanted to throw an exception from GetEnumerator() or the like.
Answer: Absolutely positively there is no way you should be mutating a collection as you iterate it. The whole point of iterators is that they provide a read-only non-destructive view of a collection. It would be deeply surprising to anyone using your code that looking at it changes it.
In particular: you do not want examining the state of your queue in the debugger to change it. The debugger calls IEnumerable just like any other consumer, and if that has side effects, they are executed.
Comment: @ZaidMasud: The name of the method `GetConsumingEnumerable` is designed to inform you that something unusual is going on.
Comment: You might be interested to see some of the responses to my other question http://stackoverflow.com/questions/4194900/should-a-class-that-has-a-getenumerator-method-but-does-not-implement-ienumerable
Comment: -1 Why, then, does the [BlockingCollection.GetConsumingEnumerable Method](http://msdn.microsoft.com/en-us/library/vstudio/dd287186(v=vs.100).aspx) remove and return items from the collection? It's absolutely positively mutating the collection as you iterate it.
Comment: @ZaidMasud: When you understand the rules deeply and know how to break them safely, then you can do so.
Comment: @EricLippert I agree. I just thought the answer was strongly worded in a way that was categorically prohibiting this by saying that there is absolutely positively no way you should ever do this.
Comment: @ZaidMasud: Do you think that the original poster understands the rules deeply enough to break them safely? If so then why are they asking the question?
Comment: @EricLippert no, but more people than the original poster will read this answer :) I am new to using `BlockingCollection` and originally thought that the `GetConsumingEnumerable` would not modify the underlying collection, in part because I had read your answer here. Therefore I was misled and wanted to point out that you might consider revising your wording :)
Comment: @EricLippert cool so I think we're saying if you're going to break the rules, don't break them in the `IEnumerable.GetEnumerator()` implementation. Do so in another method that returns an `IEnumerable`
Answer: I would suggest that you might want to have a method called something like DequeueAll which returns an item of a class that features a GetEnumerator method that represents everything in the queue, and clears the queue (if a queue item is added around the time the iEnumerable is created, the new item should either appear in the present all to AllItemsDequeued and not in the queue, or in the queue but not the present call).  If this class implements iEnumerable, it should be constructed in such a way that the returned object will remain valid even after the an enumerator has been created and disposed (allowing it to be enumerated multiple times).  If that would be impractical, it may be useful to give the class a name that suggests objects of the class should not be persisted.  One could still do
foreach(QueueItem theItem in theQueue.DequeueAll()) {}but would be less likely to (wrongfully) save the result of theQueue.DequeueAll to an iEnumerable.  If one wanted maximum performance while allowing the result of theQueue.DequeueAll to be used as an iEnumerable, one could define a widening cast that would take a snapshot of the DequeueAll result (thus allowing the old items to be discarded).
Comment: I like that, thinking outside the box.
Answer: I am going to leave the bandwagon behind and say yes. This seems like a reasonable approach. Though I have to make one suggestion. That is, do not implement this consuming iterator in the GetEnumerator method. Instead call it GetConsumingEnumerator or something similiar. That way it is plainly obvious what is going to happen and the foreach mechanism will not be using it by default. You will not be the first person to do this. In fact, Microsoft already does this in the BCL via the BlockingCollection class and they even used GetConsumingEnumerator as the method1. I think you know what I am going to suggest next right?2
1How do you think I came up with the name suggestion?
2Why not just use BlockingCollection? It does everything you have asked for and more.
Comment: I had noticed the IProducerConsumerCollection interface before but I never noticed the BlockingCollection, thanks for the heads up.
Answer: I would say no, do it the second way.
Not only is this more consistent with the built-in Queue class, but it is also more consistent with the fact that the IEnumerable<T> interface is meant to be read-only.
Also, does this really seem intuitive to you?:
//queue is full
foreach(var item in queue)
    Console.WriteLine(item.ToString());
//queue is empty!?

Comment: @Bronumski: I think you are applying the agile slogan well out of context; for the enormous benefits you gain (including, as so many others have mentioned, debugging benefits), it is definitely worth considering.  If this were an hour's worth of work, I could perhaps see the YAGNI argument as valid... but it's *one* very clean and repercussion-free line of code, which you already have written!
Comment: I agree if that is how I was going to use it, use it is a bit of abuse and I think the question I really should be asking myself is should my queue really implement IEnumerable just because the core queue does. As there is no requirement for it I would have to say no.
Comment: @Bronumski: Since it is a matter of only one line of code, I think the real question is, why not?  I could certainly imagine the ability to enumerate (or especially use Linq on) a queue's elements to be useful, so I really don't see why you wouldn't.
Comment: Sure for a core API I could see it being useful but when developing from an Agile approach and accepting I am not going to abuse the language I am going to have to call YAGNI.
Answer: Strictly speaking, queue provides only push-back, pop-front, is-empty and maybe get-size operations. Everything that you add beside that is not a part of a queue, so if you decide to provide additional operations, you don't need to keep to the queue's semantics.
In particular, iterators are not a part of the standard queue interface, so you don't need to have them remove the item current being iterated. (As others have pointed out, this would contradict the expectations on iterators as well.)
Comment: I think that was part of my problem, I was looking at it from a purest point of view where a queue should only push and pop. Good explanation.
Answer: Iterating through the queue should NOT dequeue.
This is designed to see examine the content of the Queue not to dequeue. This is also how MSMQ or MQ Series works.
Answer: I don't think that it should. It would be very implicit, and it does not communicate that intent to anyone that is used to using the .net framework.
Answer: I'd say the second one. Your enumerator definitely should not change the state of the collection.
Answer: I had code where a propperty get was not idempotent... It was such a pain to decode. Please stick with the manual Dequeue.
Also you might not be the only one working on the queue, so it could get messy with more then one consumer.


Determinant equals 1 whereas Inverse unequal to the transpose?

Question: So briefly: Given the matrix $A$ with det$(A) = 1$:
$\left(\begin{array}{ccc} 1 & a & b\\ 0 & 1 & c\\ 0 & 0 & 1 \end{array}\right)$
Its inverse however is set by
$\left(\begin{array}{ccc} 1 & -a & a\,c-b\\ 0 & 1 & -c\\ 0 & 0 & 1 \end{array}\right)$
If I'm not mistaken, that's not $A^T$. Also I hold the opinion that this kind of matrices with the property of  $\det= \pm 1$ belong to the orthogonal group, which is why I came for the conclusion.
Comment: It doesn't belong to the orthogonal group (since $A^{-1}\ne A^T$ as you noted). Maybe you mixed it up with the *special linear group*?
Comment: No, the other way: Every matrix in the orthogonal group has $\det \pm 1$ but your example shows that the converse is not true.
Comment: @Leon The orthogonal group preserves all _distances_, whereas the special linear group preserves _volumes_ (which is what $\det A$ represents). The matrix you have represents a shear; the effects might be slightly easier to see in the two-dimensional analogue, where you can see that volumes of rectangles are preserved but vector lengths are not.
Comment: The matrices with determinant 1 are 'interesting' in part because they also form a group, since the determinant of a product is the product of the determinants.
Comment: Ah, I assumed every matrix with det $\pm$ 1 is a member of the orthogonal group.
Comment: Is there something special about det $= 1$ though? Do these matrices automatically count to Lie groups?
Comment: @StevenStadnicki Ah, thank you for pointing out the symmetry property (constant volume),  which should make it a Lie group
Comment: Leon, matrix groups (over real numbers, say) are linear groups and hence automatically Lie groups. No symmetry property needed.
Answer: You are right about $A^{-1}$. Since it is distinct from $A^T$, the conclusion is that $A$ is not an orthogonal matrix. Although the determinant of every orthogonal matrix is indeed $\pm1$, most matrices whose determinant is $\pm1$ are not orthogonal.


How to add a custom field to a taxonomy term

Question: I am developing a module and I would like to know how to add a field to a taxonomy term?
My section is named special and I want to add terms in this section
I have this code:
function add($form,&$form_state) {
    $form['name'] = array(
        '#type' => 'textfield',
        '#title' => t('name'),
        '#required' => TRUE,
    );

    $form['submit_button'] = array(
        '#type' => 'submit',
        '#value' => t('send'),
    );

    $form['#submit'][] = 'special_add_submit';

    return $form;
}

function special_add_submit ($form, &$form_state) {
    $instance = array(
        'field_name' => 'nombre',
        'entity_type' => 'taxonomy_term',
        // This is the vocabulary
        'bundle' => 'special',
        'label' => t('Relates to option'),
        'description' => t('This is the description'),
        'required' => true,
        'widget' => array(
        'type' => 'text_textfield',
        'settings'=> array(
            'max_width'=>80)
        ),
        );
    field_create_instance($instance);
}

How to do that?

i create a field named name when i save that field i want to add the value to taxonomy term named special
Comment: What is the specific issue you are running into? Usually you create the field instance when enabling a module. Yours should be created when the user submits a form, or should it only save the value? Please update the question, explain what you want to achieve and what does and does not work.
Comment: @skycomputer2 If I understood  correctly you need to add some fields to a taxonomy field? If so, consider to follow the [default way](https://www.drupal.org/docs/7/organizing-content-with-taxonomies/add-a-field-to-a-taxonomy-term-drupal-7-and-later) as it is provided by Drupal and don't try to implement it from scratch
Comment: This question makes no sense. You want to create a term programmatically - not add a field to a term. Or is it vice versus? It's not clear.
Answer: here is how i can do it
  $newterm = new stdClass();
  $newterm->name = 'fashion'; // The name of the new term
  $newterm->vid = 2; // The ID of the parent vocabulary
  taxonomy_term_save($newterm);


how to monitor multiple systems in nagios

Question: I am very new to nagios 3.4.4. I was able to set up and monitor the localhost machine. I tired to copy the localhost config to create a new host, which didnt work. Is there a place where i can find example of a config file monitoring mutiple host? Or a tutorial?
Answer: The short answer: read the Nagios quickstart guide!
Comment: Better yet: read everything under The Basics in docs
Answer: You're going to need to install and configure NRPE (or NSClient++ for Windows) on the remote hosts if you want to check load, swap, and other things that are not external-facing services.  There are also a lot of plugins that will check the health of well-known external facing services (http, smtp, ssh, etc.).
The Debian and Ubuntu repositories, EPEL, etc., have NRPE.
http://exchange.nagios.org/directory/Addons/Monitoring-Agents/NRPE--2D-Nagios-Remote-Plugin-Executor/details
Comment: Unix & Linux boxes can return values for load, swap, disk space and other simple metrics with an SNMP daemon -- NRPE isn't required for this.
Comment: Fair enough;  I started with Nagios by monitoring exclusively Windows.  I still like NRPE for the ability to write custom checks.
Comment: Oh don't get me wrong, NRPE is awesome -- but it's quite heavyweight for things like load and disk.
Answer: Also, once you have glanced over the Nagios guide as @Flup suggests, I would recommend you to have a look at the amazing NagiosQL project. It makes it all a bit easier...


Can I create a custom interface to power views search?

Question: My content is well structured from an internal point of view, but I want to provide a more customer-focussed front-end to an advanced search form.
e.g. I want to offer a list of check boxes like
Show:
[ ] All
[X] Articles
[X] Yellow things
[ ] Super cheap things

I would then intercept this data and mangle it, so for example Article might become a parameter to node_type but Yellow things might be changed into node_type = things AND field_colour = 'yellow' while Super cheap things might be a different thing again.
i.e. I'd like to have a parameterised view set up but use my own customer-focussed forms, rather than use Views' own data-focussed exposed forms.
Is this straight forward?
(More info: I'm on Drupal 7.x. I'm very comfortable with PHP and SQL but I'm keen to do things the Drupal Way unless it's ridiculously inefficient)
Answer: Write a custom views_handler_filter. See Views' API for a step by step introduction to implementing handler classes for Views.


Authenticated users can not see own Ubercart order detail

Question: Using Drupal 7, Ubercart 7.x-3.10.
A user purchases product, gets a user id and logs in. He clicks on Orders tab in My Order History and sees the last order. But, when he clicks on the order number or View order icon, he gets HTTP 500 error (not access denied) instead of seeing order detail.
As admin, I can click on same link and see order detail.
In permissions, Authenticated user has checked:
View own orders
View own invoices
They can see uc_orders_user view /user/606/orders but get page not found error when they click on link to view individual order /user/606/orders/15. Oddly enough, Print order user/606/orders/15/print does work.
Rebuilt permissions, same error.
In order settings, admin/store/settings/orders, I use the Customer On-site invoice template, but I don't see any options to allow users to view orders/invoices (as referred to in this answer to similar question: User cannot view their Orders in Ubercart)
Any suggestions?
Answer: I found the offending code. It was the code for a block to display a link to "My Orders" if the user had any orders. I removed this code from the block, and the order detail now displays for authenticated user.
The offending code:
global $user;

$uid = $user->uid;

// print 'This is my user id ' . $uid;

        $count = 0;
        $args = array($uid);
        $view = views_get_view('uc_orders_user');
        $view->preview('page', $args);
        $count = sizeof($view->result);

// drupal_set_message($count);

  if ($count > 0) {
    return TRUE;
  } else {
    return FALSE;
  }

Do not know why this code causes the error, but it does.  If I find a way to tweak it to work, I'll post it here.


Converter uma string de números numa palavra

Question: Eu preciso de fazer uma função que recebe uma string composta por algarismos entre 2-9 e que o output são letras, ou seja, basicamente a função vai funcionar como um teclado de um telemóvel, onde o número '2' vai coincidir com o 'A', o '22' vai coincidir com o 'B', até ao '9999' coincidir com o 'Z'. Por exemplo:
>>> def teclas('22 2 333 33')
"CAFE"

Os valores inseridos nos argumentos podem "dar a volta", no sentido em que se for inserido '2222', a letra voltará será 'A', '22222' a letra será 'B', etc. Tal como funciona num telemóvel com teclas.
Neste momento tenho um dicionário onde atribuo todos os números às letras correspondentes assim:
dic={'2':'A', '22':'B', '222':'C', '3':'D'....}

A minha dúvida é como faço para que no caso de ser inserido '2222' como argumento, lhe seja atribuído novamente o valor 'A' (não sei como faço o programa "dar a volta").
Comment: Bem vindo a comunidade SOpt. Não ficou claro para mim, a leitura de números não será um dicionário direto? No caso, fornecer '2222' será o mesmo que fornecer '2' e fornecer '22222' será o mesmo que fornecer '22'?
Comment: Exatamente, se imaginarmos que estamos a escrever num telemóvel com teclas, ficando a clicar na tecla '2' repetidamente fará com que as letras mudem consecutivamente, no programa é isso que tem que acontecer, para no caso de ser introduzido o valor '2222' voltar a ler como letra 'A'.
Comment: Ah! Você quer fazer um teclado de celular? Então acho que seu modelo está errado. Você deveria ter um dic para cada tecla. Vou propor uma resposta.
Answer: Pelos seus comentários, entendo que você quer modelar um teclado de celular.
Se é assim, ao invés de um dicionário para todas as teclas, você deveria ter um vetor para cada uma.
tecla2 = ("A", "B", "C")
tecla3 = ("D", "E", "F")
# demais teclas...

Quando o usuário clica em uma tecla, incremente um contador e para descobrir qual a letra faça o módulo do contador com o tamanho do vetor da tecla apertada.
Seu exemplo do "2222", por exemplo, viraria "i += 4".
Considerando que o vetor começa em 0: pos = (i - 1) % 3.
O resultado seria a posição 0, que tem o "A" como você quer.
Quando o usuário escolher outra tecla, o contador deve ser zerado.
Código-conceito abaixo:
letras_tecla_2 = ("a", "b", "c")
letras_tecla_3 = ("d", "e", "f")

def string_from_teclas(teclas):
    ult_tecla = ""
    contador = 0
    string = ""

    for tecla in teclas:
        if tecla == ult_tecla:
            contador += 1
        elif ult_tecla != "":
            contador = contador % 3

            if ult_tecla == "2":
                string += letras_tecla_2[contador]
            elif ult_tecla == "3":
                string += letras_tecla_3[contador]

            contador = 0

        ult_tecla = tecla

    return(string)

print( string_from_teclas("22 222 3 33 ") )

Comment: Ipacheco, sua ideia é válida, mas lembrando que esse seu código não cria um dicionário. E que dicionários não possuem indices numéricos. Pelo menos não pelo que eu testei aqui. Modifique seu código para adequar a sua resposta. =)
Comment: Então mas sendo um vetor como ficaria ao chamar a função? Qual seria o argumento?
Comment: @Rubico, desculpe, meu Python é rudimentar, era mais para ser um pseudo-codigo. :-)
Comment: @Stagg, como ninguém deu uma resposta completa, desenvolvi o conceito em um pythonzinho vira-latas. Tenho certeza que você consegue melhorar a partir daí. Por exemplo, colocar todas as tuplas em um hash por tecla e simplificar o if que escolhe a tupla.


Convergence of Ornstein-Uhlenbeck process as a scaled Brownian Motion

Question: Let $W$ be a standard Brownian motion. Let $\alpha,\sigma^2 >0$, and let $X_0$ be a $\mathbb{R}$-valued random variable with distibution $\nu$ that is independent of $\sigma(W_t,t\geq 0)$. Now define the scaled BM $X$ by
$$ X_t = \exp\{-\alpha t\}\left( X_0 + W_{\sigma^2( \exp\{2\alpha t\}-1)/2\alpha}\right).$$
There are a few things I want to show:
(1) I want to show that the defined process is a Markov process which converges in distribution to an $N(0,\sigma^2/2 \alpha)$ distributed random variable.
(2) I'd like to show that if $X_0 \overset{d}{=} N(0,\sigma^2/2 \alpha)$ then $X_t \overset{d}{=} N(0,\sigma^2/2 \alpha)$, in other words it is invariant for the Markov process.
(3) And I want to show that $X_t$ is Gaussian with mean function $m(t)=0$ and covariance function $r(s,t) = \sigma^2\exp\{-\alpha|t-s|\}/2\alpha$.
Now to start the proof I would like to pick the "right" filtration but I have no idea how I should pick this and could I prove that it is a Markov process? The only abstract definition I know how to prove this is with transition kernels, yet I don't know how to apply (or define) these here.
My thinking so far: I tried to rewrite $X_t$ in a more useful way. Namely $X_t = \exp\{-\alpha t \} X_0 + \sigma \exp\{ - \alpha t \} \int_0^t \exp\{\alpha s \} d W_s$. But this is using stochastic integration which I guess I should not use as it should be done in the framework of stochastic processes. But by the rewritten $X_t$ above we can note that we have the integral of a nonrandom function $f(s)$ vs $dW_s$ which is always a Gaussian random variable with mean zero and variance $\int f(s)^2 ds$. Is there some other way to explain this? Also then when letting $t$ go to infinity we have get the invariant distribution. However I still have no clue how to prove that it is a Markov process. Thanks for any help.
Comment: Edited post with my tries.
Comment: Let $\big(\mathcal{F}_t  , t\geq 0 \big) $   be the filtration generated by  $W$,  set  $\mathcal{G}_t : = \sigma(X_0) \vee  \mathcal{F}_{\sigma^2( \exp\{2\alpha t\}-1)/2\alpha}$. You may want to consider the filtration $\big( \mathcal{G}_t, t\geq 0 \big)$, with respect to which $X$ is adapted. To see it is Markov, you can apply Ito formula to get a SDE for $X$ so that it follows that it is a strong Markov process (but I think you do not want to do the proof in this way)
Answer: Notice that
$$ X_t = \exp\{-\alpha t\}\left( X_0 + W_{\sigma^2( \exp\{2\alpha t\}-1)/2\alpha}\right) =\exp\{-\alpha t \} X_0 + \sigma \exp\{ - \alpha t \} \int_0^t \exp\{\alpha s \} d W_s. $$
Now we can simply note that the process $X_t$ is a Gaussian process it being a linear combination of the Gaussian process $W_t$. Its mean and variance are now easily calculated by It$\hat{\text{o}}$ isometry namely if $\mathbb{E} X_t^2 < \infty$ and $X_0 = \delta_x$ as in the example then
\begin{align*}
\mathbb{E} X_t &= e^{- \alpha t} \mathbb{E} X_0 = e^{- \alpha t} x \\
\mathbb{E} \left( X_t - \mathbb{E} X_t \right)^2 &= \sigma^2 \int_0^t \left(e^{-\alpha(t -s)} \right)^2 ds = \frac{\sigma^2}{2 \alpha}\left( 1 - e^{-2 \alpha t}\right).
\end{align*}
As the mean of the Brownian term gives zero and from the companion course the know that the variance of $\delta_x$ is zero and $\mathrm{Var} \left(\int_0^t f(s)dW_s \right) = \int_0^t f(s)^2 ds$.
Thus when as $\alpha >0$ we have that
$$ X_t \overset{d}{\rightarrow} N\left( 0, \frac{\sigma^2}{2 \alpha} \right),$$
by simply noting that the mean of $X_t$ goes to zero for $t \rightarrow \infty$ and the variance goes to $\frac{\sigma^2}{2 \alpha}$ as $t \rightarrow \infty$ and $X_t$ is Gaussian itself.
To prove that the process is infact a Markov process, as we have that $X_t$ is in fact the solution to the Ornstein-Uhlenbeck SDE defined by
$$ d X_t = \alpha( X_0 - X_t) dt + \sigma dW_t. $$
This is a Lipschitz SDE (coefficients are Lipschitz continuous obviously) and these have Markovian solutions. Hence $X_t$ must be Markovian.
Now if $X_0 \overset{d}{=} N(0,\sigma^2/2\alpha)$ then $X_t$ is still Gaussian so we only need to calculate its mean and variance. Hence
\begin{align*}
\mathbb{E} X_t &= e^{-\alpha t} \mathbb{E} X_0 = 0 \\
\mathbb{E} \left( X_t - \mathbb{E} X_t \right)^2 &= \mathrm{Var}(e^{-\alpha t} X_0) + \frac{\sigma^2}{2 \alpha}\left( 1 - e^{-2 \alpha t}\right) \\
&= e^{-2\alpha t} \frac{\sigma^2}{2\alpha} + \frac{\sigma^2}{2 \alpha}\left( 1 - e^{-2 \alpha t}\right) =  \frac{\sigma^2}{2 \alpha}.
\end{align*}
By previous calculations and thus $X_t \overset{d}{=} N(0,\sigma^2/2\alpha)$ and is thus the invariant distribution of $X$.
To calculate the covariance function of $X$ we use a simple rule of It$\hat{\mathrm{o}}$ integrals w.r.t. a BM and continuous function $f$ which states that if we define $I_f(t) = \int_0^t f(s) dW_s$ then $\mathrm{Cov} \left( I_f(t),I_f(s)\right) = \int_0^{t \wedge s} f^2(u) du$. Hence using this we obtain that for $t \neq s$ assuming $X_0$ has mean $0$ and variance $\tau^2$
\begin{align*} \
\mathrm{Cov} \left( X_t, X_s \right) &= e^{- \alpha (s+t)} \mathrm{Cov}(X_0,X_0) + \int_0^{t \wedge s} \left( \sigma e^{- \alpha(s-t)} \right)^2 ds \\
&= e^{- \alpha (s+t)} \tau^2 + \frac{\sigma^2}{2\alpha} \left( e^{-\alpha |s-t|} - e^{-\alpha (s+t)}\right),
\end{align*}
Now as $\tau^2=\frac{\sigma^2}{2\alpha}$ we obtain that the covariance equals $\frac{\sigma^2}{2\alpha} \exp\{ - \alpha |s-t| \}$. Furthermore if $\mathbb{E} X_0 = 0$ then $\mathbb{E} X_t = e^{-\alpha t} \mathbb{E} X_0 = 0$ as the Brownian motion integral has expectation zero.


How to create the background for a LED text scroller in Android?

Question: I want to create a background exactly like these two pictures:

Currently I have the text scrolling horizontally with a special LED-like font, however my background is just pure black. I'm not sure how to make the background LED-like.
Comment: Did you get answer? Have you created this app?
Answer: Everything is perfect except few things below
You need curve less fonts, get some from here : www.1001fonts.com/led-fonts.html
And let's assume one LED as one pixel so you need to move your text one pixel at a time, it means you need to move your text same as the size of one LED. It should not be smooth otherwise it will not look like LED text, anyway if you would like to make it smooth then increase speed little bit.
Comment: Yes but my question is how do I get the small dots similarly to those backgrounds? My background is currently just black so it doesn't really look like a LED.
Comment: Ok, got it, there are two solutions for this a simple one with illusion and other one will require more work with animation in android.
**Simple** : Make an image just like image you posted which has LED written in it, and move it just as size of one pixel in it, it will look like LED.
**Not Simple** : Work with android animation and create LED pixels and change colors of pixels just as those letters would move.
Answer: You can use following image as my friend has created.

Hope it will helps you.


Failed opening install.inc' when upgrading Drupal 7.x core with Drush 7.x

Question: I have Drush 7.x installed and when I run 'drush up', on a Drupal 7.x codebase, I get the following error:
Drush command terminated abnormally due to an unrecoverable error.
[error]Error: require_once(): Failed opening required '/home/user/public_html/core/includes/install.inc'

It seems like Drush 7.x may be looking for Drupal 8.x file structure. How should I be running this command?
Answer: I managed to get it fixed after tracking the issue in drush 7, this is caused as you said by trying to load install.inc as Drupal 8 folder structure while you have Drupla 7 structure
I simply modified DRUSH_ROOT/commands/core/core.drush.inc line 1120
require_once DRUPAL_ROOT . '/core/includes/install.inc';

to be like
require_once DRUPAL_ROOT . '/includes/install.inc';

I hope this help you.
Comment: OK, great. This seems like it may be a bug, so I filed an [issue](https://github.com/drush-ops/drush/issues/1025) on the Drush GitHub repository.


Jquery radio button checked value on page refresh

Question: I have the following two radio buttons. Switching between the two values works. But after a page refresh the selected value is not there anymore. How can I handle this problem. Is there a jquery library which can handle this? Any solutions which works on each browser? Thanks for suggestions.
 <input type="radio" name="lr" id="open" class="required" value="open to all" checked="checked" />

 <input type="radio" name="lr" id="login_area"  class="required myOption" value="login_area" />
 Register

...

...

 $(document).ready(function() {
    $('.myOption').click(function() {
      var $stat = null;
        $stat = $('#login_area')[0].checked;
        if ($stat === true) {
            $('.signUp_area').show();
            $('.login_area').hide();
        } else {
            $('.login_area').show();
            $('.signUp_area').hide();
        }
    });
});

Comment: May be, store the value in a cookie or local storage and then you can access that value later on.
Answer: JavaScript is stateless. You have to either use localStorage, cookies, or a server session to persist after a page refresh. Client side code does not do this unless stored in memory or a database.
Answer: Should you use jquery cookie.
To set:
$.cookie("var", "10");

To get:
$.cookie("var");

To delete:
$.cookie("var", null);


Mapping XML attributes/elements with Table Column Names for File Import

Question: I have the following xml file
<?xml version="1.0" encoding="ISO-8859-1"?>
<ProdExtract>
 <ExtractHeader>
  <Schema>
   <id>Accord ePOS Product Extract</id>
   <Version>1.00</Version>
  </Schema>
 </ExtractHeader>
 <Product>
  <Mode>Modify</Mode>
  <ProductID>
    <LongDescription>COLMANS MINT SAUCE      #</LongDescription>
  </ProductID>
  <BasicFields>
    <Units>6</Units>
    <VAT VatCode="A" VatRate="0" />
  </BasicFields>
  <Price>
    <CurrentWSP>9.55</CurrentWSP>
    <CurrentRSP>2.01</CurrentRSP>
  </Price>
  <Barcode>
    <Eancode>5000147032921</Eancode>
  </Barcode>
 </Product>
</ProdExtract>

This is my mapping for the table columns
foreach (XmlNode node in xDoc.SelectNodes("ProdExtract/Product"))
{
    insert = insert ?? new PostgreSQLCopyHelper<ProductViewModel>("public", "q_product")
        .MapUUID("q_guid", x => Guid.NewGuid())
        .MapText("q_description", x => node.SelectSingleNode("ProductID/LongDescription").InnerText)
        .MapText("q_barcode", x => node.SelectSingleNode("Barcode/Eancode").InnerText)
        .MapNumeric("q_casesize", x => Convert.ToDecimal(node.SelectSingleNode("BasicFields/Units").InnerText))
        .MapNumeric("q_sellprice", x => Convert.ToDecimal(node.SelectSingleNode("Price/CurrentRSP").InnerText))
        .MapNumeric("q_casecost", x => Convert.ToDecimal(node.SelectSingleNode("Price/CurrentWSP").InnerText))
                        ;

    entities.Add(p);
}

I can get all the values I need from the XML file and match them with my table columns no problemo, with the above method. But now how do I deal with with this section
<BasicFields>
  <Units>6</Units>
  <VAT VatCode="A" VatRate="0" />
</BasicFields>

If I want the value of VatRate i.e 0. This line
node.SelectSingleNode("BasicFields/Vat/VatRate").OuterXml;

brought me nowhere, and I have had no luck on the interwebs.
Answer: Eventually figured it out (This is in c# code by the way, I havent checked if its any different in other languages)
<BasicFields>
 <Units>6</Units>
 <VAT VatCode="A" VatRate="0" />
</BasicFields>

To get value "A"
node.SelectSingleNode("BasicFields/VAT").Attributes["VatCode"].Value;

To get value "0"
node.SelectSingleNode("BasicFields/VAT").Attributes["VatRate"].Value;


Maximal ideals in a group ring when the ring is a field

Question: Is there any simple characterization of the maximal ideals in a group ring $R[G]$ when $R$ is a field, perhaps in terms of maximal subgroups of $G$?
Comment: I don't think you can do it in terms of subgroups of $G$: take the augmentation map $k[G] \to k$, whose kernel is clearly a maximal ideal but isn't really related to subgroups of $G$. Moreover subgroups of $G$ correspond to *units* so they are sort of left out of the discussion of ideals
Comment: @Max Well, I wouldn't say the augmentation ideal *isn't related* to subgroups... the augmentation ideal *is* related to $G$ itself, and the other augmentation ideals (of the form $(\{1-h\mid h\in H\})$ where $H$ is a subgroup of $G$) are intimately related to the other subgroups by an order-preserving lattice correspondence.  This does suggest, however, that the lattice of subgroups tells you about the lattice of ideals in the augmentation ideal. Nevertheless, I agree with your overall statement that there isn't apparently any connection.
Answer: The maximal ideals of $R[G]$ are in canonical bijection with the isomorphism classes of simple $R[G]$-modules. In one direction, if $I$ is a maximal ideal, then $R[G]/I$ is a simple ring, hence has a unique simple module up to isomorphism, which you can lift to a simple module of $R[G]$. In the other direction, given a simple $R[G]$-module $M$, take $I$ to be its annihilator.
Whether or not this characterisation helps you in any way depends on further properties of $G$ and $R$. For example if $G$ is finite, then there is a very rich theory of simple $R[G]$-modules, equivalently of irreducible representations of $G$ over $R$, namely character theory if the characteristic of $R$ does not divide $\#G$, and the theory of Brauer characters in the other, the modular case. But in the generality that you have posed the question in, I am not sure whether anything more enlightening can be said.
Comment: Thank you, this seems like a promising perspective. The groups I'm looking at are (in the smallest case) limit ordinals under Hessenberg addition, making them at least countably infinite but commutative with a natural well-ordering.  Is there any literature on such group rings over characteristic $0$ fields, or perhaps more generally infinite groups carrying a total (or discrete or well-) ordering? I would also be interested in the noncommutative group case, like with ordinals under recursive addition.
Answer: I'm not aware of any such characterization, and at any rate, the maximal subgroups of $G$ do not determine the maximal ideals of $R[G]$ in general.
For example, if $F$ has characteristic $0$ and $G$ is finite and has exactly one maximal subgroup (say it is $(\mathbb Z_{p^k},+)$ for example) then $F[G]$ is semisimple with at least two Wedderburn components, and hence at least two maximal ideals, potentially many more maximal right and left ideals.
Perhaps you would be happy to know what is know about when $F[G]$ is local. It is known that $F[G]$ is local if $F$ has positive characteristic $p$ and $G$ is a locally-finite $p$-group, and in the other direction if $F[G]$ is local, then $F$ has characteristic $p>0$ and $G$ is a $p$-group.
From this I think it follows that there are local group rings with many distinct maximal subgroups, providing a counterpart to the example I gave in the second paragraph.
This appears as Theorem 1 in Renault's On group rings (1971). Full disclosure: I prepared the translation at this link. That's why I'm familiar with the result.
Comment: Much appreciated; the group rings I am looking at are generally not local, but I can always localize at maximal ideals to try and apply these methods.


evaluate $\lim_{(x,y) \to (0,0)} \frac{\sin(x)\sin(3y)}{2xy}$

Question: I'm studying calculus of multiple variables and I can solve limits of the form $x^2+y^2$, but I need to solve this.
$$\lim_{(x,y) \to (0,0)} \frac{\sin(x)\sin(3y)}{2xy}$$
Could you give me an idea of how to solve that limit?
Comment: Write it as $\frac{\sin x}{x}\cdot\frac{\sin3y}{3y}\cdot\frac{3}{2}$.
Comment: omg,, I did not see that, I've been forgetting of calculate 1,, thanks
Answer: As was written in the comments, you could use the fact that limits are multiplicative to conclude
$$\begin{split}
\lim_{(x,y)\to(0,0)} \frac{\sin x \sin 3y}{2xy} &= \frac 1 2 \cdot \lim_{(x,y)\to(0,0)} \frac{\sin x}{x} \cdot \lim_{(x,y)\to(0,0)} \frac{\sin 3y}{y}
\\ &= \frac 3 2 \cdot \lim_{x \to 0}\frac{\sin x}{x} \cdot \lim_{y \to 0} \frac{\sin 3y}{3y}
\\ &= \frac 3 2 \cdot 1 \cdot 1 = \frac 3 2.
\end{split}$$
Alternatively, you could solve it directly by seeing that, as $(x,y) \to (0,0)$, we have the first-order expansion $\sin(x) \simeq x$ and $\sin 3y \simeq 3y$, so that
$$\lim_{(x,y)\to(0,0)} \frac{\sin x \sin 3y}{2xy} = \lim_{(x,y)\to(0,0)} \frac{3xy}{2xy} = \frac 3 2. $$
Answer: As written, the quotient isn't defined if $x = 0$ or $y  = 0$. Excluding this subset, you can use that $\lim_{t\to 0}\frac{\sin t}{t} = 1$.


Can an active directory group indirectly include itself in a cycle?

Question: Is it possible for a group to directly or indirectly include itself?
In other words, is it possible for the following structure to be created:

Group-A
    └─ Group-B
             └─ Group-C
                      └─ Group-A  (recursive cycle)

Does AD detect and prevent such cases, or does it allow them and handle the recursive cycle.
If I had administrative access to an AD forest, and I wasn't afraid of unravelling the fabric of reality, I would test this myself. Google, sadly - has been of little help in answering this question ... although I may not be making the proper incantation in the search input box.
Answer: Directly:  No, an error is returned that A group cannot be a member of itself
Indirectly: There is nothing preventing this from happening in Active Directory, and is known as Circular Group Nesting.
Answer: I have a different experience.  If you use the Active Directory Users and Computers and do a right-click on a group then select "Add to a Group", you can enter the name of the group and the add succeeds, effectively making a group a member of itself.


Execution failed for task Program type already present

Question: I include this new library into my dependencies
compile 'com.github.Triggertrap:SeekArc:v1.1'

Then when I build I get build error
Error:Exception in thread "queued-resource-processor_458" java.lang.RuntimeException: Timed out while waiting for slave aapt process, make sure the aapt execute at C:\Users\kepler\AppData\Local\Android\Sdk\build-tools\27.0.1\aapt2.exe can run successfully (some anti-virus may block it) or try setting environment variable SLAVE_AAPT_TIMEOUT to a value bigger than 5 seconds
    at com.android.builder.png.AaptProcess.waitForReadyOrFail(AaptProcess.java:196)
    at com.android.builder.internal.aapt.AaptQueueThreadContext.creation(AaptQueueThreadContext.java:56)
    at com.android.builder.tasks.WorkQueue.run(WorkQueue.java:250)
    at java.lang.Thread.run(Thread.java:745)
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
> Program type already present: android.support.v4.accessibilityservice.AccessibilityServiceInfoCompat$AccessibilityServiceInfoIcsImpl

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 20s

Is it possible I have a dependency conflict according from above message?
Program type already present: android.support.v4.accessibilityservice.AccessibilityServiceInfoCompat$AccessibilityServiceInfoIcsImpl

I've tried printing my dependency tree, but I have no idea how to find the dependency conflict with it.
Answer: Try switching
compile 'com.github.Triggertrap:SeekArc:v1.1'

to
implementation 'com.github.Triggertrap:SeekArc:v1.1'`

If that doesn't work try excluding the support library from the new package
implementation('com.github.Triggertrap:SeekArc:v1.1') { exclude group: 'com.android.support' }

Comment: Well gee thanks, I wish **I** had thought of using "exclude group"


Slave DNS server is Open Zone Transfer

Question: My secondary authoritative DNS server (centos 7 - bind 9.9 hosted in Microsoft Azure) is marked as Open Zone Transfer...
although I've added the line "recursion no" in /etc/named.conf:
This is my options section in the server's named.conf file:
<code>options {

listen-on port 53 { any; };
directory   "/var/named";
dump-file   "/var/named/data/cache_dump.db";
statistics-file "/var/named/data/named_stats.txt";
memstatistics-file "/var/named/data/named_mem_stats.txt";
allow-query    { any; };
allow-transfer { none; };
recursion no;
additional-from-cache no;
dnssec-enable yes;
dnssec-validation yes;
/* Path to ISC DLV key */
bindkeys-file "/etc/named.iscdlv.key";
managed-keys-directory "/var/named/dynamic";
pid-file "/run/named/named.pid";
session-keyfile "/run/named/session.key";

};
</code>
Can you advise me why my authoritative server still marked as Open Zone Transfer?
Comment: Where / how is it marked as open zone transfer? (Who is telling you this)? Also, stupid question: You've restarted bind after making these changes?
Comment: thanks for your reply, yes I've restarted bind many times but in vain... many DNS testing websites was telling that the server is an open zone transfer (like: http://mxtoolbox.com and http://hackertarget.com/zone-transfer) you can check using one of my domains "shabakah.com"
Comment: The zone shabakah.com should have its own config file. What's the current configuration for this zone ?
Comment: Recursion and transfer are unrelated. I see that I can in fact do a zone transfer for that domain on ns4.shabakah.net.sa (126.96.36.199). Is that the server you're showing us the config files for? We need to see the `zone` context as well, because perhaps you are allowing transfer in there...
Comment: @theglossy1 the minsioned named.conf file was from NS4 , and the zone context (in the slave server NS4): **zone "shabakah.com" {type slave; file "slaves/db.shabakahcom"; masters { 18.104.22.168; };};** and in master server: **zone "shabakah.com" {type master; file "/var/named/db.shabakahcom"; };**
Comment: That's a mystery why it would allow transfers then. It should inherit the `allow-transfer { none; };` from the global configuration. I suppose for good measure you could add that to the zone definition too, but there's no reason you should have to.
Answer: after 2 days of troubleshooting, the issue was fixed
I found that the centos version installed by Microsoft Azure by default has dnsmasq service installed and running after the initial os install ...
when I disabled that service, the bind was working fine and the unauthorized zone transfer requests was denied as configured in named.conf ...
thanks

Slave DNS server is Open Zone Transfer


How to test if a primitive matrix has an eigenvalue of unit modulus

Question: Let $M$ be a primitive matrix with non-negative integer entries. Here, primitive means that there exists some exponent $n$ such that the entries of $M^n$ are all strictly positive integers. I want to algorithmically test if $M$ has any eigenvalues $\lambda$ for which $|\lambda| = 1$. Does such a test exist?
To give some more context, the Perron-Frobenius theorem says that the eigenvalue of largest modulus for $M$ is a simple eigenvalue, and is a real number greater than $1$. It's of particular interest to be able to identify those primitive matrices whose other eigenvalues $\lambda$ all lie in the punctured disk $\{z\mid 0<|z|<1\}\subset\mathbb{C}$ (sometimes called irreducible Pisot matrices). It's easy to identify if $0$ is an eigenvalue, but testing the boundary of the disk seems more tricky.
I want to emphasise that I would like the test to be complete, not 'accurate up to some bounded error', so it's not enough to numerically find approximate eigenvalues and then check their modulus, as this could produce false positives/negatives.
Comment: Is $n$ known / is it feasible to work with $M^n$?
Comment: Sure, if $\lambda$ is an eigenvalue of $M$ then $\lambda^n$ is an eigenvalue of $M^n$, so you can assume $M$ is a positive integer matrix (finding $n$ is a finite check).
Answer: STEP 1. Calculate the characteristic polynomial $\chi_A\in \mathbb{Z}[x]$ and decompose it in irreducibles over $\mathbb{Q}$ (or $\mathbb{Z}$): $\chi_A=f_1\cdots f_k$. For each $f_i$, denoted by $f$, we proceed as follows. We may assume that $n=degree(f)\geq 3$ (and even $\geq 5$).
If $f(e^{i\theta})=0$, then $f(e^{-i\theta})=0$ and $x^2-2\alpha x+1$ is a factor of $f$ in $\mathbb{Q}[\alpha][x]$ where $\alpha=\cos(\theta)$ is algebraic over $\mathbb{Q}$.
STEP 2. Calculate the "formal" euclidean division $(f:q)$: $f(x)=q(x)(x^2-2\alpha x+1)+u(\alpha)x+v(\alpha)$; note that $u,v\in\mathbb{Z}[\alpha]$ and have degrees $n-1$ and $n-2$; the condition to be fulfilled is: $u,v$ have a common real root  in the open interval $]-1,1[$.
STEP 3. Calculate $g=gcd(u,v)$. Note that, if $n$ is large, then the coefficients along the calculation of the gcd can become very large!
STEP 4. Using STURM, the Sturm's algorithm, find the number of real roots of $g$ inside $]-1,1[$. If you find $p$ such roots, then $f$ has $2p$ roots with modulus $1$. Again STURM is a polynomial long division and the coefficients can become large; yet, in general, the degree of $g$ is small.
Three instances:
i) $f(x)=x^4+x^3+x^2+x+1$. Then $u=8\alpha^3+4\alpha^2-2\alpha,v=-4\alpha^2-2\alpha+1$ and $g=4\alpha^2+2\alpha-1$. $g$ has $2$ valid roots and therefore $f$ has $4$ roots of modulus $1$, that is not a scoop !
ii) $f(x)=x^5+2$. Then $u=16\alpha^4-12\alpha^2+1,v=-8\alpha^3+4\alpha+2$ and $g=1$. $f$ has no roots of modulus $1$, that is no more a scoop.
iii) $f(x)=x^{20}+x^{15}-3x^{10}+2x^7-5x^6+3x^5-x^4+2x^2-4x+1$. Then $g=1$  (Maple en 0"04).
Comment: @  Scott Balchin , in fact it is the standard euclidean division; I added the word "formal" because it is not a digital calculation; indeed the coefficients depend on the parameter $\alpha$. The remainder of the division is a polynomial in $x$ of degree $1$ and with coefficients in $\mathbb{Q}[\alpha]$. Practically, this calculation requires a formal calculation software as Maple, Mathematica,...Note that the previous method is valid when $A\in M_n(\mathbb{Z})$ or even when $A\in M_n(\mathbb{Q})$.
Comment: In step 2 here, I am not sure what you mean by the formal euclidean divisor?  I cannot seem to work out how you got u and v in your examples.  It would be great if you could elaborate on this step!
Comment: @loupblanc We would like to cite this answer in a paper being prepared. Would you be happy to provide a real name that we may use in the citation, or would you prefer we use your username here? Feel free to email myself at firstname.lastname@example.com, or reply to this comment.