Extra character being added to string

Question: Why is there an extra character at the end of my string?
#include <iostream>
using namespace std;
int main() {
    int num;
    cin >> num;                                     // Reading input from STDIN
    cout << "Input number is " << num << endl;          // Writing output to STDOUT
    char c1, s2[10];
    for (int i=0; i<num; i++)
    {
         cin >> c1;
         if(c1==0){
             break;
         }
        s2[i] = c1;
    }
    cout <<"output= "<< s2;
}

output example
4
Input number is 4
a l e x
output= alex@

Why is the "@" being added to the end of the string? At first i thought it was  a random garbage value but every time I run the program its always the same symbol
Comment: @Atr0x You can't assign arrays with a size of a non-const variable on runtime in C++.
Answer: cout, when printing a c-string, expects it to zero terminated. Whereas you haven't done so for the array s2.
You can zero initialize the entire array:
char s2[10] = {};

Or just zero terminate the last byte:
  int i = 0;
  for (i=0; i<num; i++)
  {
      cin >> c1;
      if(c1==0) {
          break;
      }
      s2[i] = c1;
  }

  s2[i] = '\0';

In any case, you need to be wary of potential buffer overflow (e.g. if num is too large).
Alternatively, you can consider using std::string instead of a fixed length array.
Comment: If the `break` gets executed, the loop will break earlier than `num` passes, and `s2[num]` will be past the end of the input.
Comment: True. But I doubt that OP intended to input null character via stdin. It looks more like a misunderstanding.
Answer: You're reading from a memory location that hasn't been initialized. By using an array of ten characters and only initializing the first four (or whatever else the number is), all other characters stay uninitalized. What data is actually read from an uninitialized location is undefined, meaning it's pretty much up to your compiler that chooses to read the equivalent value of "@" from that location. You can fix that issue by using a memory bit of the appropriate size. For this, you just replace the line
    char c1, s2[10];

with
    char c1;
    char* c2 = new char[num + 1] //num + 1 is necessary to contain a string terminator, see the other answers

this way, you dynamically allocate exactly the size you need.
Don't forget to delete[] c2; afterwards.
Comment: If the user enters a `0` prior to the end of the array, then it will still (potentially) print junk.
Comment: This has nothing to do with the problem. The question asks about the case when `num` is 4, which fits in the statically allocated array. And even if it were larger, the allocation should be `num + 1` to allow for the nul terminator.
Comment: It does have to do with the problem, actually. 4 *does* fit into the array, so the memory that gets printed is allocated. This doesn't mean, however, that the individual memory addresses are *initialized*. Combining those uninitialized addresses with the missing string terminator causes the problem OP describes. You're right, though, it should be num + 1.
Answer: You are using a Character sequence well explained here.

By convention, the end of strings represented in character sequences
is signaled by a special character: the null character, whose literal
value can be written as '\0' (backslash, zero).
In this case, the array of 20 elements of type char called foo can be
represented storing the character sequences "Hello" and "Merry Christmas" as:

Notice how after the content of the string itself, a null character
('\0') has been added in order to indicate the end of the sequence.
The panels in gray color represent char elements with undetermined
values.

I offer a c++17 solution with the constructor initialization although I may prefer either a dynamic array or std::string instead of a char.
I also added a simple integer check that always should be used.
Also a few versions of avoiding the use of the whole namespace std for various reasons, mostly to avoid unnecessary errors.
#include <iostream>
#include <limits> //numeric_limits

using std::cout, std::endl, std::cin; //<- explicit declared

int main() {
    int num;
    while(!(cin >> num)){  //check the Input format for integer the right way
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        cout << "Invalid input.  Try again: ";
      };

    cout << "Input number is " << num << endl;
    char c1, s2[num+1]{}; // Initialize with an empty string
    for (int i = 0; i < num; i++)
    {
        cin >> c1;
        if (c1 == 0) {
            break;
        }
        s2[i] = c1;
    }
    cout << "output= " << s2 << endl;

return 0;
}

Answer: This happens because s2 is actually not a string and does not have the \0 character, which would mean the end of the string. Therefore, cout prints your string and will continue to move further in memory, byte by byte, interpreting each of them as a character to be output until it encounters the \0 character. In order to fix this, you can initialize s2 with an empty string, so the array will initially be completely filled \0.
#include <iostream>

using namespace std;

int main() {
    int num;
    cin >> num;
    cout << "Input number is " << num << endl;
    char c1, s2[10] = ""; // Initialize with an empty string
    for (int i = 0; i < num; i++)
    {
        cin >> c1;
        if (c1 == 0) {
            break;
        }
        s2[i] = c1;
    }
    cout << "output= " << s2;
}

Extra character being added to string


Javascript call function with parameters in HTML using DOM

Question: In my html page i have this code:
onclick="javascript:CheckAdd({document.getElementById('user_btn').value,document.getElementById('txt_btn').value});

but when i click on button debugger say:

Uncaught SyntaxError: Unexpected token .

what's wrong in my call?
so many thanks in advance
Answer: You are passing an object to the CheckAdd function, this object must contain keys for each value:
onclick="CheckAdd({ key1: document.getElementById('user_btn').value, key2: document.getElementById('txt_btn').value });

Without the keys, your syntax is invalid.
However, if the checkAdd functions takes two argument and not an object, call it without the brackets, like this:
onclick="CheckAdd(document.getElementById('user_btn').value, document.getElementById('txt_btn').value);

Answer: You missed to add key.
onclick="javascript:CheckAdd({k1: document.getElementById('user_btn').value, k2: document.getElementById('txt_btn').value});

If you dont want to pass object pass an array.
Answer: Remove the { } and try again or use a parameter like this
{v1:document.getElementById('user_btn').value,v1:document.getElementById('txt_btn').value }


Getting the right TID with 2 parents

Question: I'm trying to develop an script to upgrade nodes with a term reference.
But my source has 3 columns (copy to an in a db table) to the term tree, example:
fieldnames: ref1, ref2, ref3
fields: CAR -> REDCAR -> DARKRED
I can't use term name because it has is duplicates on the tree. Example:
fields: CAR -> REDCAR -> DARKRED
fields: BIKE -> REDBIKE -> DARKRED
How to get the right TID and verifying the tree with my DB table?
Comment: You might find some useful code in [this module](https://www.drupal.org/project/shs)
Comment: Thank's, I checked the module and doing a loop with an array_reverse might do the job.
Answer: Darvanen, shs code didn't help, the module has always the correct tid, but I have to find it in a tree.
So I made my own function. (note I'm not a php pro)
TABLE
CAT1|CAT2|CAT3
<code>function getcorrecttid() {

$nodes = db_query('SELECT cat1, cat2, cat3 FROM {TABLE});

// record loop
foreach($nodes as $node) {

// get TID with the last column
$query = new EntityFieldQuery;
$result = $query
  ->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('name', $node->cat3)
  ->propertyCondition('vid', 3)
  ->execute();

// check if has more than one
if (count($result['taxonomy_term']) > 1 ) {
  $tids = array();
  $tids = $result['taxonomy_term'];
  $i = 0;
  foreach ($tids as $t) {
    $Keys = array_keys($tids);

    $parent = taxonomy_get_parents($Keys[$i]);
    $pKeys = array_keys($parent);
    $c = 0;
    foreach ($pKeys as $b) {
      $pnum = array_keys($parent);
      if ($parent[$pnum[$c]]->name == $node->cat2) {
        $root = taxonomy_get_parents($pKeys[$c]);
        $rKeys = array_keys($root);
        $a = 0;
        foreach ($rKeys as $z) {
          // found a correct TID after a lot of loops, (caution this is a heavy, heavy search.....)
          $mytid = $Keys[$i];
          }
        $a++;
        }
      }
      $c++;
    }
    $i++;
  }
} else {
  $mytid = array_shift($result['taxonomy_term'])->tid;
  // Found no multi parents...
}
}
}
</code>

Getting the right TID with 2 parents


Notated With a Slur, But Played Without Slur

Question: I just got sheet music for Mack the Knife and in the 3rd bar, there is 2 eighth  note C#s, then 2 eighth note Cs.  Everyone in the band tongued it, and the recording sounds like it was tongued too.
Why?  And why not notate it as a slurred quarter C# and a quarter C?
This is the measure:
Comment: Are those not just legato phrasing marks?
Answer: Well, it wouldn't make sense otherwise, would it?  It can't be a tie since those are only between two adjacent noteheads (which need to have the same pitch and would not be used to connect two eighth notes when the first is on the beat: you'd just write a quarter), so one wants to hear four notes.
Which is what your fellows produced.  Now the question is what the slur signifies: it can be a bowing instruction, or it can be a phrasing slur indicating a legato passage.  A bowing instruction would typically also carry tenuto/portato bars.  So it's likely a phrasing instruction.
The execution would likely not or barely tongue between second and third note, and try putting just as much tongue between the equal notes to make the attack just as distinct as the valve use between second and third notes would.


Reading a specific number of lines from a file without storing in memory?

Question: I have data that I need to read and extract specific blocks from using a python code but the files are potentially tens of millions of lines long and too large to store in memory so I only want to pull the data that I actually need to analyse.
The files are formatted as follows:
4 # Number of lines per block
0 # Start of block 0
A line of data
A line of data
A line of data
A line of data
1 # Start of block 1
A line of data
A line of data
...

The issue I'm having is that once I find and read the specific block I need into a list, my code continues reading and adding data until the end of the file instead of the end of that specific block.
Here's what I have so far:
required_block = 5
ilepath = file.txt
data = []

with open(filepath, 'r') as f:
    block_length = int(f.readline())
    for line in f:
        block = int(line)
        if block != required_block:
            for _ in range(block_length)
                next(f)
        else:
            break
    for line in f:
        data.append(line)

If I try to add a range to the last 'for' loop it will just read the current line over and over.
Where am I going wrong?
EDIT: To clarify, I only want the last 'for' loop to run < block_length > number of times.
Answer: If you look at your code, your last for loop is the culprit. You're telling it to append everything no matter what. In your first for loop, you're not actually having it append anything at all. So essentially in the first loop it just runs through the data, then in the second one it appends everything because the append is outside of the logic.
I think what you want is something like this:
for line in f:
        block = int(line)
        if block != required_block:
            next(f)
        else:
            for _ in range(block_length):
                data.append(line)

Answer: Try changing your last loop to this:
for _ in range(block_length):
    data.append(f.readLine())

Answer: Reading file line by line:
filepath = 'Iliad.txt'
    with open(filepath) as fp:
       line = fp.readline()
       cnt = 1
       while line:
           print("Line {}: {}".format(cnt, line.strip()))
           line = fp.readline()
           cnt += 1


Prove that $\int_0^\infty\frac{x^n}{1+e^{x-t}}\mathrm{d}x = \frac{t^{n+1}}{n+1} + o(t^n)$, when $t \to \infty,\,n\in\Bbb{R}^+$

Question: I hae to prove that
$$\int_0^\infty\frac{x^n}{1+e^{x-t}}\mathrm{d}x = \frac{t^{n+1}}{n+1} + o(t^n), \quad\text{ when } t \to \infty,\,n\in\Bbb{R}^+$$
where $o(\cdot)$ is the Little-o notation.
What I have done so far:
Let $F_n(t) = \int_0^\infty\frac{x^n}{1+e^{x-t}}\mathrm{d}x$, then $F_0(t) =\int_0^\infty\frac{1}{1+e^{x-t}}\mathrm{d}x = \log(e^t+1)$. The derivative of $F_n(t)$ is:
\begin{align*}
F_n'(t) &= \int_0^\infty\frac{e^{x-t}x^n}{(1+e^{x-t})^2}\mathrm{d}x\\
&= -\int_0^\infty x^n\mathrm{d}\frac{1}{1+e^{x-t}}\\
&= \left.\frac{x^n}{1+e^{x-t}}\right|_0^\infty+\int_0^\infty \frac{1}{1+e^{x-t}}\mathrm{d}x^n\\
&= \int_0^\infty \frac{nx^{n-1}}{1+e^{x-t}}\mathrm{d}x\\
&= nF_{n-1}(t)
\end{align*}
Comment: Just by curiosity, in which context did you come across these functions ? (These integrals are actually involved in the physics of Bose-Einstein condensates).
Comment: @Tom-Tom Indeed, it's Fermi-Dirac. Note the $+1$ in the denominator.
Comment: There is a fine tutorial about those type of integrals in   [Pathria book](http://www.amazon.com/Statistical-Mechanics-Third-R-Pathria/dp/0123821886/ref=sr_1_1?ie=UTF8&qid=1418844811&sr=8-1&keywords=Pathria) appendix.
Comment: @FelixMarin Thanks for the book recommendation, I'll read the appendix of it. Though I'm not majoring in Math nor Physics, I truly like math.
Comment: @Tom-Tom I was answering questions in a Chinese Q&A forum. The original question is $\lim_{t\to\infty}F_1(t)/F_0(t)−t=0$. After solving it, I wanted to know the approximation of $F_n(t)$. By programming, I found out this approximation.
Comment: @FelixMarin. I indeed missed the $+1$. These fermionic functions actually have the same relation rules as the bosonic ones ($B'_n=nB_{n-1}$). Thanks for your answer and for the reference !
Answer: First, let's split up the integral:
$$
\begin{align}
\int_0^\infty\frac{x^n}{1+e^{x-t}}\mathrm{d}x
&=\int_{-t}^\infty\frac{(x+t)^n}{1+e^x}\mathrm{d}x\\
&=\color{#C00000}{\int_{-t}^0\frac{(x+t)^n}{1+e^x}\mathrm{d}x}+\color{#00A000}{\int_0^\infty\frac{(x+t)^n}{1+e^x}\mathrm{d}x}\tag{1}
\end{align}
$$
Note that the first integral on the right side of $(1)$ is
$$
\begin{align}
\color{#C00000}{\int_{-t}^0\frac{(x+t)^n}{1+e^x}\mathrm{d}x}
&=t^{n+1}\int_{-1}^0\frac{(1+x)^n}{1+e^{tx}}\mathrm{d}x\\
&=t^{n+1}\int_{-1}^0(1+x)^n\,\mathrm{d}x-\color{#0000FF}{t^{n+1}\int_{-1}^0\frac{(1+x)^n}{1+e^{tx}}e^{tx}\,\mathrm{d}x}\\
&=\frac{t^{n+1}}{n+1}+O\left(t^n\right)\tag{2}
\end{align}
$$
because
$$
\begin{align}
\color{#0000FF}{t^{n+1}\int_{-1}^0\frac{(1+x)^n}{1+e^{tx}}e^{tx}\,\mathrm{d}x}
&\le t^{n+1}\int_{-1}^0(1+x)^n\,e^{tx}\mathrm{d}x\\
&\le t^{n+1}\int_{-1}^0e^{nx}\,e^{tx}\mathrm{d}x\\
&\le\frac{t^{n+1}}{n+t}\\[6pt]
&=O\left(t^n\right)\tag{3}
\end{align}
$$
Furthermore, by dominated convergence
$$
\lim_{t\to\infty}\int_0^\infty\left(1+\frac xt\right)^n\,e^{-x}\,\mathrm{d}x
=1\tag{4}
$$
therefore, the second integral on the right side of $(1)$ is
$$
\begin{align}
\color{#00A000}{\int_0^\infty\frac{(x+t)^n}{1+e^x}\mathrm{d}x}
&\le t^n\int_0^\infty\left(1+\frac xt\right)^n\,e^{-x}\,\mathrm{d}x\\
&=O\left(t^n\right)\tag{5}
\end{align}
$$
Combining $(1)$, $(2)$, and $(5)$, we get
$$
\int_0^\infty\frac{x^n}{1+e^{x-t}}\mathrm{d}x
=\frac{t^{n+1}}{n+1}+O\left(t^n\right)\tag{6}
$$
Comment: (+1) Clever solution. This is quite similar to my approach, but more clean.
Answer: We have:
$$ F_0(t) = \log(e^t+1) = t+\log(1+e^{-t}) = t+o(1) $$
and since your identity gives:
$$ F_n(t) = n\int_{0}^{t} F_{n-1}(u)\,du $$
we have:
$$ F_1(t) = \frac{t^2}{2}+o(t), $$
$$ F_2(t) = \frac{t^3}{3}+o(t^2), $$
and so on, so the claim holds by induction for any $n\in\mathbb{N}_{>0}$. Moreover, since:
$$ F_n(t) = \frac{t^{n+1}}{n+1}-\int_{0}^{t}\frac{(t-x)^n}{e^{x}+1}\,dx+\int_{0}^{+\infty}\frac{(t+x)^n}{e^x+1}\,dx\tag{1}$$
it is sufficient to estimate:
$$ \int_{0}^{+\infty}\frac{e^{nx/t}}{e^x+1}\,dx = \frac{t}{t-n}-\frac{t}{2t-n}+\frac{t}{3t-n}-\ldots=\log 2+O\left(\frac{n}{t}\right)$$
and prove that
$$ \lim_{t\to +\infty}\frac{1}{t^n}\int_{0}^{t}\frac{(t-x)^n}{e^x+1}\,dx=\lim_{t\to +\infty}\int_{0}^{t}\frac{(x/t)^n}{e^{t-x}+1}\,dx=\log 2,$$
that follows from the dominated convergence theorem, to have the claim for $n\in\mathbb{R}^+$, too.
Comment: How to derive the last two formulas? Could you make it more clear?


How do I create a form in a modal dialog with Drupal 7?

Question: There seems to be many solutions for implementing a modal dialog including Ctools, Colorbox, Simple dialog, and Ctools Auto-modal. I'm not sure which is the best to use for simple coding through the Form API to create popup forms in a modal dialog.
The big issue seems to be validation. Are there any best practices for creating a modal form in Drupal?
Comment: Great question, but isn't it very closely related to this one: http://drupal.stackexchange.com/questions/18842/show-forms-in-a-modal-window ? Could you perhaps bounty that one instead?
Answer: A good example for using forms on modal dialogs is in Ajax Login/Register module. You could see the module code and understand how it works(ajax_register is using ctools_modal).
Or you can render the form manually and use ctools only for the responses. For example:
mymodule.module:
function mymodule_form($form, &$form_state) {
  ...
  ctools_include('ajax');
  ctools_add_js('ajax-responder');

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';
  $form['actions']['submit']['#ajax'] = array(
    'callback' => 'mymodule_ajax_callback',
    'wrapper' => 'container',
  );
  ...
}

function mymodule_ajax_callback($form, $form_state) {
  if (!form_get_errors()) {
    $commands   = array();
    $commands[] = ctools_ajax_command_reload();

    return array('#type' => 'ajax', '#commands' => $commands);
  }

  return $form;
}

Now, you can anywhere render this form and show popup (using Twitter Bootstrap or Lightbox):
Show Form

<?php print drupal_render(drupal_get_form('mymodule_form')); ?>


Centos docker proxy port - firewall

Question: I have some project which I run with docker-compose up. This project has frontend on port 4200, backend 3000 and db 5342. When I run it with docker-compose, all these ports are public. So I can (everyone can) access for example to backend https://myserver:3000/api.
How can I disable docker-proxy ports to public? My solution is that I have nginx, using as myapp.myserver.com and redirect to local frontend port 4200 (nginx.conf) - frontend is using backend port 3000 and backend 5432 - but these ports shouldn't be public. Public ports should be only 80, 443, 22 (ssh) etc.
See my netstat:
tcp        0      0 0.0.0.0:80              0.0.0.0:*               NASLOUCHÁ  11972/nginx: master
tcp        0      0 0.0.0.0:22              0.0.0.0:*               NASLOUCHÁ  848/sshd
tcp        0      0 127.0.0.1:25            0.0.0.0:*               NASLOUCHÁ  1149/master
tcp        0      0 0.0.0.0:443             0.0.0.0:*               NASLOUCHÁ  11972/nginx: master
tcp6       0      0 :::9000                 :::*                    NASLOUCHÁ  16995/docker-proxy
tcp6       0      0 :::5000                 :::*                    NASLOUCHÁ  14069/docker-proxy
tcp6       0      0 :::5001                 :::*                    NASLOUCHÁ  11557/docker-proxy
tcp6       0      0 :::8080                 :::*                    NASLOUCHÁ  11402/docker-proxy
tcp6       0      0 :::80                   :::*                    NASLOUCHÁ  11972/nginx: master
tcp6       0      0 :::22                   :::*                    NASLOUCHÁ  848/sshd
tcp6       0      0 ::1:25                  :::*                    NASLOUCHÁ  1149/master
tcp6       0      0 :::443                  :::*                    NASLOUCHÁ  11972/nginx: master
tcp6       0      0 :::8000                 :::*                    NASLOUCHÁ  17006/docker-proxy

Answer: So I solved it with change when mapping ports:
From:
ports:
      - "3000:3000"

To:
ports:
      - "127.0.0.1:3000:3000"

Now it is available only on localhost of VPS where app is running, not possible to call https://myserverip.com:3000/api.
Answer: You can use nginx.conf to redirect to backend ports as well. For instance, api.myserver.com will route traffic to backend port 3000 and db.myserver.com will route traffic to port 3000. All these containers should be on the same docker network for easier routing.
Nginx can control which ports are exposed to the outside world.
This way, your nginx will server as ingress proxy. All connections are routed through nginx and the rest of the world is oblivious to the ports used internally. This idea is used to open services behind kubernetes to the world.
Comment: Thanks, yes I can redirect backend ports on nginx. But it isn't easier just to disable ports on firewall somehow? Just allow tcp and tcp6 on 80, 22,25 and 443. Everything other will be not public. In my case it means every docker proxy disable to public.
Comment: Yes, that's easier and better.

Centos docker proxy port - firewall


perfect forward secrecy, o que é?

Question: Estava a ler uma matéria once citava PFS e então fui pesquisar, o Wikipedia é fraco de informações sobre esta, o que é? É como fazê-lo? Por favor sou leigo e gosto de exemplos, obrigado desde já.
Answer: Em uma comunicação encriptada (por exemplo, via HTTPS) o cliente e o servidor compartilham um segredo - chamado "chave de sessão" - que é responsável por garantir a confidencialidade da comunicação. Qualquer um que intercepte essa comunicação, mas não conheça esse segredo, não consegue decifrar os dados interceptados. Ele pode guardar esses dados pro futuro, entretanto, na esperança que um dia ele consiga interpretá-los (seja via criptanálise, ou através de outros meios).
A maneira como essa chave de sessão é criada tem um impacto na viabilidade desses "outros meios". Digamos que uma chave mestra (por exemplo, a chave privada do certificado do servidor) seja usada para derivar as chaves de sessão, cada vez que um cliente conecta. Cada sessão tem sua chave, mas todas vieram dessa chave mestra. Num determinado ponto futuro, o atacante consegue invadir o servidor e recuperar a chave mestra. Aí é só ele repetir o processo de derivação que originou as chaves de sessão, e usar os resultados para decifrar os dados que ele guardou.
Por outro lado, se as chaves de sessão não são diretamente derivadas de nada - são criadas por processos aleatórios, que não podem ser refeitos no futuro - aí não adianta nada o atacante invadir o servidor, roubar todos os seus segredos, etc: as comunicações passadas entre ele e os clientes continuam confidenciais (desde que não armazenadas no servidor, é claro), pois as chaves de sessão já foram jogadas fora e não existe um meio de recriá-las.
Perfect Forward Secrecy (Segurança Futura/"Pra Frente" Perfeita) é essa propriedade, em que uma comunicação presente é confidencial, e espera-se que ela se mantenha confidencial no futuro mesmo que as chaves permanentes de um ou de outro (o certificado do servidor, o certificado ou usuário/senha do cliente) sejam comprometidas. Alternativamente, se uma única comunicação for comprometida (digamos que a chave de sessão "vazou") isso não compromete a confidencialidade de todas as comunicações anteriores a ela.
É difícil dar um exemplo com confiança, pois não tenho conhecimento suficiente de protocolos criptográficos, então vou reproduzir aqui o exemplo gráfico do artigo sofre Diffie-Hellman na Wikipedia. Note que o protocolo real é um pouquinho mais complicado que isso (pois o DH original não assegurava a autenticidade da comunicação, e portanto era vulnerável a ataques Man-in-the Middle).

Digamos que Alice e Bob querem se comunicar um com o outro, e ambos combinam em um parâmetro comum (a "tinta amarela"). Cada um deles escolhe aleatoriamente um outro segredo/chave (as "tintas vermelha e azul") e combina-o com o parâmetro comum de uma forma irreversível (a "primeira mistura das tintas"). Cada um envia ao outro o resultado dessa operação, que por sua vez é combinado com o seu próprio segredo (a "segunda mistura das tintas") de modo a produzir um segredo comum (a "tinta marrom"). Esse segredo comum pode então ser usado como chave de criptografia, para garantir a confidencialidade das mensagens trocadas até o final daquela sessão. No final da sessão, todos os segredos envolvidos são jogados fora (esse é o ponto chave da PFS).
Alguém que esteja "escutando" a comunicação sabe qual é o parâmetro comum, e os resultados intermediários de cada computação, mas somente com base nisso não consegue descobrir nem os segredos individuais de Alice e Bob nem o segredo final que é compartilhado entre ambos. E como todos os segredos foram descartados, ainda que todos os dados encriptados sejam armazenados pelo atacante, não há esperança dele recuperar esses segredos no futuro, de modo que a comunicação efetuada pode ser considerada "perfeitamente segura pra sempre".
(Isto é: até que o próprio algoritmo criptográfico seja quebrado - permitindo decifrar as mensagens sem precisar das chaves - ou a velocidade dos computadores cresça tanto a ponto de viabilizar uma quebra por força bruta... Entretanto, essa é considerada a hipótese menos provável, desde que um bom algoritmo criptográfico tenha sido usado.)
Comment: Nossa, você explica bem! eu não sabia que existia uma primeira fórmula para D-H que era falha.. entendi perfeitamente o que me propôs, gostaria de confirmar. Suponhamos que A e B estabeleceram conexão e trocaram chaves através do DH e cada mensagem que um manda para o outro é encriptada usando a chave D-H + um parâmetro aleatório que será passado pela rede para poder decriptar a mensagem fazendo a derivação junto a chave D-H, podemos dizer que o PFS foi estabelecido neste?
Comment: @GabrielHenrique O ponto chave é usar chaves "descartáveis" - nem todo DH provê PFS, apenas as implementações que geram a chave na hora e depois descartam (chamado de "Diffie-Hellman [Efêmero](http://en.wikipedia.org/wiki/Ephemeral_key)" - EDH ou DHE, dependendo da suite).
Comment: Chaves descartáveis, ou seja chaves únicas para cada mensagem correto?
Comment: Não necessariamente únicas por mensagem, mas únicas por sessão. Claro, todas as mensagens da sessão formam um único conjunto, com o mesmo nível de proteção, mas cada conjunto está isolado de todos os outros (o comprometimento de um não compromete os outros).

perfect forward secrecy, o que é?


How can a deep neural network learn anything?

Question: When training a network, gradients are back-propagated throughout the entire network, updating parameters such as weights and biases.
So the last layer $n$ sees features proposed by the previous layer $n-1$, and decides, based on their performance as measured by the loss, to give a little more weight to this one and a little less to that one -- changing its output.
Simultaneously, layer $n-1$ does the same thing, and also changes its parameters, meaning that the features layer $n$ will see at the next round are not exactly the same that were used to compute an update.
But wait, layer $n - 2$ also changes its parameters... and so on till the first layer.
So, at the next round, layer 1 has changed and produces slightly different features, which are then provided to layer 2, which has also changed, and so on. When features reach layer $n$, how can they have anything in common with the features that have been used to optimize it?
Furthermore, in practice, the first layers typically have much less parameters than the last ones. It seems to me that all downstream layers depend on those first convolutions, and that any change in them deeply affects all downstream features based on them.
Now, it would be reasonable to say, "Stop thinking too hard. These are gradients. If you take a step small enough, maybe a very very small step indeed, features will change only oh so slightly. The cost will go down, this is mathematical."
But, in deep learning, the learning rate is taken as large as can be during the first phase, precisely when features are shaped.
How, in these conditions, can a network learn anything?
Answer: You're absolutely right, it makes no sense, and it's a huge problem.
The loss function is locally linear. You are effectively saying that $L(w+h) = L(w)+h\cdot dL(w)$, where $L$ is your loss function, $w$ your vector of weights, and $dL$ is the gradient vector. In this sense, the contribution of changes of each weight produces an approximately linear change in $L$ as a function of the step-size. $dL$ and in particular $dL_i$, the individual components, definitely depends on weights in a nonlinear way. This helps to decouple the range of the output from the range of how $L$ changes as the weights change. Due to the sensitivity you point out, there are also strategies which assign smaller learning rates to earlier layers, especially for the purposes of fine-tuning a network.
Even though we choose a larger learning rate initially, this learning rate is still tuned to how sensitive $L$ is, so that the above linear relationship is roughly held.
In theory the above is right, but in practice the situation is considerably more complex. For example in a recent paper The Shattered Gradients Problem: If resnets are the answer, then what is the question?
Balduzzi, et. al, evidence is presented exactly to your point, that vanilla deep learning networks have gradients that are extremely sensitivity to both weights and input images, even with batch normalization. It is shown that residual networks considerably improve this sensitivity, which makes a convincing case for why they work so well.
At the same time, initially almost anything is better than random guessing. For example if you're training a network to tell "1" apart from "7", then it's clear that "1"'s have more vertical features, vs 7's have a ton of diagonal and horizontal features, so that even first level convolutions that correlate slightly with vertical vs diagonal features will contribute to improving the model.
Answer: A recent paper addresses this topic: "Doing the impossible: Why neural networks can be trained at all" by Nathan Hodas, Panos Stinis

As deep neural networks grow in size, from thousands to millions to billions of weights, the performance of those networks becomes limited by our ability to accurately train them. A common naive question arises: if we have a system with billions of degrees of freedom, don't we also need billions of samples to train it? Of course, the success of deep learning indicates that reliable models can be learned with reasonable amounts of data. Similar questions arise in protein folding, spin glasses and biological neural networks. With effectively infinite potential folding/spin/wiring configurations, how does the system find the precise arrangement that leads to useful and robust results? Simple sampling of the possible configurations until an optimal one is reached is not a viable option even if one waited for the age of the universe. On the contrary, there appears to be a mechanism in the above phenomena that forces them to achieve configurations that live on a low-dimensional manifold, avoiding the curse of dimensionality. In the current work we use the concept of mutual information between successive layers of a deep neural network to elucidate this mechanism and suggest possible ways of exploiting it to accelerate training. We show that adding structure to the neural network that enforces higher mutual information between layers speeds training and leads to more accurate results. High mutual information between layers implies that the effective number of free parameters is exponentially smaller than the raw number of tunable weights.
Answer: This is why learning rates, despite being "as large as can be" are still quite small. On the order of $10^{-3}$ and $10^{-4}$ is common. But you are right that this can be an issue.
Batch normalization is one partial solution to this problem which often allows for faster training: Normalizing the activations after each layer so that they have the same mean and variance reduces the problem of "covariate shift" -- in other words, the fact that after an iteration of SGD, the features output at a certain layer might've changed in an unpredictable way, making it hard for the subsequent layers to do their job.
So to summarize: a combination of small step sizes and batch norm.


CSS title with triangle bottom shape

Question: im straggling to create such title style in CSS. Can someone help me please?
Comment: here is starting template: https://jsfiddle.net/d49gw21y/
Comment: This won't work without using SVG, specialized PNG images or canvas
Comment: This can be done in CSS by turning a div into a triangle and then fixing it to the bottom of the header. The header text can then be positioned over this.
Comment: See http://stackoverflow.com/a/12251346/2506219 on how to do this.
Answer: Totally possible with following css
<code>.content::after{
    content: "";
    background: #fff;
    transform: skewY(10deg);
    width: 50%;
    height: 80px;
    position: absolute;
    left: 0;
    top: 75px;
}
.content::before{
    content: "";
    background: #fff;
    transform: skewY(-10deg);
    width: 50%;
    height: 80px;
    position: absolute;
    right: 0;
    top: 75px;
}

.content{
  width:100%;
  height:75px;
  background:#fff;
  overflow:hidden;
  padding:20px;
}
</code>
you should check it on different screen sizes and tweak with height of after and before elements
In this case content class should be element you want to add triangle

CSS title with triangle bottom shape


Percorrer Array PHP

Question: Possuo a seguinte chamada para um model`
$dados = $this->atleta_model->get_atividade_semanal($__cod);

Porém ele esta me retornando um objeto que eu não consigo iterar, preciso percorrer ele para colocar os valores dele em uma tabela.
Retorno do model
array(1) {
    [0]=> object(stdClass)#26 (4) {
        ["cod_atleta_ativ_sem"]=> string(3) "164"
        ["dia_semana"]=> string(5) "Sexta"
        ["data_hora"]=> string(16) "09/11/2018 15:35"
        ["descricao"]=> string(5) "Teste"
    }
}

Estou tentando percorrer ele da seguinte maneira.
 while ($relatorio=$dados->fetch_assoc()) {

    $content .= "

            ".$relatorio["cod_atleta_ativ_sem"]."
            ".$relatorio["cod_atleta"]."
            ".$relatorio["data_hora"]."
            ".$relatorio["descricao"]."
            ".$relatorio["data_alteracao"]."
            S/. ".$relatorio["usuario_alteracao"]."

    ";
    }

Answer: Como se trata de uma StdClass, você pode converter para array apenas passando o (array) na frente:
foreach($dados as $relatorio){
    $relatorio = (array)$relatorio;

    ...
}

Percorrer Array PHP


Non-commutativity of differential operators multiplied like a quadratic

Question: I just read that if $v$ and $w$ are smooth functions of $x$ you can define operators $\partial _x + v$ and $\partial _x + w$. From there we find,
$$
(\partial _x + v)(\partial _x + w) = \partial _x ^2 + w' + (v+w)\partial_x + vw \\
(\partial _x + v)(\partial _x + w) = \partial _x ^2 + v' + (v+w)\partial_x + vw
$$
Where do these $w'$ and $v'$ terms come from? I do not follow the logic of how they appear.
Answer: A really good way to make sure we don't miss terms like this is to use the method of a "test function." We have for some differentiable function $f(x)$ that
$$ (\partial_x+v)(\partial_x+w)f = (\partial_x+v)(\partial_xf + wf) = \partial^2_xf + v\partial_xf + \partial_x(wf) + vwf. $$
It's from the third term that your $w'$ comes out:
$$ (\partial_x+v)(\partial_x+w)f = (\partial_x+v)(\partial_xf + wf) = \partial^2_xf + v\partial_xf + w'f + w\partial_xf + vwf. $$
After evaluating fully, you can now say that since the final expression is true for "any" differentiable function $f$, the operator $(\partial_x+v)(\partial_x+w)$ is equivalent to the operator
$$ \partial^2_x + v\partial_x + w' + w\partial_x + vw. $$
The logic is the same for the other operator.


Understanding general case of parabola equation

Question: I'm working on understanding how to find the equation of a parabola using directrix and focus. I understand the formulas that use the pythagorean theorem/distance formula to equate the distance from a point of the parabola $P = (x, y)$ and the directrix to the distance of said point to the focus. I also got how it works for parabolas opening left/right or opening up/down.
Now I was wondering, how does it work in the general case, for example, if the parabola is opening to the "top-right" or such.
On wikipedia I found the general formula for this:

If the focus is $F=(f_{1},f_{2})$ and the directrix $ax+by+c=0$ one gets the equation
$$\frac{(ax+by+c)^2}{a^2+b^2} = (x-f_1)^2+(y-f_2)^2$$
(The left side of the equation uses the Hesse normal form of a line to calculate the distance $|Pl|$.)

With the right side I'm familiar, it calculcates delta $x$ and delta $y$ and we equal that to the left side, the distance of some point $(x, y)$ and the directrix.
But I found the left side is giving me trouble, I read the linked wiki article on the Hesse normal form, but it didn't make it very clear to me how the distance there is calculated.
Can anyone explain more how the distance on the left hand side of the equation is calculated? What is $a$ and $b$ in this case?
Answer: Suppose we want to find the parpendicular distance of $L:~ax+by+c=0$ from $P:~(x_0,y_0)$. Note that the slope of $L$ is $-\frac ab$. Therefore slope of a line parpendicular to $L$ will be $\frac ba$. There equation if the line parpendicular to $L$ passing through $P$ will be $$L':~y-y_0=\frac ba(x-x_0)$$
Now find the point $P'$ where the line $L'$ intersects with $L$, by solving the corresponding linear equations for $L$ and $L'$. Then the distance between the points $P$ and $P'$ will give you the required distance. Carry out these calculations to get the given formula.
Answer: Let $P(x_1,x_2)$ and $\ell : ax+by+c=0$.
If we want to find the distance between $P$ and the line $\ell$, then let $H(\alpha,\beta)$ be a point on $\ell$ such that $PH\perp\ell$.
We can write
$$PH^2=(\alpha-x_1)^2+(\beta-y_1)^2\tag1$$
Since $H$ is on $\ell$,
$$a\alpha+b\beta+c=0\tag2$$
Since $PH\perp\ell$,
$$\frac{\beta-y_1}{\alpha-x_1}=\frac ba$$
implying
$$\frac{\alpha-x_1}{a}=\frac{\beta-y_1}{b}$$
If we set
$$\frac{\alpha-x_1}{a}=\frac{\beta-y_1}{b}=k$$
we have
$$\alpha=ak+x_1,\qquad \beta=bk+y_1\tag3$$
Substituting $(3)$ into $(2)$ and solving it for $k$ gives
$$k=\frac{ax_1+by_1+c}{a^2+b^2}\tag4$$
It follows from $(1)(3)(4)$ that
$$PH^2=(a^2+b^2)k^2=\frac{(ax_1+by_1+c)^2}{a^2+b^2}$$
It follows that the distance between $P$ and the line $\ell : ax+by+c=0$ is given by
$$PH=\frac{|ax_1+by_1+c|}{\sqrt{a^2+b^2}}$$
Answer: The vertical distance of a point to the axis $x$ is obviously $|y|$.
Now if you rotate the plane by an angle $\theta$, the ordinate is transformed by
$$y'=x\cos\theta+y\sin\theta.$$
And if you translate the plane to another origin,
$$y''=y'+c=x\cos\theta+y\sin\theta+c.$$
All the points at distance $0$ from the line thus fulfill the condition
$$x\cos\theta+y\sin\theta+c=0,$$ (this is the implicit equation of the line) and those at distance $d$,
$$\left|x\cos\theta+y\sin\theta+c\right|=d.$$
Instead of the angle $\theta$, you can consider two coefficients $a,b$ and write
$$\cos\theta=\lambda a,\\\sin\theta=\lambda b.$$
By elimination of $\lambda$,
$$\cos\theta=\frac a{\sqrt{a^2+b^2}},\\\sin\theta=\frac b{\sqrt{a^2+b^2}} b.$$
Then
$$d^2=\left(\frac{ax+by}{\sqrt{a^2+b^2}}+c\right)^2$$ or
$$d^2=\frac{(ax+by+c')^2}{a^2+b^2}.$$


Image Skinning a Button in Flex 4

Question: I'm trying to skin a button with images.
The following code is for flex 3, but I need the equivalent in flex 4 code.
Not using skin class.
.muteVolumeButton
{
  upSkin: Embed(source='images/sound-mute.gif');
  overSkin:Embed(source='images/sound-hover.gif');
  downSkin: Embed(source='images/sound-on.gif');
  disabledSkin: Embed(source='images/sound-mute.gif');
}

Please post the flex 4 code.
Answer: I should say that skinning in Spark framework is a bit different from Halo way.
The best description is here. And its a best and simplest way to solve your problem.
Here is code:
components.ImageButton.as
package components
{
 import spark.components.Button;

 [Style(name="imageSkin",type="*")]
 [Style(name="imageSkinDisabled",type="*")]
 [Style(name="imageSkinDown",type="*")]
 [Style(name="imageSkinOver",type="*")]

 public class ImageButton extends Button
 {
  public function ImageButton()
  {
   super();
  }
 }
}

Script:
[Embed('assets/images/btnGoUp.png')]
[Bindable]
public var btnGo:Class;

[Embed('assets/images/btnGoOver.png')]
[Bindable]
public var btnGoOver:Class;

[Embed('assets/images/btnGoDisabled.png')]
[Bindable]
public var btnGoDisabled:Class;

MXML part:
<components:ImageButton buttonMode="true"
   imageSkin="{btnGo}" imageSkinDisabled="{btnGoDisabled}"
   imageSkinDown="{btnGoOver}" imageSkinOver="{btnGoOver}"
   skinClass="assets.skins.ImageButtonSkin"/>

In all other cases you always can skin the states via CSS.

You should always put your skin: @namespace s "library://ns.adobe.com/flex/spark";
You can access component states: s|Button:down
You can extend your skin, with image, and override it via CSS, but it will be not a core component.

Here are some useful links:
http://blog.flexexamples.com/2009/03/03/styling-an-emphasized-fxbutton-control-in-flex-gumbo/
http://blog.flexexamples.com/2010/03/24/using-a-bitmap-image-skin-in-a-spark-button-control-in-flex-4/
http://opensource.adobe.com/wiki/display/flexsdk/CSS+Namespaces+Support
http://cookbooks.adobe.com/post_How_to_use_the_new_CSS_syntax_in_Flex_4-15726.html
Comment: +1 to Eugene for a good answer.  Yes, you have to do this through skins, but the good news is that you can create a generic skin once and use it for any button thereafter by setting the images in CSS just like you used to do in Flex 3.
Comment: thanks for the information.But why the adobe  removed in flex4 the easiest flex 3 image skinning of button through css.The difficulty i am facing is skinning multiple buttons with different images.
Comment: its more flexible way in spark framework, just extend button with image, and then setup it via CSS. like http://blog.flexexamples.com/2010/03/24/using-a-bitmap-image-skin-in-a-spark-button-control-in-flex-4/
Answer: In the skin open a script tag and  do:
        [Embed(source="assets/images/button-up.png", scaleGridLeft = "4", scaleGridRight = "5", scaleGridTop = "2", scaleGridBottom = "3")]
        [Bindable]
        public var upImg:Class;

        [Embed(source="assets/images/button-over.png", scaleGridLeft = "4", scaleGridRight = "5", scaleGridTop = "4", scaleGridBottom = "5")]
        [Bindable]
        public var overImg:Class;

        [Embed(source="assets/images/button-disabled-skin.png", scaleGridLeft = "4", scaleGridRight = "5", scaleGridTop = "2", scaleGridBottom = "3")]
        [Bindable]
        public var disabledImg:Class;

        [Embed(source="assets/images/button-over.png", scaleGridLeft = "4", scaleGridRight = "5", scaleGridTop = "4", scaleGridBottom = "5")]
        [Bindable]
        public var downImg:Class;

delete all the default fills and instead use:
<s:BitmapImage source="{upImg}"
               source.over="{overImg}"
               source.down="{downImg}"
               source.disabled="{disabledImg}"
               width="100%"/>

And voila'

Image Skinning a Button in Flex 4


Click on Successive Links Using IMacro

Question: I am trying to write a macro to add a digit to POS= after each loop, so that it clicks on successive links in my search results in http://www.presidency.ucsb.edu/ws/index.php (type in any keyword under "Search the Entire Document Archive). I did something very similar to the user from imacro increase attr=id by one digit after every loop
My code works, but the macro starts clicking from the third search result onward. I have changed POS= 1,2,3 but anything less than POS=4 ends up clicking on sidebars, not the search results. What should I change to get the macro to start clicking from the first search result? Thanks for any insight!
set !var1 1
add !var1 {{!LOOP}}
TAG POS=4{{!var1}} TYPE=A ATTR=TXT:*
BACK

Answer: The links you are trying to click on all have a class with value "listLink" so if you include that in the tag logic you should be able to bypass the sidebar links.
TAG POS={{!LOOP}} TYPE=A ATTR=CLASS:listLink
BACK

Click on Successive Links Using IMacro


Backup Exec Monitoring Tool

Question: Does anyone know of a monitoring tool for Backup Exec 12 and BESR 8.5?
I'm sick of going through all the email alerts or logging into servers to check the status of my backups.
Servers are Windows Server 2003 and XP workstations
Answer: What kind of monitoring do you need that you can't get from the alerts? Do you want to know when a job fails? Succeeds? Alerts support email and pager notifications, so I'm not quite clear on what you're asking for. BackupExec also supports sending SNMP traps. Can you elaborate?
Comment: I'm still confused. BackupExec does have a GUI that shows the job status. It's on the Job Monitor tab, it shows all active and scheduled jobs in the upper pane and all completed jobs (success or failure) in the lower pane. The Alerts tab shows all job errors. Am I still not understanding what you're asking for?
Comment: Why not just install the Backup Exec console onto your PC, then?
Comment: I'm really just looking for a gui that shows success/fail and active backups.
Answer: If email alerts aren't cutting it Backup Exec also supports SNMP - see here and here for help from Symantec on setting it up.
You can then tap into it with most systems monitoring software, so you can take your pick. :)
Answer: If you can't find one, you could create your own by piping the alert emails to a script which could log when a backup started, ended, and if it fails send an auxiliary alert to you via email/SMS and such. I used to do this with PHP (for a different application) and added all relevant data to database tables by parsing various parts of the message with regular expressions. I had a simple web GUI driven off the database.
If I still had it I'd offer to give it to you, but here's the barebones of an email script, then you just setup your MTA to deliver notification emails to the script.
<code>#!/usr/bin/php -q
<?php
$fd = fopen("php://stdin", "r");
$message = "";
while (!feof($fd)) {
    $message .= fread($fd, 1024);
}
fclose($fd);
// Do stuff
?
</code>
That's how I'd do it on Linux. I believe stdin would still work the same, though the shebang would be different.
Answer: I use zabbix to monitor backupexec jobs. What I did was to enable SNMP in backupexec. So, when it executes a job, it sends a trap that is listened by zabbix, that records the traps on it's database.
So, from zabbix console I can monitor all my environment.
Answer: If you have a system monitor like Nagios already, it's straightforward to set up alerts that will tell you if the backups haven't been updated.  I wrote a blog post about how to do this with Nagios.
Answer: I keep coming back to this question and wondering just how many instances of BackupExec are involved here, because you're making it sound like there are vast numbers. This should already be automated and you should not need to go through all the email alerts or log on to the servers or even open the BE console.
I find the simplest solution is a filter for my email (we use Outlook but the principles apply elsewhere). Any emails from the backup systems that include warnings or errors are moved to a separate folder and I get a pop-up telling me about them. That, coupled with a monitoring system that let's me know if the backup hasn't run or completed, lets me see at a glance when things aren't quite right. After all, I'm not really all that interested in the emails telling me the backup was successful.
No rocket science, just a little constructive laziness - the most powerful tool any sysadmin can have.
Answer: You can use CheckCentral for this. You setup your backup emails to be sent to CheckCentral, and then it takes care of logging them as success or failed, and sends a notification if the email is overdue.
Disclaimer: I work for Binary Fortress Software :)

Backup Exec Monitoring Tool


Cypress not loading page headless after click login button

Question: when i run my script headless seems not load the next page, the video recorded after execute it, shows the following:
enter image description here
and fails after that with a timeout error
enter image description here
here the test:
context('TS001-login', () => {
beforeEach(() => {
  cy.visit('/');

})

const userName = "sdfgsdfg";
const passwrd = "gsdfgsdgg";

it.only('login with valid user and password', () => {

  cy.get('#j_username', {timeout : 31500}).type(userName);
  cy.get('#j_password', {timeout : 31500}).type(passwrd);
  //cy.contains('Login').click({force: true});
  cy.contains('Login').type('{enter}');
  cy.get('#logout', {timeout : 71500}).should('be.visible');

  cy.wait(2500);

});

it.only('login with invalid user and valid password', () => {
  cy.get('#j_username', {timeout : 31500}).type('userName');
  cy.get('#j_password', {timeout : 31500}).type(passwrd);
  cy.contains('Login').click({force: true});
  cy.get('#error').should('contain', errorLP1);
  cy.wait(2500);

});

here the cypress.json:
{
"baseUrl": "http://salesportal-uat.xxxxx/",
"ignoreTestFiles": "**/ignore/*.spec.js",
"chromeWebSecurity": false,
"viewportWidth": 1280,
"viewportHeight": 720,
"defaultCommandTimeout": 30000,
"pageLoadTimeout": 60000,
"requestTimeout": 20000,
"retries": {
    "runMode": 1,
    "openMode": 1

},

"experimentalSessionAndOrigin": true

}
Also, this works perfect in protractor : headed and headless, but need it to work in cypress Im using version 9.6.1 and tried as well with 8.5.0 , Please help.

Tried with
before(() => {
cy.visit('/')
})
and works well in headed mode but not headless, Still having same results when tries to enter the page after click login, throwing timeout error.
enter image description here
enter image description here
Here working well in headed mode:
enter image description here
I think  cypress is doing something when executes it headless. Dunno what it is. Any ideas?
Answer: Use a before() hook for cy.visit,
before(() => {

  cy.visit('/')

})

not in
beforeEach(() => {
  cy.visit('/');

})

If you used to visit in beforeEach () hook, it will repeatedly try to access the basic URL you specified in your cypress.json during each test.
So,
before() runs once before all your code.
beforeEach() runs before each of your code blocks.
And also you can do the following to store all cookies between tests once.
beforeEach(function () {
  cy.getCookies().then(cookies => {
    const namesOfCookies = cookies.map(c => c.name)
    Cypress.Cookies.preserveOnce(...namesOfCookies)
  })
})

Because after Each it blocks the execution of cypress clean cookies
And if your test failed again after this, due to being unable to find an element within mentioned time, then increase ```"pageLoadTimeout" in your cypress.json or use a custom timeout.
Answer: The reason is here you activated experimentalSessionAndOrigin in your cypress.json
since all session state is now cleared between tests.
You can use the cy.session () command, which allows you to easily cache session information and reuse it through testing.
If you no need to access multiple domains within your test suite you disable or remove experimentalSessionAndOrigin in your cypress.json
Or if you need then you can improve this by using cy.session(), please refer to the document
Comment: If I take off experimentalSessionAndOrigin , when the script clicks login comes back to the login page, if I turn it on, after clicks login proceeds with the next page (all this in headed mode).
Comment: I did it with cy.session and got similar result,  here are the results : headed - OK: https://ibb.co/yfmypqT ; headless - NOT OK:  https://ibb.co/QYpK1LR
Comment: Im so done with this issue, Ill be keeping my test in protractor and work from there, a shame. #Cypress
Answer: So could you please try, this in tour test spec file
beforeEach(function () {
  cy.getCookies().then(cookies => {
    const namesOfCookies = cookies.map(c => c.name)
    Cypress.Cookies.preserveOnce(...namesOfCookies)
  })
})

And take off experimentalSessionAndOrigin in your cypress.json
Comment: Hi Pali, I took off the flag "experimentalSessionAndOrigin" from cypress json https://ibb.co/rkkX2Zn and added the cy.getCookies(...) in before each in the test https://ibb.co/2MSKqMp and fails in headed mode with chrome or edge browser, its like after click in login button comes back into the login page  ,
here the result https://ibb.co/x1bvw0d


Proof for the definition of parabola??

Question: In my maths textbook parabola is defined as path traced by a point which moves in a plane in such a way that its distance from fixed point (focus) is always equal to its distance from a fixed line(directrix) both lying in the same plane where as the given fixed point does not lie on the given line.
Is there any proof for this definition or we accept it as an axiom ?
Comment: It's not an axiom, and definitions don't have proof. You can call such a curve anything you want, but the name came from Ancient Greece
Comment: It's a definition of a parabola. Definitions don't have proofs. But there are other definitions of a parabola, for instance the classical Greek definition of a section of a cone by a plane parallel to a generator. With two different definitions, one then needs a proof that they are equivalent.
Answer: I'm going to guess that what you are actually asking is how this definition leads to the equation of a quadratic function that you're used to seeing for a parabola. For simplicity's sake, let's assume that the focus lies on the y-axis, say its coordinates are $\,(0,\alpha),\,$ and that the directrix is the horizontal line $\,y=-\alpha,\,$ with $\,\alpha \neq 0\,$ so that the focus is not on the directrix.
Let $\,P(x,y)\,$ be a point satisfying the given condition. Then the distance from $\,P\,$ to the focus is given by $\,\sqrt{x^2+(y-\alpha)^2};\,$ and since the directrix is horizontal, the distance to it from $\,P\,$ will be purely vertical, i.e. $\,\left|y-(-\alpha) \right| =\left|y+\alpha\right|=\sqrt{(y+\alpha)^2}.\,$ Then we have that
$$
\begin{align}
\sqrt{(y+\alpha)^2} &= \sqrt{x^2+(y-\alpha)^2}\\
(y+\alpha)^2 &= x^2+(y-\alpha)^2\\
(y+\alpha)^2 - (y-\alpha)^2 &= x^2\\
4\alpha y &= x^2\\
y &= \frac{1}{4\alpha}x^2\\
\end{align}
$$
Letting $\,a=\frac{1}{4\alpha}\,$ gives the familiar quadratic equation $\,y=ax^2.\,$
Every other parabola can be thought of as an expansion/compression, rotation and/or translation of this simple parabola, so by applying the appropriate transformations to the focus and directrix we can generate the equation of every parabola in the same manner.
Answer: It's not an answer. Let me add some comments. First of all, please note that one of the simplest ways of defining conic is the following:
Let S be a fixed point on the plane, and AB be a straight line that does not pass the given fixed point S. Now, consider the locus of a point P such that SP/PM is constant, where MP is the perpendicular distance from P to the line AB. The locus of P is defined as a conic.
The fixed point S is called the focus, the line AB is called the directrix, and the ratio SP/PM is called the eccentricity of the conic. Many people denote SP/PM by e.
Note that if e= 1, then we say, our conic is a parabola. Similarly, we can define hyperbola and ellipse.
By the way, the phrase "a path traced by a point" is replaced the fancy word "locus".
I hope this helps.

Proof for the definition of parabola??


Is this Sturm-Liouville problem self-adjoint?

Question: We are interested in determining whether the problem $\begin{cases}xu''-u'+u = \cos(x)\\u(0) = 0 \\ u(1) = u'(1)\end{cases}$ is self-adjoint.
This is not a Sturm-Liouville problem, the corresponding SL problem is $\begin{cases}(\frac{1}{x}u')'+\frac{1}{x^2}u = \frac{\cos(x)}{x^2}\\u(0) = 0 \\ u(1) = u'(1)\end{cases}$
According to literature and videos on the subject, it appears that the SL problem $(p(x)u')'+q(x)u=0$ with boundary constraints on $x=a$ and $x=b$ is self-adjoint if
$p(b)[u'(b)v(b)-v'(b)u(b)]-p(a)[u'(a)v(a)-v'(a)u(a)] = 0$
In our case however, $p(x) = \frac{1}{x}$ so $p(0)$ is undefined. What do I do?
Answer: Are you considering the operator
$$
              Lu=(\frac{1}{x}u')'+\frac{1}{x^2}u
$$
on $L^2[0,1]$? Or on $L^2_w[0,1]$ for some weight $w\ne 1$? A true Sturm-Liouville problem has a spectral parameter $\lambda$, and the multiplier of $\lambda$ in the symmetric form dictates the space where you are studying the equation. Without that, there is no natural way to determine $w$, and you must specify it. So this is not really a Sturm-Liouville problem.
You have an ODE that you want to solve, and you are reasonably questioning whether or not the general solution will allow you to impose endpoint conditions. This has a lot to do with the homogeneous equation
$$
     xu''-u'+u=0, \tag{$\dagger$}
$$
which can be written in the form
$$     x^2u''-xu'+xu=0.
$$
This is an equation with a regular singular point at $0$. By the method of Frobenius, it has one solution of the form $u=x^2v$ where $v=\sum_{n=0}^{\infty}a_n x^n$. The coefficient equation is
$$
    \sum_{n=2}^{\infty}a_n (n+2)(n+1)x^{n}-\sum_{n=1}^{\infty}a_n(n+1)x^{n}+\sum_{n=0}^{\infty}a_n x^{n+1}=0 \\
   a_n(n+1)^2=-a_{n-1} \\
    a_{n+1} = -\frac{1}{(n+2)^2}a_n,\;\; n \ge 0.
$$
So you have one solution $u=x^2v$ where $v$ is a power series. A second solution $w$ is obtained by variation of parameters: $w=qu$. Substituting into the equation gives
$$
      x^2(qu)''-x(qu)'+x(qu)=0 \\
      (x^2u''-xu'+xu)q+x^2(q'u'+q''u)=0 \\
       q'u'+q''u=0 \\
       \frac{u'}{u} +\frac{q''}{q'}=0 \\
       \ln(uq')=C \\
        uq' = D \\
         q = D\int \frac{1}{u} dx+E
$$
So a general second solution of equation $(\dagger)$ is
$$
       w = \left(D\int \frac{1}{u} dx+E\right)u
$$
From this it can be seen that both of the solutions $w$ and $u$ vanish at $0$. Using variation of parameters, you can then solve for $xu''-u'+u=\cos(x)$ of the form $u=Q(x)q(x)+W(x)w(x)$. So it appears that you'll have a solution, because it appears that $Qq+Qw$ will vanish at $0$, and you'll be able to add a general homogeneous solution to match conditions at $x=1$.


Change color of the text area extend arrow

Question: In the text area right bottom corner there is a small arrow to extend it in Chrome. Is there a way to change its color with CSS?
<textarea rows="3" id="textarea" placeholder="textarea"></textarea>

Comment: http://jsfiddle.net/rW5d2/1/ should work
Answer: Working Solution: JSFIDDLE
You can do it for webkit using ::-webkit-resizer selector
::-webkit-resizer {
    background: url(http://jsfiddle.net/favicon.png);
    background-size:100%;
}

Hope this helps!
Comment: looks like it works only in webkit-based browsers (Chrome, Opera, Maxthon), others won't work (the `-moz-` also does not work for FireFox), here is the similar demo using dynamic background instead of image http://jsfiddle.net/2AFGK/9/
Comment: @KingKing u can implement anything because it supports background property.
Comment: have you tried it **cross-browser**? I don't mean the background, **I mean the `::-webkit-resizer`**
Answer: In webkit browsers it can be styled with ::-webkit-resizer.


Windows Vista/7 Registry Issue

Question: I've been given the task of modifying a batch file for the installation of our software that sets certain registry values. The modification has to do with differences in the registry between Windows XP, and Windows Vista/7. Apparently in the newer OS's, there is a "shadow registry" of some sort that contains registry data that may be out of sync with the main one? I can't find any information on this.
Could this possibly be referring to the transactional nature of the registry in  Vista/7? Would a simple "commit" resolve this? If so, what is the syntax for that?
EDIT:
By "syntax", I am referring to the syntax of doing so within a batch file? i.e. I've added keys/values, what command will "commit" the transaction?
Comment: have you tried the new batch file and did it fail in someway?
Comment: Have you thought about using Powershell?
Comment: powershelll wouldn't change a thing in this case
Comment: Stackoverflow may be a better resource for this.  Unless other admins here are doing a lot of registry writing?
Answer: There is a virtual registry on Windows Vista / 7, it's basically for compatibility, as these OSes have changed the way that security is applied to the registry, and is per user.
"Prior to Windows Vista, many applications were typically run by administrators. As a result, applications could freely read and write system files and registry keys. If these applications were run by a standard user, they would fail due to insufficient access. Windows Vista improves application compatibility for these users by redirecting writes to a per-user location within the user's profile. For example, if an application attempts to write to HKEY_LOCAL_MACHINE\Software\Contoso\ it will automatically redirect to HKEY_USERS\< User SID >_Classes\VirtualStore\Machine\Software\Contoso."
And a major warning ...
"As virtualization is an interim application compatibility technology, Microsoft intends to remove this form of virtualization from future versions of the Windows operating system as more applications are migrated to Windows Vista. As a result it is imperative your application does not take a hard dependency on the presence of virtualization in the system."
http://msdn.microsoft.com/en-us/library/bb530198.aspx

Windows Vista/7 Registry Issue


mvc - binding JSON object

Question: I am following a simple video tutorial for Knockout.js by Steve Sanderson:
http://channel9.msdn.com/Events/MIX/MIX11/FRM08
At the very end of it he performs an AJAX call to show how can you use knockout to process data on the server. I repeat all of what he is doing, but for some reason my JSON object doest bind to a POCO class correctly. This is an object I send from the view:
{"firstName":"Bartosz","lastName":"Malinowski","friends":[{"name":"Zofia"},{"name":"Zenon"}],"fullName":"Bartosz Malinowski"}

and then use this code to read it in the controller:
public JsonResult Save(Person person)
    {
        var message = string.Format("Saved {0} {1}", person.firstName, person.lastName);

        return Json(new { message });
    }

    public class Person
    {
        public string firstName { get; set; }
        public string lastName { get; set; }
        public string fullName { get; set; }
        public ICollection<Friend> friends { get; set; }
    }

    public class Friend
    {
        public string Name { get; set; }
    }
}

My code on the client side looks like this:
'@{
    ViewBag.Title = "Home Page";
}

First name: <input data-bind="value: firstName"/>

Last name: <input data-bind="value: lastName"/>

Full name:

Friends ()

<button data-bind="click: addFriend, enable: friends().length < 5">Add Friend</button>
<button data-bind="click: save">Save</button>

When I run it in debug mode and check person in the Save method parameter I've got null value for each Person property. So it just doesn't bind to me??
Comment: Also, when you say 'doest bind to a POCO class correctly', does that mean that some of the fields bind?
Comment: Thanks for an answer, I have added my code from the client side to the original question.
Answer: I do exactly the same here is my code
 $.ajax({
                url: url,
                type: "POST",
                dataType: "json",
                data: ko.toJSON(viewModel),
                contentType: 'application/json; charset=utf-8',
                success: function (returnedData)
                {
                    window.location.replace(urlRedirect);
                }
            });

There is a few differences : dataType and the charset, I'd say that it's the dataType.
I also have the [HttpPost] on my action.
Comment: Yes, it was a typo in the contenttype  which should be contentType. I just couldn't spot it. Thanks

mvc - binding JSON object


Exchange Server 2013 to 2016 Migration error

Question: I'm currently facing an issue during an Exchange Server database migration process from Exchange 2013 to Exchange 2016 and could really use some assistance. The migration process is failing with the following error:
Error: MigrationTransientException: MapiExceptionMdbOffline: Unable to get mailbox information. (hr=0x80004005, ec=1142) Diagnostic context: Lid: 49384 Lid: 51176 StoreEc: 0x476 Lid: 40680 StoreEc: 0x476 Lid: 43980 Lid: 58295 StoreEc: 0x476 Lid: 50103 Lid: 48311 StoreEc: 0x476 Lid: 43959 Lid: 60343 StoreEc: 0x476 --> MapiExceptionMdbOffline: Unable to get mailbox information. (hr=0x80004005, ec=1142) Diagnostic context: Lid: 49384 Lid: 51176 StoreEc: 0x476 Lid: 40680 StoreEc: 0x476 Lid: 43980 Lid: 58295 StoreEc: 0x476 Lid: 50103 Lid: 48311 StoreEc: 0x476 Lid: 43959 Lid: 60343 StoreEc: 0x476
This error suggests that the migration process is unable to access mailbox information due to the database being offline. I've attempted several troubleshooting steps, including checking the database status, ensuring Exchange services are running, verifying network connectivity, and reviewing permissions, but the issue persists.
Also tried enabling MAPI over HTTP: Set-OrganizationConfig -MapiHttpEnabled $true
Has anyone encountered this error before, or does anyone have insights on additional steps I can take to resolve this? I'm particularly interested in understanding the significance of the error codes (ec=1142, StoreEc: 0x476) and if they point towards a specific direction for troubleshooting.
Any advice or suggestions would be greatly appreciated. Thank you in advance for your help!
Comment: I would focus on the transient part. And the inability to connect. Is this something that should work 100% and is accessible sub millisecond access on the same network?
Answer: it looks like databases might be in a dismounted state. If yes, please mount the database first and retry the migration.
There seems to be a similar case here:https://learn.microsoft.com/en-us/answers/questions/1523568/(hr-0x80004005-ec-1142)-when-trying-to-migrate-exc


How does the variance of a sample relate to the population from which it was drawn?

Question: let $X_1, X_2.....,X_n$ be iid random variables. Define the sample mean: $\bar{X}=(X_1+X_2...+X_n)/n$
Now, the sampling distribution of the sample mean has a variance given by:
\begin{align}
var(\bar{X})&=var[(X_1+X_2........+X_n)/n]\\
         &=1/n^2[var(X_1)+var(X_2)..........+var(X_n)]\\
         &=1/n^2[(\sigma)^2+(\sigma)^2+..........+(\sigma)^2]
 \end{align}
Why is $var(X_1)=var(X_2)=......=var(X_n)=\sigma^2$? What is the relation of $\sigma^2$ to the population from which the sample $X_1,X_2,X_3...X_n$ was drawn.
Comment: There is no concept of the "variance of the sample" as you alluded to before. Neither does a population vary. Each observation has a variance, since the sample of size $n$ could be repeatedly drawn and that observation's value differs with each sample. It is because we have a sample that we are able to estimate a variance.
Answer: You have started the post with the assumption that $X_1,...,X_n$ are i.i.d, namely, independent identically distributed. It is worth to add that you are assuming that $var(X)=\sigma^2 < \infty$, hence $var(X_i)=\sigma^2$ for all $i\in \mathbb{N}$.
Comment: "X1" does not refer to a "subset of the population": it is a *random variable.*
Comment: My question is how can we assume that a sample X1, which is a subset of the population have the same variance as that of the population? Is the assumption not flawed?


Accessing different JSON key/value pairs in a list comprehension

Question: Not sure if i am trying to achieve the impossible? I have this JSON string:
dot= [{"type": 1, "date": "2018-12-02T00:40:03.2186792+00:00", "device":
[{"id": "20165cf4e596", "deviceName": "17", "records": [{"timestamp": "2018-
12-02T00:40:00.499+00:00", "grp": "undefined", "val": 887}]}, {"id":
"5f401a6a6f66", "deviceName": "18", "records": [{"timestamp": "2018-12-
02T00:42:00.499+00:00", "grp": "undefined", "val": 1063}, {"timestamp":
"2018-12-02T00:41:00.498+00:00", "grp": "undefined", "val": 907}]}, {"id":
"569bb0147a72", "deviceName": "19", "records": [{"timestamp": "2018-12-
02T00:44:00.499+00:00", "grp": "undefined", "val": 817}, {"timestamp":
"2018-12-02T00:43:00.498+00:00", "grp": "undefined", "val": 1383}]}, {"id":
"ef829aa3", "deviceName": "2", "records": [{"timestamp": "2018-12-
02T00:46:00.499+00:00", "grp": "undefined", "val": 1173}]}, {"id":
"388ae8f2fa64", "deviceName": "17", "records": [{"timestamp": "2018-12-
02T00:41:00.499+00:00", "grp": "undefined", "val": 866}, {"timestamp":
"2018-12-02T00:32:00.492+00:00", "grp": "undefined", "val": 1080}]}, {"id":
"01f874b30b55", "deviceName": "19", "records": [{"timestamp": "2018-12-
02T00:43:00.499+00:00", "grp": "undefined", "val": 1050}, {"timestamp":
"2018-12-02T00:42:00.498+00:00", "grp": "undefined", "val": 1084}]}]}]

And i want to achieve the following:
[{'id': '20165cf4e596','deviceName': '17','timestamp': '2018-12-
02T00:40:00.499+00:00','grp': 'undefined','val': 887},
{'id': '5f401a6a6f66','deviceName': '18','timestamp': '2018-12-
02T00:42:00.499+00:00','grp': 'undefined','val': 1063},
{'id': '5f401a6a6f66','deviceName': '18','timestamp': '2018-12-
02T00:41:00.498+00:00','grp': 'undefined','val': 907},...]

I used the following code:
for i in dot:
    for k in i['device']:
        d2= [[{l:m},{'value':v}] for l,m in k.items() for p in m if
        isinstance(p,list) for v in p]
        print(d2)

And got empty lists:
[]
[]
[]
[]

Thanks in advance
Comment: also: your input data has linefeeds in the strings, so noone can copy/paste as-is to test. Please correct this.
Comment: check why `if
    isinstance(p,list)` is always false; possibly by unrolling your comprehension into classical loops
Comment: Thanks @Jean-FrançoisFabre not sure what you mean. It appears it has been resolved though. Thanks
Answer: You need to loop over the records element of each device. Then combine the fields from the device with each record.
result = []
for i in dot:
    for k in i['device']:
        for r in k['records']:
            result.append({"id": k["id"], "deviceName": k["deviceName"], "timestamp": r["timestamp"], "grp": r["grp"], "val": r["val"]})
print(result)

Comment: Thanks @Barmar it worked a treat. I was looking at something too complex. Thanks for simplifying. Cheers
Answer: Barmar's answer may be correct - but I believe you will have a far easier time if you deobfuscate your code by creating a hierarchy of objects which represent items in your data structure:
class SomeObject:
    def __init__(self, some_object_type, date, devices):
        self.type = some_object_type
        self.date = date
        self.devices = []

        for d in devices:
            some_device = SomeDevice(d["id"], d["deviceName"], d["records"])
            self.devices.append(some_device)

class SomeDevice:
    def __init__(self, some_device_id, name, records):
        self.id = some_device_id
        self.name = name
        self.records = []

        for r in records:
            some_record = SomeDeviceRecord(r["timestamp"], r["grp"], r["val"])
            self.records.append(some_record)

class SomeDeviceRecord:
    def __init__(self, timestamp, group, value):
        self.timestamp = timestamp
        self.group = group
        self.value = value

If you go this route, you can easily parse the entire JSON into strongly-typed objects:
some_object = SomeObject(dot[0]["type"], dot[0]["date"], dot[0]["device"])

And then it should be fairly easy/straightforward to report on specific portions of the data structure:
for device in some_object.devices:
    print(device.id, device.name, device.records[0].timestamp, device.records[0].group, device.records[0].value)

Comment: Thanks @alex, yes agreed, this gives complete control over all elements of the JSON. I added '{}' to group related values. Is there a way i can sort the values, so i can convert to a DataFrame? [{'17', '20165cf4e596', '2018-12-02T00:40:00.499+00:00', 887, 'undefined'},
 {1063, '18', '2018-12-02T00:42:00.499+00:00', '5f401a6a6f66', 'undefined'},
 {'19', '2018-12-02T00:44:00.499+00:00', '569bb0147a72', 817, 'undefined'}]
Comment: Yes.  I don't know offhand but you can probably use `sorted()` with lambdas on `some_object.devices`.
Comment: Thanks @alex, will definitely give this a go. Much appreciated!
Comment: I assumed the eventual goal was to turn it into something like a CSV, which was the point of flattening everything.
Comment: @Barmar Entirely reasonable :)


Separate line items when line item details are different

Question: As an ability the user might choose gift wrapping option for some of his/her products on add to cart form , what I did is creating a new product type called gift wrapping item, so site operators can add different kinds of wrapping options with different prices. I also altered the add to cart form so a new form item is added which gives the costumer the ability to choose a wrapping type, so far so good, user choice then is saved as a line item property (product ID of wrapping option is save in 'field_wrapping_option' which is added to product line item), and wrapping price is added to line item base price.
The problem is raised when user want to add 2 item from same product but he/she wants wrapping only for one of the two. In this case both products are stored in same line item and wrapping price also is added for them both.
I used hook_commerce_cart_product_comparison_properties_alter to force drupal create different line item when 'field_wrapping_option' are different on line items, but it didn't make things better, now every add to cart operation lead to new line item even when same wrapping option has chosen by user, and even worse situation happens when user first add a product without gift wrapping first and then adds a product with wrapping option which cause the first line item change into a product with gift wrapping.
Now the question is : How to Separate line items when line item details are different?
Answer: You could first have a look at Commerce Product Add-on module. That solution would split them per product type e.g. if you add one product with gift wrapping and one without you will have one line item for the product with quantity 2 and one for the gift wrapping with quantity 1. This gives the customer visibility of the exact pricing.
If however you still want to do it the way you described, the hook you mentioned should work.
function MY_MOULE_commerce_cart_product_comparison_properties_alter(
  &$comparison_properties,
  $line_item
) {
  $comparison_properties[] = 'field_wrapping_option';
}

Possible cause of trouble would be if the 'field_wrapping_option' of the line item being added is not set at all. The existing line item would always have the field set, even with an empty value, while you will have to set it for the incoming line item. It is possible that you set the field value only when gift wrapping is selected, try setting the field value to NULL if no gift wrapping is selected.
$line_item_wrapper->field_wrapping_option->set(NULL);

To further debug why line items are not properly combined, look at the 'commerce_cart_product_add' function at the commerce_cart.module file. The following code is the most relevant.
// Loop over each line item on the order.
foreach ($order_wrapper->commerce_line_items as $delta => $matching_line_item_wrapper) {
  // Examine each of the comparison properties on the line item.
  foreach ($comparison_properties as $property) {
    // If the property is not present on either line item, bypass it.
    if (!isset($matching_line_item_wrapper->value()->{$property}) && !isset($line_item_wrapper->value()->{$property})) {
      continue;
    }

    // If any property does not match the same property on the incoming line
    // item or exists on one line item but not the other...
    if ((!isset($matching_line_item_wrapper->value()->{$property}) && isset($line_item_wrapper->value()->{$property})) ||
      (isset($matching_line_item_wrapper->value()->{$property}) && !isset($line_item_wrapper->value()->{$property})) ||
      $matching_line_item_wrapper->{$property}->raw() != $line_item_wrapper->{$property}->raw()) {
      // Continue the loop with the next line item.
      continue 2;
    }
  }

  // If every comparison line item matched, combine into this line item.
  $matching_line_item = $matching_line_item_wrapper->value();
  break;
}


manipulating pandas dataframe - conditional

Question: I have a pandas dataframe that looks like this:
ID    Date         Event_Type
1     01/01/2019   A
1     01/01/2019   B
2     02/01/2019   A
3     02/01/2019   A

I want to be left with:
ID    Date
1     01/01/2019
2     02/01/2019
3     02/01/2019

Where my condition is:
If the ID is the same AND the dates are within 2 days of each other then drop one of the rows.
If however the dates are more than 2 days apart then keep both rows.
How do I do this?
Comment: What have you tried so far ?
Comment: I couldn't think of the logic of how to do this. @jezreal solved it for me!
Answer: I believe you need first convert values to datetimes by to_datetime, then get diff and get first values per groups by isnull() chained with comparing if next values are higher like timedelta treshold:
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')

s =  df.groupby('ID')['Date'].diff()
df = df[(s.isnull() | (s > pd.Timedelta(2, 'd')))]
print (df)
   ID       Date Event_Type
0   1 2019-01-01          A
2   2 2019-02-01          A
3   3 2019-02-01          A

Check solution with another data:
print (df)
   ID        Date Event_Type
0   1  01/01/2019          A
1   1  04/01/2019          B <-difference 3 days
2   2  02/01/2019          A
3   3  02/01/2019          A

df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')

s =  df.groupby('ID')['Date'].diff()
df = df[(s.isnull() | (s > pd.Timedelta(2, 'd')))]
print (df)
   ID       Date Event_Type
0   1 2019-01-01          A
1   1 2019-01-04          B
2   2 2019-01-02          A
3   3 2019-01-02          A


Select items by including & excluding their tags

Question: Consider the following schema:
id | question
-----------
1  | How old are you?
2  | Are you a male or female?

question_tag:

id | question_id | tag_id
--------------------------
1  | 1       | 1
2  | 1       | 2
3  | 1       | 3
4  | 2       | 1
5  | 2       | 2

tags:

id | tag
--------------
1  | some_tag
2  | some_other_tag
3  | different_tag

question and tag have many to many relationship.
I would like to select all the questions which have certain tags and haven't some other tags.
e.g. question that has both tag ids [1,2] but hasn't tag id [3]
What i have currently is:
select `questions`.`id`,
       `questions`.`question`,
from `questions`
       inner join `question_tag` on `questions`.`id` = `question_tag`.`question_id`
  where `tag_id` in (1,2)
group by `questions`.`id`, `questions`.`question`
having count(tag_id) = 2;

The 'include' part works - I get only the questions which has both the tags.
Now I need to add the 'exclude' part - e.g. filter our questions which also have tag_id = 3.
I tried adding AND tag_id NOT IN (3) without success - those questions were not filtered out from the results.
Any idea what am I missing?
Answer: You can try using correlated subquery with not exists
select `questions`.`id`,
       `questions`.`question`,
from `questions`
       inner join `question_tag` on `questions`.`id` = `question_tag`.`question_id`
  where  `tag_id` in (1,2) and not exists (select 1 from question_tag x where `question_tag`.`question_id`=x.`question_id` and x.tag_id=3)
group by `questions`.`id`, `questions`.`question`


CentOS 7 Kickstart - Software RAID 10 and LVM

Question: So I am not sure why I am having this issue, so I hope someone can see something I am missing.
I created a kickstart file for a test Cent OS 7 automated install. Nothing seems to generate a warning except for the storage portion when it comes to partitioning. This is that section:
clearpart --all --initlabel --drives=/dev/sda,/dev/sdb,/dev/sdc,/dev/sdd,/dev/sde,/dev/sdf,/dev/sdg,/dev/sdh

part raid.1 --size=1024 --ondisk=/dev/sda
part raid.2 --size=1024 --ondisk=/dev/sdb
part raid.3 --size=1024 --ondisk=/dev/sdc
part raid.4 --size=1024 --ondisk=/dev/sdd
part raid.5 --size=1024 --ondisk=/dev/sde
part raid.6 --size=1024 --ondisk=/dev/sdf
part raid.7 --size=1024 --ondisk=/dev/sdg
part raid.8 --size=1024 --ondisk=/dev/sdh

part raid.9 --size=256 --ondisk=/dev/sda
part raid.10 --size=256 --ondisk=/dev/sdb
part raid.11 --size=256 --ondisk=/dev/sdc
part raid.12 --size=256 --ondisk=/dev/sdd
part raid.13 --size=256 --ondisk=/dev/sde
part raid.14 --size=256 --ondisk=/dev/sdf
part raid.15 --size=256 --ondisk=/dev/sdg
part raid.16 --size=256 --ondisk=/dev/sdh

part raid.17 --size=20480 --ondisk=/dev/sda
part raid.18 --size=20480 --ondisk=/dev/sdb
part raid.19 --size=20480 --ondisk=/dev/sdc
part raid.20 --size=20480 --ondisk=/dev/sdd
part raid.21 --size=20480 --ondisk=/dev/sde
part raid.22 --size=20480 --ondisk=/dev/sdf
part raid.23 --size=20480 --ondisk=/dev/sdg
part raid.24 --size=20480 --ondisk=/dev/sdh

raid /boot --fstype="xfs" --device=boot --level=10 raid.1 raid.2 raid.3 raid.4 raid.5 raid.6 raid.7 raid.8
raid /boot/efi --fstype="efi" --device=boot_efi --level=10 raid.9 raid.10 raid.11 raid.12 raid.13 raid.14 raid.15 raid.16
raid pv.1 --fstype="lvmpv" --device=root --level=10 raid.17 raid.18 raid.19 raid.20 raid.21 raid.22 raid.23 raid.24

volgroup vg1 pv.1

logvol / --fstype="xfs" --size=1 --grow --name=root --vgname=vg1

bootloader --append=" crashkernel=auto" --location=mbr

I am trying to create three partitions:

/boot - 1024 MiB size, formatted to xfs, RAID 10
/boot/efi - 256 MiB size, formatted to efi, RAID 10
/ - 20 GiB size, formatted to xfs, RAID 10 + LVM

I am using the graphical install so I can look at everything quickly, it looks like its marking /boot/efi as efi, yet regardless I still get the below error preventing me from completing the installation.

No valid boot loader target device found. See below for details.
  For a UEFI installation you must include a EFI System Partition on a GPT-formatted disk, mounted at /boot/efi.

The other weirdness I am seeing is that its not using my values for the premade partition sizes. Based on the kickstart file I wrote above these are the sizes I am seeing:

/boot - should be 1024 MiB, CentOS 7 makes it 4092 MiB
/boot/efi - should be 256 MiB, CentOS 7 makes it 1020 MiB
/ - should be 20 GiB, Cent OS 7 makes it 79.93 GiB

I would appreciate any assistance on this.
Answer: Your sizes seem exactly what they are supposed to be given the part commands .  Your first partition on each device is 1024 you have 8 devices in a RAID10, so that is 1024 * 8 / 2 or 4096.  For RAID10 the size of the volume is the number of active devices X maximum size of smallest member / 2.
I highly doubt a software RAID10 is valid for a EFI partition, and it unless something has changed it isn't going to be valid for your /boot partition either. I suspect your only choice for that is a simple RAID1 volumes.  It is valid to have a RAID1 volume that spans 8 devices.  So you could try changing your boot / efi over to RAID1.  With RAID1 the of the volume will just be the size of the smallest active member.
Comment: RAID 10 is fine for /boot, but it's correct that you can't use such a thing for the ESP volume. Use a RAID 1 for that. Nothing else in this situation requires that. You might also consider not separating / and /boot, since it's all going to the same place (with the same FS type) anyways.

This is caused by the way your motherboard reads the ESP volumes. It finds the first intact one and reads form that. However, it expects to find an intact ESP on a single disk. RAID 1 makes exact copies to all disks, so that's the mechanism to use here.
Comment: Good catch on the RAID 10 sizes. I didn't realize that it was multiple.
Comment: Also, @Zoredache I just restarted the install with your suggestion to use RAID1 and not RAID10, and it seems to work. Thanks for catching that, I don't fully understand why RAID1 works, but RAID10 does not? Is that because of how Linux does RAID10?
Comment: Thanks @SmallLoanOf1M. I realized after I wrote my question that if I was trying to find the first bootable partition in a software raid setup, I should take into account that I wouldn't know which disk it would be on initially in a RAID 10 setup. Your answer confirmed this. I appreciate it!


Why can only admin user access the print version of a view?

Question: I have installed the Printer, email and PDF versions module and I have a view named XXX and the admin can access to the print version of the XXX view with the path /printpdf/XXX.
If I change the user to other user without admin permission, I get this message

Access denied
You are not authorized to access this page.

I don't know how to allow non admin users to access the print version of a view.
I set this permissions for non admin users like so:

Bypass views access control.
Access the printer-friendly page.

But such user still does not have access to the print version of a view.
Is there a way to achieve the access with non admin users?
Answer: I have a help at this moment from a friend. The solution is simple, just search the permission Access the PDF version in admin/people/permissions and set the permission to the users. The problem was that the permission page is too long and if you search for print you will never find Access the PDF version` permission
Answer: PDF version (print_pdf)
Head over to your "permissions" page, located at admin/people/permissions. Then in the field near the top, which says "Filter list", just type "pdf".
That'll give you a narrowed down list of all permissions that have "pdf" in their description. One of them is "Access the PDF version", which is the permission you want to fine tune to fit your requirements. And each of them is preceded by a line, in bold, which shows the name of the module the permission is related to.
The "narrowed down" list in my case shows only 2 permissions (the 2nd one is because I have 1 other module enabled that also has a PDF-related permission). So hard to not catch the one I should be looking for, right?
Printer friendly pages (print) and send by eMail (print_mail)
print_pdf is one of the sub-modules of the Printer, email and PDF versions module. Other submodules of it are print (= Printer friendly pages) and print_mail (send by eMail). Some more details about those sub-modules:

The print submodule has a similar permission, which is "Access the printer-friendly page" (= View the printer-friendly pages and the links to them in the original pages).
The print_mail submodule has a similar permission, which is "Send by email" (= Provides the ability to send pages by email and the links to them in the original pages). Attention: if you want to use this eMail feature, make sure you do not (repeat NOT) allow that for anonymous users. Because if you do allow that, you open up a huge spamming opportunity for your anonymous users ... imagine a spammer using it enters an eMail Id of somebody that the spammer wants to spam ... typically with a message content that is 100% spam, instead of what you'd expect (something like "hey, have a look at this interesting URL" ... But: the message will arrive with something like "from = an eMail id related to your website".

PS: Permission "Bypass views access control" should be used carefully (do not grant it to anybody unless you really have a need for it ... in this case it does not seem to be needed to solve your access issue).


How to prove a formula tend to zero as limit of $x$ goes to infinity?

Question: Given the condition:
$$0\leq \frac{\psi(x)}{x}-\frac{\vartheta(x)}{x}\leq\frac{(\log x)^2}{2\sqrt{x}\log(2)} ,$$
how to prove the formula in the middle tend to zero as limit of x goes to infinite
Comment: Note that the right hand side $\frac{(\log x)^2}{x \sqrt{x} \log 2}$ approaches $0$ as $x \to 0$. (Of course, the left hand side $\to 0$ clearly.) Now apply the sandwich (also called the squeeze)  theorem.
Comment: @Will: I take a different view than you. Someone is interested in math, and so why wouldn't we encourage him? I would not be nearly so harsh with someone. Instead, I think that if I explain ideas at his level, and point out where additional material can be found so that he can learn, then no one is harmed. Is this not the best place to ask these questions? I also think that people can learn the most when they are a bit out of their comfort zone - I certainly did. But that's just my view.
Comment: @Srivatsan - i am a beginner that without knowing much of limit, please explain about your hint in your answer, thanks in advance
Comment: @Srivatsan - Actually it is x goes to infinity instead of x goes to 0 in my book
Comment: I am sorry, what I wrote was a typo.  I meant to write $x \to \infty$.
Comment: @Srivatsan - But how to get to the answer, is this immediate result or not?
Answer: There is a general, highly intuitive idea at play here. This is called the squeeze theorem (wiki link). The idea is that if we know that our function is always bounded by something above, and by another thing below, then when the two bounds take the same value, so does our function. This should feel right. Draw a picture to illustrate.

No matter how strange the behavior of the blue line, as long as we know its bounded by green and red, we can say some things about its behavior. This picture describes the case when the bounds meet at the same point at $x = 0$. Even though the problem we are considering is for $x \to \infty$, the idea is the same.
It turns out that it is well known that $\dfrac{\log ^2 x}{\sqrt x \log 2} \to 0$ as $x \to \infty$. In fact, $\dfrac{\log^p x}{x^{0 + \epsilon}}$ for any $p$ and any $\epsilon > 0$ also tends to $0$. In words, this means that logs grow really, really, really slowly compared to any polynomial, or even roots. This follows from L'Hopital's rule or Taylor expansions, or many other methods. But the important part is that it goes to $0$.
Then we have two bounds: $0$ and something that goes to $0$. Thus our function must also tend to $0$.
Comment: +1 for an explanation tailored for the OP's level. It might be useful for the OP to point out that the picture depicts a case when the variable $x$ approaches a real number, not $\infty$.
Comment: That's a good idea. I'll do that.


Given real $x\geq1$, show that: $\lim_{n\to\infty} (2\sqrt[n] x -1)^n=x^2.$

Question: I proved it using this method. Is this proof correct? $
\lim_{n\to\infty} (2\sqrt[n] x -1)^n =
\lim_{n\to 0+} e^{\frac{\log(2x^n -1)}{n}}
=\lim_{n\to 0+} e^{\frac{2x^n\log x}{2x^n-1}}
= e^{2\log x} = x^2.$
Comment: The result is correct but I don't understand the step I've indicated.
Comment: @gimusi, thanks for your reply. In that step, I used Hospital's rule.
Comment: Ok that's fine but maybr you should explain that step! It's fine. Bye
Answer: The result is correct but you should clarify that step
$$\cdots \lim_{n\to 0+} e^{\frac{\log(2x^n -1)}{n}}
=\lim_{n\to 0+} e^{\frac{2x^n\log x}{2x^n-1}}=\cdots$$
As an alternative
$$(2\sqrt[n] x -1)^n =(1+(2\sqrt[n] x -2))^n=\left[(1+(2\sqrt[n] x -2))^{\frac1{2\sqrt[n] x -2}}\right]^{n(2\sqrt[n] x -2)}\to e^{\log x^2}=x^2$$
indeed
$$y=2\sqrt[n] x -2 \to 0 \implies (1+y)^\frac1y \to e$$
and
$$n(2\sqrt[n] x -2)=2\frac{ x^\frac1n -1}{\frac1n} \to2\log x$$
Answer: $$L=\lim_{n \rightarrow \infty} (2~ x^{1/n}- 1)^n= x \lim_{n \rightarrow \infty} \left( 2-\frac{1}{(1+y)^{1/n}}\right)^n, y>0, x=1+y. $$ Then
$$L=x \lim_{n \rightarrow \infty} \left( 2- (1-y/n)\right)^n=\lim_{n \rightarrow \infty} x (2-(1-ny/n)= x (1+y)= x^2.$$
Here we use binomial approximation twice: $\frac{1}{(1+y)^{1/n}}\approx 1-y/n$ and $(1-y/n)^{n} \approx 1-ny/n.$
Answer: $(2\sqrt[n] x -1)^n =(2 x^{\frac{1}{n}} -1)^n= (2 e^{\log(x) \frac{1}{n}} -1)^n \\=(2 \left(1 + \log(x) \frac{1}{n}+(\log(x) \frac{1}{n})^2+  ...\right) -1)^n\\= (1 +  \frac{1}{n}\left(  2\log(x) \right))^n\to e^{2\log(x) }= x^2 $
Here we have used the definition $\lim_{n\to\infty} \left( 1+ \frac{z}{n}\right)^n = e^z$
Comment: The last step should be $\cdots = (1 +  \frac{1}{n}\left(  2\log(x) \right)+O(1/n^2))^n\to\cdots $?
Comment: Yes, that is implicit.
Comment: As a suggestion, I think it should be better to indicate the last as $\sim$ to be more rigorous. Bye!


What is the smallest possible cardinality of a non-finitely based magma?

Question: I was told that every magma $(S,*)$ whose base set $S$ has 2 elements has a finite basis of identities. The natural question is, what is the smallest possible cardinality of a non-finitely based magma? I would be very interested to see a 3-element set and a binary operation on it which is not finitely based.
Answer: V.L. Murskii in 1965 found an example of a 3 element magma that is not finitely based.
Here is its multiplication table:
$$\begin{array}{c|ccc}
& 0 & 1 & 2 \\
\hline
0 & 0 & 0 & 0 \\
1 & 0 & 0 & 1\\
2 & 0 & 2 & 2\\
\end{array}$$
Comment: I've added a link to the article in question.


Influence the order of digits and characters in compare method

Question: I have a Wicket web application, that sorts table rows in the following order:
Ascending:

first characters (A-Z)
then numbers (1-9)

Now i'm writing a webunit test to test the sorting mechanism, but it seems to switch the order of characters and numbers like:
Ascending:

first numbers (1-9)
then characters (A-Z)

So this code will fail, when sorting ascending and it encounters the two entries:

...
ZZZ
111
...

My simplified sorting code:
protected int compare(String val1, String val2) {
        return val1.compareTo(val2);
}

What's the "java way" of telling my test code to test the order like my web application produces it?
May be something like Collator? I would prefer a JRE solution over a selfwritten Comparator over a 3rd party library.
Comment: I don't know of a built-in JRE solution.  Writing your own `Comparator` or wrapping strings is a custom `Comparable` class is probably your best bet.
Answer: You could try using a RuleBasedCollator like this:
String rule = "<a,A<b,B<c,C<[...]<'1'<'2'<'3'<'4'[...]";
RuleBasedCollator collator = new RuleBasedCollator(rule);
return collator.compare(val1,val2);

Comment: Thanks, this is working. Could you edit the rule and remove the second comma after 'A'?