É possível chamar function sem ser por onclick?

Question: É um ciclo, onde a cada rodada a função tem que ser executada, andei pesquisando e só achei como chamar por onclick. Acredito que seja feito por um script, mas não acho o código.
http://exage-rado.tumblr.com/

.
.
.

    <input id="tudo" type="button" value="All" onclick=control('all') />
    <input id="imagem" type="button" value="Image" onclick=control('image') />
    <input id="texto" type="button" value="Text" onclick=control('text') />

.
.
.
{block:Posts}

        {block:Text}{block:Title}
{Title}
{/block:Title}{Body}{/block:Text}
        {block:Quote}

"{Quote}"

            {block:Source}
 — {Source}
{/block:Source}
        {/block:Quote}
        {block:Link}

{Name}

            {block:Description}
{Description}
{/block:Description}
        {/block:Link}
        {block:Chat}
{block:Lines}
{block:Label}{Label}{/block:Label} {Line}
{/block:Lines}
{/block:Chat}
        {block:Answer}

                    {Question}
                    ◤

{Asker}

{Answer}

        {/block:answer}

        {block:Photo}
        {block:Caption}{Caption}{/block:Caption}{/block:Photo}
        {block:Photoset}{Photoset-500}
        {block:Caption}{Caption}{/block:Caption}{/block:Photoset}
        {block:Video}{Video-500}{block:Caption}{Caption}{/block:Caption}{/block:Video}

    {block:Audio}{AudioPlayerBlack}{block:Caption}{Caption}{/block:Caption}{/block:Audio}

        {block:ContentSource}
            {lang:Source}:{block:SourceLogo}

            {/block:SourceLogo}{block:NoSourceLogo}{SourceLink}{/block:NoSourceLogo}
        {/block:ContentSource}

{block:HasTags}
{block:Tags} #{Tag} {/block:Tags}{/block:HasTags}
{/block:Posts}

Comment: Além disso, acredito que o problema seja, na verdade, como obter uma ***referência*** às ``s criadas pela API que ele está usando.
Comment: é no tumblr, então tem um bloco, block:post, e a cada post ele carrega todas as divs dentro dele, então quando carregar quero que execute a função, que é um filtro do que deve aparecer ou não
Comment: coloquei todo o código que acredito ter a ver, como veem, a cada postagem, tudo entre {block:post} e {/block:post} se repete, estou tentando fazer um filtro, como podem conferir lá no link, mas só funciona com as postagens já carregadas... Pensei que a solução seria chamar a função a cada post...
Comment: acabo de descobrir que não sei como funciona, ele só faz um loop com as 8 primeiras postagens, as demais não entendo como...
Answer: Acho que neste caso pode usar o evento DOMNodeInserted.
var div = document.getElementById('involves');
div.addEventListener('DOMNodeInserted', function(e){
  console.log(e.target); // veja na consola os novos elementos

  // corra a sua função
  control('all');
});

Este oscultador de evento vai ser ativado a cada vez que fôr inserido elementos DOM dentro de #involves. Aí pode correr a sua função e pode também ver que elementos foram adicionados.
Nota: O seu código (e confirma-se no link que colocou agora) está a repetir todas as IDs a cada post. IDs têm de ser únicas.
Nota2: O evento DOMNodeInserted irá provavelmente ser substituido no futuro por Mutation Observers mas que por enquanto só estão acessíveis para o IE11+ e browsers modernos
O código nesse caso seria:
var div = document.getElementById('involves');
var observer = new MutationObserver(function(mutations) {
    // corra a sua função
    control('all');
});

// configuração:
var config = { attributes: true, childList: true, characterData: true };
observer.observe(div , config);

// Caso queira parar o observador
observer.disconnect();

Comment: @RodrigodeOliveira Fazendo no onscroll você vai ativar a função várias vezes a mais, denecessariamente.
Comment: não entendi... até tentei, mas não deu...
Comment: @RodrigodeOliveira pegue o código que está no inicio da resposta e coloque no fundo da sua página, dentro de tags script e antes do body. Coloque um alert (ou use o console.log que coloquei) e vai ver ele a ser chamado quando a página carregar novos posts.
Comment: muito obrigado pela ajuda, mas depois de muito quebrar a cabeça, achei uma solução simples e 100% funcional                          window.onscroll = function () {
control();
}
Comment: sim, eu sei, mas não achei outra maneira
Comment: @RodrigodeOliveira da maneira que eu sugeri na resposta a função corre 1 vez por cada post adicionado. Parece-me mais razoável que o scrol...
Comment: mas não funcionou
Comment: @RodrigodeOliveira funciona bem para mim quando testo na consola do seu site. Pode mostrar como implementou no seu site?
Comment: como só preciso que chame control, deixei assim:

   var div = document.getElementById('involves');
   div.addEventListener('DOMNodeInserted', function(){control();});
Comment: http://pastebin.com/yx8HYmsM
Comment: @RodrigodeOliveira tenho de sair mas vou rever esse código e fazer melhorias e colocar aqui de novo mais tarde.
Comment: muito obrigado, até
Comment: @RodrigodeOliveira testa assim (só juntei o meu código no dinal): http://pastebin.com/q5DjLnuh
Comment: deu, agora não entendi mais nada, aquela hora eu dei só um ctrl+c e ctrl+v e não deu... mas valeu cara, valeu mesmo
Answer: Uma vez declarada, uma função pode ser chamada em qualquer trecho de JavaScript.
Para as finalidades comuns dos scripts de Internet, pode-se dizer que quase sempre as chamadas de funções e outras operações são feitas em resposta a eventos: o carregamento da página, o click de um botão, uma alteração em um <input />, entre outros.
Porém, nada impede o programador de chamar a função como primeira instrução da primeira linha de scripting; o problema, no entanto, é que, por vezes, nem todos os elementos HTML e demais scripts foram carregados na memória, o que costuma causar erros.
De qualquer forma, seu problema é mais relacionado a saber qual elemento escutar por eventos do que propriamente a "chamar function sem ser por onclick". Assim, sugiro que você verifique a documentação do plugin/API que você está usando, pois deve haver suporte à adição de uma função callback como ouvinte do evento de criação de cada uma dessas
s às quais você se refere.
Comment: Porque deram -1? ..
Comment: Seria legal mesmo, saber! :D assim dá pra melhorar, se for o caso.


openLDAP config broken after Ubuntu upgrade (20.04 -> 22.04)

Question: I have problems with openLDAP after updating from Ubuntu 20.04 to 22.04. If I use slapcat after the update it leads to the following error:
olcAttributeTypes: value #0 olcAttributeTypes: Duplicate attributeType:
"188.8.131.52.18.104.22.168.220.127.116.11"
config error processing cn={4}ppolicy,cn=schema,cn=config: olcAttributeTypes: Duplicate attributeType: "18.104.22.168.18.104.22.168.184.108.40.206"
slapcat: bad configuration file!

The folder /etc/ldap/slap.d contains still all configurations files. Before the Ubuntu update everything worked just fine. Any ideas?
*Edit: Configuration file exported with slapcat -n 0 -l filename.ldif. Part that leads to the error:
dn: cn={4}ppolicy,cn=schema,cn=config
objectClass: olcSchemaConfig
cn: {4}ppolicy
olcAttributeTypes: {0}( 126.96.36.199.18.104.22.168.18.104.22.168 NAME 'pwdAttribute' EQUALI
 TY objectIdentifierMatch SYNTAX 184.108.40.206.4.1.14220.127.116.11.38 )
olcAttributeTypes: {1}( 184.108.40.206.126.96.36.199.22.214.171.124 NAME 'pwdMinAge' EQUALITY
 integerMatch ORDERING integerOrderingMatch SYNTAX 188.8.131.52.4.1.1466.115.121.
 1.27 SINGLE-VALUE )
olcAttributeTypes: {2}( 184.108.40.206.126.96.36.199.18.104.22.168 NAME 'pwdMaxAge' EQUALITY
 integerMatch ORDERING integerOrderingMatch SYNTAX 126.96.36.199.4.1.1466.115.121.
 1.27 SINGLE-VALUE )
olcAttributeTypes: {3}( 220.127.116.11.126.96.36.199.126.96.36.199 NAME 'pwdInHistory' EQUALI
 TY integerMatch ORDERING integerOrderingMatch SYNTAX 188.8.131.52.4.1.1466.115.1
 21.1.27 SINGLE-VALUE )
olcAttributeTypes: {4}( 22.214.171.124.126.96.36.199.220.127.116.11 NAME 'pwdCheckQuality' EQU
 ALITY integerMatch ORDERING integerOrderingMatch SYNTAX 126.96.36.199.4.1.1466.11
 184.108.40.206 SINGLE-VALUE )
olcAttributeTypes: {5}( 22.214.171.124.22.214.171.124.22.214.171.124 NAME 'pwdMinLength' EQUALI
 TY integerMatch ORDERING integerOrderingMatch  SYNTAX 126.96.36.199.4.1.1466.115.
 121.1.27 SINGLE-VALUE )
olcAttributeTypes: {6}( 184.108.40.206.188.8.131.52.22.214.171.124 NAME 'pwdExpireWarning' EQ
 UALITY integerMatch ORDERING integerOrderingMatch  SYNTAX 22.214.171.124.4.1.1466.
 220.127.116.11 SINGLE-VALUE )
olcAttributeTypes: {7}( 184.108.40.206.126.96.36.199.184.108.40.206 NAME 'pwdGraceAuthNLimit'
 EQUALITY integerMatch ORDERING integerOrderingMatch  SYNTAX 18.104.22.168.4.1.146
 126.96.36.199.27 SINGLE-VALUE )
olcAttributeTypes: {8}( 22.214.171.124.184.108.40.206.220.127.116.11 NAME 'pwdLockout' EQUALITY
  booleanMatch SYNTAX 188.8.131.52.4.1.14220.127.116.11.7 SINGLE-VALUE )
olcAttributeTypes: {9}( 18.104.22.168.188.8.131.52.184.108.40.206 NAME 'pwdLockoutDuration'
  EQUALITY integerMatch ORDERING integerOrderingMatch  SYNTAX 18.104.22.168.4.1.14
 126.96.36.199.27 SINGLE-VALUE )
olcAttributeTypes: {10}( 126.96.36.199.18.104.22.168.188.8.131.52 NAME 'pwdMaxFailure' EQU
 ALITY integerMatch ORDERING integerOrderingMatch  SYNTAX 188.8.131.52.4.1.1466.1
 126.96.36.199 SINGLE-VALUE )
olcAttributeTypes: {11}( 184.108.40.206.18.104.22.168.184.108.40.206 NAME 'pwdFailureCountInt
 erval' EQUALITY integerMatch ORDERING integerOrderingMatch  SYNTAX 22.214.171.124.
 4.1.14184.108.40.206.27 SINGLE-VALUE )
olcAttributeTypes: {12}( 18.104.22.168.184.108.40.206.184.108.40.206 NAME 'pwdMustChange' EQU
 ALITY booleanMatch SYNTAX 126.96.36.199.4.1.14188.8.131.52.7 SINGLE-VALUE )
olcAttributeTypes: {13}( 184.108.40.206.188.8.131.52.22.214.171.124 NAME 'pwdAllowUserChange
 ' EQUALITY booleanMatch SYNTAX 18.104.22.168.4.1.14126.96.36.199.7 SINGLE-VALUE )
olcAttributeTypes: {14}( 22.214.171.124.22.214.171.124.188.8.131.52 NAME 'pwdSafeModify' EQU
 ALITY booleanMatch SYNTAX 184.108.40.206.4.1.14126.96.36.199.7 SINGLE-VALUE )
olcAttributeTypes: {15}( 18.104.22.168.4.1.4718.104.22.168 NAME 'pwdCheckModule' DESC
 'Loadable module that instantiates "check_password() function' EQUALITY cas
 eExactIA5Match SYNTAX 184.108.40.206.4.1.1422.214.171.124.26 SINGLE-VALUE )
olcAttributeTypes: {16}( 126.96.36.199.188.8.131.52.22.214.171.124 NAME 'pwdMaxRecordedFail
 ure' EQUALITY integerMatch ORDERING integerOrderingMatch  SYNTAX 184.108.40.206.4.
 1.14220.127.116.11.27 SINGLE-VALUE )
olcObjectClasses: {0}( 126.96.36.199.4.1.47184.108.40.206 NAME 'pwdPolicyChecker' SUP t
 op AUXILIARY MAY pwdCheckModule )
olcObjectClasses: {1}( 220.127.116.11.22.214.171.124.184.108.40.206 NAME 'pwdPolicy' SUP top AU
 XILIARY MUST pwdAttribute MAY ( pwdMinAge $ pwdMaxAge $ pwdInHistory $ pwdC
 heckQuality $ pwdMinLength $ pwdExpireWarning $ pwdGraceAuthNLimit $ pwdLoc
 kout $ pwdLockoutDuration $ pwdMaxFailure $ pwdFailureCountInterval $ pwdMu
 stChange $ pwdAllowUserChange $ pwdSafeModify $ pwdMaxRecordedFailure ) )
structuralObjectClass: olcSchemaConfig
entryUUID: cb6c1fd8-9c5b-103c-96b7-758a4a648933
creatorsName: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
createTimestamp: 20220720094054Z
entryCSN: 20220720094054.645718Z#000000#000#000000
modifiersName: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
modifyTimestamp: 20220720094054Z

Best regards,
Arne
Comment: I assume you use the Ubuntu built-in packages. 20.04 includes OpenLDAP 2.4, till 22.04 has OpenLDAP 2.5. Some of your configuration options may became deprecated. It would also help if we could see those configs...
https://www.openldap.org/doc/admin25/appendix-upgrading.html
Comment: I added the ppolicy part of the config to the question.
Answer: OpenLDAP 2.5+ now ships the ppolicy schema hard-coded in the overlay slapo-ppolicy. So you have to remove this schema from your cn=config data before reloading it (your entry cn={4}ppolicy,cn=schema,cn=config).
See also second paragraph of upgrade docs section B.2. ppolicy overlay.
Answer: Here is an excellent instruction how to find your old data from (automatic apt) backups, and how to manually migrate your data from 2.4 to 2.5 in an event of any error:
https://discourse.ubuntu.com/t/service-migrating-from-openldap-2-4-x-to-2-5-x/23807
I got the same error. It's caused by the password schema being incorporated to the core. The fix is to manually remove the complete section (starting from empty line and ending to an empty line) from your backup cn=config.ldif referring to the offending pwdAttribute .. pwdPolicy. After this follow the instructions.


Multivariable chain rule for a pair of implicit equation

Question: This is one of the questions we were asked in our iniversity examinations.
Find $\left(\frac{\partial u}{\partial x}\right)_y$  for the system:
\begin{align}
\begin{cases}
x+y^3+u^3+v^3=0\\
x^3+y-u^4-v^4=0
\end{cases}
\end{align}
Looking at the system we can say there will be two dependent variables. Since $x$ and $y$ are independent variables as specified in the question, $u$ and $v$ will be considered as dependent variables.
I have figured out two ways through which the problem can be approached.
a) Eliminate $v$. Partially differentiate the expression containing $u$, $x$ and $y$ w.r.t $x$ treating $y$ as constant and get the answer.
b) Partially differentiate both the equations w.r.t $x$ treating $y$ as constant. Now eliminate $\left(\frac{\partial v}{\partial x}\right)_y$ and get the required answer.
What i am not able to figure out is how to draw the dependency diagram (tree diagram) and write the chain rule for the given system. Kindly help by generalizing as to how to write the formula of chain rule for a system of implicit equations.
Comment: What is $\frac{\partial u}{\partial x}$ with index $y$? Do you mean, that argument for $\frac{\partial u}{\partial x}$ is $(x,y)$ or something else?
Comment: There are two dependent variables and two independent variables in the given system. Had the question just mentioned delu/delx it would have meant u is a dependent variable and x is an independent variable thus leaving room for confusion about the nature of the other two variables. (Delu/delx)y basically means u is a dependent variable and x and y are dependent variables.
Comment: Possibly related: https://math.stackexchange.com/questions/2875041/implicit-function-theorem-to-solve-frac-partial-u-partial-x-when-f-bigx/
Comment: Thanks a lot. Indeed, it's related.
Comment: x and y are independent variables*
Answer: Having system
$$\begin{cases}
x+y^3+u^3+v^3 = 0 & \\
x^3+y-u^4-v^4 = 0
\end{cases}$$
and differentiate each equation by $x$, assuming $u=u(x,y)$ and $v=v(x,y)$, we obtain
$$\begin{cases}
1+3u^2u'_x+3v^2v'_x = 0 & \\
3x^2-4u^3u'_x-4v^3v'_x = 0
\end{cases}$$
Now we have system of two linear equations with respect to variables $u'_x$ and $v'_x$, which can be solved by well known formulas in appropriate conditions.
For general case let's assume, that we have mapping $F$ continuous in neighborhood $W$ of the point $(x_0, y_0)\in \mathbb{R}^m\times \mathbb{R}^n$,  with values in $\mathbb{R}^m$ and with continuous partial derivative $F'_y(x,y)$ in it. If $F(x_0, y_0)=0$ and there exists $(F'_y(x_0,y_0))^{-1}$ and $|| (F'_y(x_0,y_0))^{-1}||<\infty$, then there exists neighborhood $U=U(x_0)$ and neighborhood $V=V(y_0)$ and function $f\colon U \to V$, continuous at $x_0$, such that $U \times V \subset W$ and $(F(x,y)=0 \text{ within }U \times V) \Leftrightarrow (y=f(x),x \in U)$. If in addition we know, that $F$ is differentiable at the point $(x_0,y_0)$, then the implicit function is also differentiable at the point $x_0$ and holds
$$f'(x_0)=-(F'_y(x_0,y_0))^{-1}F'_x(x_0,y_0)$$
More details and proofs you can find, for example, in Vladimir A. Zorich - Mathematical Analysis I-Springer, 2016, pages 595-597, or on Implicit function theorem in section "Statement of the theorem"  in formula for $\frac{\partial g}{\partial x_j}$.
Comment: I have already mentioned about this method. I want to know how to use the chain rule here.
Comment: Do you mean to write general form?
Comment: What we refer to as the chain rule here is a direct formula which takes into account the dependency between variables  and is used to find partial derivatives in cases where we have more than 1 equation.
Comment: @chemophilic that is the chain rule.
Comment: Like take the system u=x+y+z x=e^tsink, y=e^tcosk, z=e^t. Now we are asked to find delu/del t..then delu/delt=(delu/delx)(delx/delt)+(delu/dely)(dely/delt)+(delu/delz)dz/dt. This kind of direct formula is what i mean by chain rule
Comment: @chemophilic. Let me little time, I'll write direct general formula, but in your concrete case it will coincide with brought  solution of linear system.
Comment: @chemophilic. Wrote as promised. Write, please, if/when something find unclear.


Distinguishing 2 lines in a file read

Question: I am doing this in order to read a file
f = subprocess.Popen(["../../../abc/def/run_script.sh", "cat", "def/data/ex/details.json"], stdout=subprocess.PIPE)
out = f.stdout.readline()

The file's contents that is being read from above looks like this:
{
         "def1": {
         "val1": 31.6, "val2" : 10
         },
         "def2": {
         "9": {
          "val1": 20.1, "val2": 22
         }
         }
         }

How should i go about it. When there was only 1 "val1" and 1 "val2", i did a simple search with regex and saved the values. Now that there are two, I need to be careful to know which one I am dealing with.. is there an easy way out..?
 File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
                                                                                return _default_decoder.decode(s)
                                                                                File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
                                                         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
                                                                                File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
                                                                                obj, end = self.scan_once(s, idx)
ValueError: Expecting object: line 1 column 3 (char 2)

Comment: Given that it's JSON, can you use a JSON parser in your language of choice?
Answer: Use the json module to parse JSON.
Python 3 code:
import json
import subprocess

with subprocess.Popen(["cat", "/tmp/foo.json"], stdout=subprocess.PIPE) as f:
    j = f.stdout.read()
o = json.loads(j.decode("UTF-8"))
print(o)
print(o["def1"]["val1"])
print(o["def2"]["9"]["val1"])

Output:
{'def1': {'val1': 31.6, 'val2': 10}, 'def2': {'9': {'val1': 20.1, 'val2': 22}}}
31.6
20.1

Edit:
For Python 2, use this instead.
import json
import subprocess

f = subprocess.Popen(["cat", "/tmp/foo.json"], stdout=subprocess.PIPE)
j = f.stdout.read()
o = json.loads(j.decode("UTF-8"))
print o
print o["def1"]["val1"]
print o["def2"]["9"]["val1"]

Comment: Lutz. thanks for your response. How would I build "s"?. "out" prints the cat of the file line by line..
Comment: Isn't  `out` the string?
Comment: s = []
        for i in iter(f.stdout.readline,""):
            s.append(i) If I did this that does not seem right. I cant seem to use "json.loads()" here. then?. Yes "out" is the string line after line.
Comment: I edited my question with the error that I am seeing using your solution. Could u please see it Lutz?
Comment: I have changed my answer.
Comment: with subprocess.Popen(["../../../abc/def/run_script.sh", "cat", "def/data/ex/details.json"], stdout=subprocess.PIPE) as f:
AttributeError: __exit__
Comment: I am using Python2.7.. http://www.diveintopython3.net/files.html has a similar error and they say that the fix is Python 3.1. I cant move from this version I am using now.
Comment: I've changed my answer for Python 2.7.
Comment: o = json.loads(f.decode("UTF-8"))
AttributeError: 'Popen' object has no attribute 'decode'
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/65343/discussion-between-lutz-horn-and-user2921139).
Comment: Works perfectly for my Python2.7. The 3.0 solution also is correct.

Distinguishing 2 lines in a file read


Drupal 7 form_state[redirect] does not work

Question: I am new to Drupal development and I stuck on a problem.
I have got a form which I append to a node. The custom submit method is called correctly, but my redirect does not work. When I press the button I got redirected to the form.
Thank you very much in advance
    function ticketGenerator_node_view($node, $view_mode) {
    $nodetype = node_type_get_type($node);
    $nodetype = $nodetype->type;
    if ($view_mode == 'full' && node_is_page($node) && $nodetype=='event') {
    $node->content['buttonKaufentest'] = drupal_get_form('ticketGenerator_generateform',$node);
    }
    return $node;

}
    function ticketGenerator_generateform($form, &$form_state,$node){
    $form = array();
    $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
);
    $form['submit'] = array(
    '#type' => 'submit' ,
    '#value' => 'buttonalter',
    '#submit' => array('ticketGenerator_list_submit')
 );
 return $form;

}
   function ticketGenerator_list_submit($form,$form_state){
   drupal_set_message('custom submit has been invoked');
   $form_state['redirect'] = 'www.google.de';
   }

Comment: As nearly as I can tell, your custom submit function does nothing but set the message and the value of $form_state['redirect']. It does not actually submit the form. You do not get redirected back to the form. You never left it. All that happened is your browser refreshed itself with the message.
Comment: If that is all you want to have happen, add the line `drupal_redirect_form($form_state);` after setting the redirect (and after changing the parameter to pass by reference) and try it again.
Answer: You need to pass $form_state in by reference, or the change won't be persisted outside of the function scope:
function ticketGenerator_list_submit($form, &$form_state) {

Comment: Ahh damn! How couldnt I see it myself?Thank you very much! That fixed it.
Comment: Thanks. I was working on old code and didn't spot the missing &.
Answer: In my case for Drupal 7 forms. I was setting $form_state[redirect] in the submit handler function and I also did a print_r() to make sure it was there and it was. But it wouldn't redirect. I had to unset the following variables in order for it to work:
unset($form_state['rebuild']);
unset($_GET['destination']);


setTimeout() function stops scrolling

Question: I have created a simple chat app . I have used setTimeout to refresh the messages every .5 ms and scrolltop to keep the scroll bar at the bottom.
    <?php
    session_start();
    ?>

       <title>Live Table Data Edit</title>
       <link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
    />

You Are : <?php echo $_SESSION['name']; ?>

            <textarea id="text" name="text"style="    border: 1px solid #ccc;
width: 350px;
height: 50px;
padding: 10px;" ></textarea>
            <input type="submit" id="sub" name="sub" value="Send" />

everything works fine as accordance to my need but when I use setTimeout() {as I m using it right now} the scrolling gets stuck and when I remove setTimeout scrolling part work fine but the other user cant see the new messages in real time as it is not refreshing in their side.
Answer: Your code is behaving as expected. Every 5ms it sets the scroll to the top. This effectively negates any attempt by the user to scroll, as every 5ms the scroll gets reset.
A few options:
use a div with fixed size to hold your chat and then manage the contents accordingly.
Make it so that you only update the scroll if there are new messages. You can do this via etags or by caching the last message and verifying that the next request has the same last message.

setTimeout() function stops scrolling


listview adapter repete os valores salvos em id

Question: Eu estou tentando trazer os valores do banco de dados e carregar em uma listview, eu já trago do banco um objeto com os dados (uma lista de "modulos"), e tentei passar o id da linha correspondente no banco via Intent para a outra activity carregar os valores correspondentes ao id que foi passado, o problema é que o adapter carrega os dados do banco colocando cada item certinho no listView, mas o id ele só passa para outra activity como intent com o valor 1, indepentente de qual seja o id verdadeiro.
segue o trecho de codigo:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if(convertView == null) {
        LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.list_adapter,null);
        holder = new ViewHolder();
        holder.tituloView = (TextView)convertView.findViewById(R.id.titulo2);
        holder.progressBar =
(ProgressBar)convertView.findViewById(R.id.progress);
        holder.button = (Button)convertView.findViewById(R.id.buttonModulo);

    }else{
        holder = (ViewHolder)convertView.getTag();
    }

    modulos = new Modulos();
    modulos = modulosList.get(position);

    Log.i("idModulo:"," "+modulos.getId());
    String titulo = modulos.getTitulo();
    holder.tituloView.setText(titulo);

    baixarImagem(convertView,modulos,context,holder);

    holder.progressBar.setMax(8);

    holder.progressBar.setProgress(4);

    holder.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Bundle bundle = new Bundle();
            bundle.putString("id",modulos.getId());
            Intent intent = new Intent(context, ListaAulasActivity.class);
            intent.putExtras(bundle);
            intent.addFlags(intent.FLAG_ACTIVITY_NEW_TASK);
            Log.i("idModuloEnviado: ",""+modulos.getId());
            context.startActivity(intent);
        }
    });

    convertView.setTag(holder);
    return convertView;
}

Answer: Para chamar os atributos de cada item da lista, use OnItemClickListener no ListView.
seuListView.setOnItemClickListener(onCliqueItemLista());

Evento:
private AdapterView.OnItemClickListener onCliqueItemLista() {
    return new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            idModulo = modulosList.get(position).getId();
            Bundle bundle = new Bundle();
            bundle.putString("id",modulos.getId());
            Intent intent = new Intent(context, ListaAulasActivity.class);
            intent.putExtras(bundle);
            intent.addFlags(intent.FLAG_ACTIVITY_NEW_TASK);
            Log.i("idModuloEnviado: ",""+modulos.getId());
            context.startActivity(intent);
        }
    };
}

Comment: Funcionou!!! Voce é um genio cara! fiquei muito tempo travado nisso...
mas sabe me dizer como eu faco para que o evento de clique fique no botao, e nao no item inteiro?
Comment: Acho que o problema está no seu ViewHolder, pois ele é usado com RecyclerView. Parece que você criou um Adapter para seu ListView, o que é outra forma de fazer, mas nesse caso não é necessário ViewHolder, remova ele e pegue seus componentes do convertView. O evento de clique para o botão deve ser tratado dentro da classe do seu Adapter customizado.


apache name virtual host - two domains and SSL

Question: I'm trying to setup Apache(2.2.3) to run two websites with SSL using both different domains and IP addresses. Both websites run fine on port 80 but when I tried to enable SSL for website2 I get a ssl_error_bad_cert_domain error; website2 picks up the SSL cert for website1.
Here is my setup in httpd.conf:
# Website1
NameVirtualHost 192.168.10.1:80

<VirtualHost 192.168.10.1:80>
DocumentRoot /var/www/html
ServerName www.website1.org
</VirtualHost>

NameVirtualHost 192.168.10.1:443

<VirtualHost 192.168.10.1:443>
SSLEngine On
SSLCertificateFile conf/ssl/website1.cer
SSLCertificateKeyFile conf/ssl/website1.key
</VirtualHost>

# Website2
NameVirtualHost 192.168.10.2:80

<VirtualHost 192.168.10.2:80>
DocumentRoot /var/www/html/chart
ServerName www.website2.org
</VirtualHost>

NameVirtualHost 192.168.10.2:443

<VirtualHost 192.168.10.2:443>
SSLEngine On
SSLCertificateFile conf/ssl/website2.cer
SSLCertificateKeyFile conf/ssl/website2.key
</VirtualHost>

Update:
In answer to Shane (this wouldn't fit in comment box) here is the output from apachectl -S:
VirtualHost configuration:
192.168.10.2:80       is a NameVirtualHost
         default server www.website2.org (/etc/httpd/conf/httpd.conf:1033)
         port 80 namevhost www.website2.org (/etc/httpd/conf/httpd.conf:1033)

192.168.10.2:443      is a NameVirtualHost
         default server bogus_host_without_reverse_dns (/etc/httpd/conf/httpd.conf:1040)
         port 443 namevhost bogus_host_without_reverse_dns (/etc/httpd/conf/httpd.conf:1040)

192.168.10.1:80       is a NameVirtualHost
         default server www.website1.org (/etc/httpd/conf/httpd.conf:1017)
         port 80 namevhost www.website1.org (/etc/httpd/conf/httpd.conf:1017)

192.168.10.1:443      is a NameVirtualHost
         default server bogus_host_without_reverse_dns (/etc/httpd/conf/httpd.conf:1024)
         port 443 namevhost bogus_host_without_reverse_dns (/etc/httpd/conf/httpd.conf:1024)

wildcard NameVirtualHosts and _default_ servers:
_default_:443          192.168.10.1 (/etc/httpd/conf.d/ssl.conf:81)
Syntax OK

Comment: What output do you get from `apache2ctl -S`?
Comment: Can you confirm your .website2.org is resolved to 192.168.10.2?
Answer: SSL vhosts are not NameVirtualHosts - they're IP-based vhosts.
Remove the NameVirtualHost *:443 from your config.
Comment: I don't have `NameVirtualHost *:443` in my httpd.conf file.
Comment: You have **two**. Remove them.
Comment: I removed both and restarted apache but the website2 is still inheriting the SSL cert from website1.
Answer: Please remove
NameVirtualHost 192.168.10.1:443

and
NameVirtualHost 192.168.10.2:443

It doesn't make sense to activate the name based virtual hosting stuff of Apache for SSL/TLS connections or you'd like to use the SNI extension.
Comment: I removed those lines, it didn't solve the problem.
Comment: Please remove the _default_ section in your ssl.conf file as well (see Shane Madden's comment)
Answer: Here is how I got it working. I had to move the ssl configuration out of httpd.conf and setup two virtualhosts in ssl.conf.
httpd.conf
# Website1
<VirtualHost 192.168.10.1:80>
DocumentRoot /var/www/html
ServerName www.website1.org
</VirtualHost>

# Website2
<VirtualHost 192.168.10.2:80>
DocumentRoot /var/www/html/chart
ServerName www.website2.org
</VirtualHost>

ssl.conf
<VirtualHost 192.168.10.1:443>
DocumentRoot "/var/www/html/"
ServerAdmin firstname.lastname@example.com
ServerName www.website1.org
SSLEngine On
SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:
+EXP:+eNULL
SSLCertificateFile /etc/httpd/conf/ssl.crt/website1.crt
SSLCertificateKeyFile /etc/httpd/conf/ssl.key/website1.key
SetEnvIf User-Agent ".*MSIE.*" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
</VirtualHost>

<VirtualHost 192.168.10.2:443>
DocumentRoot "/var/www/html/chart/"
ServerAdmin firstname.lastname@example.com
ServerName www.website2.org
SSLEngine On
SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:
+EXP:+eNULL
SSLCertificateFile /etc/httpd/conf/ssl.crt/website2.crt
SSLCertificateKeyFile /etc/httpd/conf/ssl.key/website2.key
SetEnvIf User-Agent ".*MSIE.*" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
</VirtualHost>

Comment: This is more or less what everyone here tried to recommend ;-) . Apache includes different files for configuration purposes. So its required to check all of them or to get a output of "apache2ctl -S". Anyway I like the way most administrators are going to split the configuration into different files. So you keep the overview about all the different settings (usually).
Answer: Now that Apache2 handles named based virtualhosts for both HTTP AND HTTPS I would recommend setting your domains up in their own config file. Just as Apache does now with it's "sites-available/sites-enabled" config directories. Place both your http and https declarations in one file and either save that file to the "sites-enabled" directory or save wherever you want and sym-link it.
Like:
/etc/apache2/sites-enabled/Website_ONE.com.conf:
<VirtualHost *:80>
  ServerName Website_ONE.com
  #if you want to redirect to https:
  Redirect permanent / https://Website_ONE.com/
  DocumentRoot /WWW/Website_ONE.com/
</VirtualHost>

<VirtualHost *:443>
  ServerName Website_ONE.com
  DocumentRoot /WWW/Website_ONE.com/

  ### SSL Setup ###
  SSLEngine on
  SSLCertificateFile /etc/SSL_conf/Website_ONE.com/cert.pem
  SSLCertificateKeyFile /etc/SSL_conf/Website_ONE.com/privkey.pem
  SSLCertificateChainFile /etc/SSL_conf/Website_ONE.com/chain.pem
</VirtualHost>

Then: /etc/apache2/sites-enabled/Website_TWO.com.conf:
<VirtualHost *:80>
  ServerName Website_TWO.com
  #if you want to redirect to https:
  Redirect permanent / https://Website_TWO.com/
  DocumentRoot /WWW/Website_TWO.com/
</VirtualHost>

<VirtualHost *:443>
  ServerName Website_TWO.com
  DocumentRoot /WWW/Website_TWO.com/

  ### SSL Setup ###
  SSLEngine on
  SSLCertificateFile /etc/SSL_conf/Website_TWO.com/cert.pem
  SSLCertificateKeyFile /etc/SSL_conf/Website_TWO.com/privkey.pem
  SSLCertificateChainFile /etc/SSL_conf/Website_TWO.com/chain.pem
</VirtualHost>

These files can, as I said, be kept anywhere - providing they are safe (i.e. readable by only the people that need access) - and linked into the sites-enabled folder. Same with the key files and all that. It makes it easier IMHO to keep track of your virtualhosts if all the config is in a file named after the domain.
BTW, I would use absolute paths in the your config vs relative - as you did in your answer.
Answer: Try removing or commenting out  the <VirtualHost _default_:443> block in /etc/httpd/conf.d/ssl.conf.
Comment: I tried this too, then stopped and started apache but the problem still exists.
Comment: Has Apache *ever* presented the correct certificate?  Say, when you access the site with a SNI-capable browser?
Comment: No, I've been hitting the site w/ Firefox 11, latest Chrome, IE 9 and never get correct cert. If I modify my httpd.conf to list website2 before website1 then the issue is reversed website2 has the correct cert but website1 now inherits website2 cert.
Comment: Oh.. old Apache!  What do your `Listen` directives look like?
Comment: Seriously, this is a whole lot easier in IIS.Within httpd.conf: `Listen 80`, within ssl.conf: `Listen 443`.
Comment: Let's split those up to `Listen 192.168.10.1:80`, `Listen 192.168.10.2:80`, `Listen 192.168.10.1:443`, and `Listen 192.168.10.2:443`.
Answer: You need ServerName www.server[1|2}.com in  section
Answer: If you really run apache 2.2.3 the problem is that you cannot do name-based Virtual Hosting on SSL, because your mod_ssl doesn't support it.
You need apache version 2.2.12 or later for that.
You can however use ip-based virtual hosting. The solution you posted is actually doing that (two sites on two different ip adresses)
Answer: You can not use vhosts with SSL unless you use a fairly recent development called SNI.
You could also use a wildcard cert (e.g. *.myhostname.com) if all your TLDs are the same.
For more detail, see:

http://wiki.apache.org/httpd/NameBasedSSLVHosts
http://en.gentoo-wiki.com/wiki/Apache2/SSL_and_Name_Based_Virtual_Hosts
Comment: I thought it was possible as long as you have different IPs?
Comment: Yes, of course, but then you are not using name based virtual hosts :)
With name based vhosts, you are attaching several names to a single ip and telling the server how to sort them out.

I've been through the same process you are now going through... although there are ways around it, they are not yet reliable or common.
Comment: Do other solutions exist? I'd rather not run two instances of apache.
Comment: @BrillPappin There aren't several names on any of those IP/port combinations?
Comment: Those two links I posted above should give you all the info an options you need.

I think pretty much the only way your going to get what you want is if all the domains have the same TLD so you can use a while-card cert.

However, you should not take my word as the last word, go check those links for other options.
Comment: While it's true you can't do name based virtual hosting over ssl without sni support, that's not what the above config is trying to achieve. It configures vhosts on seperate IP's/ports which is acceptable.
Comment: From http://httpd.apache.org/docs/2.2/vhosts/name-based.html - "..unless you are using a mod_ssl version without SNI support (standard in Apache releases since 2.2.12)..."


Nested object with *ngFor

Question: Am trying to create a list using mat-list with below Json structure
{
    "Parent1": [
        {
            "Data1": [
                "child1",
                "child2"
            ]
        }
    ],
    "Parent2": [
        {
            "Data2": [
                "child3",
                "child4"
            ]
        }
    ]
}

Html Code
<mat-list >
       <ng-container *ngFor="let item of (jsonData | keyvalue) ;">
         <mat-list-item>

 {{item.key}}

           <mat-icon>close</mat-icon>

             <mat-divider></mat-divider>

         </mat-list-item>
         <ng-container *ngFor="let child of (item |keyvalue) ;">
           <mat-list-item *ngFor="let subChild of (child |keyvalue) ;">
             {{subChild.value}}
             <mat-icon>close</mat-icon>
           </mat-list-item>
<mat-list>

On the first page load it showing values like below.I need to avoid those values

I need to create a list like below based on the above Json

Note: Am not sure it is the right way to iterate the  object
It will appreciate some one give solution.
Thanks in advance.
Answer: Solution 1: With $any()
A cheating way by using $any() type cast function to prevent type checking.
<mat-list>
  <ng-container *ngFor="let item of jsonData | keyvalue">
    <mat-list-item>

{{ item.key }}

      <mat-icon>close</mat-icon>

        <mat-divider></mat-divider>

    </mat-list-item>

    <ng-container *ngFor="let child of $any(item.value)">
      <ng-container *ngFor="let subChild of child | keyvalue">
        <ng-container *ngFor="let value of $any(subChild.value)">
          <mat-list-item>
            {{ value }}
            <mat-icon>close</mat-icon>
          </mat-list-item>
        </ng-container>
      </ng-container>
    </ng-container>
  </ng-container>
</mat-list>

Solution 2: Restructure the JSON Data
From my perspective, the data that you want to represent in the HTML is something like:
{
  Parent1: ["child1", "child2"],
  Parent2: ["child3", "child4"],
}

Hence, you can work with Object.keys() or Object.entries() (require es2017) to iterate key-value pair and with .reduce() to transform your input data to representation data.
formattedJsonData = {};

this.formattedJsonData = Object.keys(this.jsonData).reduce((acc, cur) => {
      acc[cur] = [];

      for (let item of this.jsonData[cur]) {
        for (let prop in item) {
          for (let value of item[prop]) acc[cur].push(value);
        }
      }

      return acc;
    }, {});

<mat-list>
  <ng-container *ngFor="let item of formattedJsonData | keyvalue">
    <mat-list-item>

{{ item.key }}

      <mat-icon>close</mat-icon>

        <mat-divider></mat-divider>

    </mat-list-item>

    <ng-container *ngFor="let child of item.value">
      <mat-list-item>
        {{ child }}
        <mat-icon>close</mat-icon>
      </mat-list-item>
    </ng-container>
  </ng-container>
</mat-list>

Demo Solution 1 & 2 @ StackBlitz
Comment: great example.can we remove an item when clicking the close button.Can u give the solution this.am new in angular

Nested object with *ngFor


How to prove that a ring $R$ is Morita-equivalent to $M_n(R)$?

Question: Let $R$ be a ring and $M_n(R)$ the ring of $n \times n$ matrices with elements in $R$. Let $\textrm{mod} R$ denote the category of left modules over $R$.
How to define a equivalent functor $F: \textrm{mod} R \to \textrm{mod} M_n(R)$?
In Example, one defines $F(X) = X^n \in \textrm{mod} M_n(R)$ for a left $R$-module $X$.
I do not know how to define the inverse functor $F^{-1}$. In case that $n=2$, $(M_1, M_2)^{T} \in \textrm{mod} M_2(R)$, then what is $F^{-1}((M_1, M_2)^{T})$?
Answer: Let me explain the general picture. Let $R,S$ be two rings. The cocontinuous functors $$\mathsf{Mod}(S) \longrightarrow \mathsf{Mod}(R)$$ are given by $P \otimes_R -$ for some $(R,S)$-bimodule $P$ - this the Eilenberg-Watts Theorem. It follows that pairs of pseudoinverse functors
$$\mathsf{Mod}(R) \longleftrightarrow \mathsf{Mod}(S)$$
are given by pairs $(P,Q)$, where $P$ is a $(R,S)$-bimodule and $Q$ is a $(S,R)$-bimodule such that $P \otimes_S Q \cong R$ as $(R,R)$-bimodules and $Q \otimes_R P \cong S$ as $(S,S)$-bimodules. These pairs (together with the isomorphisms actually) are called Morita contexts, since they classify Morita equivalences between $R$ and $S$. If you want to know more details, you can find them for instance in Lam's book Lectures on modules and rings in the chapter on Morita theory. There you can also find some details for the example below.
In the standard example $S=M_n(R)$, a possible choice is the $(R,M_n(R))$-bimodule $R^{1 \times n}=R^n$ (row vectors) and likewise the $(M_n(R),R)$-bimodule $R^{n \times 1}=R^n$ (column vectors). One has to check that $R^{n \times 1} \otimes_R R^{1 \times n} \cong M_n(R)$ as $(M_n(R),M_n(R))$-bimodules and $R^{1 \times n} \otimes_{M_n(R)} R^{n \times 1} \cong R$ as $(R,R)$-bimodules.
The corresponding pseudoinverse functors are
$$\mathsf{Mod}(R) \to \mathsf{Mod}(M_n(R)),~X \mapsto R^{n \times 1} \otimes_R X = X^{n \times 1}$$
and
$$\mathsf{Mod}(M_n(R)) \to \mathsf{Mod}(R),~ X \mapsto R^{1 \times n} \otimes_{M_n(R)} X \cong E_{11} X.$$
Comment: Yes. $E_{ij}$ are the standard matrix units.
Comment: Thank you. But I have a problem: what is $E_{11}$? Whether $E_{11}$ is the matrix whose $(1,1)$-th entry is 1 and 0 elsewhere.
Answer: Given any $M_n(R)$-module $Y$, we can treat it like an $R$-module (since $R\hookrightarrow M_n(R)$ diagonally), in which case $Y=\bigoplus_i e_{ii}Y$ as $R$-modules. To see why $Y=\sum_i e_{ii}Y$, simply note $I_n=\sum_i e_{ii}$ and to see the sum is direct, suppose $y$ is in both $e_{ii}Y$ and $\bigoplus_{j\ne i}e_{jj}y$, then apply $e_{ii}$ to $y$ to get $y=0$ (since $e_{ii}$ acts as the identity on $e_{ii}Y$ and as $0$ on all other $e_{jj}Y$s). Moreover, observe $e_{ii}Y\cong e_{jj}Y$ as $R$-modules, with multiplications by $e_{ij}$ and $e_{ji}$ as mutually inverse homomorphisms (hence isomorphisms), from which we conclude $Y\cong X^n$ as $M_n(R)$-modules with $X=e_{ii}Y$.
So the inverse of $X\mapsto X^n$ is $Y\mapsto e_{11}Y$.
Comment: I think there's a problem in your proof of $e_{ii}Y \simeq e_{jj}Y$, since multiplying $e_{ii}$ by the permutation matrix associated to the transpositions $(ij)$ can only give you $e_{ji}$, not $e_{jj}$.
Comment: @penseur_32 True. Fixed.


Facebook Parallel image upload - How does parallel thing works

Question: I am trying to implement an ajax style submission form for File Upload.
I was successfully able to get a progress bar updated. i mean the whole logic works fine.
But then I looked at Facebook. I found that -
1) Facebook allows multiple selection of Images. -> I am able to do so
2) Once all images are selected. They start uploading simultaneously and user can see individual progress of each upload.
Analysis:
In my case when I submit, I submit all the images selected by user at once, So I get progress bar for the complete submission not the individual file submission.
My Query is: How can we achieve parallel uploads on all selected images and get a individual progress on all.
Comment: Is it possible that - Once user selected multiple files, FB actually splits all the selected files into individual forms and then manually submit all those forms. Thats the only solution I am able to reach upto?
Comment: This is a jquery solution: http://blueimp.github.io/jQuery-File-Upload/ I don't know about the php side, although this supports it.
Comment: Create one FormData object, set the file data to it, then send it with ajax. Doesn't repeating this in a loop do the trick? I created a small jQuery plugin that behaves like FB's pic uploader and that's basically what it does to upload many files simultaniously.
Comment: Thanks for you response @iharby But It seems they might be using html5, Even though I would give it a try, But a diff approach would be much appreciated. My main motive is not to find an api which I can integrate. jquery.forms should be all I need. I wanted to understand the logic. I mean how does it work actually
Answer: For uploading multiple files at the same time, I will follow the steps-

First I when the form will be submitted, depending on the number of file selected I will dynamically create that much different number of independent ajax request through javascript(Jquery will help for that).
While uploading the files, I can monitor through the javascript and one server script that how much data is remaining to upload, based on that I can show the progress bar for each of the files being uploaded.
Next in server side, I don't need to worry about because the php script what one will write that will take all the request separately.

How to monitor the Uploading progress

In small files, you may not get the exact progress details because it
  will upload very fast but in large file you can monitor.

What you will have to do is creating a separate PHP file which will generate the information that how much % file is uploaded, through the session variable $_SESSION, when a file is started uploading it creates a session for it and how much data is processed is stored(in bytes) and what is the file size(in byte) in the keys bytes_processed and content_length respectively.
And that information I will process through javascript by sending another request. And that request will be made for each of the files being uploaded by binding, and after limited number of time(may be 1 sec.) I will again send the request for knowing the progress by setTimeout() till when the file is 100% is uploaded.
Answer: Facebook uses the HTML5 Files API to make independent XHR2 requests for multiple file upload. When it is not supported it'll try to use Flash and when that is also not supported it falls back to the basic form submission.
You can achieve the same result with this code:
function upload(files){

    for(i=0;i<this.files.length;i++){
        window['xhr'+i] = new XMLHttpRequest();
        window['xhr'+i].open("POST", "/ajax/upload", true);
        window['xhr'+i].upload.addEventListener("progress", function (evt) {
            if (evt.lengthComputable) {
               var progress = Math.round((evt.loaded / evt.total) * 100);

               //Change the progress bar value
            }
        })
        window['xhr'+i].addEventListener("load", function () {

               //Upload Complete. Run callback function
               callback(this.responseText);

        }, false);
    var _params = new FormData();
    _params.append('file'+i, this.files[i]);
    window['xhr'+i].send(_params);

   }
}

Then in your body:
<input type="file" id="files" multiple />

Comment: To check if the browser supports HTML5 File API :

var supported = (!!(window.XMLHttpRequestUpload && window.FileReader) && new XMLHttpRequest().upload && !!window.FormData);


Positive definiteness and eigenvalue inequalities of two symmetric matrices

Question: Let $A = A^T \in \mathbb{R}^{n \times n}$ and $B = B^T \in \mathbb{R}^{n \times n}$ be any symmetric matrices. Then, I know that if $A$ and $B$ are positive definite, and $A-B$ is positive semi-definite, that is, $A, B>0$ and $A \geq B$, then
\begin{equation}
  \lambda_j(A) \geq \lambda_j(B) > 0 \;\; \forall j =1,2,\cdots,n,
\end{equation}
where $\lambda_j(X)$ for a symmetric matrix $X = X^T \in \mathbb{R}^{n \times n}$ denotes the $j$-th eigenvalue of $X$ in a decreasing order: $\lambda_n(X) \leq \cdots \leq \lambda_1(X)$.
Regarding this, I considered the following converse statement.
$\qquad \qquad \lambda_j(A) \geq \lambda_j(B) > 0$ $\forall j =1,2,\cdots,n$
   $\quad\Longrightarrow \quad $ $A \geq B$.
Now, I have found the simple counter example of this converse statement:
$\qquad\qquad A = \begin{bmatrix} 2 & 0 \\ 0 & 1\end{bmatrix}$,
$\qquad B = \begin{bmatrix} 0.5 & 0 \\ 0 & 1.5 \end{bmatrix}$.
In this case, $\lambda_1(A) = 2 \geq 1.5 = \lambda_1(B) > 0$ and
$\lambda_2(A) = 1 \geq 0.5 = \lambda_2(B) > 0$ hold, but
\begin{equation}
  A - B =
  \begin{bmatrix}
     1.5 & 0 \\ 0 & -0.5
  \end{bmatrix},
\end{equation}
so $A-B$ is indefinite. The question is: "what are the other conditions required for $A \geq B$ in addition to the eigenvalue inequalities $\lambda_j(A) \geq \lambda_j(B) > 0$?"
Answer: Unless the smallest eigenvalue of $A$ is $\ge $ largest eigenvalue of $B$ you can do the same trick with diagonal matrices that you did above. Hence the condition is :
$\lambda_n(A) \ge \lambda_1(B)$.


Laravel Homestead vagrant up times out

Question: I'm following the official guide for running Laravel 5.1 on Homestead.
But when I try vagrant up it hangs up at homestead-7: SSH auth method: private key and eventually times out with the message:
Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.

If the box appears to be booting properly, you may want to increase
the timeout ("config.vm.boot_timeout") value.

My SSH keys were generated using ssh-keygen -t rsa -C "you@homestead".
Can't access the machine through vagrant ssh, it outputs ssh_exchange_identification: read: Connection reset by peer.
Tried vagrant destroy and deleting the ~/.homestead folder to start again from scratch but same result.
Using Ubuntu 16.04 64-bit, Vagrant 1.8.4 and VirtualBox 5.0.18. Virtualization is enabled in my computer, other boxes boot up without problems.
Comment: Possible duplicate of [Vagrant ssh authentication failure](http://stackoverflow.com/a/23554973/4133798)
Comment: Tried all approaches mentioned in that answer, same result. Also tried accessing through SSH but I get `ssh_exchange_identification: read: Connection reset by peer`.
Answer: Running Win 10 Pro v 1607, VirtualBox 5.0.30, Vagrant 1.9.1 and Homestead 1.0.1.
I had same issues as described. Vagrant up command would run cleanly but hang at the SSH username: private key message.
Reinstalled, checked .yaml file, recreated ssh keys - tried all the usual stuff without success.
Finally working when I changed the network setting in my Virtual Box.

Brought up VirtualBox program with windows UI
Clicked on Network - in the 'Adapter 1' tab, then opened up Advanced
Clicked 'Cable Connected' checkbox
At console $ prompt, vagrant halt
then vagrant up

All then worked as expected. Unticked 'cable connected' and again vagrant up hanged. Reset 'cable connected' and vagrant up running correctly again.
The default settings for importing the base Laravel/Homestead box leaves the 'cable connected' setting unchecked/off
See vagrant issue 7648 for some background
If you don't want to keep ticking the cable connected box, the permanent fix is:
Locating the Vagrantfile file in the Homestead folder (probably its file path is ~/Homestead/Vagrantfile), and adding following to the Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| block fixes issue:
config.vm.provider 'virtualbox' do |vb|
    vb.customize ['modifyvm', :id, '--cableconnected1', 'on']
end

With this change to the Vagrantfile vagrant up works on new imported laravel/homestead box
Comment: Hmm is this still valid @HamptonNorth, cause when i put it inside i get an error when i tried to destroy with homestead destroy

Line number: 16
Message: NoMethodError: undefined method `config' for File:Class
Answer: If you are using Windows, you may need to enable hardware virtualization (VT-x). It can usually be enabled via your BIOS. If you are using Hyper-V on a UEFI system you may additionally need to disable Hyper-V in order to access VT-x.
I had virtualization turned on, but in VirtualBox it showed that no, I turned off Hyper-V and it all worked.
Comment: This is for you guys, who where messing up with Hyper-V, Windows feature for installing virtual OSes like Ubuntu, etc. That was my exact case.
Answer: I sometimes hang on vagrant up with the error SSH username: private key
try
vagrant halt
vagrant up
Comment: actually i just ran into this problem again, `vagrant reload` did not work, had to find my original answer to get it back up
Answer: If it times out on ssh-key authentication it seems to be a host/guest communication error.
To confirm try ssh email@example.com
If it throws an error or times-out again make sure the virtual machine is shut down completely, by running vagrant halt and using the Virtualbox GUI to confirm this.
Under network I sure my adapter was "Cable Connected" and for my host only adapter I set "allow all" for promiscuis mode.

!Virtual box Network settings screen]2
I then ran vagrant up --provision
 and there was no wait during the authentication between the two.
After the vagrant provisioner script has run you may now vagrant ssh in
Answer: I was facing this problem and tried editing it in the VirtualBox Gui but my Homestead machine didn't appear in the list, here's the solution if it doesn't :
VBoxManage list runningvms

find your homestead machine in the list, it'll mostly be labelled "Homestead-x" (For me it was "Homestead-7")
then run the following commands :
VBoxManage startvm "homestead-7" --type emergencystop
VBoxManage modifyvm "homestead-7" --cableconnected1 on

Afterwards cd into your homestead folder and you'll notice the machine was aborted, a simple vagrant up will start your machine successfully and without stop.
Also consider adding the bit of code provided by @HamptonNorth to your VagrantFile for a permanent fix.
Answer: In my case it worked by deleting ".vagrant" folder located next to Vagrantfile.
Scenario were following:

I was working with this box previously
Reinstalled my PC. Before that I exported box package file so its ready for setup next time.
Imported package.box after fresh Windows 10 installation
vagrant up , and then got stuck similar as described in question.

Looks like there are some kind of conflict if there are existing ".vagrant" folder, probably ssh keys or something.
Comment: Deleting the .vagrant folder inside the Homestead folder worked for me. Homestead rebuilt everything, and it fixed other problems I was having at the same time. Thanks :)

Laravel Homestead vagrant up times out


Multiple datasets not working with Twitter Typeahead/Bloodhound when remote data source is used

Question: The Twitter Typeahead examples page show how to use multiple datasets with Typeahead. Here is working example code using the local data source option:
var nbaTeams = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: []
});

var nhlTeams = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: []
});

nbaTeams.initialize();
nhlTeams.initialize();

$('#multiple-datasets .typeahead').typeahead({
        highlight: true
    },
    {
        name: 'nba-teams',
        displayKey: 'team',
        source: nbaTeams.ttAdapter(),
        templates: {
            empty: [
                '
',
                'No Results',
                '
'
            ].join('\n'),
            header: '
1
'
        }
    },
    {
        name: 'nhl-teams',
        displayKey: 'team',
        source: nhlTeams.ttAdapter(),
        templates: {
            empty: [
                '
',
                'No Results',
                '
'
            ].join('\n'),
            header: '
2
'
        }
    });

JSFIDDLE
If you try out the above JSFIDDLE by typing in the input on the page, you'll see that the two datasets are shown in the typeahead dropdown.
The problem I'm facing is that if I change the data source to remote, only the second dataset is shown in the dropdown. I've simplified my remote code (which actually sends the query using POST instead of get) and you can see it here:
JSFIDDLE
If you try this JSFIDDLE, you'll see that only the second dataset is shown in the typeahead dropdown. if you view the network traffic when typing in the input, you'll see that only one AJAX request is made, when it should be two (one for each dataset).
When I view the network traffic on my website (with my real code), it also shows that a request is only made for the second dataset. So, for some reason, Typeahead/Bloodhound is only making a request for the second dataset instead of one for each dataset. It also only displays results (or lack thereof) for the second dataset, instead of for each dataset.
Why don't multiple datasets work when using the remote data source option?
Comment: This turned out to be a legit bug in v0.10.3. See the fix here: https://github.com/twitter/typeahead.js/pull/899
Answer: This actually appears to be a bug with the latest version of Typahead (0.10.3), because I tried my code with 0.10.2 and it works fine. I filed a bug report here.
I guess I'll leave my Q&A in case it helps someone else.


A commerce fees rule works fine, but is giving the warnings in the log

Question: I've enabled the Commerce Fees module and added a rule with the following details:
{ "rules_setup_fee" : {
    "LABEL" : "Setup Fee",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce License Billing" ],
    "REQUIRES" : [ "rules", "commerce_fees" ],
    "ON" : { "commerce_fees_order" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "commerce-order:commerce-line-items:0:line-item-label" ],
          "match" : "book"
        }
      }
    ],
    "DO" : [
      { "commerce_fees_apply" : {
          "entity" : [ "commerce-order" ],
          "fee" : "setup_fee",
          "amount" : "999",
          "currency_code" : "USD"
        }
      }
    ]
  }
}

which correctly adds $9.99 setup fee to a shopping cart when customer selects any product which has the "book" string in its title (or SKU which we try to keep the same). So the whole thing serves its purpose just fine, however unfortunately it also leaves the following traces in the logs:

Unable to evaluate condition text_matches. Unable to get the data
  value for the variable or parameter text. Error: Unable to get the
  data property line_item_label as the parent data structure is not set.

What am I doing wrong here? Thanks!
Answer: You should add a data_exists to ensure that the delta/label you're trying to access actually exists. It looks like line-item-label is a custom property.
Comment: What version of commerce are you using?
Comment: Without looking at the code, it's hard to say, but as long as there are no errors, it sounds like debugging is just turned on and adding stuff to the log. The rules will re-apply on order refresh which can happen on every page load.
Comment: Nick, I am not sure if I should post this question separately, but it's relevant. The above rule works fine now without giving any errors, however the log is full of "Reacting on event Apply a fee to a given order." messages. Seems like the rule is invoked even if nobody is going to order page, is it normal or should I re-write my rule?
Comment: It shows Commerce 7.x-1.11 in the modules page.
Comment: O yea, I enabled debug logs on admin/config/workflow/rules/settings, but is it really normal that this particular rule is invoked on every page load? The reason I am worried is that other rules are invoked only when needed.
Comment: Do you have discounts enabled? Discounts operates in the same way but other systems like shipping don't work in the same manner. It might not be the best way to do things, but it is pretty normal as far as commerce goes.
Comment: No, only the Commerce Fees with the above rule, nothing else with regard fees/prices.
Comment: Nick, I believe without adding some kind of condition the above rule is adding performance issues on every page visit: `Rules debug information:
" Reacting on event Apply a fee to a given order.
0 ms Reacting on event Apply a fee to a given order.
3.138 ms Evaluating conditions of rule Setup Fee. [edit]
3.583 ms The condition data_is_empty evaluated to TRUE [edit]
3.59 ms AND evaluated to FALSE.
3.605 ms Finished reacting on event Apply a fee to a given order.`


String#codePointAt ou String#charCodeAt?

Question: No ECMAScript 6 foram adicionados novos métodos semelhantes à String.fromCharCode() e String#charCodeAt(): String.fromCodePoint() e String#codePointAt().
Qual a diferença entre eles?
Answer: Da documentação:
String.fromCodePoint()

O método estático String.fromCodePoint() retorna uma seqüência de caracteres criado usando a seqüência especificada de pontos de código

String.prototype.codePointAt()

O método codePointAt() retorna um inteiro não-negativo que é o código
  Unicode do ponto de código

Links:
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint
Answer: A diferença é simples. Primeiro, um valor do tipo String (mais expressado como "string") armazena uma sequência de números inteiros não negativos, do tamanho de 2 bytes (16 bits), chamados "elementos" para facilitar a referência.
O método String#charCodeAt(índice), por exemplo, apenas retorna o valor do elemento na índice (que por convenção inicia do 0) especificada como um número. O método estático String.fromCharCode(...códigos) retorna um valor do tipo String, onde cada elemento equivale à cada código dado.
Agora, a diferença de String#codePointAt(índice). Baseado na codificação UTF-16, retorna o código do caractere na índice (índice dos elementos, não do código) dada.
O método estático String.fromCodePoint(...códigos) também diferencia de String.fromCharCode() por conta da codificação UTF-16 (cria dois elementos se precisar de surrogate pairs para representar o código de um caractere), mas enfim, não dá excepções para códigos entre 0xD800 e 0xDFFF (certamente deveria).


Reading data with PHP inserted to MongoDB with .NET

Question: I've made some search but I can't understand how it works.
The mongo C# driver is using an _t to store the type so when I deserialize I can know which subclass to use, but I'm trying to understand how it works if I want to use the same DB with PHP or another programming language.
I'm afraid it would make deserialization impossible because of that _t type. If someone can explain me how all this works, I've tried to get answers on web but it's still partial.
Here is one record example I get with mongodb and C#:
{
    "_id" : "7aafd454629944c3a1a4b6a9c80db677",
    "_t" : "a-WhereIsFrom",
    "clickfrom" : "here",
    "whichwidget" : "none",
    "Name" : "Franck"
}

Comment: Maybe I misunderstand. Mongo stores/transfers BSON which is binary JSON. Meaning the context itself is JSON. JSON deserialization can happen in any language since it is just a text representation of an object. C# is a statically typed language, and while you can deserialize as `dynamic` thats not good. The `_t` field is just so the Mongo deserialization library can know what objects it was translated from (i.e. if you have an inherited class `FooBar : Foo`, the driver knows if it needs to translate the object as `Foo` or as `FooBar`. You're just trying to understand how that works?
Comment: Yeah this seems legit to me, i've been arguing about this with some friend and came up with the same explication. I think, like you said, that the _t is usefull to C# wich is typed but for others langage it could, like you said too, work since json deserialization can happen in any language. I'm trying to understand how it works yes but to finaly make it with php !
Answer: Just to put this in an answer: MongoDB stores its data in BSON (binary JSON). Essentially allowing each record to be interpreted as JSON string, which can be deserialized into any language.
C# is statically typed, and when deserializing something free-form (like JSON), it will try to understand it as a typed object (unless using dynamic, but I've done that before and it just creates messy code.) The _t field is meant to allow the Mongo deserializer to understand what type it is supposed to translate it as.
Given:
public class Foo { public string Bar {get;set;} }
public class FooBar : Foo {}

If I'm reading a serialized object that looks like:
[
    { "_t": "Foo", "Bar": "Foo" },
    { "_t": "FooBar", "Bar": "Foo" }
]

It allows the library to return to you a list of respected objects.
If another language is inserting records without the _t, you can just pull the BsonDocument and conduct your own lookups, but this is obviously a bit messier.
Translating back into something like PHP, you could have:
class Foo implements MongoDB\BSON\Serializable
{
   public $bar;

   public function __construct($bar)
   {
       $this->id = new MongoDB\BSON\ObjectID;
       $this->bar = (string) $bar;
   }

   function bsonSerialize()
   {
       return [
           '_id' => $this->id,
           'Bar' => $this->bar,
       ];
   }

   function bsonUnserialize(array $data)
   {
       $this->id = $data['_id'];
       $this->bar = $data['Bar'];
   }

}
Then use TypeMap to tell the client what to translate each object as.
Comment: Had the variables mixed up. `Bar` was the property name in the C# object, so I updated to match. You could potentially use the `_t` provided in the object to help you understand what to translate to in a different language as well. It's entirely up to you how you'd go about it, but at least in C# its nice to let the driver do the messy logic of interpreting what property should associate to the data document. There are also annotations that allow you to be more specific on what to name each property, what to ignore, what is required, etc. https://blog.oz-code.com/how-to-mongodb-in-c-part-1/
Comment: Thanks a lot for those explications. Hope the Q/A will be usefull to other people ! The PHP function you wrote can be used for example to unserialize data from c# integration ? so foo would be my _t if i understand
Comment: I get it ! This way both serialization and deserialisation works with c#


Auto import Facebook page photos as nodes for views display

Question: I have some experience using feeds and views, and I've looked at a few modules designed to integrate Drupal with Facebook. But I'm unable to figure out how to set up an importer to automatically pull Facebook photos from a page and turn them into nodes. I'd also like to map three fields for views display: image, description and FB album title to Drupal taxonomy term.
Suggestions on how best to approach this?
Answer: JSON parser did the trick with a feeds importer properly mapped. Once I figured out how to get the data from Facebook, it was really just a matter of configuring the importer properly with the right expressions. I was pleasantly surprised to find that I could get the data without any token because the data comes from a public page, rather than a private profile. The url structure: http://graph.facebook.com/[album id]/photos.


Treatment level as random effect?

Question: I'm trying to make sense of a SAS program that I have inherited.  It uses a linear mixed model to examine the effects of applied fertilzer rate on the grain yield of corn.  There are five different fertilzer rates and three replicates of each rate, and the experiment was repeated each year for three consecutive years.
The existing SAS model is as follows:
<code>proc mixed data = grainYield
        plots = studentpanel;
    class year treatment rep;
    model grainYield = treatment / ddfm = kr;
    random int treatment / sub = year;
    repeated / sub = rep*treatment type = cs;
    lsmeans treatment / diff adjust=bon;
run;
</code>
Can anyone tell me why treatment would be specified as a random effect in this model?
Answer: because fertiliser is a 'rate', i assume like a dosage with increasing increments, thus you have a random intercept and then random slope for treatment. Plot the data and see what they look like ie for a given year plot yield versus treatment. Then see if this helps elucidate the model estimates

Treatment level as random effect?


php7.4-fpm / Apache2: Getting PHP FPM Status Page To Load?

Question: I'm trying to get my php7.4-fpm status page to show up on an URL. I'm running an Apache 2.4.41 server. Instead, I am getting a "File Not Found." error.
Here is what I've done. First I edited:
/etc/php/7.4/fpm/pool.d/www.conf

I uncommented and edited two lines:
pm.status_path = /status
ping.path = /ping

Next, I went to my website's apache configuration file:
/etc/apache2/sites-enabled/mywebsite.com.conf

and added the lines:
<VirtualHost *:443>
  ServerAlias mywebsite.com
  DocumentRoot /home/mywebsite/mywebsite.com

  # added these lines to get the php status page to show up
  <LocationMatch "/(ping|status)">
    SetHandler "proxy:unix:/run/php/php7.4-fpm.mywebsite.sock|fcgi://localhost/status"
  </LocationMatch>

</VirtualHost>

It seems like this should be a simple setup, but I've spent hours unsuccessfully trying to get the status page working to diagnose unexplained php-fpm problems that started up a few days ago with all the php-fpm processes being used on all websites.
Now I'm resigned to playing the shotgun game trying different handlers in an attempt to get something working:
SetHandler "proxy:unix:/run/php/php7.4-fpm.sock|fcgi://localhost/status"
SetHandler "proxy:unix:/run/php/php7.4-fpm.sock|fcgi://localhost"
SetHandler "proxy:unix:/run/php/php7.4-fpm.sock|fcgi://localhost/"
SetHandler "proxy:unix:/run/php/php7.4-fpm.mywebsite.sock|fcgi://localhost"

If I try "proxy:unix:/run/php/php7.4-fpm.sock", which is what the www.conf actually listens on, I get a 503 Service Unavailable.
If I try my website socket "proxy:unix:/run/php/php7.4-fpm.mywebsite.sock", the page actually loads up, but it just shows a "File Not Found", and it doesn't matter if it's "fcgi://localhost/status" or "fcgi://localhost". I don't know what the deal is.
Answer: After taking a break and eating food, I figured this out in minutes. If anyone else has the same problem, you must edit your individual site's pool conf, not the [www] one.
/etc/php/7.4/fpm/pool.d/mywebsite.conf

Then add to that:
pm.status_path = /status
ping.path = /ping

In my case, I never use www.conf. Instead, I have a VPS setup where each site has it's own pool, and apache just doesn't use www.conf.
The next step is to use the socket corresponding to your individual site's pool conf, such as the following for your Apache:
proxy:unix:/run/php/php7.4-fpm.mywebsite.sock|fcgi://localhost/status

sudo systemctl reload php7.4-fpm
sudo systemctl reload apache2

Thanks for looking. I'll probably come across my own post again some years later, so to my future self, this is how it's done. Don't forget to use the URL https://www.mywebsite.com/status?full for the full list of each individual process, not just the summary.


Dovecot 2 /auth-userdb permissions

Question: Error in log file:
 userdb lookup: connect(/var/run/dovecot/auth-userdb) failed: Permission denied
(euid=5000(vmail) egid=5000(vmail) missing +r perm: /var/run/dovecot/auth-userdb,
euid is not dir owner)

Section of 10-master.conf:
service auth {
  # auth_socket_path points to this userdb socket by default. It's typically
  # used by dovecot-lda, doveadm, possibly imap process, etc. Its default
  # permissions make it readable only by root, but you may need to relax these
  # permissions. Users that have access to this socket are able to get a list
  # of all usernames and get results of everyone's userdb lookups.
  unix_listener auth-userdb {
    #mode = 0600
    #user = root
    #group = root
  }

  # Postfix smtp-auth
  unix_listener /var/spool/postfix/private/auth {
    mode = 0666
  }

  # Auth process is run as this user.
  #user = $default_internal_user
}

service auth-worker {
  # Auth worker process is run as root by default, so that it can access
  # /etc/shadow. If this isn't necessary, the user should be changed to
  # $default_internal_user.
  #user = root
}

Permission of /var/run/dovecot directory:
drwxr-xr-x.  4 root  dovecot 4096 Jan 10 14:00 dovecot

and listing of /var/run/dovecot directory:
drwxr-xr-x.  4 root    dovecot  4096 Jan 10 14:00 .
drwxr-xr-x. 14 root    root     4096 Jan 10 13:36 ..
srw-------   1 root    root        0 Jan 10 14:00 anvil
srw-------   1 root    root        0 Jan 10 14:00 anvil-auth-penalty
srw-------   1 root    root        0 Jan 10 14:00 auth-client
srw-------   1 dovecot root        0 Jan 10 14:00 auth-login
srw-------   1 root    root        0 Jan 10 14:00 auth-master
srw-------   1 root    root        0 Jan 10 14:00 auth-userdb
srw-------   1 dovecot root        0 Jan 10 14:00 auth-worker
srw-------   1 root    root        0 Jan 10 14:00 config
srw-------   1 root    root        0 Jan 10 14:00 dict
srw-------   1 root    root        0 Jan 10 14:00 director-admin
srw-------   1 root    root        0 Jan 10 14:00 director-userdb
srw-rw-rw-   1 root    root        0 Jan 10 14:00 dns-client
srw-------   1 root    root        0 Jan 10 14:00 doveadm-server
lrwxrwxrwx   1 root    root       25 Jan 10 14:00 dovecot.conf -> /etc/dovecot/dovecot.conf
drwxr-xr-x.  2 root    root     4096 Sep 23 15:47 empty
srw-rw-rw-   1 root    root        0 Jan  9 14:10 lmtp
drwxr-x---.  2 root    dovenull 4096 Jan 10 14:00 login
-rw-------   1 root    root        5 Jan 10 14:00 master.pid

What am I doing wrong?
Answer: You're running dovecot as user vmail:vmail (uid and gid 5000) while /var/run/dovecot/auth-userdb is owned by root:root with permissions of 0600. You should either change mode to 0604 or change owner to vmail in unix_listener auth-userdb directive (2nd listing).
Comment: If you have this error, read this posting carefully.  It **does** contain the answer to your question.

Dovecot 2 /auth-userdb permissions


Finding sum of integral values of '$a$'

Question: Question: Find the sum of all integral values of  '$a$' such that $$a(x^2+x-1) \leq(x^2+x+1)^2 \text { for all } x \in R$$
My attempt:
I thought about representing $$a\leq \frac{(x^2+x+1)^2}{(x^2+x-1)}$$
but as $x\rightarrow \infty$, This goes to $\infty$ also. I don't really know the approach further. Please help out. I considered quadratic equations for a while but no fruitful result.
Comment: Reworking the final inequality a bit yields $a\le x^2+x+3+{4\over x^2+x-1}$.  What is the minimum value this inequality takes on in the RHS?
Answer: Hint: write your inequality as $$a(x^2+x+1-2)\le (x^2+x+1)^2$$ and set $$t=x^2+x+1$$
then you have to solve $$a(t-2)\le t^2$$
can you proceed?
Comment: Got my answer. Thanks
Comment: @UddeshyaSingh What was your answer?
Comment: @aras  I got $a \in [-9/20 , 8]$ Thus sum was 36
Comment: @UddeshyaSingh Great, thanks. I got that too.

Finding sum of integral values of '$a$'


Passing $form_state data into \Drupal::entityQuery('user')

Question: I have the following D8 form
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['bulk_perfplans_roles'] = array(
      '#type'          => 'checkboxes',
      '#title'         => $this->t('Generate plans for which roles?'),
      '#options'       => user_role_names(),
    );
    $form['bulk_add'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Create new Performance Plans'),
    );

    return $form;
  }

I'm trying to pass the information into an entityQuery as follows...
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $selectedRole = $form_state->get('bulk_perfplans_roles');
    $uids = \Drupal::entityQuery('user')
      ->condition('roles', $selectedRole)
      ->sort('created', 'ASC')
      ->execute();

I'm trying to make it so it conditionally alters the query based on the user selected roles from $form_state. It's currently not working, and I'm not sure where to go next. Any thoughts?
Answer: Does $selectesRole have the expected value? I'm pretty sure you want to use $form_state->getValue('bulk_perfplans_roles') instead. Details here.
Also is it a single value field? You may need to pass an additional IN parameter to your field condition and do some additional prep if the result from getValue is an array.
Also make sure you're passing the machine name of the role and not the label.
Answer: As @sonfd said you submit function will be like:
public function submitForm(array &$form, FormStateInterface $form_state) {
    $selectedRole = $form_state->getValue('bulk_perfplans_roles');
    $uids = \Drupal::entityQuery('user')
      ->condition('roles', $selectedRole,'IN')
      ->sort('created', 'ASC')
      ->execute();
}

After submitting your roles look like:

And UID's will be like:


Linking to My Blog on Menu

Question: I am creating a new Drupal website.  I want to create a menu tab that links to the My Blog section.  What URL link do I use for this?
Comment: What exactly is the My Blog section? Is it a view? If so, use the page display URL that you find in the Edit View screen.
Answer: Should be just (whatever your drupal directory)/blog, if it's installed in root directory, then it would look like http://www.example.com/blog, if the blog you created is different from the system default one, it would be http://www.example.com/your_blog_machine_name

Linking to My Blog on Menu


Elasticserch 2.3.5 encrypting string values

Question: I just built Cluster with Elasticsearch 2.3.5, and I have loaded data using the elasticsearch-spark(elasticsearch-hadoop 2.3.4) connector. Everything looks good except strings get encrypted as below...
<code>    "changeaudioodstreams": "LTguMw==",
    "enm": "QW50aWRvdGU=",
    "pid": 33,
    "uid": 33,
    "upid": 33,
    "pnm": "VHJhdmlzIFNjb3R0",
    "upnm": "VHJhdmlzIFNjb3R0",
    "rd": "MjAxNS0wNy0zMA==",
    "weekid": 201601
</code>
Is there any property to disable this?
Comment: I have corrected a typo in your question title, and tightened up the wording in the question. Feel free to [edit] your question further to make more improvements - editing is encouraged on Stack Overflow.
Comment: I don't think elasticsearch is able to actually do anything to your document values. Also, there's no such thing as an encryption feature in Elasticsearch. So, I think you are probably looking at the wrong part of your architecture for solving this.
Comment: Thanks Vince Bowdren and Jilles. I have manually created an index in ES and added data through curl command. it does not encrypt data.

I am using spark job to load data using hadoop elasticsearch connector(elasticsearch-hadoop-2.3.4.jar),Not sure how data getting encrypted, any help Pl?

I had used earlier elasticsearch-hadoop-2.1.0.jar with Elasticsearch 1.7 and see no issues.
Answer: setting below property in spark code fixed the issue
<code>sqlContext.setConf("spark.sql.parquet.binaryAsString", "true");
</code>


How I can get the selected option on element upon change in Jquery?

Question: I have the following select and using Jquery I manage to get the new value so I can process it further:

 $("select[name=time]").on('change',function(e){
    const target = event.target;
    console.log(target);
    console.log($(target).val());
 });

<select name="time" class="container-full">
       <option value="12:00" data-payvalue=2300>12:30</option>
       <option value="13:00" data-payvalue=2301>13:00</option>
       <option value="14:00" data-payvalue=2101>14:00</option>
    </select>

But what I want is to also retrieve the data-payvalue of he selected options as well. Do you know how I can do it?
In order words I want to do:
     $("select[name=time]").on('change',function(e){
        const target = event.target;
        console.log(target);
        console.log($(target).val());
        const payvalue=''; //populate with selected option having data-payvalue
        console.log(payvalue)
     });

What I want to do is once I select in the example the value 13:00 to display:
  console.log(payvalue)

How I can do that?
Answer: you need to call the custom attribute like this:
const payvalue = $('option:selected').attr("data-payvalue"))

Comment: It works as long as value is unique inside the option. If there are 2 `option` nodes with same `value` attribute it may not work.
Comment: understood, I edited it , you didn't mention that
Answer: One way to do this is:

 $("select[name=time]").on('change',function(e){
    const target = event.target;
    console.log(target);
    console.log($(target).val());

    //populate with selected option having data-payvalue
    const payvalue=$(target).find(":selected").attr('data-payvalue');
    console.log(payvalue)
 });

<select name="time" class="container-full">
       <option value="12:00" data-payvalue=2300>12:30</option>
       <option value="13:00" data-payvalue=2301>13:00</option>
       <option value="14:00" data-payvalue=2101>14:00</option>
    </select>

Pay attention upon:
        //populate with selected option having data-payvalue
        const payvalue=$(target).find(":selected").attr('data-payvalue');
        console.log(payvalue)


mysqli_commit not working?

Question: The function below, as its name suggests, registers/records the data from signup form into the database. In order to avoid table addresses from getting the wrong adressID(which references members(memberID)), I have to wrap the two insert queries into members and addresses respectively with autocommit and commit.
<code>function register($un, $fname, $lname, $email, $pwd, $phone, $street, $city, $country, $postal, $state )
    {
        $this->conn->autocommit(FALSE);

        $query_insert_members = "INSERT INTO members(fname, lname, uname, email, phone, password, joinDate) VALUES('".$fname."', '".
                                $lname."', '".$un."', '".$email."', '".$phone."', '".md5($pwd)."', NOW())";

        $registerquery_members = $this->conn->query($query_insert_members);

        $last_id = $this->conn->insert_id;

        $query_insert_addresses = "INSERT INTO addresses(addressID, street, city, state, country, zip) VALUES('".$last_id."', '".
                            $street."', '".$city."', '".$state."', '".$country."', '".$postal."')";

        $registerquery_addresses = $this->conn->query($query_insert_addresses);

        if($this->conn->commit)
        {
            return true;
        }
        else
        {
            $affectd_rows = $this->conn->num_rows;
            return $affectd_rows.$this->conn->error;
            $this->conn->rollback();
        }
    }
</code>
It doesn't seem to commit anything and doesn't return any error messages either. I only get a blank message.
Answer: You access the property "commit", not calling the function "commit()".
The reason you get no error is because $this->conn->commit inside the if statement will effectively check if a commit property exists in the $this->conn object which evaluates to false. You then execute the else branch where you just return affected rows concatenated with the error string which works of course without failure no matter what. Calling rollback after the return will never execute btw.

mysqli_commit not working?


Ruby class inheritance and how to avoid calling super twice

Question: I'm constructing a chess game. I'm trying to generate each chess piece with a Combining Enclosing Square, and while I can manually type it into each class, I'd like to do it through inheritance. I can't avoid calling super twice per subclass. I'd appreciate any help.
Code:
class Piece
  attr_accessor :color, :piece

  def initialize(color)
    @color = color
    @piece = "#{@piece}\u20DE"
  end
end

class King < Piece
  def initialize(color)
    super
    @piece = "♔" if @color == "white"
    @piece = "♚" if @color == "black"
    super
  end
end

Comment: What is `Combining Enclosing Square`?
Comment: It's a Unicode character.
Comment: I'm going a little off-topic here, but this seems a little funny to me: `@piece = "#{@piece}\u20DE"`. It looks like `Piece` is the superclass, and you're initializing `@piece` using `@piece` + some unicode. But `@piece` isn't defined until that line, so wouldn't it always just be the unicode `\u20DE`?
Comment: I think it's a poor choice of naming on my part. @piece is defined in the attr_accessor method in the Piece superclass, I think. I should probably change that to something else to make it less confusing.
Answer: I'd define a setter. It's cleaner anyway.
 class Piece
  attr_accessor :color, :piece

  def initialize(color)
    @color = color
    @piece = "#{@piece}\u20DE"
  end
  def piece=(piece)
    @piece = "#{piece}\u20DE"
  end
end

class King < Piece
  def initialize(color)
    super
    self.piece = "♔" if @color == "white"
    self.piece = "♚" if @color == "black"
  end
end

k =  King.new('white')
puts k.piece
w = King.new('black')
puts w.piece

Result:
$ ruby chess.rb
♔⃞
♚⃞

Two more things:

Having a class Piece with an attribute @piece is confusing.
Use attr_reader if you don't expect to modify @piece. (I'd say a pawn promotion is a new piece, not a pawn changing into a queen).
Skip the setter, just define to_s, which adds some semantic value.
Comment: You're defining a `piece=` setter but you never use it. Do you mean to do `self.piece = ...` instead of `@piece = ...`? The latter sets the instance variable directly and doesn't invoke the setter.
Answer: Personally, I would move this logic out of the constructor entirely:
class Piece
  attr_reader :color

  def initialize(color)
    @color = color
  end

  def piece
    @piece ||= "#{base_piece}\u20DE"
  end
  alias :to_s :piece

  private
  def base_piece
    self.class.const_get(color.upcase)
  end
end

class King < Piece
  WHITE = "♔"
  BLACK = "♚"
end

puts King.new(:black), King.new(:white)
# => ♚⃞
#    ♔⃞


I have mutiple folders I want to include in doxywizard

Question: I have mutiple folders I want to include in doxywizard. Any Idea how can I do that? Currently If I select folder with multiple subfolder in it and when I run doxygen, It is not showing me any output.
Comment: Which version of doxygen are you using? Did you have a look at the `RECURSIVE` flag?
Comment: No I didn't. But now it worked. Thanks :)
Answer: When having specified just folders in the INPUT tag the files here are handled but not the files in subdirectories. For the later ones one needs the RECURSIVE tag (from the documentation):

RECURSIVE
The RECURSIVE tag can be used to specify whether or not subdirectories should be searched for input files as well.
The default value is: NO.


Snow until the end of the page

Question: I have a script of snow for the site, I took it from this site. As you can see, the snow does not go the bottom of the page. How can I make it go to the bottom?
Source code:
var SNOW_Time;
var SNOW_dx, SNOW_xp, SNOW_yp;
var SNOW_am, SNOW_stx, SNOW_sty;
var i, SNOW_Browser_Width = $(document).width(), SNOW_Browser_Height = $(document).height();

SNOW_dx = new Array();
SNOW_xp = new Array();
SNOW_yp = new Array();
SNOW_am = new Array();
SNOW_stx = new Array();
SNOW_sty = new Array();

for (i = 0; i < SNOW_no; ++i) {
    SNOW_dx[i] = 0;
    SNOW_xp[i] = Math.random() * (SNOW_Browser_Width - 50);
    SNOW_yp[i] = Math.random() * SNOW_Browser_Height;
    SNOW_am[i] = Math.random() * 20;
    SNOW_stx[i] = 0.02 + Math.random() / 10;
    SNOW_sty[i] = 0.7 + Math.random();
    if (i == 0) document.write("<\div id=\"SNOW_flake" + i + "\" style=\"position: absolute; z-index: " + i + "; visibility: visible; top: 15px; left: 15px; width: " + SNOW_Width + "; height: " + SNOW_Height + "; background: url('" + SNOW_Picture + "') no-repeat;\"><\/div>");
    else document.write("<\div id=\"SNOW_flake" + i + "\" style=\"position: absolute; z-index: " + i + "; visibility: visible; top: 15px; left: 15px; width: " + SNOW_Width + "; height: " + SNOW_Height + "; background: url('" + SNOW_Picture + "') no-repeat;\"><\/div>");
}

function SNOW_Weather() {

    for (i = 0; i < SNOW_no; ++i) {
        SNOW_yp[i] += SNOW_sty[i];

        if (SNOW_yp[i] > SNOW_Browser_Height) {
            SNOW_xp[i] = Math.random() * (SNOW_Browser_Width - SNOW_am[i] - 30);
            SNOW_yp[i] = 0;
            SNOW_stx[i] = 0.02 + Math.random() / 10;
            SNOW_sty[i] = 0.7 + Math.random();
        }

        SNOW_dx[i] += SNOW_stx[i];

        document.getElementById("SNOW_flake" + i).style.top = SNOW_yp[i] + "px";
        document.getElementById("SNOW_flake" + i).style.left = SNOW_xp[i] + SNOW_am[i] * Math.sin(SNOW_dx[i]) + "px";
    }

    SNOW_Time = setTimeout("SNOW_Weather()", 10);

}

SNOW_Weather();

Comment: sorry, accidentally hit the button ... :)
Comment: I see you have unaccepted my answer. Was there something you wanted me to add to make it satisfying to you?
Comment: Haha thanks, I was wondering what was wrong with it :)
Answer: It looks like it's determined by the variable SNOW_Browser_Height. $(document).height() doesn't return the proper height. You could use this instead:
document.body.getClientRects()[0].height

Comment: @MaksudAbdurahmanov welcome to Stack Overflow. If an answer solves your problem, you can mark it as the accepted answer by clicking the checkmark next to it.

Snow until the end of the page


Are the $n$-th roots of unity over an arbitrary field generated by a single element?

Question: Let $\mathbb F$ be a field. If we take the set of numbers such that $x^n=1$ (for a fixed $n$), is it true that said group is finitely generated?
What I mean is, let $n\in\mathbb Z^+$, $G_n(\mathbb F):=\{x\in\mathbb F| x^n=1\}$. Is there any $y\in G_n(\mathbb F)$ such that $G_n(\mathbb F)=\langle y^m\rangle$?
I found this earlier question: Do the $n$-th roots of unity of an *arbitrary* field form a cyclic group? but there was no proof provided for what I'm asking.
For what is worth, I know that they form a cyclic group, but I'm failing to find if they're generated by a single element.
Comment: Wait, you know it is a cyclic group? That means that it is generated by a single element.
Comment: Yes, this is true. The crux is that if $x_1,x_2\in G_n$ with orders $d_1,d_2$ respectively, then you can find Integers $a,b$ such that $x_1^ax_2^b$ has order $\operatorname{lcm}(d_1,d_2)$
Comment: I know that a finite subgroup $G$ of $\mathbb F^\times$ is a cyclic subgroup, and I saw that the roots of unity are a group ($(\alpha\beta)^n=\alpha^n\beta^n=1$ [because a field is commutative] and $(\alpha^{-1})^m=1$) so they are cyclic.
But I'm not sure if every cyclic group can be generated by a single element or is isomorphic to the sum of many single generated groups.
Comment: I'm a complete idiot, I confused the cyclic group definition and the abelian group one.
Answer: For any field $K$, any finite subgroup G of the multiplicative group $K^*$ is cyclic.
Proof. From the structure theorem for finite abelian groups, $G\cong Z/a_1 \times...\times Z/a_n$ (in additive notation), wih $a_1\mid a_2\mid ...\mid a_n$. Denote by $y$ the class of $1$ in $Z/a_n$, then $x=(0,0,...,y)$ has obviously  order $a_n$. For any $z=(z_1,...,z_n)\in G$, because $a_i$ divides $a_n$, one has $a_n z=0$, so the order of $z$ divides $a_n$. Thus the order $m=a_n$ of $x$ is the l.c.m. of the orders of the elements of $G$, hence any $g\in G$ is a root of the polynomial $X^m -1$. As $X^m -1$ has at most $m$ roots in the field $K$, the order of $G$ is at most $m$. But, as $x$ has order $m$, the powers $x, x^2,..., x^m=1$ are distinct. It follows that $G$ is cyclic of order $m$.
Answer: It has been answered in the comments but the explicit solution looks like a good exercice :
With $p=char(F)$ and $n=p^k m,p\nmid m$ then the polynomial $x^n-1\in F[x]$ splits completely in some finite extension $E/F$ and its roots are the cyclic group generated by any root of the cyclotomic polynomial $\Phi_m(x)\in E[x]$


Flat maximum effect?

Question: I've seen this referred to in relation to model selection but haven't come across a definitive description of it.
What the flat maximum effect?
Comment: I don't think I've seen the phrase used in this context. Who says it, where, and in what context is it used?
Answer: The flat maximum effect is simply that models with very different coefficients can have very similar performance on a particular prediction or classification task.  When this happens it makes interpreting model coefficients difficult.
One example of where this occurs is in linear regression with multicolinearity of the predictor variables.
As another example, consider a classification problem in which population 1 consists of points very tightly clusters around (-1, 0) and population two consists of points very tightly clustered around around (1,0).  In this situation there are many separating hyperplanes that can be used to produce a perfectly effective linear classifiers.  (x1=0 is one such separating hyperplane, but so is x2=x1 or even x2=0.1x1.)
In terms of the optimization problems solved to fit these kinds of models, what happens is that the maximization has many optimal solutions and thus a "flat maximum."

Flat maximum effect?


SQL single row result set from multiple sql

Question: I have table like below
create table #temp
(
 a int null,
b int null,
c int null,
d int null
)

insert into #temp values (0,0,0,0)
insert into #temp values (0,1,0,0)
insert into #temp values (0,0,0,1)
insert into #temp values (0,1,0,0)

i tried
select * from(
(select count(*)  a from #temp where a=1 group by a) dt1 cross join
(select count(*)  b from #temp where b=1 group by b) dt2 cross join
(select count(*)  c from #temp where c=1 group by c) dt3 cross join
(select count(*)  d from #temp where d=1 group by d) dt4
)

but not getting any output
i want to get output like below
a  b  c  d
0  2  0  1

how to i achieve this?
Answer: Try this:
DECLARE @temp TABLE( a int , b int , c int , d int )
insert into @temp values (0,0,0,0),(0,1,0,0),
(0,0,0,1),(0,1,0,0)

SELECT SUM(a) a,SUM(b) b,SUM(c) c,SUM(d) d FROM @temp

Hope it helps. :)
Comment: Thanks Dheeraj sharma
Comment: Welcome. @Geeme
Answer: IF OBJECT_ID('tempdb..#TEMP') IS NOT NULL
DRop Table #TEMP

CREATE TABLE #TEMP
(
A INT NULL,
B INT NULL,
C INT NULL,
D INT NULL
)

INSERT INTO #TEMP VALUES (0,0,0,0)
INSERT INTO #TEMP VALUES (0,1,0,0)
INSERT INTO #TEMP VALUES (0,0,0,1)
INSERT INTO #TEMP VALUES (0,1,0,0)

SELECT * FROM #TEMP

SELECT SUM(A)A,SUM(B)B,SUM(C)C,SUM(D)D FROM #TEMP

Answer: If the values are only 0 and 1 then use can simply use SUM:
select sum(a), sum(b), sum(c), sum(d) from #temp;

If there can be more other values, and you want to count only 1 then use can use sum on case:
select sum(case when a = 1 then 1 else 0 end),
    sum(case when b = 1 then 1 else 0 end),
    sum(case when c = 1 then 1 else 0 end),
    sum(case when d = 1 then 1 else 0 end)
from #temp;