Factoring extremely large integers.

Question: The question is about factoring extremely large integers but you can have a look at this question to see the context if it helps. Please note that I am not very familiar with mathematical notation so would appreciate a verbose description of equations.
The Problem:
The integer in question will ALWAYS be a power of N and will be known to us to calculate against. So let's assume N = 2 for example. That will give us a sequence of numbers like:
2, 4, 8, 16... up to hundreds of thousands of digits.

I need to find all possible factors (odd, even, prime, etc.) as efficiently as possible.
The Question:
What is the solution and how could I understand this from mathematical and computational perspectives?
EDIT:
Does the fact that each number to be factored is a power of 2 help in eliminating any complexity or computational time?
Answer: If the number in question is known to be a power of 2, you are just trying to find $n$ such that $N=2^n$.  If the input number is in decimal notation, just count the digits, subtract 1,  multiply by 3.3219, and round up. Then add 1 if the initial digit is 2 or 3, 2 if the initial digit is 4, 5, 6, or 7, and 3 if the initial digit is 8 or 9.
For example, suppose $N=1267650600228229401496703205376$. This has 31 digits; $30\cdot3.3219 = 99.657$, so $N=2^{100}$. Or take $N=$
43699499387321412970609716695670835099367888141129535719972915195176
79444176163354392285807163181819981286546206512408458617685052043667
09906692902245553277900892247131030458103436298545516643924637451297
481464347472084863384057367177715867713536

which has 246 digits. $245\cdot3.3219 = 813.872383$; we round up to 814, add 2 because the first digit is 4, so this number is $2^{816}$.
The magic constant 3.3219 is actually $\log 10 / \log 2$.  For input numbers in the hundreds of thousands of digits you will need a more accurate version, say 3.3219281.
Answer: If $N = 2$ (or any prime) and you can get $k$ as Ross indicated, then the divisors of $A$ are $\{1, N, N^2, \ldots, N^i, \ldots, N^{k} \}.$ If $N$ is a composite, then you will incur extra time complexity in computing the prime factorization of $N = \prod_{i = 1}^{\ell} p_i^{e_i}$ and the divisors of $A$ are all possible numbers of the form $\prod_{i=1}^{\ell} p_i^{r_i}$ where $\mathbf{0} \le r_i \le ke_i.$ Notice $r_i$ can be zero for some terms. There are $\prod_{i=1}^{\ell}(ke_i + 1)$ such possible divisors.
Comment: $101$ ${}{}{}{}{}{}{}{}{}$
Comment: @RaheelKhan Simpler example: $2^5.$ There are 6 divisors: $2^0 = 1,$ $2^1 = 2,$ $2^2 = 4,$ $2^3 = 8,$ $2^4 = 16,$ and $2^5 = 32.$ The numbers $1$ and $2^k$ itself are counted in.
Comment: Given 2^100 = 1,267,650,600,228,229,401,496,703,205,376, would that mean there are 100 possible factors?
Comment: Thanks. I'm presuming 101 includes the number 1.
Comment: Yes, $101$ includes both $1$ and $2^{100}.$
Answer: Are you given $N$?  Then if the number to be factored is $A$, you have $A=N^k$ and only have to find $k$.  Taking logs, $k=\frac {\log A}{\log N}$.  So, yes, if you know $N$ it helps a lot.
If $N$ is prime, all the possible factors of $A$ are of the form $N^m$ for $0 \le m \le k$ so you have them.  If $N$ is composite, factor it as $N=p_1^{q_1}p_2^{q_2}\ldots p_n^{q_n}$.  Then  all the factors are of the form $p_1^{m_1}p_2^{m_2}\ldots p_n^{m_n}$ where $0 \le m_1 \le kq_1$ etc.
Comment: Yes we will know N and can assume it to be 2 in this case.

Factoring extremely large integers.


jQuery cookie not writing

Question: I cant get a cookie to write through jQuery.
This is the function:
<code><script type="text/javascript">
$(document).ready(function() {
    $('.jp-volume-bar,.jp-volume-bar-value').click(function(){
        var volval=$('.jp-volume-bar-value').width();
        var voltot=$('.jp-volume-bar').width();
        var vol=volval/voltot;
        $.cookie('jp_volume', vol, { expires: 7, path: '/'});
    });
});
</script>
</code>
I have confirmed that the three variables are outputting a value.
But checking in chromes cookie logs, and using the PHP page to output the cookie value, both result with nothing appearing, so jQuery isnt actually writing the cookie.
Is there an issue with my code?
Comment: Are you using a jQuery cookie plugin?
Answer: This action requires a jQuery cookie plugin. http://archive.plugins.jquery.com/project/Cookie

jQuery cookie not writing


Indicator variables and backward elimination with GLM

Question: I am running logistic regression using glm in R on data, that has some indicator variables to it. Two of those have multiple levels and have been rewritten as (#levels-1) new dummy predictors respectively.
As for variable selection, I use step (backward variable selection based on AIC), which is where I struggle:
Even though all dummies of the initial indicator were kept or removed, I wonder what one would do, if a single dummy (i.e. one of a set of associated dummies) was eliminated during the variable selection? After all, this would mean that I lose the information encoded for the base-level (since it is "indicated" by 0s in all the other dummies).
Could someone tell me what to do if such a case occurred?
Thanks & Regards
Answer: You shouldn't be rewriting your categorical data into dummies yourself. Just feed your categorical data into glm as-is; R will internally turn it into dummies. Then stepAIC() and similar methods can work correctly and either keep or remove the entire predictor, not only single levels.
Alternatively, you can look at whether collapsing different levels of your categorical variable improves matters, either using AIC or with Likelihood Ratio or Wald tests. As an example, let's create some toy data:
set.seed(1)
foo <- data.frame(dv=sample(x=c(0,1),size=100,replace=TRUE),
  iv=sample(LETTERS[1:5],size=100,replace=TRUE))
model <- glm(dv~iv,family="binomial",data=foo)
AIC(model)
[1] 140.7574

Next, we collapse a couple of levels of foo$iv into single levels of a new predictor and fit a model with the new predictor:
foo$new.iv <- NA
foo$new.iv[foo$iv %in% c("A","B")] <- "a"
foo$new.iv[foo$iv %in% c("C","D")] <- "b"
foo$new.iv[foo$iv == "E"] <- "c"
AIC(update(model,.~new.iv))
[1] 137.8161

AIC is lower with collapsed factor levels. This is not surprising, given that there is no relationship between foo$iv and the dependent variable, so reducing the degrees of freedom should always reduce AIC.
Of course, you should not simply test all possible combinations of factor levels for collapsing; that would be data dredging and even using AIC would invalidate subsequent inferences if you do not account for this process. Instead, let theory on how the data were generated guide you. And report what you did so consumers of your analysis can get a feeling how much iterative model fitting was involved.
Comment: It all depends on your data, of course. One example which I encountered in real life: retailers run promotions (like multi-page flyers in people's mailboxes) to increase sales, and a promotion predictor may have levels like "ad on the first page of a flyer", "ad on the second page", "ad on the last page" and so on. However, it is unclear whether the flyer page actually makes a difference, so collapsing all levels into one level or into two levels "ad on first page" and "ad somewhere else" may be better in terms of parsimony and predictive power.
Comment: Thanks for your reply, can't vote up or accept yet, but will do as soon as I can.
Could you please elaborate on the collapsing part? Say I had 4 levels, would I simply combine a subset of levels to an artificial new one whilst keeping the others (subsequently enumerating through all proper subsets and subset-combinations of the indicator)?
Comment: I edited my answer; clearer now?
Comment: thanks a lot for the additional comments & the illustrative example! it's much clearer to me now.
Comment: come to think of it, i would have one last question if you don't mind:i think i get your point about data dredging, since the enumerative approach (testing all subsets & combinations) is an exhaustive in-sample optimization of which the result is imposed on new instances (for prediction). am i correct so far? in your example, quite clear that the reduction of dfs will reduce the AIC - accompanied by the knowledge about, as you said, how the data was generated. however, since i seldom know about that in practice, could you give an example when you would collapse factors? thanks again!
Comment: Stephan, can you kindly visit the dilemma [if we ought to create tag "dummy-variables"](https://stats.meta.stackexchange.com/a/4881/3277) and leave there a comment either con or pro?
Comment: @ttnphns: thanks for the pointer. I looked at the discussion and honestly can't make a decision - both sides have very good arguments. So I'll refrain from voting.


Test to compare event count and cumulative incidence across two time periods

Question: I would like to compare cumulative incidence/ event count across two different time periods. As an example, I am looking at patients presenting with stroke in a one month period in 2015 and again in 2017 (to eliminate the remote possibility of seasonal variation).
There is a small possibility that these patient groups may overlap, but assuming that they are completely independent (the events are independent, at the very least, even if the the patients may not be), is there a statistical test that can compare events occurring in these time periods directly?
I wondered about the chi square test (assuming that the events are entirely independent) if that was valid when different time periods are taken into account.
I am a relative novice at this and would be very grateful for any advice. I have tagged the question as SPSS solely because that is the only statistical package I am familiar with at present.
Answer: A Poisson regression model is commonly used for count data. SPSS will fit such models in the GENLIN procedure for either independent counts (Analyze>Generalized Linear Models>Generalized Linear Models) or repeated counts (Analyze>Generalized Linear Models>Generalized Estimating Equations), and the GENLINMIXED procedure will also handle both kinds (Analyze>Mixed Models>Generalized Linear).
For starters I would suggest the basic approach using GENLIN with Analyze>Generalized Linear Models>Generalized Linear Models, applied to data with a binary variable indicating the time period to use as a predictor variable and a variable with the count as the dependent variable. Poisson loglinear is one of the options for Type of Model on the initial tab.


How to solve the congruence equation $x^e\equiv c \pmod p$ for $x$

Question: Given the equation:
$$x^e\equiv c \pmod p$$
where $p$ is prime number, $c$ is positive integer and $e$ is positive integer and $\gcd(e, p-1) = 1$. Explain how would you solve given equation.

Also, using that explanation solve next equation:
$$x^{77} \equiv 2 \pmod{246}$$
I know that I need to use Chinese reminders theorem but I am not sure how... Please can you provide some explanation how to solve this.
Comment: 246 is not prime. You can use the chinese remainder theorem to split it into prime factors before you can apply the answer given by Watson, but I think his answer may work if there exists a solution anyways.
Answer: By Bézout's theorem, there are integers $a,b$ such that $ae+b(p-1)=1$.
Therefore, $$x = x^{ae+b(p-1)}\;\; \equiv c^a \cdot (x^{p-1})^b \equiv c^a \pmod p.$$

For your specific question, you have
$$\begin{cases}
x^{77} \equiv x \equiv 2 \equiv 0 \pmod 2\\
x^{77} \equiv x \equiv 2 \pmod 3\\
x^{77} \equiv 2 \pmod{41}\\
 \end{cases}$$
The last equation becomes, because of the Bézout's identity $-25 \cdot 40 + 13 \cdot 77 = 1$,
$$x \equiv 2^{13} \equiv 33 \pmod{41}$$
Then using the CRT you get $x \equiv 74 \pmod{246}$.
Comment: In fact the computations which you omitted (inverse computation, and CRT lifting) can be done *completely* with simple *mental* arithmetic if you know the shortcuts - see my answer.
Comment: If I understood, there are three equations mod 2, 3 and 41. You have transformed only the last one, and used CRT for which equations?
Comment: @clzola: Yes. I only needed to transform the last one because for the first one I used $y^{77} \equiv 0 \pmod 2 \implies y \equiv 0$, and for the second one $y^2 \equiv 1 \pmod 3$ if $y≠0$. $\tag*{}$ I have the system $$\begin{cases}
x \equiv 0 \pmod 2\\
x \equiv 2 \pmod 3\\
x \equiv 33 \pmod{41}\\
 \end{cases}$$ so I used the CRT to solve it.
Comment: @clzola: When you have $am+bn=1$, with $m,n$ coprime, then the system $$\begin{cases}
x \equiv r \pmod n\\
x \equiv s \pmod m\\
 \end{cases},$$ has the solution $x \equiv r(1-bn) + s(1-am) \pmod{nm}$.
Comment: @Watson, thank you! Does this equation has some name, so I can look on google for more examples. I have only this one, but would be great if I could find more...
Comment: @clzola: something like "system of linear congruences" or just "chinese remainder theorem", see http://math.stackexchange.com/questions/201328
Comment: @Watson what about $x^7 \equiv 3 \pmod {162}$ I get $$x^7 \equiv 3 \pmod 2$$ $$x^7 \equiv 3 \pmod {3^4}$$ and the problem for me is to transform second equations ... :/
Comment: @clzola: here the exponent $e=7$ is coprime with $p-1=2-1=1$ and with $\phi(3^4)=54$, so you just have to follow my reasoning using a Bezout relation between $e$ and $1$, and between $e$ and $54$.
Comment: @clzola: Otherwise you should ask a new question for this. But first, try to think by yourself! Have a good luck!
Answer: Yes, CRT works. $\ $ Easily $\,x\equiv 2\pmod{6}\,$ and $\ x\!\pmod{41}\,$ can be computed mentally:
${\rm mod}\ 40\!:\,\ \color{#c00}{\dfrac{1}{77}}\equiv \dfrac{-39}{-3}\equiv \color{#c00}{13},\ $ so $\,\ {\rm mod}\ \color{#0a0}{41\!:\ \, x}\equiv 2^{\color{#c00}{\large 1/77}}\!\equiv 2^{\color{#c00}{\large 13}}\!\equiv 2^{\large 3}(2^{\large 5})^{\large 2}\equiv 8(-9)^{\large 2}\equiv \color{#0a0}{-8}$
${\rm mod}\ 6\!:\ 2\equiv x\equiv \color{#0a0}{-8+41k}\equiv -8\!-\!k\!\iff\! k\equiv 2,\, $ so $\,x\equiv -8+41\cdot 2\equiv 74\pmod{\!6\cdot 41}$


Question about domain name server

Question: I have set up a DNS server in my home, will I have to wait for the isp to refresh there cache before DNS is active?
Some website I have found says this is called "DNS propagation time" and how long could this take?
Answer: This is dependent on whether your DNS server is actually taking over any actual DNS configuration for your Internet Domain - e.g. NS entry/function. If your DNS server is just a free-standing internal server and no actual Internet DNS entries/updates are required, then no impact.
If is it taking the place of or being placed in as an additional NS for an active Internet DNS domain configuration, then it will require some time for the entry from where the actual Internet DNS server was made to propagate/update to the rest of the Internet DNS servers. This used to take around 72 hours in the past, but may now be as quick as completing within 24 hours.
Comment: Thank you for your help, I can only connect via domain only on the domain server and out side our network only by the i.p at the moment so I *think* it should work
Comment: It sounds like you have setup an internal DNS server at this point, so no DNS propagation is involved across the Internet.
Answer: It depends.

If you aren't even running a content DNS server at all, then there's nothing to cache or to replicate by other people.  For a proxy DNS server you cache what the rest of the world publishes, not the other way around.
If no-one has ever asked about names in the domains that you now publish DNS data for, no-one will have cached anything at all.
If people have previously obtained answered from somewhere else, then how long they were told those answers were valid — the TTL values on the resource record sets — will determine how long they are cached for.user48838 is leading you a bit up the garden path on this one.  There is no universal set length for TTL values — 72 hours, 24 hours, or otherwise.  They're whatever people choose them to be.  In your case, they're currently whatever the people who heretofore were publishing the data chose them to be.
If no-one knows that your content DNS server exists, because you haven't asked/told any superdomain owners to delegate domans to you, then what you publish will be simply ignored by the world, because no-one will ever be directed to ask you for it.  Arranging delegations involves talking to human beings.

There's a lot of nonsense that people believe when they talk of "DNS propagation", that is based upon a wholly incorrect mental model of how the DNS operates.

Your ISP doesn't necessarily have anything to do with things.  Your ISP is who shoves IP datagrams between you and the rest of Internet.  Your ISP's (resolving proxy) DNS servers have nothing to do with what you, on your machines, choose to publish with DNS content servers.
Things are cached for as long as the TTLs say.  The resolving proxy DNS servers that the rest of Internet uses (and indeed that you use) will cache data for anywhere up to the entire time-to-live period at the point that they last received those data from a content DNS server.
Caching by resolving proxies is quite different to database replication.  A set of coöperating content DNS servers replicates a database, with all of the to-be-published data, amongst themselves.  This database replication can use one of quite a few mechanisms, from "zone transfer" to simple scp.  None of them have anything at all to do with the TTLs on the resource records in the database.  Only a few of them even have anything to do with the various replication fields in SOA resource records.  And the database replication amongst coöperating content DNS servers has nothing to do with the response caching in proxy DNS servers.

Question about domain name server


find an element by an id and hide the previous div

Question: Perhaps a simple question but I can't figure this one out.
What I try to do is to find an id which is placed within a div. When found I want to add an extra class name to the previous div. The problem is that the only id is placed within a div.
HTML

 // to this class I want to add an extra class like "hide"
   <input type="radio" id="invoice-method">
   .....

So I need to find "id=invoice-method" and then add an extra class like so

This is the only way because the html is generated automatically.
Comment: And where exactly are you stuck? You must have tried *something*, haven't you?
Comment: Can you elaborate on what you mean by "find an id which is placed within a div"?
Answer: You need closest parent that is div with class radio instead of previous element.
$('#invoice-method').parent().addClass("hide");

OR
$('#invoice-method').closest('div').addClass("hide");

Comment: Stupid me... off course I didn't thought "closest". Thx for your help.
Answer: $('#invoice-method').parent().addClass('hide');

Answer: $('#invoice-method').closest('div')...

Comment: Can you please expand on this?
Comment: `$('#invoice-method')` finds the element by id. `closest('div')` finds the closest ancestor that is a div.


Swift - Como parar uma animação?

Question: Em minha Viewcontroler inicial possuo um slide que fica carregando da internet e alternado na tela imagens num tempo estipulado por mim.
Como eu posso parar a animação? Queria fazer isso antes de ir para outra ViewController
Animação:
<code>func animate(images: [String], index: Int = 0) {
    print(index)
    UIView.transitionWithView(imageView, duration: 10, options: .TransitionCrossDissolve, animations: {
        if let checkedUrl = NSURL(string: self.vetString[index]) {
            self.downloadImage(checkedUrl)
        }
        }, completion: { value in
            let idx = index == images.count-1 ? 0 : index+1
            self.animate(self.vetString, index: idx)
    })
}
</code>
Answer: Descobri uma forma. Fiz assim:
<code>@IBAction func paraAnimacao(sender: AnyObject) {
    var layer = imageView.layer.presentationLayer() as! CALayer
    var frame = layer.frame
    print(frame)
    imageView.layer.removeAllAnimations()
    imageView.frame = frame
}
</code>

Swift - Como parar uma animação?


Any tips on playing 5 and 6 note tuplets? (sheet music in desc)

Question: http://www.gangqinpu.com/pu/2015/7/2/104346_155341.pdf
bar 66 - 73 the notes are easy but just timing the triplets with the dotted notes in the left hand (whats it called? syncopation?)
here is the reference midi

as you can see, that some of the arpeggio is played quicker.
but I have a feeling that the rhythm for both left hand and right hand is more free. I dunno maybe for consistency sake I should practice with the left hand and right hand dead on.
here is the original performance

 now that I've listen to this, he accented some notes making them anchors. so maybe I should just learn the notes and later just practice anchoring the notes that he is anchoring
Answer: It's not a 5 or 6 note "triplet" they are a 5-let and a 6-let, or 5-tuple, and 6-tuple.  You simply fit 5 (or 6) notes evenly into one beat.  So these would be played faster than a triplet.
Answer: A sextuplet is pretty straightforward: it's a triplet on each half of the beat.  You can count it off as "one-trip-let-and-trip-let", or you can set a metronome to twice the beats per minute and play triplets against the click.
Quintuplets are a little harder.  You can syllabify them by using any five-syllable word like 'university', but methods like that get a little dicey - they're actually easier to feel than to count.
To develop a feel for them, count "1-2-3-4-5" over and over, clapping on the one count.  Then speed it up; if you reach a point where you can't enunciate fast enough, just use "dit-dit-dit-dit-dit" or any other sounds you can handle.
Once you get the right hand part down, the second half of measures 66, 68, 70, and 72 should come together fairly easily - you can think about the 12 tuplet parts as being set against 4 eighths, so you'll have one triplet against each eighth note count.  The first half of those measures and all of measures 67, 69, 71 and 73 are the real crux of the problem, because they're all five tuplet parts against four sixteenths, and the left hand is a syncopated dotted eighth-dotted eighth-eighth.
Comment: Five-syllable words starting with a plosive, e.g. paracetamol, may work better for you than five-syllable words that don't, e.g. university. But as you say, the key to mastery is repetition and internalization. I'd also suggest keeping the same metronome tick and move between various tuplet patterns - fives to sixes to fours, and so on.


Pop up para imprimir, mantendo os valores do action

Question: Tenho um formulário que ao apertar submit ele pega o valor selecionado e leva para a pagina destino do action e abre a pagina, porém sobrepõem a pagina atual, preciso levar esses valores do formulário para a pagina pop up sem que o formulário abra a pagina do action.
  <form id="form1" name="form1" method="get" action="folhapgt_imprimir.php">
     <select name="data_selecionada" id="data">
            <?php $dados = mysql_query("SELECT DISTINCT periodo FROM folha_func_sal_cc ORDER BY periodo DESC") or die(mysql_error());
                   while ($data = mysql_fetch_array($dados))
                   {
                        echo "<option value='{$data['periodo']}'";
                        if($_GET['data_selecionada'] == $data['periodo'])
                            echo "selected='selected'";
                            echo ">{$data['periodo']}</option>";
                   }
            ?>
     </select>
     <input type="submit" name="submit" id="submit" value="OK" style="margin-left: 10px;">
  </form>

tentei com
function pop()
      {
        POP = window.open('folhapgt_imprimir.php', 'thePopup', 'width=350,height=350');
      }

mas sem sucesso, abre a pagina que preciso mas não leva o valor.
Comment: Passa via get na URL, tipo "window.open('popup.html?var1=value', ...)
Answer: Basta usar como target o nome da janela do popup. Desta forma não haverá ação na página atual.
Inclua no botão o evento onclick="pop()" que chamará a função:
<input onclick="pop()" type="submit" name="submit" id="submit" value="OK" style="margin-left: 10px;">

Em seguida inclua o .target para o nome da janela da popup na função pop():
function pop(){
  var POP = window.open('folhapgt_imprimir.php', 'thePopup', 'width=350,height=350');
  var form = document.body.querySelector("#form1");
  form.target = "thePopup";
}

Assim o formulário será enviado via GET (atributo method do form) para a popup aberta. Se quiser enviar via post, deve acrescentar na função mais uma linha:
form.method = "post";

Comment: Desculpe, ficou mal entendido. Aquele pop up la é que eu uso em outra coisa, o que eu testei foi

 POP = window.open('folhapgt_imprimir.php', 'thePopup', 'width=350,height=350');
Comment: Dá na mesma, só precisa algumas correções... só um instante
Comment: Fica dentro do while?
Comment: No caso você deve pegar com $_GET... se quiser pegar com $_POST, tem que adicionar na função `form.method = "post";`
Comment: Deu certo, muito obrigado.


Erro ao estabelecer uma conexão com o Banco de Dados

Question: Estou recebendo várias vezes essa mensagem :
Erro ao estabelecer uma conexão com o Banco de Dados

Li algumas matérias sobre esse problema e sempre a solução que indicam é verificar o arquivo WP-config  e verificar se o nome de usuario e senha do MYsql estão corretos, e estão corretos.
Existe alguma outra maneira de verifica o que pode está sobrecarregando o Mysql?
No meu tema no arquivo index.php, adicionei o codigo abaixo:
   <?php echo catch_that_image(25, 14) ?>

e no arquivo Function.php esse outro:
function catch_that_image($w, $h) {
global $post, $posts;
$first_img = '';
$new_img_tag = "";

ob_start();
ob_end_clean();
$output = preg_match_all('//i', $post->post_content, $matches);
$first_img = $matches [1] [0];

if(empty($first_img)){ //Defines a default image with 0 width
    $new_img_tag = "";
}

else{
    $new_img_tag = 'post_title . ' - " title="' . $post->post_title . '" src="' . $first_img . '" width="' . $w . '" height="' . $h . '" class="" />';
}

return $new_img_tag;
}

Esse codigo é para chamar imagens hospedadas fora do wordpress e mostra-las no tema.
Esse codigo pode está relacionado ao erro de Mysql?
Comment: Verifique se o usuário e senha do mysql estão corretos.
Comment: Já verifiquei e estão corretos
Comment: Você poderia colar o erro e o código de conexão no post?
Comment: Editei a pergunta olha lá
Comment: Anexei uma imagem com erro
Comment: Verifique se o servidor MySQL está  ativo e ligado, por exemplo usando o `service mysqld status`, se tiver acesso ao SSH do servidor do MySQL ou utilize `mysql -h 111.222.333.444 -p -u Usuario DB`
Comment: estão hospedados na mesma hospedagem?
Answer: Isso é um problema muito simples de ser resolvido.
Tá dando erro, mas porque? É claro que existe um problema na conexão, então, a princípio, pode ser os dados de login ou a permissão de acesso.
O banco está localizado no mesmo servidor onde os arquivos do WP estão? Se estiver em outro servidor, lembre-se que é necessário liberar acesso remoto e no firewall (se houver).
Crie um arquivo .php com o código abaixo e altere as informações de conexão informando os dados corretos.
<?php

$host = ''; //Se o banco de dados estiver no mesmo servidor deste arquivo, use localhost
$database = '';
$user = '';
$password = '';
$charset = 'utf8';

header('Content-type: text/html; charset=utf-8');

try{
    $pdo = new PDO("mysql:host={$host};dbname={$database};charset={$charset}",
        $user, $password);
    echo 'Conexão feita com sucesso.';
} catch (PDOException $e) {
    echo '
Falha na conexão com o banco de dados
'
        .'
'
        .'
';
    var_dump($e);
}

Se der erro, ele irá exibir o motivo do erro, basta ler a saída que será imprimida na tela.
Detalhe: o charset é utf8 mesmo, sem hífen.
Se os dados estão corretos, as permissões de acesso estão corretas e não existe erros no código de conexão, então o que resta é: o MySQL não está rodando ou está mal configurado.
Comment: Se isto der solução ao problema, sugiro renomear a pergunta para *"Como debugar uma conexão MySQL"*


How to finfd the limit of this sequence?

Question: Let  $(a_n)$ be a sequence defined by $a_1=1, a_2=2$ and $a_{n+2}=\frac{3}{4}a_n+\frac{1}{4}a_{n+1}$ for all $n\ge1$. How to prove this recursive sequence is convergent and find the limit?
Answer: You can find the general term by solving $4x^2-x-3=0\implies x=1,-{3\over4}$.
So $a_n=A(-{3\over4})^n+B$ and sub in initial values you can find $a_n={16\over21}(-{3\over4})^n+{11\over7}$ hence it converges to $11\over 7$.


Need to create a tag for deploying sprint changes

Question: Need to create a tag for deploying sprint changes in to prod env in Azure devops??
I tried some approaches but couldn't figure it out.. Any suggestions?
Comment: Could you specify where you want to put the tag on or what you want to tag? repo, build, release?
Comment: Automatically a tag needs to get add to dev branch by end of each sprint.
Comment: `Tag Git Release` task probably is what you are looking for. You can check my answer below.
Answer: There are two ways to achieve this.
Tag Git Release task
You can use task Tag Git Release at the end of your deployment pipeline.
1, In additional options of the deployment job, Check Allow scripts to access the OAuth token

2, Add Tag Git Release task

Powershell task
Powershell is an another way to achieve this. But it is a little complicated.
For it has to call restful API to set the tag to dev branch.
1,add a powershell task to the end of your deployment pipeline.

2,Call restful api to set the tag to specified branch. Tag branch is actually based on commit id.So in the requeset body $(Release.Artifacts.{alias}.SourceVersion) to refer the commit ID.
To get your person assess token refer to this.
For more information about release variable check here.
$url ="$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/git/repositories/{repo Name}/annotatedtags?api-version=5.1-preview.1"

$bodyrb = "{'message': 'tag for develop via api', 'name': 'tagfromazuredpowershellapi', 'taggedObject': {'objectId':'$(Release.Artifacts.{alias}-CI.SourceVersion)'}}"

connectionToken="{person assess token}}"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))

Invoke-RestMethod -Uri $url -Headers @{authorization = "Basic $base64AuthInfo"} -ContentType "application/json" -Method POST -Body $bodyrb

Hope above could be of a litte help!


Counterup JS to work

Question: According to Counter JsInclude

(I've defined the library in the theme.libraries.yml and attached the library in the theme.info.yml and it shows in the header)
statcounter:
 version: 8.x-1.0
js:
 scripts/jquery.counterup.min.js: { minified: true }
dependencies:
 - core/jquery

HTML
1,234,567.00
$1.99
12345

(Have added this in a block in the front page and the markup is displayed)
jQuery
$('.counter').counterUp(); **or with extra parameters**
$('.counter').counterUp({
delay: 10,
time: 1000
});

(Have placed the jquery in a separate custom js; and defined it in the theme, the js is loaded and no errors till now)
   custom:
    version: 8.x-1.0
   js:
    scripts/custom.js: {}

I want to attach the last bit of jquery to the theme and make the counter work...Any ideas how to get it to work? Thanks.
Comment: can you show the library definition ? the path seems wrong, should be like libraries/counterup/jquery.counterup.min.js
Comment: @remy edited to add library defnition
Comment: ok - so the file is in your theme, is it really there ? no 404 ? your custom js is loaded too on the page ?
Answer: Make sure all files are present !
The drupal way for custom js in your theme is a behavoir, so your js file should look like this:
    (function ($) {
      Drupal.behaviors.myThemeBehavior = {
        attach: function (context, settings) {
           $(context).find('.counter').once('myThemeCounter').counterUp({
             delay: 10,
             time: 1000
           });
        }
      };
    })(jQuery);

This will ensure the script is executed after the DOM is loaded and only will run once.
Comment: Worked great.... Thanks for you time. Helped me a lot :)

Counterup JS to work


How to model this mixed model

Question: I have following data:

Each column represents a specific manufacturer (that's why I skipped the title) and from each one I have several sensors. Now I would like to perform a mixed model. I thought about using the manufacturer and the sensors as random effects but I'm not quite sure about that.
In r resp. lme4 the syntax would be:
lmer( R ~ c + (Manufacturer | sensor), data = data)

Is this correct?
What you can see here is the response of the resistance of the sensors against several gas concentrations.
edit: More information:
There are three manufacturers with two of 5 sensors each and one of 10 sensors. Basically it is:
Manufacturer A: SensorA1, SensorA2, SensorA3, SensorA4, SensorA5
Manufacturer B: SensorB1, SensorB2, SensorB3, SensorB4, SensorB5
Manufacturer C: SensorC1, SensorC2, SensorC3, SensorC4, SensorC5, SensorC6, SensorC7, SensorC8, SensorC9, SensorC10

All the sensors are housed in the same experimental unit and measured in parallel under varying conditions. Here in this case it is the applied concentration varying from 50 to 500 ppm.
So all I did in the plot is to group these sensors according to their manufacturer. The colours represent the different concentrations (it is hardly visible in the index, I have to admit..), so basically the colours are not necessary as the axis already provides this information.
My goal now is to figure out how the sensors react to the different gases individually and how do the manufacturers.
Plots:
The formula
lmer(R~ poly(c, 1) + Manufacturer + (c | Manufacturer/Sensor), data = data)

results in

respectively in

and the formula
lmer(R~ poly(c, 1) + Manufacturer:c + (c | Sensor), data = data)

results in

I think the blue fit for the third group is not bad while the other two need an improvement. I'm playing a bit around but I'm not really able to enhance the situation. What I wonder is: Without any knowledge I would draw an almost straight line through the data points, separately for each Manufacturer (color). Why are above formulas not able to do so?
editedit:
Matteo's suggestion lmer( I(log(R)) ~ I(log(c)) + Manufacturer + I(log(c)):Manufacturer + ( I(log(c)) | sensor), data = data) results in

I can't get my head around it why the fit behaves as it does. Why are they so off all the time?
data: https://www.file-upload.net/download-13853720/data.csv.html
my code:
lmer_model<- lmer(log10(R) ~ log10(c) + Manufacturer + log10(c):Manufacturer +
                    (log10(c) | Sensor), data = data)
ggplot(data, aes(x = c, y = R, colour = Manufacturer)) +
  geom_point(alpha = 0.5) +
  scale_x_continuous(
    trans='log10'
    , breaks = round(seq(min(data$c), max(data$c), by = 150),500)) +
  scale_y_continuous(
    trans='log10'
    , labels=format_si()
    , breaks = round(seq(min(data$R), max(data$R), by = 500000), 1000000)) +
  theme_classic() +
  geom_line(data = cbind(data, pred = predict(lmer_model)), aes(y = pred), size = 1) +
  ylab(TeX("R / $ \\Omega $ ")) + xlab(TeX("c / ppm")) +
  theme(
    legend.position = "none",
    panel.spacing = unit(2, "lines"),
    legend.text=element_text(size=7.5),
    legend.box.margin=margin(-13,-13,-13,-13)
  )

Comment: I am having trouble understanding the experiment. Can you edit the question to give a bit more detail ? In particular is sensor nested in manufacturer ?
Comment: I don't think that formula does what you want.. but just to be sure: what does `sensor` represent exactly? each dot is a measurement from a different sensor? (i.e., each of concentration levels is measured multiple times with different sensors?). Does the different manufacturers produce the "same" type of sensors?
Comment: Firstly, thanks for the fast responses though I was absent for some time now. @matteo 'sensor' holds different sensors where each sensor represents all measurement points belonging to one specific sensor. The colours represent the different concentrations. In the plot you can only see three different manufacturers, from which there are 5 sensors from A, 5 sensors from B and 10 sensors from C.
Comment: @RobertLong Yes, sensor is nested in manufacturer. I will extend the background information!
Answer:
In r resp. lme4 the syntax would be:
lmer( R ~ c + (Manufacturer | sensor), data = data)

Is this correct?

No. The above model specifies that observations are clustered within sensor (which is correct) but it also says that the  effect of Manufacturer varies within each level of sensor (ie there are random slopes for Manufacturer), which is incorrect, since sensor is nested within Manufacturer. Also, you do not specify Manufacturer as a fixed effect which means that the random slopes vary around zero.
You could start with the following model:
lmer( R ~ c + (1 | Manufacturer/sensor), data = data)

which is equivalent to
lmer( R ~ c + (1 | Manufacturer) + (1 | Manufacturer:sensor), data = data)

and assuming that sensor is coded uniquely as it seems to be in the information you added, it is also equivalent to:
lmer( R ~ c + (1 | Manufacturer) + (1 | sensor), data = data)

These models fit fixed effects for concentration and random intercepts for Manufacturer and sensor. The main issue I see with this is that there are only 3 levels of Manufacturer so you are unlikely to get a good estimate of it's variance. So an alternative is to specify Manufacturer as a fixed effect:
lmer( R ~ c + Manufacturer + (1 | sensor), data = data)

You might also want to allow the effect of concentration to vary across sensors by specifying random slopes for concentration:
lmer( R ~ c + Manufacturer + (c | sensor), data = data)

Comment: You're welcome. Do you mean the number of levels ?
Comment: That's because the random effects are assumed to be normally distributed and the software will estimate a variance for each variable, so in the case of your manufacturers you only have 3 levels so it means the software has to estimate the variance from only 3 observations. You can still do it, but the estimate is unlikely to be very good and you have no way of knowing how good it is.
Comment: Yes. Imagine that you wanted to estimate the variance of exam scores for 200 student's taking the same exam. If you only took 3 samples then you are unlikely to get a good estimate.
Comment: Kind of but I can't manage to apply the model description successfully, hence, I would prefer to keep it open.
Comment: Thank you very much for the detailed line-to-line explanations. This helps me a lot to dive deeper into the topic! Here I have, among others but as I would like to learn the concepts, to get started the first question why the levels of a variable play a role when it comes to treat them as random effects?
Comment: yes, in this case the numer of manufacturers
Comment: Thank you! Not knowing what exactly is not good? The variance estimation?
Comment: @Ben does this or the other answer answer your question ? If so, please mark one of them as the accepted answer.
Comment: Ahh I had not noticed your updates to the question. Sorry ! Can you also please include the code you used to create the plots...
Answer: I think the model you want in lme4 syntax should be written as
lmer( R ~ c + Manufacturer + c:Manufacturer + ( c | sensor), data = data)

This model will have sensor-specific random intercept and slopes, and manufacturer specific (fixed) intercept and slopes, so I think it address your goal of estimating how individual sensors and manufactures respond to gas concentration.
I think that conceptually also Manufacturer should be a random effects, but because you have only three of them it is not very practical and not much to gain in trying to estimate the between-manufacturers variance.
One final note, by looking at your plot it seems that the relationship is linear when both variables (concentration and response) are expressed in logarithmic units. So I think it would be appropriate to log-transform the variables before entering them in the model. Note that this changes the interpretation of the coefficients which would code for relative difference instead of absolute differences as in standard linear regression. In a nutshell, a slope coefficient of $\beta$ would indicate that a $x\%$ increase in the predictor correspond approximately to $x\beta\,\%$ increase in the response, or more precisely to a change in the response equivalent to multiplying it by $e^{\beta\log\left(\frac{100+x}{100}\right) }$.

EDIT
I had a look at the data you posted, and fit the model I suggested above. The model seems to fits quite well, so there must be an issue in the way you computed or plotted the model predictions. I paste below the code and the resulting plot.
d <- read.table("data.csv",header=T,sep="\t")
library(ggplot2)
library(lme4)

# log transform variables
d$log_c <- log(d$concentration)
d$log_R <- log(d$Resistance)

# fit mixed model
m0 <- lmer( log_R ~ log_c + Manufacturer + log_c:Manufacturer + ( log_c | Sensor), data = d)

# not converging, try some more iterations
ss <- getME(m0, c("theta","fixef"))
m0 <- update(m0, start=ss, control=lmerControl(optCtrl=list(maxfun=2e4))) # OK

# make a new data frame for calculating model predictions
# (note that I am calculating them using only the fixed effects)
nd <- expand.grid(Manufacturer = unique(d$Manufacturer), log_c = seq(min(d$log_c),max(d$log_c), length.out=100))
nd$log_R <- predict(m0, newdata=nd, re.form=NA)
nd$concentration <- exp(nd$log_c)
nd$Resistance <- exp(nd$log_R)

# plotting
ggplot(data=d,aes(x=concentration, y=Resistance, color=Manufacturer))+geom_point()+ scale_x_continuous(trans = 'log10') +scale_y_continuous(trans = 'log10')+facet_grid(.~Manufacturer)+geom_line(data=nd)

Comment: The point is that if you tell lme4 that `Manufacturer` is a random factor, e.g. with random manufacturer-specific intercepts, it will estimate the variance of these random intercepts. With only 3 manufacturer this would amount to trying to estimate a variance with only 3 data points: there is just not enough data to give a sensible estimate!
Comment: It doesn't matter but if you put `log()`in the lmer formula make sure to use the `I()` function, e.g. `lmer( I(log(R)) ~ I(log(c)) + Manufacturer + I(log(c)):Manufacturer + ( I(log(c)) | sensor), data = data)`
Comment: If you add them as interactions make sure you add them also as main effects. If you have many more possible predictions the number of interactions grows quickly and you might start overfitting, so for each terms that you add in the model you may want to check that it does not decrease the _predictive_ ability of the model, using e.g. likelihood ratio test or cross-validation.
Comment: Thanks a lot for the great and helpful answer! I just noticed that you were aware of the log-transformations as well. I will take this into account now. Despite from that I would like to know why the number of Manufacturers plays a role in regards to the between-variances?
Comment: By the way, I think the discrepancy you see in the plots for the first two groups might be due to fitting the model on the original scale and then plotting in log-scale: try first transforming both `R` and `c` and then fitting the model. Also, the use of `poly` in this context seems superfluous (since you are asking to generate a polynomial of order 1, I think the only thing that the function does is centering and rescaling the predictor).
Comment: Ok, I will try out. Does it play a role if I transform the data and fit it afterwards or if I put the log() into the lmer-formula?
Comment: The fits are still offside, it somehow looks like a conceptual issue.. but on which side?
Comment: There must be something wrong in how you compute the predicted values. Not only because they are way off, but also because the predicted relationship should be linear in log-units but instead it looks like its curved (evident from the red line). Perhaps it would be more helpful if you posted your data and code, so we can see if there's something wrong.
Comment: Sure, I already wanted to do so and I just did that. The r code is not necessary, or? Thanks a lot in advance! Atm I'm still trying out some stuff but I'm a bit stuck now..  maybe it is a plotting issue, will investigate this soon!
Comment: @Ben I have updated my answer. The plot seems OK so you might want to compare your code with mine.
Comment: Yes, great, it's also working on my side. You probably did something smart I didn't.. I think it is connected to creating the new dataframe 'nd' though I also didn't try to improve the convergences but I don't think they caused this huge difference. And when you create that new dataframe I cannot realize everything but I will dig into it. I will add my code so you will probably see directly my major failure..  but still, thanks a lot! You did not only solve it but I also have some aspects to deepen!
Comment: It must be lmer() formula.. with your plotting code lines it works as well (though it looks a bit different). Will have a closer look asap and come back!
Comment: something else, I'm not sure if I should create another question for that: When I want to add more features like humidity, temperature and another gas: How do I take into account these additional informations? Do I just add them like more interactions term, e.g. like " ( ... ) humidity:c + temperature:c + humidity:temperature + humidity:temperature:c (...) " ?
Comment: Ok, thanks a lot! I just stumbled over another situation: How do I make use of the model now? :) Is there any possibility to extract means and variances in regards to the manufacturers per concentration?

How to model this mixed model


How to get a widget to run with multiple actions from typoscript?

Question: In creating a new uncached widget for login/logout/registering users in the Frontend, am unable to get it to work. How can I call two different controllers from typoscript (see code below)?
Am using TYPO3 9.5. Knowing how to create one is important because I'll need that info in creating many others for various uses. I have previously created a complex login system without widget/controller/action in TYPO3.
In ext_localconf.php, there is;
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
    VendorName.ExtensionName,
    PluginName,
    [
    'Frontend' => 'index',
    'Account' => 'index,login,logout,register'
], [
    'Account' => 'login,logout,register'
]);

Under folder structure Classes/Controller there is class VendorName\ExtensionName\Controller\AccountController which has;
class AccountController extends AbstractWidgetController {

    /**
     * @var array
     */
    protected $supportedRequestTypes = [
        Request::class,
        WidgetRequest::class
    ];

    public function initializeAction() {

    }

    public function indexAction() {

    }

    public function loginAction() {

        return $this->view->assign('raw', 'Hello World');
    }

    public function logoutAction() {

    }

    public function registerAction() {

    }

    /**
     * Handles a request. The result output is returned by altering the given response.
     *
     * @param \TYPO3\CMS\Extbase\Mvc\RequestInterface $request The request object
     * @param \TYPO3\CMS\Extbase\Mvc\ResponseInterface $response The response, modified by this handler
     *
     * @return void
     * @api
     */
    public function processRequest(RequestInterface $request, ResponseInterface $response) {

        #ActionController::processRequest($request, $response);
    }
}

And in the ts file there is;
page = PAGE
page {
    ...

    10 = USER
    10 {
        ...

        userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run
        vendorName = VendorName
        extensionName = ExtensionName
        pluginName = PluginName

    }
}

...

5 = USER_INT
5 {
    userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run
    vendorName = VendorName
    extensionName = ExtensionName
    pluginName = PluginName
    controller = Account
    action = login
}

When running this code, the PAGE ts produces the page using the Frontend controller index action which returns raw html through a fluid template. But when I add the USER_INT part, TYPO3 runs out of memory and displays a blank page.
Answer: Widgets are a type of ViewHelper used in Fluid templates. From what you describe, I think you want a plugin. Your Controller class needs to extend TYPO3\CMS\Extbase\Mvc\Controller\ActionController, not TYPO3\CMS\Fluid\ViewHelpers\Widget\Controller\AbstractWidgetController for that.
Comment: Thanks for response. Am actually trying something similar to extension sr_langauge_menu. You see, it displays a menu upon which one can change the site language. But in my case the login should be uncached coz it is supposed to change upon login.
Comment: So I tried changing the controller to Action Controller but still not working.
Comment: Am actually not getting any error. I dove into the TYPO3 code yesterday to check why this wasn't working, and found something very interesting. Values from TypoScript were not being picked up (and they should). So if you have two calls for bootstrap from TypoScript and both assigned controller and action, the controller and action gets ignored and results in an endless loop. Will write to TYPO3 forge see if this is by design or was overlooked during TYPO3 9.5 development. But thanks alot for your help. I appreciated it.


Terraform Combine Variable and String

Question: I'm trying to do a rather simple task in Terraform and it's not working:
tfvars:
hosted_zone       = "example.com"
domain            = "my.${var.hosted_zone}"

route_53_record:
resource "aws_route53_record" "regional" {
  zone_id = "${data.aws_route53_zone.selected.zone_id}"
  name    = "${var.domain}"
  type    = "A"
  ttl     = "300"
  records = ["188.8.131.52"]
}

When I run terraform plan I'm getting this:
+ aws_route53_record.regional
      id:                 <computed>
      allow_overwrite:    "true"
      fqdn:               <computed>
      name:               "my.${var.hosted_zone}"
      records.#:          "1"
      records.3178571330: "220.127.116.11"
      ttl:                "300"
      type:               "A"
      zone_id:            "REDACTED"

domain should be my.example.com. How do I join the variable hosted_zoned and a string to form domain?
Answer: You can't use interpolation in a tfvars file.
Instead you could either join it directly in your Terraform like this:
terraform.tfvars
hosted_zone = "example.com"
domain      = "my"

main.tf
resource "aws_route53_record" "regional" {
  zone_id = data.aws_route53_zone.selected.zone_id
  name    = "${var.domain}.${var.hosted_zone}"
  type    = "A"
  ttl     = "300"
  records = ["184.108.40.206"]
}

Or, if you always need to compose these things together you could use a local:
locals {
  domain = "${var.domain}.${var.hosted_zone}"
}

resource "aws_route53_record" "regional" {
  zone_id = data.aws_route53_zone.selected.zone_id
  name    = local.domain
  type    = "A"
  ttl     = "300"
  records = ["220.127.116.11"]
}

Comment: It's not removed. You get a warning when using bare interpolation such as `name    = "${local.domain}"` instead of `name    = local.domain` but you can still use `"${var.domain}.${var.hosted_zone}"` to join two variables with another string (the `.`).
Comment: In terraform 0.13 interpolation is removed. How can we concat without interpolation?
Answer: Did you try escaping the dot?
      name:               "my\.${var.hosted_zone}"

Of course, you don't need the "domain" variable in .tvars then either.

Terraform Combine Variable and String


IE9 - Position: relative; hover issue

Question: I'm getting some strange hover behaviour from IE9 which seems to be resulting from positioning an element relative to a parent.  It's a bit difficult to explain so I've made a working example available here: http://jsfiddle.net/CVPhW/2/  I've stripped it out as much as I can but I left all the containing divs in there in case they were somehow relevant.
Try hovering your cursor over the very bottom of each button and you'll see the hover doesn't activate unless you move the cursor around 10 pixels upwards.  It works fine in FF, Chrome and believe it or not, even IE6.
It's something to do with the bottom: 12px; style applied to #menucontainer ul li a.  If I remove that, the whole portion activates properly, but it's not positioned correctly.  The text position in that example is how I'd like it to be, but with a fix for the hovering.
Has anyone else encountered something like this before?  I've been trawling SO and Google for an answer but I haven't found anything remotely similar.  I'd be really grateful for some help with this.
Answer: I forked your example here
it seems to work in all browsers. I changed a couple of styles on the
 and the  elements
Comment: Thanks a lot man.  That didn't work in IE6 but a few typical hacks for that and it worked a charm.

IE9 - Position: relative; hover issue


How can I print a views exposed form into a custom block?

Question: I have a page view with exposed filters and would like to print said filters into a custom block in order to add extra html markup above the actual form.  This block will be used on other pages using Context.
I know I can create a block by setting 'exposed filters in block' to yes, however that's not the solution I am looking for.
Answer: Hours and hours of searching and nothing was working.  Several minutes after posting this question, I figured it out.  The following code can be used in template files or blocks.
<code><?php
  $block = module_invoke('views', 'block_view', '-exp-VIEW_NAME-DISPLAY_NAME');
  print render($block['content']);
?>
</code>
Comment: Yeah, there were tons of other very complex solutions out there!  This one is short and simple.  Granted I am sure there are use cases for the other solutions.
Comment: On another note, thanks for coming back to tell people your solution!
Comment: There are so many ways to manage this with `code`. Nice finding though.
Answer: Its simple take a look at the screenshot.
Comment: I understand thats one way to do it, but that wasn't the solution I was looking for.  I needed to be able to add HTML markup above the actual form.  Thanks though.
Comment: @filmoreha Well. A simple tweak is to make a module with custom markup and handle it same way like this form via contextual filters or something.. I am also looking for a better solution.
Answer: For Drupal 7:
<code>$view = views_get_view('view_name');
$display_id = 'page'; // Display: page/block
$view->set_display($display_id);
$view->init_handlers();
$form_state = array(
    'view' => $view,
    'display' => $view->display_handler->display,
    'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'),
    'method' => 'get',
    'rerender' => TRUE,
    'no_redirect' => TRUE,
    'always_process' => TRUE, // This is important for handle the form status.
);
$form = drupal_build_form('views_exposed_form', $form_state);
print drupal_render($form);
</code>
'always_process' is main form state argument for handle the exposed filter form status.
From https://www.drupal.org/node/2854114


Using either x-roots or logarithms to simplify equation

Question: I have the equation:
$.5 = 1-(1-s^r)^b$
And want to solve for $s$.
Would the correct solution involve (1) b-roots and r-roots or (2) logarithms?
Here's approach (1):

Here's approach (2):

Approach (1) seems to be less messy algebraically, but beyond that am I missing something that makes one approach better (or more correct) than the other?
Comment: Both approaches seem fine. For many purposes I prefer the log approach, since it involves familiar functions and may make estimates easier.
Answer: You are not missing anything.  When I teach Calc I, I teach my students both of these approaches.

Compare the following four equations: $2^x=b$, $x^b=e$, $x^by^c=f(y)$, and your equation.  To be solved algebraically: in the first case, you have to take log$_2$; in the second case, you have to raise to $1/b$ power; in third case, you have to divide by $y^c$; in your case, you have to take a root.  And it's hard for first-time students to figure out which one to do when.
The log approach, however, is failsafe.  One approach works for all four types of equations.  The drawback is, log is much slower than the algebraic approach.
When you get to logarithmic differentiation, most of those problems can be solved without log as well (e.g., $x^x=e^{x\log x}$; then use chain rule to differentiate).  However, logarithmic differentiation is often taught just because it's one uniform approach that works for all types of problems, including $(x+2)^2(x+1)^3(x-3)^4$.


Symfony 3.1 CSRF token not valid in login form

Question: I'm using Symfony 3.1 with FOS user bundle.
I get a "CSRF invalid token" message for the login form the first time I logged in (in incognito mode)
I noticed that in the 1st request, I get a token. Then I refresh the page and get another one. From then on, I get the same token (and works correctly). For example:
1st request: maJl7bBRR0iuOX4A96cOxrsLdklBIxz3mCP7fSMGqQY
2nd request: q21SVH98tbMLeRIypv2aTn0xBDXJ1khrcL8fIMOU4Y8
3rd request: q21SVH98tbMLeRIypv2aTn0xBDXJ1khrcL8fIMOU4Y8
4th request: q21SVH98tbMLeRIypv2aTn0xBDXJ1khrcL8fIMOU4Y8

I tested twice resulting in the same behavior.
It doesn't seem to be a browser cache problem because of the header:
Cache-Control:no-cache

The csrf input in the form is generated like this:
<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">

After it fails the first time, everything goes ok (the 2nd csrf token works properly)
I want to don't fail validation the first time I login because of the CSRF token, which I suspect is failing because of what I mentioned above. Removing CSRF protection is not a solution.
Thanks!
UPDATE
I found the problem but not the solution. The project stores the session data in MySQL. The first time it access it doesn't insert the data in the database, but the second it does. The data is present in $_SESSION, but as it's not stored in MySQL the first time, the csrf token is lost.(I found this logging the queries made from the app thanks to this How to show the last queries executed on MySQL?).
Storing the session in files works fine. This is not a solution because there are going to be multiple instances of the app in different servers.
Answer: The problem was that in a service used in almost all the app, there was a
$session = new Session();

Which for some reason caused the PDO Session Handler not be set.
The solution was to inject the session to the service
 public function __construct(..., Session $session)

and in the service.yml inject it like
 - '@session'


Correlation of levels vs. differences vs. percents

Question: Sometimes, I have seen people using correlation of levels, correlation of differences and also correlation of percent changes.
I understand these answer different questions. For example, for "what is the correlation between shoes and T-shirt quantities", one would use levels (perhaps after standardizing). For "what is the correlation between the growth rates of shoes and T-shirts", one would use percent changes. For what question would you use the correlation in differences?
<code>Q(shoes)    Q(T-shirts)     delta(shoes)    delta(T-shirts) pct_change(shoes)   pct_change(T-shirts)
1000005     34
1000342     36              337             2               0%                  6%
1000842     32              500             -4              0%                  -11%
1000042     42              -800            10              0%                  31%
1000122     40              80              -2              0%              -   5%
1000432     51              310             11              0%                  28%
1000932     58              500             7               0%                  14%
</code>
Further, I know that you could log your data if it follows an exponential pattern. Then you would find the correlation of the two series using this logged data. This is normalizing the data, which I believe is different from what is being done above (ie. simple transformations).
What is the terminology distinction here? For example, square rooting or logging your data is 'normalization', but converting it to differences or percents is not (I believe). After normalizing, can you still transform the data? (eg. differences of logs would effectively give you percent changes, but are there other transformations to consider?)
To reiterate my questions, when would you use correlation of differences? Are there any other 'transformations' (like converting to percents) that I am missing, but are also useful to consider? This question is not really about methods for normalization (because I suspect I will mostly rely on Box-Cox transformations).
Answer: In Finance and economics all three are used a lot for different purposes. For instance, if you have series of asset prices $p_i$, then you can create series of simple returns $r_i=\frac{p_i}{p_{i-1}}-1$ or log returns $r_i=\ln p_i-\ln p_{i-1}$
The price series are usually non-stationary, that's why the correlation between them is usually nonsensical. You look at the correlation of returns. You can also look at the changes: $\Delta p_i= p_i- p_{i-1}$.
The price to return conversion is a data transformation. You can apply further transformations, of course.


Pager in Render Array

Question: In a custom module I have a block defined and the function that builds the block returns a render array. In that render array I am looking to create a pager for my content since it is a listing of items.
If I run pager_default_initialize during my query building like so this automatically adds a pager to the top of the block.
$total = $query->countQuery()
  ->execute()
  ->fetchField();

$page = pager_default_initialize($total, $per);

$query->extend('PagerDefault')
  ->limit($per)
  ->range($page * $per, $per);

I want to have more control over the pager, like adding it to the bottom of the block. If I remove the pager_default_initialize from the query building code like so, I can stop the pager from automatically being added.
$total = $query->countQuery()
  ->execute()
  ->fetchField();

$page = pager_find_page();

$query->extend('PagerDefault')
  ->limit($per)
  ->range($page * $per, $per);

So, the question is, how do I add the pager to my render array so it renders the pager at the bottom of the block?
My render array currently looks like this:
$content['results'] = array(
  '#type'       => 'container',
  '#attributes' => array(
    'class' => 'results',
  ),
);

if ($data->rowCount()) {
  foreach ($data as $record) {
    $content['results'][] = array(
      '#theme' => 'CUSTOM_NODE_THEME',
      '#node'   => node_load($record->nid),
    );
  }
  if ($per > 0) {
    $content['results']['pager'] = array(
      '#theme' => 'pager',
    );
  }
}

The theme_pager() is not being run when the block is rendered.
Any help would be awesome!
Answer: Here is the solution. I knew as soon as I asked the question I would find the answer!
First off, the query building code must not run pager_default_initialize, like so:
$total = $query->countQuery()
  ->execute()
  ->fetchField();

$page = pager_find_page();

$query->extend('PagerDefault')
  ->limit($per)
  ->range($page * $per, $per);

The pager render array should be created like so:
$content['results']['pager'] = array(
  '#pre_render' => array('CUSTOM_PRE_RENDER'),
  '#theme' => 'pager',
  '#variables' => array(
    'total' => $total,
    'per' => $per,
  ),
);

And then run pager_default_initialize in the custom pre render function:
function custom_pre_render_intialize_pager($_element) {
  pager_default_initialize($_element['#variables']['total'], $_element['#variables']['per']);

  return $_element;
}

This code will only work to add a single pager to the block and may not work if there is more then one pager on the page.

Pager in Render Array


Proving an expression is 0 over a curve

Question: Let $\Gamma$ a differentiable curve over $\mathbb{R^2}$. Given $z\in\Gamma$, we define $T_z$ as the unit tangent vector at $z$. I want to prove that the expression
$$\frac{T_w}{w-z}-\frac{\overline{T_z}}{\overline{w-z}}, \hspace{0.3cm} w,z\in \Gamma,  w\neq z$$
equals $0$ when there exists a circular arc tangent to both points $w,z$.
I do not have any idea how to solve it. Any hint?
Answer: Hint
When there exists a circular arc tangent to both points $w,z$, there exists a rotation $R$ of the complex plane of center $a$ and angle $\theta$ such that $w-a = (z-a)e^{i \theta}$ and $T_w = e^{i\theta} T_z$. Also have in mind that the modulus of $T_z,T_w$ is equal to one and that $T_z$ (respectively $T_w$) is orthogonal to $z-a$ (respectively $w-a$).
Using those relations, you'll get the desired result.

Proving an expression is 0 over a curve


right sidebar doesn't shrink in zen responsive theme

Question: I have a Zen 7.x.5.x Responsive subtheme with Right sidebar...
I know, I am new with all this responsiveness staff; but - I think the right sidebar doesn't shrink when I resize my browser....it just moves inside, staying about the same size....or may be I don't understand something....
so, I have made up my content area - it consists now from 2 blocks floating left and right; I put them width proportionally to content area : 67% and 33% - they resize, when I resize browser....but sidebar looks too big and not shrinking; even it seems to be set in percents from page's 1200px.....
Answer: Inspect the right sidebar element in your browser. Then select

in the DOM and it should give you the width as a percentage. This is proof that the sidebar is responsive. Now drag the browser window smaller and observe the media query changing at breakpoints and the percentage should also change. At mobile breakpoint the sidebars should be 100%.
Now look in your sub theme's sass/layouts folder for the file _responsive.scss
You will see snippets like this
$zen-column-count: 3;
...

#content {
          @include zen-grid-item(2, 1);
        }

        /* Span 1 column, starting in 3rd column from left. */
        .region-sidebar-second {
          @include zen-grid-item(1, 3);
        }

This is where the sidebar width is set in relation to the content area. In the above case it is 1 column wide starting at column 3. As there are a total of 3 columns it is 1/3 the total width.
You can change it here if you have compass set up and working and properly watching the folder for changes.
Comment: OK, but 33% from 1200 would be what?! - near 400px? I need to plan there a banner of 320px in future, but now I have put there image thumbnail of 220px and it looks like full sidebar?
Comment: ...and what is this line in responsive.css about: /* Span 1 column, starting in 5th column from left. */
  .sidebar-second .region-sidebar-second {
    float: left;
    width: 20%;
    margin-left: 80%;
    margin-right: -100%;
  } - so is it only 20% and not 33%?
Comment: Look in _responsive.scss at the breakpoints also. If you have sass and compass installed then you can alter it using the zen grids mixin. But you don't have to. If you want you can scrap the whole file and create your own using only css. But then you would miss out on a whole lot of functionality. Look at [The Complete Guide To Omega 4](http://www.youtube.com/watch?v=2CM177ldAy8) series. It explains how to install sass and compass. It is quite a process but once it is done it will take your theming to a whole new level.


Clean OAuth2 token in swift

Question: In swift I'm calling successfully a callback URL which revoke a token after the user is logout, and right after I call this to enable re-logging
func runOauth(){
    self.loadingLabel.isHidden=true
    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    appDelegate.oauth2!.logger = OAuth2DebugLogger(.debug)

    //code executed when OAuth have finished
    appDelegate.oauth2!.afterAuthorizeOrFail = self.callBackOAuth

    var url:URL?
    do{
        //the url for authorizing the user, kronos://oauth/callback" is called after the OAuth finish
        url = try appDelegate.oauth2!.authorizeURL(withRedirect:"kronos://oauth/callback", scope: "auth",params: ["tg":"addon/kronos/main","idx":"login.OAuth","formId":"iOS"])
        do{
            let authorizer = appDelegate.oauth2!.authorizer as! OAuth2Authorizer
            //launch OAuth in embeded view "SafariVC"
            print("Safari embeded")
            safariVC = try authorizer.authorizeSafariEmbedded(from: self,at: url!)

        }catch let error {
            DispatchQueue.main.async {
                print("ERROR authorizing\(error)")
                //self.runOauth()
            }
        }
    }catch let error {
        DispatchQueue.main.async {
            print("ERROR creating OAuth URL \(error)")
            //self.runOauth()
        }
    }
}

But it re-logging the user automatically when loading logging page, I've tried this:
 let appDelegate = UIApplication.shared.delegate as! AppDelegate

 let authorizer = appDelegate.oauth2!.authorizer as! OAuth2Authorizer
 authorizer.oauth2.forgetTokens()

Does someone have a solution?
EDIT:
In fact the first logoff woks well but if I relog I can not sign off anymore and I have that line in the console when it fail
[Debug] OAuth2: Did exchange code for access [true] and refresh [true] tokens

EDIT2:
I've tried
let appDelegate = UIApplication.shared.delegate as! AppDelegate
 appDelegate.oauth2?.forgetClient()
 appDelegate.oauth2 = OAuth2CodeGrant(settings: OAuthParams  )
 appDelegate.oauth2!.authConfig.authorizeContext = KronosWebsite?.window//KronosWebsite the WKWebview
 runOauth()

and I've this in the console
[Debug] OAuth2: Forgetting client credentials and removing them from keychain
[Warn!] OAuth2: Failed to delete credentials from keychain: Error Domain=swift.keychain.error Code=-25300 "(null)"

EDIT3:
I've tried to empty keychains
let secItemClasses = [kSecClassGenericPassword,
                kSecClassInternetPassword,
                kSecClassCertificate,
                kSecClassKey,
                kSecClassIdentity]
for secItemClass in secItemClasses {
      let dictionary = [kSecClass as String:secItemClass]
       SecItemDelete(dictionary as CFDictionary)
}

But maybe I need to use  attributes keychainAccountForClientCredentials and keychainAccountForTokens, so is this possible to access data stored in those keychains?
Answer: I've solved this issue, I just had to clean cookies for the SFSafariViewController (I've done that in PHP)

Clean OAuth2 token in swift


experimental sequence of number

Question: I'm doing a small numerical experiment. I got, from the first simulations, the following sequence of numbers. I'm trying to imagine a mathematical law behind this sequence. It could be a geometric progression?
1.333333333
1.75
2.491107286
3.835656425
6.219456109
10.44686695
17.99815841
31.6031634
56.31814911
101.5516622
...
Comment: Since $$\frac{2.4911...}{1.75}\neq\frac{1.75}{1.3333333...}$$ the sequence cannot be a geometric one.
Comment: It is likely that the sequence grows geometrically. Perhaps you could share in which context you got these values, what is your experiment exactly?
Comment: You're giving no error bounds -- does that mean you trust all the significant digits you quote?
Comment: The ratios between successive terms are roughly constant, but they do increase monotonically… so there looks to be a super-exponential trend.
Answer: Your data looks like a simple exponential growth. To a rough approximation:
<code> y = A*exp(x/t) + y0

 y0 0.95321
 A  0.26613
 t  1.68515
</code>
...which makes it a geometric progression with an added constant term.

experimental sequence of number


App Flutter funciona no Emulador do Android Studio mas não no celular

Question: Todo o projeto, inclusive o back-end funciona perfeitamente quando executado no emulador do Android no Android Studio, mas quando gero o arquivo APK em modo release e executo no meu smartphone, somente o front-end funciona, já o back-end não funciona.
Estou clonando o projeto https://github.com/PatilShreyas/Flutter2GoogleSheets-Demo e obtenho o resultado negativo. Mesmo seguindo as orientações do site https://itnext.io/dart-working-with-google-sheets-793ed322daa0, também tenho o mesmo resultado. Funciona no PC mas quando gero o APK e instalo no celular não funciona, mesmo utilizando os mesmos códigos.
Já tentei o comando $flutter doctor e não aparece nenhum erro!
Tentei utilizar versões diferentes do Android para debugar sem sucesso!
Creio que possa ser uma configuração no Android Studio que está passando desapercebido.
Eu sinceramente não sei onde está o problema, agradeço caso alguém possa me apontar possíveis soluções.
Answer: Consegui Resolver com base nas orientações encontradas em https://codeshare.io/5M6nA3.
Entretanto tive dificuldade para encontrar onde era necessário fazer a alteração:
É preciso abrir o arquivo:
..\android\app\src\main\AndroidManifest.xml
que está nas pasta do seu projeto
e acrescentar a permissão:

<uses-permission android:name="android.permission.INTERNET"/>

na segunda linha. logo após o <manifest ....>
Espero ter ajudado outros que tenham tido o mesmo problema!!


Linear Dependence

Question:
Hey everyone, so for this question I take the three row vectors and put them on top of each other putting $A$ on top and $B$ at the bottom. I then proceed to augment the matrix with the zero vector. I row reduce and solve for the variables $a$, and $b$ in terms of $c$. I then get the non-trivial linear relation but the computer says it isn't right. Can anyone help me with what I'm doing wrong?
Answer: Your relations are dependence relations for the columns of the input matrix, rather than the rows.  To get the right answer, you need to take the transpose of your matrix before augmenting and row-reducing.

Linear Dependence


Search for the most populated area in a game of life matrix

Question: I programmed a game of life in C and it works quiet well, the only problem the game board is much bigger than can be displayed. I know the number of rows and and the columns the that the monitor can display and I thought it would be a great idea following the action so to say (searching for the most populated area). Therefor I wrote a little function to receive the 4 indexes of the corners of the part of the  field I should display, but somehow the code seems to give random sections, which sometimes are obliviously false, the calculated worth of the living cells (max) is completely false (sometimes even bigger than the whole matrix it self). Here is the code:
<code>int* most_populated_area(int m, int n, bool a[m][n], int r, int c){
    int * rr=malloc(sizeof(int)*4); //return value
    rr[0]=0;
    rr[1]=r;
    rr[2]=0;
    rr[3]=c; //we first assume that the most populated arrea is upper left corner
    int summe=0;
    int max=0; //to controll wheater or not we found a more populated area we need a summe and the max we founded until now
    for(int isearch=0; isearch<m; isearch++){ //we search the matrix row for row
        for(int jsearch=0; jsearch<n; jsearch++){ // and column for column
            for(int ik=0; ik<=r; ik++){ // now from the current flied we go as many rows we are allowed
                for(int jl=0; jl<=c; jl++){ //and also as many columns we are allowed to go
                    int iks=isearch+ik; //we looking on the field is 0 to r
                    int jls=jsearch+jl; //and 0 to c flieds away from our current field
                    if(iks>=m){ //if the field is outside the matrix we have to go back
                        iks%=r; // iks is clearly bigger than r (because m bigger than r) but iks%r can be r-1 at most,
                        //so we have the rest from iks through r over the edge
                    }
                    if(jls>=n){ //analog to iks
                        jls%=c;
                    }
                    summe+=a[iks][jls];
                }
            }
            if(summe>max){// the summe is greater than the max we found a more populated area and we save the the results
                max=summe;
                rr[0]=isearch;
                rr[1]=(isearch+r>=m)?(isearch+r)%r:isearch+r;
                rr[2]=jsearch;
                rr[3]=(jsearch+c>=n)?(jsearch+c)%c:jsearch+c;
            }
            summe=0; //anyway we reset the summe to search accurate
        }
    }
    printf("Lifing in this area %d \n", max);
    return rr;
}
</code>
Comment: Could be simplified somewhat by doing: `for (int isearch = 0; isearch < (m - r); isearch++)` and the corresponding change on the other axis.  This might even solve your problem as these: `if (iks >= m) { iks %= r; }` don't seem right to me.
Comment: Size appears to be `r` by `c`
Comment: Too many nested `for` loops, are you sure there is no other way?
Comment: Also, the most populated area of what size?
Comment: If your displaying a rectangular area you can just go through and try every possible area. Thus making it take `O((n-n1)*(m-m1)*n1*m1)` time where your board is `n x m` and the rectangle `n1 x m1` in size. This may be suitable for your board/rectangle size.
Comment: My monitor displays 1920 x1080 pixels. Are you using a text console of say 80x25 characters?
Comment: I would say that I need 4 loops so that I thoroughly search, my idea was making every flied the upper left corner of field to display and see how much is populated in these field.
Comment: @Vane Yes I use a console to display this, also the window isn't always full with.
Comment: @Murphy that was my idea as well, I get every area with every field being the upper left corner, there for I use my 4 loops.
Comment: I can't solve your problem except to say: move the mountain and aim for a GUI presentation: 1 pixel per life.
Comment: @Hascall How would your method would found more populated in the right half of the matrix? Yeah I also suspect the mistake to be somewhere there, but the field can suspend the edges of the matrix and come in at line/coloumn 0 again.
Answer: There is an approximate solution that is O(n).
Split the board into x and y components and search for the most populous X and Y values. Then set those as the midpoints (adjusted for the edges) to be displayed.


Use SQL Select command as forumula in a table

Question: I have a SELECT command that I used to pull out a single value from my table.
My table (Table_1) is:

So for my new table I want to use the command
SELECT [AMOUNT]
FROM [TABLE_1]
WHERE [REDS] = 'Type1'

and so on for each of the types in my new table. So I wanted to use those SELECT commands but I guess for formulas for a column they can only be things like Average or Count or Sum. Is there a way to go about this using the SELECT commands?
Comment: Please explain more. Perhaps give example output.
Comment: @PaulDraper, Here is the error I received: - Unable to modify table.
Subqueries are not allowed in this context. Only scalar expressions are allowed.
Answer: You're using [REDS] as a field here (implied by the brackets).  I am not really sure what you are trying to do based on the rest of your lower question though.  Can you re-word your question at all?
I think what you need to do is pivot the data so that your values for [Key] are converted to fields, so it would look like
[Type] [Red] [Greens] [Oranges]
Type1  4     0        0
Type2  0     6        0
Type3  0     0        8

This data could then be put in a temporary table, which you can issue your query to aggregate the data as required.
I can help you with the pivot if this sounds like what you are trying to do?
Stuart
Comment: this is what I am trying to do. So my SELECT would be SELECT [RED] FROM [TABLE_1] WHERE [TYPE] = [TYPE1]. I needed to build a new table with a few of those SELECT commands to create the values. Hope this makes sense. New to using SQL this extensively so not really sure of proper wording or lingo. Thanks
Comment: You seem to have a syntax issue here.  [TYPE] is your fiend, and TYPE1 is data.  So you should use something like

SELECT [Key] FROM [TABLE_1] WHERE [TYPE] = 'TYPE1'.  This would give you 'REDs' as your result.

If this is still not what you are after, then can you please provide what you'd like to see as an example like you did with the input table?  Your request is a bit tough to understand I'm sorry.


Usando Concat para concatenar array de strings

Question: Estava vendo sobre strings e que elas são imutáveis e não pode ficar adicionando nelas em quantidade sob pena de ficar muito lento.
A recomendação é usar o StringBuilder. Mas também vi que existe uma versão do Concat() que aceita um array.
Não seria o caso de usá-lo?
Comment: Viu que eu usei o *method group* passando no `Time()`? http://pt.stackoverflow.com/q/189905/101. No caso o grupo só tem um método, mas não deixa de ser um grupo.
Comment: @bigown Entendi. Ficou bem claro, obrigado!
Answer: Provavelmente o que leu foi uma "boa prática" (que eu sou um crítico). Eu mesmo caio nessa besteira quando vou escrever porque nem sempre temos tempo para explicar todos os detalhes, mas se a pessoa aceita afirmação de alguém sem um contexto está apenas seguindo as tais das "boas práticas" e pode desde não ter o resultado esperado, como aquilo pode ser o oposto e se tornar uma péssima prática.
De fato o StringBuilder é recomendado quando tem que adicionar várias strings em uma só. Porém se esta operação for a única e não tem que fazer outras ações no laço então não precisa usar o StringBuilder, até porque eu acho que o Concat() usa um StringBuilder internamente, assim consegue um código one liner.
Mas vamos ter certeza e fazer um benchmark:
using System;
using static System.Console;
using System.Diagnostics;
using System.Text;

public class Program {
    const int Limit = 100000;
    static int[] dataInt = new int[Limit];
    static string[] dataString = new string[Limit];

    public static void Main() {
        for (int i = 0; i < Limit; i++) {
            dataInt[i] = i;
            dataString[i] = i.ToString();
        }
        Time(ConcatenationInt);
        Time(JunctionInt);
        Time(BuilderInt);
        Time(AdditionInt);
        Time(ConcatenationString);
        Time(JunctionString);
        Time(BuilderString);
        Time(AdditionString);
    }

    static void Time(Func<int> action) {
        var sw = Stopwatch.StartNew();
        int result = action();
        sw.Stop();
        WriteLine($"{result} - {sw.ElapsedTicks:000,000,000} - {action.Method.Name}");
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }

    static int AdditionInt() {
        var tmp = "";
        for (int i = 0; i < Limit; i++) tmp += dataInt[i];
        return tmp.Length;
    }

    static int AdditionString() {
        var tmp = "";
        for (int i = 0; i < Limit; i++) tmp += dataString[i];
        return tmp.Length;
    }

    static int ConcatenationInt() => string.Concat(dataInt).Length;

    static int ConcatenationString() => string.Concat(dataString).Length;

    static int JunctionInt() => string.Join("", dataInt).Length;

    static int JunctionString() => string.Join("", dataString).Length;

    static int BuilderInt() {
        var tmp = new StringBuilder();
        for (int i = 0; i < Limit; i++) tmp.Append(dataInt[i]);
        return tmp.Length;
    }

    static int BuilderString() {
        var tmp = new StringBuilder();
        for (int i = 0; i < Limit; i++) tmp.Append(dataString[i]);
        return tmp.Length;
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
O ideal é fazer o teste em sua máquina sem nada afetando a execução. Testes em ambientes compartilhados como esses usados acima não são válidos. Tentei minimizar o efeito do GC, mas não tem jeito neste ambiente de memória restrita.
A conclusão que dá para tirar é que em caso assim a concatenação é ótima, a junção também, e a construção da string é uma opção quase tão boa, só a adição individual é que é trágica.
O código do Concat()pode ser visto e ele faz algo até um pouco mais inteligente que o StringBuilder. No .NET Core.


Optimizing MySQL Query With MAX(), GROUP BY en ORDER BY

Question: Is there any way I can optimize this query to run faster.
Here is my query:
SELECT MAX(datum) AS maxdatum
       FROM forumtext
       GROUP BY id_forumtops
       ORDER BY maxdatum DESC
       LIMIT 10

id  select_type table       type    possible_keys   key     key_len ref     rows    Extra
1   SIMPLE      forumtext   index   NULL            datum_2 8       NULL    283037  Using index; Using temporary; Using filesort

I don't know how to improve the performance in this query further. I know that it is slow because I am using MAX() and that has no index. Is there something else I can do to prevent it from slowing down the query?
UPDATE
@Marcus, I have created a multi-column index on id_forumtops and datum, in that order. It isn't quite faster...
id  select_type table   type    possible_keys   key             key_len ref     rows    Extra
1   SIMPLE  forumtext   index   NULL            id_forumtops_2  8       NULL    283070  Using index; Using temporary; Using filesort

Comment: Here you can see some nice explanation http://dba.stackexchange.com/questions/48072/why-does-mysql-ignore-the-index-even-on-force-for-this-order-by
Answer: LIMIT isn't helping the performance much here because MySQL has to calculate the max values, then sort them, before it can apply the limit. Basically, you're only saving bandwidth.
Probably the only optimization you can do for the query is provide a covering index that speeds up the GROUP BY and reading the values. Create a multi-column index on id_forumtops and datum, in that order.
Comment: Thanks, but it isn't quite faster. I think I have to 'cheat' and create an additional field last_post_date in table forumtopics and update it when a new post is posted in table forumtext.
Comment: @Marianne, can you post the EXPLAIN result after adding the above index. Also, you might have to hint MySQL to use it.
Comment: I have posted the EXPLAIN above. I don't understand what you mean with 'to hint MySQL to use it'.


Distributivity of `subst`

Question: Suppose I have a transitive relation ~with two endomaps f and g.
Assuming f and g agree everywhere and f a ~ f b ~ f c
then there are two ways to show g a ~ g c:
transform each f into a g by the given equality then apply
transitivity,
or apply transitivity then transform along the equality.
Are the resulting proofs identical? Apparently so,
open import Relation.Binary.PropositionalEquality

postulate A : Set
postulate _~_  : A → A → Set
postulate _⟨~~⟩_ : ∀{a b c} → a ~ b → b ~ c → a ~ c
postulate f g : A → A

subst-dist : ∀{a b c}{ef : f a ~ f b}{psf : f b ~ f c} → (eq : ∀ {z} → f z ≡ g z)
     →
         subst₂ _~_ eq eq ef ⟨~~⟩ subst₂ _~_ eq eq psf
       ≡ subst₂ _~_ eq eq (ef ⟨~~⟩ psf)

subst-dist {a} {b} {c} {ef} {psf} eq rewrite eq {a} | eq {b} | eq {c} = refl

I just recently learned about the rewrite keyword and thought it might help here; apparently it does. However, I honestly do not understand what is going on here. I've used rewrite other times, with comprehension. However, all these substs are confusing me.
I'd like to know

if is there a simplier way to obtain subst-dist? Maybe something similar in the libraries?
what is going on with this particular usage of rewrite
an alternate proof of subst-dist without using rewrite (most important)
is there another way to obtain g a ~ g c without using subst?
what are some of the downsides of using heterogeneous equality, it doesn't seem like most people are fond of it. (also important)

Any help is appreciated.
Answer: rewrite is just a sugared with, which is just sugared "top-level" pattern matching. See in Agda's documentation.

what are some of the downsides of using heterogeneous equality, it
  doesn't seem like most people are fond of it. (also important)

This is OK
types-equal : ∀ {α} {A B : Set α} {x : A} {y : B} -> x ≅ y -> A ≡ B
types-equal refl = refl

this is OK as well
A-is-Bool : {A : Set} {x : A} -> x ≅ true -> A ≡ Bool
A-is-Bool refl = refl

This is an error
fail : ∀ {n m} {i : Fin n} {j : Fin m} -> i ≅ j -> n ≡ m
fail refl = {!!}

-- n != m of type ℕ
-- when checking that the pattern refl has type i ≅ j

because Fin n ≡ Fin m doesn't immediately imply n ≡ m (you can make it so by enabling --injective-type-constructors, but that makes Agda anti-classical) (Fin n ≡ Fin m -> n ≡ m is provable though).
Originally Agda permitted to pattern match on x ≅ y when x and y have non-unifiable types, but that allows to write weird things like (quoting from this thread)
  P : Set -> Set
  P S = Σ S (\s → s ≅ true)

  pbool : P Bool
  pbool = true , refl

  ¬pfin : ¬ P (Fin 2)
  ¬pfin ( zero , () )
  ¬pfin ( suc zero , () )
  ¬pfin ( suc (suc ()) , () )

  tada : ¬ (Bool ≡ Fin 2)
  tada eq = ⊥-elim ( ¬pfin (subst (\ S → P S) eq pbool ) )

Saizan    or maybe it's just ignoring the types and comparing the constructor names?
pigworker Saizan: that's exactly what I think is happening
Andread Abel:

If I slighly modify the code, I can prove Bool unequal Bool2, where true2, false2 : Bool2 (see file ..22.agda)
However, if I rename the constructors to true, false : Bool2, then suddenly I cannot prove that Bool is unequal to Bool2 anymore (see
  other file). So, at the moment Agda2 compares apples and oranges in
  certain situations. ;-)

So in order to pattern match on i ≅ j, where i : Fin n, j : Fin m, you first need to unify n with m
OK : ∀ {n m} {i : Fin n} {j : Fin m} -> n ≡ m -> i ≅ j -> ...
OK refl refl = ...

That's the main drawback of heteregeneous equality: you need to provide proofs of equality of indices everywhere. Usual cong and subst are non-indexed, so you also have to provide indexed versions of them (or use even more annoying cong₂ and subst₂).
There is no such problem with "heteroindexed" (I don't know if it has a proper name) equality
data [_]_≅_ {ι α} {I : Set ι} {i} (A : I -> Set α) (x : A i) : ∀ {j} -> A j -> Set where
  refl : [ A ] x ≅ x

e.g.
OK : ∀ {n m} {i : Fin n} {j : Fin m} -> [ Fin ] i ≅ j -> n ≡ m
OK refl = refl

More generally, whenever you have x : A i, y : A j, p : [ A ] x ≅ y, you can pattern match on p and j will be unified with i, so you don't need to carry an additional proof of n ≡ m.
Heterogeneous equality, as it presented in Agda, is also inconsistent with the univalence axiom.
EDIT
Pattern matching on x : A, y : B, x ≅ y is equal to pattern matching on A ≡ B and then changing every y in a context to x. So when you write
fail : ∀ {n m} {i : Fin n} {j : Fin m} -> i ≅ j -> n ≡ m
fail refl = {!!}

it's the same as
fail' : ∀ {n m} {i : Fin n} {j : Fin m} -> Fin n ≡ Fin m -> i ≅ j -> n ≡ m
fail' refl refl = {!!}

but you can't pattern match on Fin n ≡ Fin m
fail-coerce : ∀ {n m} -> Fin n ≡ Fin m -> Fin n -> Fin m
fail-coerce refl = {!!}

-- n != m of type ℕ
-- when checking that the pattern refl has type Fin n ≡ Fin m

like you cannot pattern match on
fail'' : ∀ {n m} -> Nat.pred n ≡ Nat.pred m -> n ≡ m
fail'' refl = {!!}

-- n != m of type ℕ
-- when checking that the pattern refl has type Nat.pred n ≡ Nat.pred m

In general
f-inj : ∀ {n m} -> f n ≡ f m -> ...
f-inj refl = ...

works only if f is obviously injective. I.e. if f is a series of constructors (e.g. suc (suc n) ≡ suc (suc m)) or computes to it (e.g. 2 + n ≡ 2 + m). Type constructors (which Fin is) are not injective because that would make Agda anti-classical, so you cannot pattern on Fin n ≡ Fin m unless you enable --injective-type-constructors.
Indices unify for
data [_]_≅_ {ι α} {I : Set ι} {i} (A : I -> Set α) (x : A i) : ∀ {j} -> A j -> Set where
  refl : [ A ] x ≅ x

because you don't try to unify A i with A j, but instead explicitly carry indices in the type of [_]_≅_, which make them available for unification. When indices are unified, both types become the same A i and it's possible to proceed like with propositional equality.
EDIT
One another problem with heterogeneous equality is that it's not fully heterogeneous: in x : A, y : B, x ≅ y A and B must be in the same universe. The treatment of universe levels in data definitions has been changed recently and now we can define fully heterogeneous equality:
data _≅_ {α} {A : Set α} (x : A) : ∀ {β} {B : Set β} -> B -> Set where
  refl : x ≅ x

But this doesn't work
levels-equal : ∀ {α β} -> Set α ≅ Set β -> α ≅ β
levels-equal refl = refl

-- Refuse to solve heterogeneous constraint Set α : Set (suc α) =?=
-- Set β : Set (suc β)

because Agda doesn't think suc is injective
suc-inj : {α β : Level} -> suc α ≅ suc β -> α ≅ β
suc-inj refl = refl

-- α != β of type Level
-- when checking that the pattern refl has type suc α ≅ suc β

If we postulate it, then we can prove levels-equal:
hcong : ∀ {α β δ} {A : Set α} {B : Set β} {D : Set δ} {x : A} {y : B}
      -> (f : ∀ {γ} {C : Set γ} -> C -> D) -> x ≅ y -> f x ≅ f y
hcong f refl = refl

levelOf : ∀ {α} {A : Set α} -> A -> Level
levelOf {α} _ = α

postulate
  suc-inj : {α β : Level} -> suc α ≅ suc β -> α ≅ β

levels-equal : ∀ {α β} -> Set α ≅ Set β -> α ≅ β
levels-equal p = suc-inj (suc-inj (hcong levelOf p))

Comment: @Musa Al-hassy, there is Ulf Norell's [thesis](http://www.cse.chalmers.se/~ulfn/papers/thesis.pdf), but it's from 2007 and I doubt it describes the current machinery. There are papers about dynamic pattern unification (like this [one](http://adam.gundry.co.uk/pub/pattern-unify/pattern-unification-2012-07-10.pdf)), but they are more for language implementators rather than users. I don't know any manual that would simply describe what you can and what you can't do. Also, I edited the answer.
Comment: Thanks for the speedy reply! Why is `tada` considered 'weird'?

Also, `fail` and `OK` seem nearly identical and I'm not sure why carrying the index-function `A` unifies the indices. I mean with hetero equality we know the type of the arguments since it is implicit, why is that not sufficient for unifying indices?
Comment: @Musa Al-hassy, `tada` is weird, because it compares constructor names of different types. That would work in LISP or PHP, but not in a formal language. If you have `C : D1` and `C : D2` it doesn't make any sense to compare one `C` with the other — those are different things even if they look similar. I edited the answer.
Comment: woah; I really appreciate your replies. I've never given much thought to how things are unified or rewritten --I mostly play with Agda for math's sake, not programming, and seldom run into such errors. Could you link me to any good reads on learning more about how Agda unifies things and rewrite them. Thanks!
Comment: Thank-you for your help :-)

Distributivity of `subst`


Should I input 2 digit numbers in TINYINT?

Question: I need a column that can store values from -1 (negative 1) to +15 (positive 15).
I am using a TINYINT(2) column at the moment and it works just fine.
I need to know if this is ideal and safe to use because I read online that TINYINT should ONLY be used for binary value such as 1 and 0.
Comment: You are good. A signed `TINYINT` is perfect for this usage, if your values are in the range -128 to +127.
Comment: BIT is the data type that can only store 0 and 1. You are fine using TINYINT for storing a number -1 to +15. As has been stated multiple times TINYINT can store between 0 and 255 OR -128 and 127
Comment: Where did you read that?
Comment: Beware of learning rules along the line of "X should ONLY be used for Y". If that didn't come with a) reasons and b) constraints on when that rule should be followed/can be ignored, it's probably bad advice. If it did come with such, you need to remember/reference those and determine whether this rule actually applies to your situation.
Comment: What should the Length/Value be instead of 2? If I remove it and save, it automatically sets to 4
Answer: MySQL TINYINT has a storage of 1 byte.
Unsigned value in range 0 to 255 or signed value of range -128 to 127 can be stored.
Also note that 2 in TINYINT(2) does not limit the length of your value to 2 digits. more info in this link - What is the size of column of int(11) in mysql in bytes?
Comment: display width 4 is the default for mysql TINYINT, and i suggest you leave it as it is. In majority of cases display width will not matter. You can read more on this in the link i shared above. As far as limiting the length is concerned, easy way is to have this logic in your application(this is how its mostly done) or use mysql check constraint in your db.
Comment: Then what should be the ideal Length/Value of TINYINT if not 2, for my specific requirement?
Answer: TINYINT will store your value perfectly fine; however it will not guarantee that it will be correct (exactly in that range). Please note that (2) is just related to padding when selecting via the command line and it has nothing to do with the limit. Normally you do not need it at all. TINYINT (signed) will store values from -128 to 127 regardless if you add (n) at the end of it or not.
If you want to make sure that the value is always exactly in the range between -1 and 15, you have two options:

Using CHECK constraint over the existing TINYINT (recommended solution):
CREATE TABLE tiexample(
  val TINYINT NOT NULL,
  CONSTRAINT val_range CHECK(val>=-1 AND val<=15)
);

INSERT INTO tiexample(val) VALUES(122);
ERROR 4025 (23000): CONSTRAINT `val_range` failed for `test`.`tiexample`

INSERT INTO tiexample(val) VALUES(12);
Query OK, 1 row affected (0.001 sec)

Listing all values as ENUM:
CREATE TABLE tiexample(
   val ENUM("-1","0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15") NOT NULL,
   CONSTRAINT val_range CHECK(val<>"")
);

INSERT INTO tiexample(val) VALUES("122");
ERROR 4025 (23000): CONSTRAINT `val_range` failed for `test`.`tiexample`

INSERT INTO tiexample(val) VALUES("12");
Query OK, 1 row affected (0.001 sec)

Note that using this method you must insert the values with quotes (like "8", not just 8). Also first it may seem strange that we use CHECK constraint here but it is needed because by default inserting invalid value on ENUM field will insert an empty string in the table (not NULL - it's an empty string). You can get around that issue and skip the CHECK constraint if you use this sql mode before inserting into the table:
SET SQL_MODE = 'Traditional';

Personally I would not struggle with the ENUM type. It is more suitable for different use-cases.

Footnote: CHECK constraints are available and working only in MySQL MySQL 8.0.16+ and MariaDB 10.2.1+. Prior versions accept the constraint but never use it (it will ignore them).
Comment: You do not understand what the (2) is doing. It is a display width setting. It does not control the value ranges that the column can store - therefore TinyINT(2), TINYINT(4) or just TINYINT is all storing exactly the same data. What is does is just a formatting for how the table is displayed in the console when you execute the query. For practical uses, it is not important at all.
Comment: Then what should be the ideal Length/Value of TINYINT if not 2, for my specific requirement?
Comment: Just use TINYINT. There is no need to add (2) after it.
Comment: when I remove the length/value, it automatically sets it to 4 after saving.