Is there a quicker argument from the HBL derivability conditions to the equivalence of fixed points of $\neg\Box$ to $\mathsf{Con}$?

Question: I'm just about to send off the final, final corrected PDF of the second edition of my Gödel book, and the following (neurotic?!?) question occurs to me.
In discussing matters around and about the Second Incompleteness Theorem, I use (of course) the three HBL derivability conditions governing the provability predicate for $T$
C1. If $T \vdash \varphi$, then $T \vdash \Box\varphi$,
C2. $T \vdash \Box\mathsf{(\varphi \to \psi)} \to (\Box\varphi \to \Box\psi)$,
C3. $T \vdash \Box\varphi \to \Box\Box\varphi$,
I give the following argument for the theorem that if $\gamma$ is fixed point for $\neg\Box$ in $T$ it is provably equivalent to $\neg\Box\bot$. [If you use "Gödel sentence", as some do, to mean a fixed point of $\neg\Box$, then this shows that, at least relative to a choice of provability predicate, Gödel sentences are provably equivalent.]

$T \vdash \gamma \equiv \neg\Box\gamma$
$T \vdash \gamma \to (\Box\gamma \to \bot)\quad\quad\text{From
    1, by logic}$
$T \vdash  \Box(\gamma \to (\Box\gamma \to \bot))\quad\quad\text{From 2 by C1}$
$T \vdash  \Box\gamma \to \Box(\Box\gamma \to
    \bot))\quad\quad\text{From 3, by  C2}$
$T \vdash  \Box\gamma \to (\Box\Box\gamma \to
    \Box\bot)\quad\quad \text{From 4, by  C2}$
$T \vdash \Box\gamma \to \Box\Box\gamma\quad\quad \text{From C3}$
$T \vdash \Box\gamma \to  \Box\bot\quad\quad \text{From 5 and 6}$
$T \vdash \bot \to \gamma\quad\quad\text{Logic}$
$T \vdash \Box(\bot \to \gamma)\quad\quad \text{From 8, by C1}$
$T \vdash \Box\bot \to \Box\gamma \quad\quad \text{From 9, by C2}$
$T \vdash \Box\gamma \equiv \Box\bot \quad\quad \text{From 7 and
     10}$
$T \vdash \gamma \equiv \neg\Box\bot \quad\quad \text{From 1 and
     11}$

Question/problem: This is the proof that was in the first edition, and no one complained -- but is this the shortest proof? Or have I gone round the houses in an inelegant way?
Comment: I have no complaints! (And I suspect the lack of complaints/negative feedback is a fair indicator of its quality.) I'm not in a position to know whether it's the shortest proof, but it seems rather apparent that it is *not in any sense of the term* inelegant!
Answer: It's pretty elegant from my computer-science viewpoint:
Viewed through the Curry-Howard correspondence, the HBL conditions correspond to basic typed metaprogramming, where $\Box \tau$ is the type of closed fragments of program text of type $\tau$. If for readability we write $\Box \tau$ as $[\tau]$ and the arrow associates to the right, the conditions are
C1. If $M$ is a closed term of type $\tau$, then $\ulcorner M\urcorner$ is a term of type $[\tau]$.
C2. For every $\alpha$ and $\beta$ there's a term $\mathtt{App}_{\alpha,\beta}$ of type $[\alpha\to\beta]\to[\alpha]\to[\beta]$.
C3. For every $\alpha$ there's a term $\mathtt{Lift}_{[\alpha]}$ of type $[\alpha]\to\bigl[[\alpha]\bigr]$.
Conditions C1 and C2 allow us to form quasiquotations:
$$ \ulcorner \cdots \llcorner M \lrcorner \cdots \urcorner
\qquad\text{means}\qquad \mathtt{App}\;\ulcorner \lambda x. \cdots x \cdots \urcorner\; \ulcorner M \urcorner$$
In your proof given $\gamma \equiv \Box\gamma\to\bot$, you're assuming a term $\mathtt{p}: \gamma\to[\gamma]\to\bot$. You also have, from logic, $\mathtt{Explode}:\bot\to\alpha$ for all $\alpha$.
Your proof now corresponds to constructing, (with some $\beta\eta$-redexes from the quasiquote translation already reduced):
$$\lambda x.\ulcorner \mathtt p\;\llcorner x\lrcorner\;\llcorner \mathtt{Lift}\;x\lrcorner\urcorner ~:~ [\gamma]\to[\bot] $$
$$ \lambda x:\ulcorner \mathtt{Explode}\;\llcorner x \lrcorner\urcorner ~:~ [\bot]\to[\gamma] $$
It is difficult to see how that could be done shorter. Essentially all of what you do appears to be necessary set-up for being able to use $\mathtt{p}$ for anything, given that $\mathtt{Lift}$ only works when you already have one $\Box$.
I toyed a bit with starting from $\delta\equiv\Box\neg\delta$ instead, but that seems to lead nowhere.

By the way, I can't resist pointing out that the usually fairly impenetrable standard modal proof of Löb's theorem becomes very simple and beautiful through this correspondence. The premise of the theorem is that we know a term $\mathtt{eval}$ of type $[\tau]\to\tau$ (where the name "eval" is suggestive but not quite trustworthy because all we really know is that $\mathtt{eval}$ will produce some value of type $\tau$, not necessarily one related to the input to $\mathtt{eval}$).
Löb's theorem (and the standard proof) then simply observes that the type $\tau$ is inhabited by a program that goes:

Produce a copy of my own source code, by the fixpoint property.
Apply $\mathtt{eval}$ to that source code and output its result.
Comment: I should adopt this quasiquotation notation!
Comment: @HenningMaklholm  "Pretty elegant" is good enough for me, thanks! :) Your comments are very interesting, and remind me that I really ought to get more up to speed on viewing things through Curry-Howard spectacles. If you were going to recommend one reasonably accessible book to look at for an illuminating treatment, what would you choose?
Comment: (I should add that I know of the Morten Sørensen and Paweł Urzyczyn book, and have been meaning to read it for a while -- or is there a better place to start?)
Comment: @PeterSmith: I haven't read the final version of the Sørensen-Uyzyczyn book, but I was in the graduate course the earliest (I think) draft of it was written for, and that was a really good course. I know nothing else I'd recommend over it. (I can't give any a reference that applies C-H specifically to metaprogramming, quasiquotes and the Hilbert-Bernays conditions -- I noticed by myself that they map to each other, but am probably not the first to do so. On the other hand, typed homogeneously staged metaprogramming is something of a specialty subject even within CS, so perhaps...).


Log return of sp500. Stationary vs strictly stationary

Question: By first glance of this time series; will you say it is stationary?
I can easily see some "seasonality" which means that this is not strictly stationary since the distribution will not be the same; higher variance around 1987 and 2008. But is it weakly stationary?
The expected value at any timepoint will be zero, so I will say yes it is weakly stationary. Am I right?
Comment: I don't think "seasonality" is the right term for what I think you're referring to (the patches of low and high variance). Also, how do get the expected value being zero (which implies a return of 1 on the original scale, which I presume means no actual return from holding those shares, which seems unlikely) - just by eyeballing it?  For any of these things I think you need additional analysis not just this chart (although it is a start).
Comment: Constant mean and constant variance (i.e. mean and variance that do not vary with time) are the requirements to define a series as weakly stationary.  However, as @Peter points out, you need to run some statistical tests that determine whether or not this series is, in fact, weakly stationary.  One critical assumption of weakly stationary series is that their ACF's should rapidly tend towards zero.
Comment: One way to start with checking the assumption would be a unit root test (like Dickey Fuller), whose null is that the data are not weakly stationary and assesses the fit of the data against random walk models (since random walk models assume unit root).  If you can reject the D-F null, then you may be able to apply some AR/MA/ARMA models to the data.  You can use appropriate identification techniques for these model orders that depend on your model of choice (PACF for AR, ACF for MA, EACF for ARMA).
Comment: Also, constant mean across time does not have to mean zero mean across time; although it could sometimes be the case.  t-tests of the sample mean are not going to help you validate stationarity, because they are not telling you whether the mean is changing with time, just the expected value of the data across all time.
Answer: The commenters are correct in saying that various tests allow you to check for stationarity or not when in doubt.
For anyone looking into this question, there's an enlightening discussion around your cross-post in the Quantitative Finance section.
And I'll repeat my QF answer here too:
————————————
They probably can be modelled using a weakly stationary process.
To quote Section 1.2.1 from these lecture notes:

[Asset] returns [...] typically fluctuate around a constant level,
  suggesting a constant mean over time. [...] In fact most asset returns
  can be modeled as a stochastic process with at least time-invariant
  first two moments.

Mathematically, a time series $\{ Y_t \}$ is weakly stationary if, for all time indices $k,s,t$

$\text{E}[Y_s] = E[Y_t]$, i.e. the first moment (the mean) is constant
$\text{Cov}[Y_t, Y_{t+k}] = \text{Cov}[Y_s,Y_{s+k}]$, i.e. the second moment is constant

From a visual inspection of your series of asset returns,

the mean/first moment does indeed appear to be constant
the series clearly exhibits the phenomenon of volatility clustering, implying that it has a non-constant "conditional volatility" / exhibits heteroskedasticity - however we cannot make any visual judgements as to the behaviour of the unconditional volatility.


input type button - label vs value

Question: I think that the normal behavior of a button like the one below is that the value attribute serves as a label as well:
<input type="submit" name="submitButton" value="DeleteAnswer22" />

Is it possible to have separate attributes for display label and value?
Comment: Possible duplicate of [HTML Submit-button: Different value / button-text?](http://stackoverflow.com/questions/4171664/html-submit-button-different-value-button-text)
Answer: Use the HTML Button element, with type submit, instead:
<button type="submit" name="submitButton" value="DeleteAnswer22">Delete Answer 22</button>

This will result in a submit button that sends the value DeleteAnswer22 but displays "Delete Answer 22".
Comment: This solution may have problems with some browsers. see https://stackoverflow.com/questions/13134631/button-text-different-than-value-submitted-in-query-string
Comment: @MuratTutumlu do you know if these problems are still relevant? The information that post refers to no longer exists.

input type button - label vs value


I need to make cross domain requests server side

Question: I have 2 different servers of mine.
I am using one server for managing all the data, and the system.
The other server is just for giving user points.
I need to to make a call in my first server on server side in php,
to the second server, and to get response from the server.
Example in PHP:
<code>$response = getDataFromOtherServer("http://otherServer.com");
// manipulate response
</code>
Comment: do you have access to both servers?
Answer: you could do something like this
<code>$response = fopen("http://otherServer.com?var1=some&var2=thing","r");
</code>
Answer: You can switch between getting data from 2 servers by changing the connection to those servers like for host 1

mysql_connect('host1','username','password')

execute data for host1 and save. Now when you need data from host2 connect to that and manipulate your data
Answer: use REST API from Phil Sturgeon ->
REST SERVER:
https://github.com/philsturgeon/codeigniter-restserver
REST CLIENT:
https://github.com/philsturgeon/codeigniter-restclient
Answer: Assuming that you have a web service on your data server, you can use CURL to make HTTP requests to that service. http://php.net/manual/en/book.curl.php


Linux out of memory on VPS

Question: On my VPS (CentOS) 4GB ram (2 + 2 dynamically assigned when needed) and i have tomcat running with following options JAVA_OPTS="-Xms256m -Xmx2048m -XX:MaxPermSize=256m".
Now when i try to start other java based app (like hudson server) i get following error:

 There is insufficient memory for the Java Runtime Environment to continue.
 Native memory allocation (malloc) failed to allocate 664080 bytes for Chunk::new
 An error report file with more information is saved as:
 /server/hs_err_pid26476.log

It seems as if system could not allocate 650KB of memory, but it should have like 1.2 GB
 free.

free -m
             total       used       free     shared    buffers     cached
Mem:          4096       2816       1279          0          0          0
-/+ buffers/cache:       2816       1279
Swap:            0          0          0

I found somewhere that i should also check /proc/user_beancounters, which shows failcnt on privvmpages. I have no clue what that means (does the provider give 4GB of memory as he is supposed to? or is he cheating?)

# cat /proc/user_beancounters
Version: 2.5
       uid  resource                     held              maxheld              barrier                limit              failcnt
 70692271:  kmemsize                 15371949             15388993             41943040             46137344                    0
            lockedpages                     0                    0                 1024                 1024                    0
            privvmpages                720030               720189              1048576              1048576                 9604
            shmpages                     9001                 9001                65536                65536                    0
            dummy                           0                    0  9223372036854775807  9223372036854775807                    0
            numproc                       109                  109                  256                  256                    0
            physpages                  173670               173780  9223372036854775807  9223372036854775807                    0
            vmguarpages                     0                    0               262144               262144                    0
            oomguarpages               174598               174708  9223372036854775807               262144                    0
            numtcpsock                     30                   30                 1440                 1440                    0
            numflock                       14                   14                  752                  826                    0
            numpty                          1                    1                   64                   64                    0
            numsiginfo                      0                    0                 1024                 1024                    0
            tcpsndbuf                  601840               601840              6881280             10813440                    0
            tcprcvbuf                  491520               491520              6881280             10813440                    0
            othersockbuf               174600               174600              4504320              8388608                    0
            dgramrcvbuf                     0                    0              1048576              1153432                    0
            numothersock                  117                  118                 1440                 1440                    0
            dcachesize                      0                    0              7340032              8074035                    0
            numfile                      3516                 3516                16384                16384                    0
            dummy                           0                    0                    0                    0                    0
            dummy                           0                    0                    0                    0                    0
            dummy                           0                    0                    0                    0                    0
            numiptent                      18                   18                  400                  405                    0
Comment: Don't use OpenVZ. Java doesn't play well with OpenVZ.
Comment: You're confusing physical memory and virtual memory. You have 1.2GB of *physical* memory free and the process was unable to allocate 650KB of *virtual* memory. These things have very, very little to do with each other.
Answer: OpenVZ providers typically sell RAM capacity of their virtual machines as two numbers: "guaranteed" and "burst" RAM. You are supposed to always get the "guaranteed" amount of RAM, and may use up to the "burst" amount if host resources permit. For example a VPS might be sold as "512MiB guaranteed 1GiB burst RAM".
You should always have a successful memory allocation below the "guaranteed" amount, but memory allocations may sometimes fail above that amount, if other virtual machines on the host are consuming RAM as well, or if the provider has oversubscribed the machine (almost always).
To learn what these numbers are, look at the barrier for vmguarpages which represents the "guaranteed" RAM, and the limit for privvmpages which represents the "burst" RAM. Each of these numbers is expressed in a number of 4KiB pages.
So in your case, we can see that you have 1GiB (262144) "guaranteed" RAM, and 4GiB (1048576) "burst" RAM. (If these aren't the numbers you were promised, you need to have a very unpleasant talk with your VPS provider.)
Since you are already well over 2GiB used in the VM, your memory allocation may fail, because it is above the "guaranteed" amount.
Answer: Your provider very likely only guarantees 2 GB of memory and two more if available, that is, if the other costumers currently need less (which rarely will be the case). You would hence be better off to assume a maximum of 2 rather than 4 GB.
The failcount on privvmpages shows how often your system failed to allocate some memory (roughly speaking).

Linux out of memory on VPS


Problema para "Salvar imagem como" php

Question: Tenho um código que gera uma assinatura eletrônica porém quando o usuário clica com o botão direito na imagem gerada para "Salvar imagem como" o nome da imagem vem como padrão o nome_da_pagina.php.png.
Como eu faço pra tirar o .php do nome do arquivo a ser salvo?
Pois os usuários leigos não estão sabendo renomear o nome do arquivo pra tirar a extensão .php
<?php
header("Content-type: image/png");

$image = imagecreatefrompng("assinatura.png");
$imageCel = imagecreatefrompng("cel.png");
$imageWhats = imagecreatefrompng("whats.png");
$imgPira = imagecreatefrompng("piracicaba.png");
$imgBotucatu = imagecreatefrompng("botucatu.png");
$imgLencois = imagecreatefrompng("lencois.png");
$imgJau = imagecreatefrompng("jau.png");

if (!empty ($_POST["name"])) {
    $fotinha = $_POST["name"];
    $imgFotinha = imagecreatefrompng("upload/".$fotinha.".png");
}

$tileColor = imagecolorallocate($image, 0, 63, 114);
$gray = imagecolorallocate($image, 100, 100, 100);

$nome = $_POST["nome"];
$funcao = $_POST["funcao"];
$telefone = $_POST["telefone"];
$email = $_POST["email"];
$cel = $_POST["cel"];

if (!empty($_POST["cel"])) {
    imagecopy($image, $imageCel, 445, 17, 0, 0, 12, 16);
    imagettftext($image, 10, 0, 460, 30, $tileColor, "C:\\xampp\\htdocs\\assinatura\\fonts\\Helvetica\\Helvetica-Normal.ttf", $cel);
    if (isset($_POST["whats"])) {
        imagecopy($image, $imageWhats, 560, 17, 0, 0, 15, 16);
    }
}

if (!empty ($_POST["name"])) {
    imagecopy($image, $imgFotinha, 10, 16, 0, 0, 100, 100);
}

imagettftext($image, 12, 0, 110, 33, $tileColor, "C:\\xampp\\htdocs\\assinatura\\fonts\\Helvetica\\Helvetica Bold.ttf", $nome);
imagettftext($image, 10, 0, 120, 50, $tileColor, "C:\\xampp\\htdocs\\assinatura\\fonts\\Helvetica\\Helvetica-Normal.ttf", $funcao);

imagettftext($image, 10, 0, 332, 30, $tileColor, "C:\\xampp\\htdocs\\assinatura\\fonts\\Helvetica\\Helvetica-Normal.ttf", $telefone);
imagettftext($image, 11, 0, 334, 56, $tileColor, "C:\\xampp\\htdocs\\assinatura\\fonts\\Helvetica\\Helvetica-Normal.ttf", $email);

$filial = $_POST["filial"];

if ($filial == "piracicaba") {
    imagecopy($image, $imgPira, 310, 75, 0, 0, 324, 11);
}

if ($filial == "botucatu") {
    imagecopy($image, $imgBotucatu, 310, 75, 0, 0, 324, 11);
}

if ($filial == "lencois") {
    imagecopy($image, $imgLencois, 310, 75, 0, 0, 324, 11);
}

if ($filial == "jau") {
    imagecopy($image, $imgJau, 310, 75, 0, 0, 324, 11);
}

imagepng($image);
imagedestroy($image);

?>

Comment: Esse é um exemplo simples de como fazer https://www.taniarascia.com/the-simplest-php-router . Tem formas mas completas e complexas, mas inicialmente isso deve resolver
Comment: Isso acontece pois você está gerando uma imagem a partir de uma página php, você pode definir uma roa para uma imagem à parte ou fazer um botão **baixar imagem**
Comment: como posso fazer esta rota?
Answer: Basta alterar o header Content-disposition.
Cabeçalho
De acordo com RFC6266, "o campo de cabeçalho Content-Disposition é usado para transmitir informações adicionais sobre como processar a carga útil da resposta e também pode ser usado para anexar metadados adicionais, como o nome do arquivo a ser usado ao salvar a carga útil da resposta localmente."
Esse cabeçalho possui dois campos: disposition-type e filename.
Disposition Type
Se o tipo de disposição corresponder a "attachment", isso indica que o destinatário deve solicitar ao usuário que salve a resposta localmente, em vez de processá-la normalmente (conforme seu tipo de mídia).
Por outro lado, se corresponder a "inline", isso implica em processamento padrão.
Filename
Este campo fornece informações o nome do arquivo, que poderá ser baixado pelo usuário.
Caso o valor do campo disposition-type seja inline, o valor deste campo poderá ser utilizado na janela Salvar como….
header("Content-type: image/png");
header('Content-disposition: inline; filename="psr.png"');

Caso o valor do campo disposition-type seja attachment, o navegador poderá forçar o download do conteúdo conforme o content-type e o filename indicado nos cabeçalhos de resposta.
header("Content-type: image/png");
header('Content-disposition: attachment; filename="psr_f.png"');

Comment: perfeito. obrigado

Problema para "Salvar imagem como" php


Why is a penalty not given if a goal comes right after the foul?

Question: In the game between Spain and Russia, in the World Cup 2018, one Russian defender (Ignashevich) tackled a Spanish player (Ramos) inside the Russian penalty area (video here or here). This was technically a foul, and thus a penalty for Spain. However, right after the tackle, the ball hit Ignashevich and entered the Russian goal. Thus, it was an own goal.
Now, in terms of timing, the foul happened before the goal. Thus, why is a penalty not given? Why give the goal to Spain, instead of giving them the chance to score, but without 100% probability of doing so? Surely, if the time difference between the foul and the own-goal had been longer, the referee would have given the penalty. But if so, isn't this just an arbitrary application of the rules?
Update (based on comment asking for more info):
Why would the foul be given before the goal awarded? Because technically, the foul happened first. You can think of the strict rule being something like "IF foul, THEN penalty", whereas in practice it seems more like "IF foul AND goal AND goal-foul > epsilon, then penalty". Thus, only if the time difference is long enough would the penalty be given. But if epsilon is small enough (so the goal happens just after the foul), then the goal is given. This seems to me arbitrary. Sure, there are technical limitations involved in the referee (e.g. when epsilon is too small, the referee has little capacity to react in time). But the current approach seems to be based on assumptions by players that, if a goal happens after a penalty foul, it will be awarded. Maybe the VAR can precisely help to reduce the arbitrariness of rules like this.
Comment: Just a query regarding the premise of this question - are you suggesting that it would be somehow preferable to take away a goal and replace it with a ~70% chance at scoring a goal? I might be able to provide an answer, but I need more information as to why this question was asked, as it isn't entirely clear in its current form.
Comment: @studro I believe they are proposing to count the goal and then award the penalty. I think something like that is done in basketball.
Comment: @luchnacho - Ahh, right, I understand. I think the question is based on failing to include the advantage rule into the equation. The correct logic both in theory and (in practice) for all offences committed when the ball is in play is IF offence committed THEN (IF appropriate to play advantage THEN play advantage OTHERWISE penalise the offence immediately). I think gdrt's answer is the most correct based on this.
Comment: @luchonacho `What happens next - including how long it happens - should not make a single difference to the decision!` You have to look at the **intent of the Law**, not the algorithm. The point is to punish the offending team. Often, a team would benefit more from the punishment that the current state of the game. They shouldn't be able to benefit from a foul. Hence, the "advantage rule". Not applying it would lead to the offended team being *punished* after receiving a foul, adding insult to injury. It could make sense, though, to add the foul consequence AFTER the goal, like basketball does
Comment: @luchonacho Wikipedia has an article on [free throws](https://en.wikipedia.org/wiki/Free_throw) in basketball. Note that a successful free throw scores less than a field goal and that, if a goal was scored, only one free throw is awarded to the fouled player.
Comment: @luchonacho There's also a difference in scoring between basketball and football/soccer.  A free throw in an NBA game is worth 1 point of the 90-120 points that a team will score in a game.  An extra PK or set piece would potentially put the game out of reach.
Comment: @studro Yes, because technically, the foul happened first. You can think of the strict rule being something like "IF foul, THEN penalty", whereas in practice it seems more like "IF foul AND goal AND goal-foul > epsilon, then penalty". Thus, only if the time difference is long enough the penalty would have been given. But if epsilon is small enough (so goal happens just after the foul), then goal is given. This seems to me arbitrary. Sure, there are technical capabilities involved in the referee, but isn't it the point of VAR precisely to help reduce the arbitrariness of rules. See question.
Comment: @Haem Interesting! Have you a reference to this? I would like to read more about it.
Comment: Your logic formula could be correct if you consider that _epsilon = time for ref to blow the whistle_. The time between the foul being committed and the ball crossing the line was of the order of a second. Well inside the reaction-time of the referee.
Comment: @OscarBravo But the point is that the matter should not depend on epsilon, i.e. on human technical skills. If foul in penalty area, then penalty; as simple as that. **What happens next - including how long it happens - should not make a single difference to the decision!** (Well, actually, here is there the advantage rule enters into the argument).
Answer: This is due to the advantage rule, From Laws of the Game - Law 5: The Referee - 3. Powers and Duties:

The referee allows play to continue when an offence occurs and the
  non-offending team will benefit from the advantage and penalises the
  offence if the anticipated advantage does not ensue at that time or
  within a few seconds.

The referee allowed to play on advantage because Spaniards (non-offending team) benefited from it (they scored a goal).
Comment: @luchonacho, the whole thing (the foul and the own goal) happened in the blink of an eye. There was neither need nor time for referee to show the repsective "play on advantage" signal.
Comment: @gdrt I disagree - if they did not, the referee should have signalled advantage before pointing to halfway for the goal. However, the referee's failure to use the signal does not negate whatever advantage was applied. [This clip](https://www.youtube.com/watch?v=NNGug-e0K7s) shows Mike Dean doing so in the Premier League (albeit perhaps a little to enthusiastically).
Comment: But the referee did not do the advantage rule signal, as they do in general.
Comment: @studro - Anytime you find your argument hinges on Mike Dean being an example of proper referee behavior, you really ought to [stop and rethink things](http://www.dailymail.co.uk/sport/football/article-4083560/Why-Mike-Dean-Premier-League-s-controversial-referee.html).
Comment: @T.E.D. Are you suggesting that the Daily Mail are a better judge of referee competence (or any subject, for that matter) than [PGMOL](https://www.efl.com/clubs-and-competitions/match-officials/pgmol/)? Either way, the comment was not about his flamboyant mannerisms, it was about the signal itself.
Answer: I shall leave details of the specific clauses that are relevant, and why this  situation falls under their jurisdiction. Instead I shall address why you would want to design the rules like this:
If you give the foul, then the defending team has benefited from the foul.
A foul should never be more appealing than not-fouling.
Supposing you implemented the rules as you describe. Then, and at some point an attacker has a huge breakaway run, where he's passed all the defenders.
Some other defender in the other half of the pitch, might choose to push over an opponent, just to stop play, prevent the attacker from having the chance to score, and being the ball back into the other had of the field.
Clearly, if the rules permitted such choices with no penalisation, then the whole game would break-down, into a mess of tactical fouls.
Comment: `A foul should never be more appealing than not-fouling` Suarez in the Uruguay Ghana game?
Comment: Stephen and Chris, I think you're both misinterpreting what Brondahl means here. What they mean is that if a foul leads to an advantage for the team that was fouled against, the foul is ignored, to let the advantage stand. Your examples are both of advantages for the team that committed the foul. They may not have been adequately penalised, but they're not examples of what Brondahl means.
Comment: @StephenS - yes, that is a failing of the rules. If the Laws of the Game allowed penalty goals (like penalty tries in rugby), then once again it would be less appealing. Brondahl's point still stands - if it is to the advantage of the team who did not commit the foul to allow play to continue, play continues.
Comment: In the situation you describe (almost certain goal prevent by foul) then it is what is often called a "Professional Foul" and the player should be sent off.  The advantage may still be played, of course.  The reasoning behind this is exactly as you describe.  See https://resources.fifa.com/image/upload/laws-of-the-game-2018-19.pdf?cloudid=khhloe2xoigyna8juxw3 pages 107-108
Comment: Or Jorgensen's foul in the Denmark vs. Croatia game to prevent a 100% chance in front of the empty goal?
Comment: @StephenS - One could argue that's the example that proves the rule. As the last play of the game, most of the disincentives for that particular cheat were no longer effective.
Comment: @StephenS and Chris, In both of those cases, there was some additional penalty (as in penalisation, not a penalty-kick) awarded as an attempt to dis-incentivise the infraction. As T.E.D. says, if it's the last play of a knock-out game, it's pretty hard to incentivise enough against cheating, but that's the logic behind cards and multi-match-bans in the Premier League and international games. The systems may not (yet?) be perfect, but this answer discusses the design intent behind them.


$f$ is a function from $\Bbb R$ to $\Bbb R$. $f \geq 0$ and $f$ is midpoint concave, then how to prove $f$ is a constant function?

Question: $f$ is a function from $\mathbb{R}$ to $\mathbb{R}$. $f \geq 0$ and $f$ satisfies $\frac12f(x_1)+\frac12f(x_2) \leq f(\frac{x_1+x_2}2)$ for all $x_1, x_2 \in \Bbb R$. How to prove that $f$ is a constant function?
Thanks in advance!
Comment: Are we assuming $f$ is continuous?
Comment: Not needed, Jensen-concave function bounded below is necessarily continuous.
Comment: Suppose there are $a,b$ with $f(a) > f(b)$. What can you say about $f(a + 2^k(b-a))$?
Comment: @DanielFischer $f(a+2^k(b-a)) \geq \frac{f(2a)+f(2^{k+1}(b-a))}{2}$?
Comment: Think in the other direction. We want an upper bound (that eventually becomes negative).
Comment: @DanielFischer Is it true that $f(a+2^k(b-a)) \leq f(a) + f(2^k(b-a))$, if $a,b>0$?
Comment: Maybe. What I was aiming at is $f(a + 2^k(b-a)) \leqslant f(a) + 2^k\cdot (??)$ with a negative $(??)$.
Comment: @DanielFischer It seems that when $a,b>0, b-a>0$, $f(b) \leq f(b-a) + f(a)$, then $f(b) - f(a) \leq f(b-a)$. I still have difficulty proving that $f(b-a) <0$.
Comment: Forget $f(b-a)$. What about $f(b) - f(a)$? (And that regardless of whether any of $a,b,b-a$ is positive.)
Comment: @DanielFischer $f(b) - f(a) < 0$. But are we going from $f(a + 2^k(b-a)) \leq f(a) + 2^k f(b-a)$, and going to prove that $f(b-a)<0$?
Comment: No. We never look at $f(b-a)$. That might be positive for all we know.
Comment: @DanielFischer OK. Let me think about it again
Comment: [Related question about a concave function](https://math.stackexchange.com/q/165833/721644).
Answer: Let's suppose $f$ isn't constant, then exists $x_1 > x_2$ (it could be $x_1 < x_2$, the proof is analogous) such that $f(x_1) > f(x_2)$, define $\Delta x = x_1 - x_2$ and $x_{i+1} = x_i - \Delta x$, then by concavity we have for every $i\geq1$:
$$ \frac{1}{2}(f(x_i) + f(x_{i+2})) \leq f(x_{i+1}) $$
$$ f(x_{i+1}) -f(x_{i+2}) \geq f(x_{i})-f(x_{i+1}) $$
Repeat the last inequality and we get:
$$ f(x_{i+1}) -f(x_{i+2}) \geq f(x_{1})-f(x_{2}) $$
Now we will use that $f\geq 0$:
$$f(x_1) - f(x_n) = (f(x_1)-f(x_{2})) + (f(x_{2})-f(x_{3})) + \cdots + (f(x_{n-1}) - f(x_n))$$
$$f(x_1) - f(x_n) \geq (n-1)(f(x_1)-f(x_2))$$
But it's possible to find $N$ such that $(N-1)(f(x_1)-f(x_2)) > f(x_1)$, then:
$$f(x_1) - f(x_N) \geq (N-1)(f(x_1)-f(x_2)) > f(x_1)$$
$$f(x_N) < 0$$
But we had $f \geq 0$, then $f$ must be constant.


AR(k)-GARCH(1,1) model. Why am I getting same Log-likelihoods and AICs?

Question: I am trying to for loop an AR(k)-GARCH(1,1) model, however it seems that I am getting same log-likelihoods and AICs. I believe that my code is fine, since I manually checked the iterations. Is there any statistically theoretical reason why is this happening?
garch_models = pd.DataFrame(columns=['AIC','Log-Likelihood'],index=garch_columns)
for i in np.arange(len(garch_models)):
    AEX_GARCH_0 = arch_model(log_r['AEX'], lags=i, vol='Garch', p=1, o=0, q=1, dist='t')
    res_AEX = AEX_GARCH_0.fit()
    res_AEX.summary()
    garch_models.iloc[i,0]= res_AEX.aic
    garch_models.iloc[i,1]= res_AEX.loglikelihood

Here's what I am getting in the data frame:

Here are two of the iterations (so I can save some space):
Answer: You need to add mean = 'AR' (see documentation):
arch_model(log_r['AEX'], mean='AR', lags=i, vol='Garch', p=1, o=0, q=1, dist='t')

Try to check the model specification of AEX_GARCH_0 for the different iterations.
Comment: Thanks a lot. I don't know how I didn't see this before.... silly me
Comment: No problem. Sometimes we just miss something. Please accept the answer :)


Problem 2B.4 in Finite Group Theory by Isaacs

Question: Suppose a finite group $G$ has more than one Sylow-2 subgroup and any two intersects trivially. Show $G$ contains exactly one conjugacy class of involutions.
Here are some of my thoughts: Suppose not, then there exist involutions $s,t$ such that they are not conjugate.
$s,t$ generates a dihedral group $D_{2n}$.  $n$ is even since $s,t$ are not conjugate in $D_{2n}$.
If $n$ is not a power of 2, then $D_{2n}$ has more than one Sylow 2 subgroups and $D_{2n}$ are generated by them. But any two of the Sylow 2 subgroups of $D_{2n}$ has a nontrival intersection, and any two Sylow-2 subgroups of G intersects trivally, so all  Sylow 2 subgroups of $D_{2n}$  must lie in the same  Sylow-2 subgroup of $G$. So $D_{2n}$ lie in a Sylow-2 subgroup of $G$, this leads a contradiction.
But what if $n$ is a power of 2?
Comment: Welcome to Stackexchange. You'll find that simple "Here's the statement of my question, solve it for me" posts will be poorly received. What is better is for you to add context (with an [edit]): What you understand about the problem, what you've tried so far, *etc.*; something both to show you are part of the learning experience and to help us guide you to the appropriate help. You can consult [this link](https://math.meta.stackexchange.com/q/9959) for further guidance.
Comment: Note that your arguments would work with any pair of non-conjugate involutions, and the conclusion so far is that they generate a subgroup of order $2^n$ for some $n$. So they are contained in the same Sylow $2$-subgroup. What does this tell you?
Comment: I think the name of the author of the book in question is Isaacs not Issac, which is an acronym for  International Symposium on Symbolic and Algebraic Computation.
Answer: Thanks to a comment, I have solved it as follows.
My argument shows that any two non-conjugate  elements generates a dihedral group  whose order is  a power  of 2. Thus $s,t$ and $s,gtg^{—1}$ lies in a same Sylow-2 subgroup of G, for all $g\in G$. Thus it has only one Sylow-2 subgroup, contradiction.
Answer: Let's first consider the case where $G$ is dihedral with cyclic group $C$. Since $C\triangleleft G$, given $P,\,Q\in\text{Syl}_2(G)$ we have $C\cap P,\; C\cap Q\in\text{Syl}_2(C)$ (in any group the intersection of Sylow with normal is Sylow). But $C$ is abelian and therefore $C\cap P=C\cap Q$, which is trivial (if and) only if $|C|$ is odd.
In the general case take two different involutions $s$ and $t$. Let $P$ and $Q$ be the only Sylow $2$-subgroups of $G$ such that $s\in P$ and $t\in Q$. Since we can replace $s$ with $s^a$ for appropriate $a\in G$, we are allowed to assume that $P\ne Q$. Hence, $P\cap Q=\langle1\rangle$.
Consider the dihedral group $D=\langle s,t\rangle$ of order $2n$. The uniqueness of $P$ and $Q$ implies that $D\cap P$ and $D\cap Q$ are two different Sylow $2$-groups of $D$. Moreover, they have trivial intersection. As we saw above, this can only happen if $n$ is odd. Then, by Problem 2B.2, $s$ and $t$ are $D$- and hence $G$-conjugates.


find number of automorphisms of (Z,+)

Question: What's the number of group isomorphisms from the group (Z, +) to itself??
my approach:
I think it has to be infinity, but that is an incorrect  answer...
Comment: Think about $f(1)$ . Since $f$ is an isomorphism (proper term is automorphism) then where should $f(1)$ go ?
Comment: Use the group automorphism axioms / definition and you should see that it will need to fix $0$ as the additive identity.  This answer depends on the precise type of isomorphism and whether you need to fix $0$ as the identity or whether in your morphed group you could have e.g. $1$ as the additive identity instead.
Answer: Any homomorphism of a cyclic group is determined by what it does to a generator.  So, by what it does to $1$.
But to be an automorphism, it has to be surjective.  This won't happen unless $1$ is mapped to a generator.
So we need $\varphi(1)=1$, or $\varphi(1)=-1$.  Thus there are two.
Comment: @samerivertwice  This means we have to prove that $1/n$ isn't an integer for $n\ne\pm1$.  Point taken.
Comment: This depends upon the theorem that $\{-1,1\}$ are the only generators of $(\Bbb Z,+)$ which the OP may not already have.
Comment: OP would appear to think that $x\mapsto x+i$ is an automorphism for any $i\in\Bbb Z$.
Comment: Yes, or some such.  But of course the only one of those that works is for $i=0$.  @samerivertwice

find number of automorphisms of (Z,+)


Measure correlation for distance and binary outcome

Question: I know enough about statistics to know that I don't know enough about statistics.  This is therefore a humble question, and apologies in advance for asking a question that is likely to be missing key information or phrased badly.
I have two variables.

One is a real-world metre distance between two points, and is therefore always >= 0.  It doesn't seem to be normally distributed.
The other is an outcome, with two values.  It's not a 50:50 split.

I want to see if there is a correlation between these.  Could someone advise me on a good way to do this?
A sample set of data is here.  I'm providing this not out of laziness, but because it might be that there is some simple characteristic of this information which someone might want to know, and this might be quicker than asking me to provide it.
I would also be interested in the correct way to have phrased this question, or relevant tags.
Answer: Welcome to crossvalidated. It looks like there is some "connection" between the two variables. Here are two histograms of the logarithm of the distance--one for each level of the Outcome variable. Observe that taking the log makes this variable look normally distributed.

If you regress log distance on outcome, there seems to be something going on. I get a p-value of $0.0254$ on the t-test. Hopefully this will give you some ideas. And here's the code used to generate all of this:
df <- read.csv("~/Desktop/sample_data_xv.csv")

# plot 1
hist(log(df$Distance[df$Outcome=="Up"]), col = "red", xlab="log distance", main = "log distance by outcome (red = up, blue = down)")
hist(log(df$Distance[df$Outcome=="Down"]), col = "blue", add = T)

# plot 2
hist(log(df$Distance[df$Outcome=="Up"]), col = "red", xlab="log distance", main = "log distance by outcome (red = up, blue = down)", freq = F)
hist(log(df$Distance[df$Outcome=="Down"]), col = "blue", add = T, freq = F)

# regress log distance on outcome
is.factor(df$Outcome)
mod <- lm(log(Distance+.000001) ~ Outcome, data = df)
summary(mod)

Edit: here's an image that plots density on the y-axis, instead of frequency, so it doesn't show the relative count as well. It does, however, show how the mean is shifted by the dummy variable in our regression.
Comment: Thanks for the reply.  It's useful to know that there seems to be a connection!
Answer: First, note that your second column is a categorical variable, i.e. Yes/No, Up/Down in your case.
So, a first step will be to convert your non-binary data in the "Outcome" column to binary $0-1$ variables.
An Excel Implementation:
The next step will be to use the CORREL function in excel, to compute the correlation between your two types of variables - Distance and Outcome. To do so, apply =CORREL(A2:A3417,B2:B3417) in any empty cell (after you have converted your UP/Down into 1/0 respectively!) and you will obtain the correlation as desired.
R Implementation
(You can use readxl to read the .xlsx file directly instead)
If you try out the straightforward way in excel or by invoking cor(x,y) in R, you will find that there is almost no relation between the 2 variables, which kinda makes sense as one of them is a binary/categorical variable. ($cor(x,y) = -0.005750405$).
test <- read.csv("sample.csv", header = TRUE, sep = ',')
Outcome <- test$Outcome
Distance <- test$Distance
cor(Outcome,Distance)
-----------------------Outputs------------------------------
[1] -0.005750405

From the result above, I don't think that's the kind of result you want as not much can be interpreted from it. I highly suggest you take a look at Correlation between a nominal (IV) and a continuous (DV) variable, where a detailed breakdown of a problem similar to yours has been given.
In any case, if you are interested in descriptive statistics, you can try the following:
If you call a general linear model, you obtain the following:
lm1 <- glm(test$Outcome ~ test$Distance, data = test)
summary(lm1)
-----------------------Outputs------------------------------
Call:
glm(formula = test$Outcome ~ test$ï..Distance, data = test)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-0.8588   0.1413   0.1415   0.1417   0.1712

Coefficients:
                   Estimate Std. Error t value Pr(>|t|)
(Intercept)       8.588e-01  6.380e-03 134.606   <2e-16 ***
test$ï..Distance -4.717e-08  1.404e-07  -0.336    0.737
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for gaussian family taken to be 0.1218882)

    Null deviance: 416.14  on 3415  degrees of freedom
Residual deviance: 416.13  on 3414  degrees of freedom
AIC: 2508.7

Number of Fisher Scoring iterations: 2

Or if you call a linear model (lm):
lm1 <- lm(test$Outcome ~ test$Distance, data = test)
-----------------------Outputs------------------------------
Call:
lm(formula = test$Outcome ~ test$ï..Distance, data = test)

Residuals:
    Min      1Q  Median      3Q     Max
-0.8588  0.1413  0.1415  0.1417  0.1712

Coefficients:
                   Estimate Std. Error t value Pr(>|t|)
(Intercept)       8.588e-01  6.380e-03 134.606   <2e-16 ***
test$ï..Distance -4.717e-08  1.404e-07  -0.336    0.737
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.3491 on 3414 degrees of freedom
Multiple R-squared:  3.307e-05, Adjusted R-squared:  -0.0002598
F-statistic: 0.1129 on 1 and 3414 DF,  p-value: 0.7369

Also remember that correlation coefficients are used in statistics to measure how strong a relationship is between two variables, not to show causation. More information about interpreting correlation can be found at http://www.statisticshowto.com/probability-and-statistics/correlation-coefficient-formula/ and https://www.dummies.com/education/math/statistics/how-to-interpret-a-correlation-coefficient-r/.
Comment: Thanks for the reply. I don't need to use Excel, I can code (or use libraries) in various languages. So I'm primarily concerned about the correct algorithm. I want to avoid reaching for the most convenient thing for lack of knowledge, though if the Excel function is the correct one to use then that is handy. I understand the point about correlation and causation.
Comment: I understand your concern. The correlation obtained is indeed almost zero, so not much interpretation can be done from it. Do check out the link I have added into the edited post above, which gives a more detailed breakdown of your problem and data.


Calculating the coefficient of a generating function

Question:
Calculate the coefficient of $x^{10}$ in $$\frac{1+x^3}{1-2x+x^3-x^4}$$

I am unsure how to even start and would appreciate a hint? I haven't dealt with problems like this (complicated) before.
Comment: So I would start by attempting to perform polynomial long division such that the power of $x$ increases with each next term.  Keep performing long division, even if there is a remainder, like dividing $1/7$ into a decimal format.
Answer: HINT: Write $$ \frac{1 + x^3}{1 - 2x + x^3 - x^4} = \sum_{n = 0}^{\infty} a_n x^n$$, multiply the denominator on both sides of the equation and compare coefficients. Do you get a recurrence relation?
Comment: +1 Yes. A little lateral thinking: instead of using a generating function to solve a recurrence relation, use a recurrence relation to get the coefficients in a function.
Comment: I am not getting a recurrence per say. But, I have that, $a_3 = 2a_2$ and that $a_0 = 1$.
Comment: One term after multiplying both sides by the denominator is $\sum_{n=0}^{\infty} -2a_nx^{n+1}$. You can rewrite this as $\sum_{n=1}^{\infty} -2a_{n-1}x^{n}$
Comment: Please accept the answer if it helped, or I'll complete the answer if needed


Sec-WebSocket-Protcol is not working with react native

Question: I'm trying to establish WebSocket connection with server using WebSocket library. Server requires Sec-WebSocket-Protocol : "sip" as request headers for authentication. I added it in WebSocket using new WebSocket("wss://abc.xyz:7443", "sip") but it's not working. I'm not getting that header in reqest at server side. Can anyone help?
Answer: There was an issue of TLS version suppport on client and server side. Server was not supporting TLS v1.2 and React Native support TLS v1.2, so it was creating an issue.


How should the percussion on an Acoustic guitar be played in the song "Californication"?

Question: I've seen this arrangement for "Californication" (guitar fingerstyle). I'm don't know how to thumb slap well, but I'd like to understand how the slap works here.
For example, look at the first slap in the video at 0:11, He is slapping the E string but which strings should I hit while slapping? What do the "X"-s in the tab mean? I googled and I think it means "to mute", but how should I do that (if that's the correct meaning of the "X")?

After investgating and not understanding, It seems like the only notes that makes sound is the one I marked in red (D string, fret 0), so is this muting? If so, how is it done?
p.s. I tried hitting the 3 bottom strings (marked with X) as I slapped the low E with my thumb, the sound I got was clearly not the right one, which again makes me thing this is muting, so I'm still left wondering if indeed this is the case and how should I mute if it is)
Answer: 'X' can mean different things in different places. Here they indicate which strings you have to slap. You don't have to be really accurate as to which strings you hit as long as they're not strings that are sounding notes.
Comment: so I need to try to only hit those strings while slapping with my thumb?
Comment: Sometimes he hits the higher strings with his fingers, but that's all in the tab.
Comment: For a while I tried to understand how to do what he does, but I can't get this right. Are you sure X marks the strings that should be slapped? it seems like he always slaps one of the two top strings with his thumb, and the notes I hear are the ones that aren't marked with X
Comment: @ArielYael At your red mark the only note you hear is the open D string, It looks like he's playing it with a down stroke of his first finger. The other three fingers are slapping the higher strings so they are muted
Comment: if he is slapping them shouldn't we hear them as well? How is the muting done?
Comment: You hear the sound of the strings hitting the fretboard. The fingers stay on the strings, muting them.
Comment: so he leaves the fingers from his *left* hand on the string, slightly touching them, so once the fingers on his right hand strum those strings, the sound is muted?
Comment: No, the left hand has nothing to do with those X-notes.
Comment: I played the video in slow motion, his right hand fingers don't appear to be staying on the strings


Practical way to combine conflicting options

Question: I have a script which accepts multiple options as arguments. The list of valid options may be large (>20) which could result with conflicts. Is there a practical way to combine the conflicted ones together, and non-conflicted into another without creating multiple lists, groups, etc. Changes to one group will result in changes to other groups.
For example, the list of available options:-a, -b, -c, -d
The following options conflict: [-a, -c], [-a, -d]
The following options don't conflict: [-a, -b], [-c, -d]
EDIT, A more precise example:
For example, the script allows to start/stop a specific task and has additional options for creating/deleting logs.
A normal start would look like :
./script -start Task -logFile C:\out.tmp
And the script should notify the user in case something like:
./script -start Task -stop Task is executed, since start and stop are two opposite actions.
Another conflicting action:
./sript -start Task -logFile C:\out.tmp -deleteLog C:\out.tmp , which would create a log file and delete it at the same time
Now, if the options are start, stop, logFile, deleteLog,
The following would be conflicting: [start, stop], [logFile, deleteLog]
The following would not be conflicting: [start, logFile], [stop, deleteLog]
Comment: Could you be more precise as to what the input is and what the expected output is? Can you give a complete example?
Comment: I would blindly parse options into a configuration dictionary, and then set variables internally based what is in that configuration.  While setting variables I'd scatter checks for conflicts, check whether files exist, and so on.
Answer: Let us assume that, as you are writing the source, you can decide how to organize your arguments for parsing time. For example (using JSON notation, you can easily adapt this to C structs, Java enums or what-have-you), you can annotate the available options to explicitly indicate which of them conflict:
const options = [
  {
    name: "start",
    description: "starts foobaring the fizzbuzz",
    parameters: [
      {
        name: "task",
        type: "string",
        optional: false,
        description: "the type of task to foobar"
      }
    ]
    conflicts: ["stop"] // <-- explicit simple conflict detection
  },
  { ... }
]

This would be used by a command-line parsing module to

generate a nice help screen, possibly including conflicting options
return a map of command-line options, say parsedArgs, so that parsedArgs['start'] would correspond to the parameters of the start parameter if it was specified.
detect simple conflicts, by complaining if conflicting options are detected at parse-time.

Note that there may be additional conflicts that it may not be worthwhile to detect at the parsing stage. For instance, if the value of option foo must be larger than bar + baz, it is better to code a check for this fact after parsing, rather than complicating the parser to handle arbitrary relationships between option values.


tokenHandler() doesn't fire when you open app (ios, PushPlugin), have to minimize the app then reopen it to fire event

Question: I'm trying to implement the new PhoneGap PushPlugin for iOS but can't figure out why I'm having this issue.
When the app loads, it successfully calls the OnDeviceReadyPush function:
var pushNotification;

function onDeviceReadyPush() {
$("#app-status-ul").append('
deviceready event received
');

pushNotification = window.plugins.pushNotification;
if (device.platform == 'android' || device.platform == 'Android') {
    pushNotification.register(successHandler, errorHandler, { "senderID":     "661780372179", "ecb": "onNotificationGCM" });
} else {
    pushNotification.register(tokenHandler, errorHandler, { "badge": "true", "sound":     "true", "alert": "true", "ecb": "onNotificationAPN" });
}
}

document.addEventListener('deviceready', onDeviceReadyPush, true);

Which is suppose to kick of the tokenHandler function:
function tokenHandler(result) {
$("#app-status-ul").append('
token: ' + result + '
');
// Your iOS push server needs to know the token before it can push to this device
// here is where you might want to send it the token for later use.

$.get("", { "deviceid": result}, processResult);

function processResult(data, textStatus) {
    alert(data);
}
}

It doesn't work until I minimize the app and then come back into it. It then fires the tokenHandler event.
Please help, I've been looking at this trying everything I can think of for two days now and am going crazy.
Answer: Have you tried this:
document.addEventListener('deviceready', onDeviceReadyPush, FALSE);
Comment: Thanks for your input, I did try that but it still didn't work. I ended up updated everything to the newest version and it started working as expected. I think I was using the wrong cordova file.
Answer: I was using the wrong cordova file. After updating everything to the newest at the time, it started working as expected.
Comment: Could you explain this in more detail? I have the same issue. Just upgraded to Cordova 3.1.0-0.2.0, and updated the PushPlugin as well, now iOS does not call the token handler function, but the equivalent Android one works fine.


How to assign a user to administer one content type only?

Question: I have created a content type "TestContent". I created view using the content type. I can add content using the TestContent and I can see the content just fine in view. And I am the admin. Now, I have created a role "David" and I have created a user "xpress". I also have assigned the user to the role.
Then in Admin > People > Permission: I have selected check box for 'David' for the below items:
<code>David: TestContent: Create new content
David: TestContent: Edit own content
David: TestContent: Edit any content
David: TestContent: Delete own content
David: TestContent: Delete any content
</code>
I logged out as admin and logged back in as xpress but I did not see the add content, find content for the content type that he has permission. Note that this user only have the permission to add content, edit content, update content, delete content for the content type.
Can you please help?
Thanks.
Answer: The xpress is not an admin, right? So the xpress won't be able to see the admin toolbar. Have you tried accessing the link of node/add/testcontent, node/node-id/edit? was xpress able to access it? if yes then you need to provide a link/button for the xpress to see when he/she logs in. Then I think you need to use views to show the lists of TestContent where xpress can search/filter.
Comment: 1. node/add/testcontent  - Yes, xpress can see add page.            2. node/node-id          - Yes, xpress can see and edit.           3. I can create a view for him to see the list of contents plus search and filter. Is there way he can add a content and not publish it?  Thanks.
Comment: Then you can create a link for that, either put it on a template, block, menu or wherever then just restrict it to a specific role so that it will only appear if that certain role is logged in. then if you want, you can create a view page or block for the find content, with exposed filter of title and a filter criterion of content type: testcontent restrict it to that specific role also. Did I understand you case correctly?
Comment: You want that specific role to not publish it whenever that role creates new content? you can do that via rules module. It's somehow like this: Event: after saving content, Condition: User has role/s (choose the desired role) Action: Unpublish Content
Comment: Why down voted? was the answer wrong?
Comment: This answer was useful. I was using cell phone and may be pressed it by mistake. Sorry for confusion. Thanks for your help. Also, why down and up vote both gives negative 1?
Comment: As for publishing, xpress may enter 50 % data and then save it for later. He may not have all the information at the time he is adding content. So, I am trying to help him with an option to save it and not publish it. Once he is done completely and he can then publish it. I will follow your all the instruction you have given me. I may come back with some questions. Let me see how much I can do myself. Thank you again for help.


Web Scraping returns None

Question: I'm trying to get the price of a list of monitors from Amazon, using request and bs4 -
Here is the code:
from bs4 import BeautifulSoup
import re
import requests

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',}

res = requests.get("https://www.amazon.com/s?i=specialty-aps&bbn=16225007011&rh=n%3A16225007011%2Cn%3A1292115011&ref=nav_em__nav_desktop_sa_intl_monitors_0_2_6_8", headers=headers)

print(res)

soup = BeautifulSoup(res.text, "html.parser")

price=soup.find_all(class_="a-price-whole")

print(price.text)

I don't understand why it returns None - I'm basically following a video, https://www.youtube.com/watch?v=Bg9r_yLk7VY&t=467s&ab_channel=DevEd, and on their side it returns the text - can someone point out what I'm doing wrong?
Answer: You've probably received captcha page. Try to add "Accept-Language" HTTP header:
import re
import requests
from bs4 import BeautifulSoup

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
    "Accept-Language": "en-US,en;q=0.5",
}

res = requests.get(
    "https://www.amazon.com/s?i=specialty-aps&bbn=16225007011&rh=n%3A16225007011%2Cn%3A1292115011&ref=nav_em__nav_desktop_sa_intl_monitors_0_2_6_8",
    headers=headers,
)

soup = BeautifulSoup(res.text, "html.parser")
prices = soup.find_all(class_="a-price-whole")
for price in prices:
    print(
        price.find_previous("h2").text[:30] + "...",
        price.text + price.find_next(class_="a-price-fraction").text,
    )

Prints:
Sceptre IPS 27-Inch Business C... 159.17
EVICIV 12.3'' Raspberry Pi Tou... 199.99
Portable Monitor, 17.3'' IPS H... 349.99
Acer R240HY bidx 23.8-Inch IPS... 129.99
Dell SE2419Hx 24" IPS Full HD ... 169.95
HP Pavilion 22cwa 21.5-Inch Fu... 139.99
Sceptre E248W-19203R 24" Ultra... 127.98
LG 27GL83A-B 27 Inch Ultragear... 379.99
LG 24M47VQ 24-Inch LED-lit Mon... 99.99
LG 27UN850-W 27 Inch Ultrafine... 404.14
Sceptre IPS 24-Inch Business C... 142.17
Planar PXN2400 Full HD Thin Pr... 139.00
Sceptre IPS 24-Inch Business C... 142.17
Portable Triple Screen Laptop ... 419.99
ASUS ZenScreen 15.6" 1080P Por... 232.52
HP M27ha FHD Monitor - Full HD... 199.99
ASUS 24" 1080P Gaming Monitor ... 189.99
Dell P2419H 24 Inch LED-Backli... 187.99
LG 32QN600-B 32-Inch QHD (2560... 249.99
LG 29WN600-W 29" 21:9 UltraWid... 226.99
Acer Nitro XV272U Pbmiiprzx 27... 299.99
AOC C24G1 24" Curved Frameless... 186.99
Samsung CF390 Series 27 inch F... 199.00
ASUS VY279HE 27" Eye Care Moni... 219.00
SAMSUNG LC24F396FHNXZA 23.5" F... 149.99
Sceptre E275W-19203R 27" Ultra... 169.97
ASUS VG245H 24 inchFull HD 108... 164.95
PEPPER JOBS 15.6" USB-C Portab... 199.99
13.3 inch Portable Monitor,KEN... 96.99
Eyoyo Small Monitor 8 inch Min... 76.98

Web Scraping returns None


Modify Reference on Taxonomy Field Output

Question: I want to modify the output of a 'Reference on Taxonomy Field'.
I created a 'Reference on Taxonomy Field' in a content type that relates to terms in a vocabulary that have a title and a picture.
The content type is displayed by a view that outputs the fields of the content type. I added the field and created the template file views-view-field--kategorieseiten--page--field-produkteigenschaften.tpl.php and it works.
It should be displayed like this:
OUTPUT_OF_THE_TERM_PICTURE

The problem is that I don't know how to address the fields from the taxonomy term, since they are not directly stored in the node.
Thanks for your help!
Answer: I managed to load the fields of the taxonomy term with this code:
<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>

<?php $taxonomy_term = taxonomy_term_load(54); ?>
<a rel="tooltip" data-placement="bottom" target="_blank" data-original-title="<?php print $taxonomy_term->name; ?>"><img src="<?php print $taxonomy_term->field_icon['und'][0]['filename']; ?>">

But I want to load the terms dynamically from the tid stored in this field:

The field 'field_produkteigenschaften' is part of the content type and is stored in the node object.
How do I now address the tid stored in the field 'field_produkteigenschaften' in this template?
Answer: I could get the output with:
$row->_field_data['nid']['entity']->field_produkteigenschaften['und'][0]['tid']

Complete code:
<?php if ($row->_field_data['nid']['entity']->field_produkteigenschaften) { ?>
<?php foreach ($row->_field_data['nid']['entity']->field_produkteigenschaften['und'] as &$eigenschaft) { ?>
<?php $taxonomy_term = taxonomy_term_load($eigenschaft['tid']); ?>
<a rel="tooltip" data-placement="bottom" target="_blank" data-original-title="<?php print $taxonomy_term->name; ?>"><img src="<?php print image_style_url("icon", $taxonomy_term->field_icon['und'][0]['uri']); ?>">
<?php } ?>
<?php } else { print " "; } ?>


Injective continuous subset of set of functions of class $C^1$

Question:
Let $\mathcal{C}^1([a,b],\mathbb{R})$ be the vectorial space of functions of class $C^1$ (i.e. functions $f:[a,b]\to\mathbb{R}$ such that $f'$ is continuous) with a norm given by
$$||f||_1=\sup_{x\in[a,b]}\left(|f(x)|+|f'(x)|\right).$$
Let $H\subset\mathcal{C}^1([a,b],\mathbb{R})$ the subset of injective functions prove that if $h\in H$ and there exists $x\in[a,b]$ such that $h'(x)=0$ $h\notin \operatorname{int}(H)$. In particular $H$ is not open.

Attempt:
If $h\in H$ then is a continuous injection therefore $h$ is a homeomorphism over some close interval. Given $\epsilon>0$ exist $f\in B(h,\epsilon)$ such that $f'=0$.
Answer: Suppose that given $h\in H$, there exists some $x\in [a,b]$ such that $h'(x)=0$.
Because $h$ is injective, we cannot have $h'\equiv 0$ on any open interval, so there is some open interval $(c,d)\subset [a,b]$ containing $x$ such that $|h'(t)|>0$ for all $t\in(c,d)$, $t\neq x$. Because $h'$ is continuous, $h'(t)$ has the same sign for all $t\in(c,x)$.
Because $h'$ is continuous and $h'(x)=0$,  for any $\epsilon>0$ we can choose our interval $(c,d)$ containing $x$ to also have the property that $|h'(t)|<\frac{\epsilon}{4}$ for all $t\in (c,d)$.
For any $r,s$ with $c<r<x<s<d$, we can create a non-zero $C^\infty$ function $w:[a,b]\to\mathbb{R}$ supported on $[r,s]\subset (c,d)$ such that

$\|w\|<\epsilon$
$|w'(z)|>\frac{\epsilon}{2}$ for some $z\in (r,x)$
$w'$ has the opposite sign of $h'$ on $(r,x)$

Thus
$$\|(h+w)-h\|=\|w\|<\epsilon,$$
and $h+w\in C^1([a,b],\mathbb{R})$, but the sign of $(h+w)'$ changes between $r$, where
$$(h+w)'(r)=h'(r)+w'(r)=h'(r)+0=h'(r)$$
has the same sign as $h'$, and $z$, where
$$(h+w)'(z)=h'(z)+w'(z)$$
has the opposite sign of $h'$ because $w'$ has the opposite sign of $h'$ on $(r,x)$ and $|w'(z)|>\frac{\epsilon}{2}>\frac{\epsilon}{4}>|h'(z)|$.
Thus $h+w$ is not injective, and thus $h+w\notin H$. Because, for any $\epsilon>0$, we can find some $h+w$ such that $\|(h+w)-h\|<\epsilon$ and $h+w\notin H$, the set $H$ is not closed in $C^1([a,b],\mathbb{R})$.
Comment: Thanks for an interesting and simple proof.
Answer: Suppose $h \in H$ such that $\exists x_0$ with $h'(x_0) = 0$. Since $h$ is injective, it must be monotonic. Hence $h'$ must either be $\geq 0$, or $\leq 0$. I will assume that it is decreasing, the other case is handled similarly. Note that since $h$ is decreasing, we have $h(a) > h(b)$.
Let $\epsilon >0$, and define $h_{\epsilon}$ as $h_{\epsilon}(x) = h(x) + \epsilon (x-x_0)$. Clearly $h_{\epsilon}'(x) = h'(x) + \epsilon$, and we have $||h-h_{\epsilon}||_1 \leq \epsilon \max(|a-x_0|,|b-x_0|)+\epsilon$, so $h_{\epsilon}$ can be chosen arbitrarily close to $h$.
Suppose $x_0 \in (a,b)$. Then we have $h(a) > h(x_0) > h(b)$. Now choose $\epsilon$ small enough so that $h_{\epsilon}(a) > h_{\epsilon}(x_0) > h_{\epsilon}(b)$. Since $h_{\epsilon}'(x_0) = \epsilon >0$, we can conclude that there must be a point $x_1 \in (a,x_0)$ such that $h_{\epsilon}(x_1) = h_{\epsilon}(x_0)$, which means that $h_{\epsilon} \notin H$. Hence $h\notin H^{\circ}$.
If $x_0 = a$, choose $\epsilon$ small enough so that $h_{\epsilon}(a) = h_{\epsilon}(x_0) > h_{\epsilon}(b)$. By similar reasoning, we see that there must be a point $x_1 \in (x_0,b)$ such that $h_{\epsilon}(x_1) = h_{\epsilon}(x_0)$, with the same consequences.
The case $x_0=b$ is handled similarly.
Comment: Nice construction! Thanks!!


php - Quebra de linha em array

Question: Estou querendo pular linha em uma tabela, mas não consigo arranjar uma lógica para fazer isso. Já tentei o explode e não obtive sucesso.
<?=$teste['cod_refugo_teste'];?>
<?=$teste['qtd_refugo']; ?>

O código fica assim:
Quero que as linhas de refugo e quantidade se quebrem, mas não acho um jeito de fazê-lo.
Comment: Veja: https://jsfiddle.net/mgd2b75p/6
Comment: Está a utilizar o datatable?
Comment: Tenta assim...
`".$teste['qtd_refugo']; ?>`
Comment: Poste sua estrutura html da tabela. Isso é questão da tabela, não do php
Comment: Marcelo, o problema é que eu estarei pulando os arrays cod_refugo_teste e qtd_refugo. Quero que pule a linha a cada refugo e a cada quantidade, entende?
Comment: Quando diz pular a linha é deixar os campos todos a branco menos o refugo e quantidade ? Acho que seria mais claro se colocasse um exemplo do como esperava que ficasse.
Comment: Sem um exemplo fica muito confuso o que você realmente precisa.
Answer: Você precisa utilizar o atributo rowspan na tag .
Veja este exemplo,apresenta exatamente o comportamento que você deseja:
https://www.w3schools.com/TAGS/att_td_rowspan.asp
Answer: Silvia, nesse caso seria mais interessante ver seu código completo para entender o que está dentro da variável $teste.
A tag HTML para pular linhas é a

 que cria uma nova linha. A cada linha nova, deve ser adicionado um

.
Caso os valores da variável $teste estejam em um array, você pode criar uma função de loop, como o for, como por exemplo:
<?php

$valores = [
    'produto1',
    'quantidade1',
    'responsavel1',
    'data1',
    'produto1',
    'quantidade2',
    'responsavel2',
    'data2'
];

$html = "";

for ($n = 0 ; $n < count($valores) ; $n++) {
    if ($n % 3 == 0 || $n == 0)
        html += "
";

    html += $valores[$n];

    if($n % 3 == 0 || $n == 0)
        html += "
";
}

php - Quebra de linha em array


Taylor coefficients of $e^{-\pi n^2e^{2x}}$.

Question: I am trying to write down a closed form expression for the Taylor series of the function $e^{-\pi n^2 e^{2x}}$ expanded at $x=0$, where $n$ is a positive integer.
Differentiating explicitly one finds that
$$e^{-\pi n^2 e^{2x}} = e^{-\pi n^2}(1-2\pi n^2x+2\pi n^2 (\pi n^2-1)x^2-\frac{4}{3}\pi n^2 (\pi^2 n^4-3\pi n^2+1)x^3+O(x^4))$$
From here one can conclude that the general term $\frac{c_m x^n}{m!}$, in the Taylor series, satisfies $c_m \neq 0$, since $\pi$ is trancendental and $c_m$ contains at worst polynomial factors.
I have also tried the usual composition of Taylor series, but i cannot obtain any more information on $c_m$.
Any suggestions will be greatly appreciated!
Comment: The Taylor series has coefficients you mentioned across the 0. The only way to avoid $\pi$ may be expansion of this function across some other point I would suggest $\ln[1/\pi]$.
Comment: Expanding at $\ln(1/\sqrt{\pi})$ one obtains exactly the same as the expansion i wrote above with the $\pi$ terms deleted, and $x \to x+0.5\ln(\pi)$. This doesnt help that much to find the general form of $c_m$, but, thank you, it simplifies!
Comment: I am not sure that the expected coefficients will be rational or even algebraic. Even more I assume that the only way to get the rational coefficients is expansion around the transcendental point. Even in that case the simplicity you are looking for is not always possible.
Comment: $c_m$ will be polynomials in $\pi n^2$, since we are repeatedly differentiating $e^{-\pi n^2 e^{2x}}$. However there is no clear indication as to the form they take. I was assuming there was formula given by a product but I cannot quite write it down.
Comment: Then I should be misunderstood you. Please take a look at the Faa Di Bruno formula this will solve the issue. https://en.wikipedia.org/wiki/Fa%C3%A0_di_Bruno%27s_formula
Comment: This is exactly what I was looking for! Thank you very much !
Comment: Note the expansion of $\theta(x)= \sum_{n=1}^\infty e^{-\pi n^2 x}$ at $x=0$ is obtained from $\theta(x) = \frac{1}{2i\pi} \int_{\sigma-i\infty}^{\sigma+i\infty} \zeta(s) \pi^{-s/2} \Gamma(s/2) x^{-s}ds$ and the functional equation, ie. $1+2\theta(x)  = x^{-1/2}(1+2\theta(1/x))$
Comment: @reuns I think this questions corresponds ( if one takes the sum as you proposed ) to the expansion of the theta function at $x=1$!
Answer: Expanding $e^{te^x}$ on the outer exponential first, and then on the inner exponential, and finally switching order of summations gives
$$\begin{align}
e^{t e^x}
& = \sum_{m=0}^{\infty} \frac{1}{m!} \left(t e^x \right)^m \\
& = \sum_{m=0}^{\infty} \frac{1}{m!} t^m e^{mx} \\
& = \sum_{m=0}^{\infty} \frac{1}{m!} t^m \left( \sum_{k=0}^{\infty} \frac{1}{k!} (mx)^k \right) \\
& = \sum_{k=0}^{\infty} \frac{x^k}{k!} \left( \sum_{m=0}^{\infty} \frac{t^m}{m!} m^k \right) \\
\end{align}$$
The inner parenthesis can now be written as
$$\sum_{m=0}^{\infty} \frac{t^m}{m!} m^k = \left(t\frac{d}{dt}\right)^k e^t = p_k(t) e^t,$$
where $p_k(t)$ are polynomials satisfying $p_0(t) = 1$ and $p_{k+1}(t) = t \left( p_k'(t) + p_k(t) \right).$ I don't know if there is an explicit formula for the coefficients of these polynomials.
Thus,
$$e^{t e^x} = \sum_{k=0}^{\infty} \frac{x^k}{k!} p_k(t) e^t = e^t \sum_{k=0}^{\infty} \frac{x^k}{k!} p_k(t)$$
and
$$
e^{-\pi n^2 e^{2x}}
= e^{-\pi n^2} \sum_{k=0}^{\infty} \frac{(2x)^k}{k!} p_k(-\pi n^2)
= \sum_{k=0}^{\infty} \frac{2^k e^{-\pi n^2} p_k(-\pi n^2) }{k!} x^k.
$$
i.e. the coefficient of $x^k$ is
$$c_k = \frac{2^k e^{-\pi n^2} p_k(-\pi n^2)}{k!}.$$
Comment: I have reproduced your proof, apart from the step $\sum_{m=0}^{\infty} \frac{t^m}{m!}m^k=(t\frac{d}{dt})^k e^t$. How do you deduce this ?
Comment: The series $\sum_{m=0}^{\infty} \frac{t^m}{m!} = e^t$ is well-known. Then notice that $(d \frac{d}{dt})^k t^m = m^k t^m$ and you are done.


How to serve a finished Wordpress Website locally

Question: I downloaded a website and its respective database from Microsoft Azure using FTP with Filezilla and I want to serve it locally. I already set the environment:

MySQL
Apache
PHP
phpMyAdmin
Wordpress

What is the next step to deploy the website? Should I copy the website folder in htdocs directory?
Answer: Finally I used the plugin Duplicator of Wordpress. This plugin allows me to create a full copy of a remote Wordpress site and an installer file. Once you generate these files you just have to copy them in the web server directory (or in a subdirectory like "MyWebsite") and execute the installer with your web browser going to:
http://localhost:port/MyWebsite/installer.php

I hope this is useful to someone. Cheers!


NullPointerException in Loop

Question: I've created a program that attempts to crack password protected zip files using a dictionary. The program reads from a line, stores that line in an ArrayList at position 0, then tries to open the locked zip file with it. If it is successful, it closes the buffered reader and announces the working password. If it is not successful, it ignores the produced ZipException, clears the password from position 0 in the ArrayList, and continues with the next line. I've included debugging to show the number of items in the ArrayList after each attempt (should always be 1).
Code Snippet (Error):
Exception in thread "main" java.lang.NullPointerException
    at net.lingala.zip4j.core.ZipFile.setPassword(ZipFile.java:650)
    at zZipCracker.zZipCracker.zZipCracker(zZipCracker.java:87)
    at zZipCracker.zZipCracker.main(zZipCracker.java:55)

Code Snippet (My Loop):
while(true) { //while elements are still in the array list
                    String line;
                    if ((line = br.readLine()) != null) {
                       passwordArray.add(line);
                       System.out.println(line);
                    }
                    zipper.setPassword((String) passwordArray.get(0)); //set the password to element position [passwordCounter]
                    System.out.println("Testing password no." + passwordCounter + ", which is " + passwordArray.get(0));
                    passwordCounter = passwordCounter + 1;

                    try {
                         zipper.extractAll(dest);
                         br.close();
                         JOptionPane.showMessageDialog(null, "The zip has been cracked. The password is " + passwordArray.get(0));
                         break;
                    } catch(ZipException ze) {
                        System.out.println(passwordArray.size());
                        passwordArray.remove(0);
                        continue;
                    }
                }
        } else {
                zipper.extractAll(dest);
                JOptionPane.showMessageDialog(null, "The selected zip was not password protected. It was extracted anyways.");
        }

Code Snippet (Just line 87):
zipper.setPassword((String) passwordArray.get(0));

Code Snippet (Output before the exception):
darkside
Testing password no.4747, which is darkside
1
angie1
Testing password no.4748, which is angie1
1
321456
Testing password no.4749, which is 321456
1

Exception in thread "main" java.lang.NullPointerException

Comment: Why are you calling `passwordArray.get(0)` and why are you casting to `String`?
Comment: for that matter, why are you testing on `(line = br.readLine()) != null`, acknowledging that it can become `null`, but then not have all the code that should trigger on not null inside that conditional?
Comment: It was a damn blank line in the dictionary... http://pastebin.com/UMRBPTnB
Answer: Make this condition to the whole while loop, When the line is null, it wont add with the passwordArray. But the next line you are trying to get the value from the passwordArray.get(0).  So you have to make the condition for the whole code.
   while (true)
    { //while elements are still in the array list
        String line;
        if ((line = br.readLine()) != null)
        {
            passwordArray.add(line);
            System.out.println(line);

            zipper.setPassword((String) passwordArray.get(0)); //set the password to element position [passwordCounter]
            System.out.println("Testing password no." + passwordCounter + ", which is " + passwordArray.get(0));
            passwordCounter = passwordCounter + 1;

            try
            {
                zipper.extractAll(dest);
                br.close();
                JOptionPane.showMessageDialog(null, "The zip has been cracked. The password is " + passwordArray.get(0));
                break;
            }
            catch (ZipException ze)
            {
                System.out.println(passwordArray.size());
                passwordArray.remove(0);
                continue;
            }
        }
    }

Answer: Check the dictionary first...
gorillaz
foxylady
darkside
angie1
321456

summer05
sabrina1
rosalinda
roderick
muslim
matilde
indigo

"So simple it hurts."

NullPointerException in Loop


Problema em salvar relacionamento muitos para muitos com Entity Framework Core

Question: Estou com problema em salvar um relacionamento de muitos para muitos com Entity Framework Core
Tenho as seguintes entidades
[Table("quadros")]
public class Quadro : BaseEntity
{
    public bool Ativo { get; set; }
    public string Titulo { get; set; }
    public List<CheckList> Checklists { get; set; }
    public bool Concluido { get; set; }
    public DateTime DataUltimaOperacao { get; set; }
    public List<UsuarioQuadro> Usuarios { get; set; }
    public long EmpresaId { get; set; }
    public Empresa Empresa { get; set; }
    public List<Atividade> Atividades { get; set; }
}

[Table("usuarios")]
public class Usuario : BaseEntity
{
    public bool Ativo { get; set; }
    public string Nome { get; set; }
    public string SobreNome { get; set; }
    public string Email { get; set; }
    public string Login { get; set; }
    public string Senha { get; set; }
    public int TipoUsuario { get; set; }
    public long EmpresaId { get; set; }
    public Empresa Empresa { get; set; }
    public List<UsuarioQuadro> Quadros { get; set; }
    public List<Atividade> Atividades { get; set; }
}

entidade de relacionamento
[Table("usuarioQuadro")]
public class UsuarioQuadro : BaseEntity
{
    public Usuario Usuario { get; set; }
    public long UsuarioId { get; set; }
    public Quadro Quadro { get; set; }
    public long QuadroId { get; set; }
}

Meu DataContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
 modelBuilder.Entity<UsuarioQuadro>()
     .HasKey(uq => new { uq.UsuarioId, uq.QuadroId });
   modelBuilder.Entity<UsuarioQuadro>()
        .HasOne(u => u.Usuario)
        .WithMany(uq => uq.Quadros)
        .HasForeignKey(u => u.UsuarioId)
    modelBuilder.Entity<UsuarioQuadro>()
        .HasOne(q => q.Quadro)
        .WithMany(uq => uq.Usuarios)
        .HasForeignKey(u => u.QuadroId);
}

porém quando vou salvar o quadro com os usuários recebo a seguinte Exeception

System.InvalidOperationException: 'The property 'UsuarioId' on entity type 'UsuarioQuadro' has a temporary value. Either set a permanent value explicitly or ensure that the database is configured to generate values for this property.'
Comment: Não sei se tem relação, mas acho que na sua `BaseEntity` tenha um campo para **ID**, talvez o problema esteja ao tentar fazer a chave composta `.HasKey(uq => new { uq.UsuarioId, uq.QuadroId }); `. Tente remover a chave composta e deixar apenas a *PK*
Comment: no EF Core, você não precisa colocar os campos `long UsuarioId` ele reconhece a composição como chave automaticamente, não precisa nem mexer no `OnModelCreating`
Comment: @Barbetta Fiz o teste porem sem sucesso, creio que precisa de mapear a chave composta, pois fiz igual esta na documentacao EF Core no site da Microsoft  https://docs.microsoft.com/pt-br/ef/core/modeling/relationships
Comment: @RovannLinhalis Posso remover as propriedades `UsuarioId` e `QuadroId` da entidade `UsuarioQuadro`
e também remover todo o mapeamento da referente a entidade `UsuarioQuadro` na `OnModelCreating`
  ?
Comment: Falta você colocar o código que faz o preenchimento dos dados antes de salvar. Normalmente se forem novos registros (você não tem o ID), você apenas faz o set das instâncias no UsuarioQuadro e adiciona na lista. O EF vai preencher os IDs depois que salvar a entity.
Comment: sim, e me parece que não é necessário que UsuarioQuadro  herde BaseEntity (que deve possuir uma PK), você deve definir Usuario e Quadro como [KEY]
Answer: Baseado no erro acima, eu creio que você poderia colocar no modelBuilder:
modelBuilder.Property(x => x.userId).ValueGeneratedOnAdd();


What would be the best way to setup a mobile theme for an existing domain with domain access module?

Question: We have implemented a multidomain portal using domain access module. Now we would like to setup a mobile site for each domain added.
Initially we thought about going for responsive layout, but as the mobile portal has very simple layout with minimum elements, using responsive model might be an overkill as it load every html elements to mobile even if most of the elements are not used in mobile theme. Also there are few features/blocks like slider etc implemented differently in mobile theme.
The m.domain and separate theme for mobile site looks like a feasible solution. But I am not sure what would be the best way to integrate it with domain access.
We want all content in the desktop domain available in the mobile domain, only theme need to be changed. It would be good if we were able to setup a domain alias where we can provide the m.domain.com in the configuration for the main domain and use the same access control as main domain, only change will be the theme and the links rel="alternate" and rel="canonical"
Also we need to setup a http redirection when a user visit the site from a mobile device. (Any suggestion for switching back to the desktop theme from mobile device and vice versa)
Is there any way to implement something like this using domain access?
Answer: You need these two modules to do this:
https://www.drupal.org/project/simple_mobile_redirect
(detects mobiles and redirects them to pre configured paths)
&
https://www.drupal.org/project/themekey
(serves any theme (e.g. a customized mobile theme) under any pre configured path)
Comment: If we use domain access, then themekey is not required as the domain access module itself supports separate themes for each domain. Will check simple_mobile_redirect.
Answer: We have finally decided to go with the domain access for the separate m. website.

We have to create a domain variable to map the primary domain and its mobile domain
Assign all the content added from the primary domain to the corresponding mobile domain also. - This can be done programatically on node save.
Need to follow the standard practices for the mobile sites with separate urls. Here is a good documentation regarding what all need to be taken care of when we create a mobile site with different URL - https://developers.google.com/webmasters/mobile-sites/mobile-seo/configurations/separate-urls
Implement a UserAgent based mechanism in javascript/JQuery for redirecting the users access the site from a mobile device to m. website.


Trying to set-up Authoritative-Only DNS Servers. My domains are not directed to the server

Question: Guys I am hoping I can find help here.
I am having trouble setting up Authoritative-Only DNS Servers.
One server is a Cloud Virtual Server XL (master server and web server - has Plesk) the other one is Cloud Virtual Server S (slave server).
Please note that servers have different IPS and aren't in the same range but they are something like this: The XL Virtual Server(8X.1XX.1XX.2XX) and the S Virtual Server (9X.9X.2XX.9X).
I am aware that there are more types of DNS, but with some light reading and googling I figured Authoritative-Only are best for my use.
The current problem I am having is that my domains aren't getting through to my nameservers. I'm getting a server not found on all of them, the main domain however is pointed correctly and resolves to the main machine.
The guide I used: https://www.digitalocean.com/community/tutorials/how-to-configure-bind-as-an-authoritative-only-dns-server-on-ubuntu-14-04.
I followed it from word to word, only part that I left out is Reverse Zones (in-addr.arpa) I am not sure on how to proceed on those. However, I did set my hostnames and Reverse DNS in their Control panel (1and1 Control Panel) to vps1.xxx.space and vps2.xxx.space (Hopefully my hunch was on point on this one and that should be solved? - again I am probably wrong).
My db.xxx.space file looks like this:
root@vps1:~# sudo nano /etc/bind/zones/db.xxx.xxx
  GNU nano 2.5.3                    File: /etc/bind/zones/db.xxx.space

; BIND data file for local loopback interface
;
$TTL    604800
@       IN      SOA     ns1.xxx.space. admin.xxx.space. (
                              5         ; Serial
                         604800         ; Refresh
                          86400         ; Retry
                        2419200         ; Expire
                         604800 )       ; Negative Cache TTL
;
; Name Servers
xxx.space.  IN      NS      ns1.xxx.space.
xxx.space.  IN      NS      ns2.xxx.space.

; A records for name servers
ns1     IN      NS      8X.1XX.1XX.2XX
ns2     IN      NS      9X.9X.2XX.9X

; other A records
@       IN      A       8X.1XX.1XX.2XX
www     IN      A       8X.1XX.1XX.2XX
vps1.xxx.space.     IN      A       8X.1XX.1XX.2XX
vps2.xxx.space.     IN      A       9X.9X.2XX.9X
xxx.space.  IN      MX      10      mail.xxx.space.
mail.xxx.space.     IN      A       8X.1XX.1XX.2XX
ns1.xxx.space.      IN      A       8X.1XX.1XX.2XX
ns2.xxx.space.      IN      A       9X.9X.2XX.9X
www.xxx.space.      IN      CNAME   xxx.space.

My /etc/bind/named.conf.local file (master):
//
// Do any local configuration here
//

// Consider adding the 1918 zones here, if they are not used in your
// organization
//include "/etc/bind/zones.rfc1918";

zone "xxx.space" {
        type master;
        file "/etc/bind/zones/db.xxx.space";
        allow-transfer { 9X.9X.2XX.9X; };
};

My /etc/bind/named.conf.options file:
options {
        directory "/var/cache/bind";

        recursion no;
        allow-transfer { none; };

        // If there is a firewall between you and nameservers you want
        // to talk to, you may need to fix the firewall to allow multiple
        // ports to talk.  See http://www.kb.cert.org/vuls/id/800113

        // If your ISP provided one or more IP addresses for stable
        // nameservers, you probably want to use them as forwarders.
        // Uncomment the following block, and insert the addresses replacing
        // the all-0's placeholder.

        // forwarders {
        //      0.0.0.0;
        // };

        //========================================================================
        // If BIND logs error messages about the root key being expired,
        // you will need to update your keys.  See https://www.isc.org/bind-keys
        //========================================================================
        dnssec-validation auto;

        auth-nxdomain no;    # conform to RFC1035
        listen-on-v6 { any; };
};

My /etc/bind/named.conf file:
// This is the primary configuration file for the BIND DNS server named.
//
// Please read /usr/share/doc/bind9/README.Debian.gz for information on the
// structure of BIND configuration files in Debian, *BEFORE* you customize
// this configuration file.
//
// If you are just adding zones, please do that in /etc/bind/named.conf.local

include "/etc/bind/named.conf.options";
include "/etc/bind/named.conf.local";
include "/etc/bind/named.conf.default-zones";

My /etc/bind/named/conf.local (slave) file:
//
// Do any local configuration here
//

// Consider adding the 1918 zones here, if they are not used in your
// organization
//include "/etc/bind/zones.rfc1918";

zone "xxx.space" {
        type slave;
        file "slaves/db.xxx.space";
        masters { 8X.1XX.1XX.2XX; }; #ns1 private IP
};

My advanced DNS settings for the main domain (xxx.space) that is supposed to have nameservers.Advanced Panel at namecheap.com
Rest of the domains have their custom name servers option set and point to the ns1.xxx.space and ns2.xxx.space nameservers.
I registered the name servers with namecheap.com as well, through the advanced DNS panel!
My Plesk DNS configuration: Plesk Screenshot
If you have any more questions feel free to ask.
Misc information:

All domains are hosted (except a few - not working as well) at namecheap.com
Servers are hosted at 1and1.com - Germany
Everything on the servers is up to date. (BIND etc.)
Servers are running Ubuntu 16.04

My questions:

What could be causing these issues for me?
Could there be an issue because I am using IPs that aren't in the same range?
How should I address Reverse Zones for two single IPs in the files?

I appreciate any help, suggestions or pointers!
Comment: Another DNS question that has omitted or obfuscated the domain name. How do you think we're going to help you? The problem COULD LITERALLY BE ANYTHING. Do yourself and us a favor and provide the domain name so that we can actually, you know, check DNS for ourselves.
Comment: This is way too long. Please clearly and succinctly state your question, and put it in the title too.
Comment: Please avoid useless obfuscation and if you absolutely need to use it do not obfuscate like you did but use data from RFC2606 and 5737/3849. But as @joeqwerty said, if you want relevant and quick help, you need to provide all data without obfuscation, specifically with a post so long as yours (I was unable to read it to its end because of the obfuscation).
Comment: Also you have online testing tools: https://zonemaster.net/ and https://dnsviz.net/
Comment: Thanks for the tip. Reduced the unescessary information. Hopefully its more clearer now.
Comment: You show an image from NameCheap where you have configured various DNS RRs. Are you trying to use NameCheap to host your DNS, or are you trying to have your Ubuntu servers host the DNS? Also, you should post your `bind` configuration, like `named.conf`, `named.conf.options`, etc.
Comment: Thanks for commenting, the configuration is same as per the guide for named.conf and named.conf.options. But I will add them as soon as I am home. Only the main domain is hosted on namecheap and thats the picture i posted. The configuration for it. To clarify I am trying to make my ubuntu servers host everything, but as per my understanding of the guide the main domain should be hosted at namecheap? Or am I wrong?
Comment: I've added the files you mentioned. If some more are needed feel free to tell me, I'll add them.
Answer: Troubleshoot the problem properly. Start at the bottom, for your NS servers to serve records for your domain, the domain in question needs to list them.
Perform a whois on example.com, what NS servers are listed? If they're correct, move to the next step.
Are your NS servers' hostnames at example.com as well (the domain you're trying to be authoritative for)? Then you need glue records. Are your those working? Test them.
If it's a .com domain, for example
$ dig +short com. NS
a.gtld-servers.net.
i.gtld-servers.net.
m.gtld-servers.net.
k.gtld-servers.net.
l.gtld-servers.net.
g.gtld-servers.net.
e.gtld-servers.net.
h.gtld-servers.net.
j.gtld-servers.net.
c.gtld-servers.net.
d.gtld-servers.net.
f.gtld-servers.net.
b.gtld-servers.net.

$ dig +norec @h.gtld-servers.net. example.com NS
...
;; QUESTION SECTION:
;example.com.            IN  NS

;; AUTHORITY SECTION:
example.com.     172800  IN  NS  ns1.example.com.
example.com.     172800  IN  NS  ns2.example.com.

;; ADDITIONAL SECTION:
ns1.example.com. 172800  IN  A   10.10.10.1
ns2.example.com. 172800  IN  A   10.10.10.2

If the hostname of your NS servers is not on the same domain you're being authoritative for, then test those records and see that they resolve.
If your glue exists, or your NS hostnames resolve correctly, then can the outside world actually talk to your NS servers? Query them directly from an outside host you haven't made special accommodations for.
dig @ns1.example.net example.com

By this point I'm going to assume you've encountered a problem because judging by the content of your db file, unless you've left information out - it looks incorrect as it's missing an SOA.
Comment: Thanks for you reply man.The domain I'm using as the main domain is xxx.space so its a .space domain. The xxx.space is now finally directing towards the VPS. In regards to the test you mentioned using the dig +norec @h.gtld-servers.net. yourdomain.com NS I get this [response](https://pastebin.com/VM6uvFWx) as for the email@example.com yourdomain.com I get a `dig: couldn't get address for 'ns1.myotherdomain.com': failure`

Sorry, I did leave out the SOA accidentally. I've added it now as well as some of the files @Andrew mentioned I should add.
Comment: Read the commands I wrote - you should be replacing information with ones relevant to yourself where applicable. I wouldn't recommend running a publicly accessible NS server yourself if you're having this kind of trouble. Badly configured nameservers are the bane of many service providers who have to suffer through DoS attacks originating from them. Play with things on private networks.
Comment: I understand your concern, I did replace everything where its applicable. Therefore I am not willing to post any of my information publicly exactly because I am having this kind of trouble. (hance I am removing most of it and placing dummy content instead of it). I am just telling you the results of queries I am having, hoping that you can give me the right pointers in order to solve the problem.
Comment: whois is not a tool to test DNS issues, never start from there
Comment: Not all domain names use glues, in fact it is a minority
Comment: @steviss If you did provide the domain name, people would be able to give you relevant information. **Of course** `dig +norec @h.gtld-servers.net.` will not work for your `.space` domain since these nameservers are authoritative for `.COM` and `.NET` TLD and **NOT** for `.SPACE`. `dig NS space.` will show you the ones authoritative for .SPACE.
Comment: "Therefore I am not willing to post any of my information publicly exactly because I am having this kind of trouble. (hance I am removing most of it and placing dummy content instead of it)." this is a bad idea and very selfish too. Bad idea for you since you will not get correct help and you obviously do not understand the basics of DNS so people can not help you in the blind. Selfish because this website is not there just to answer your problem but to build a Q&A database that can be useful in the future for other people having the same problem...
Comment: whois is a tool that gives you an easy way to determine a domain's nameservers. It's simpler than explaining how someone can query the root NS for a TLD, and simpler still than figuring out just who the registrar for a domain is and how to check the configuration in their management panel. I recommended it as the first step since it will immediatley point to an issue (e.g., their domain still uses their registrar's NS), before going on to explain more involved troubleshooting steps.
Comment: I thought I was clear as well about the situation when glue is involved - when the authoritative NS for a domain is on the same domain. e.g., example.com's authoritative NS is ns1.example.com. It's a loop, thus needs glue.
Answer: So, guys, I solved the problem myself (a couple of days after posting here).
1and1  started offering a hardware-based firewall with its Cloud-Based servers. My configurations were correct and everything was set-up correctly server-side but no ports were allowed through.
After allowing them manually the server started working flawlessly.
You can set this up by going into your 1and1 control panel, selecting your server (under "Contract and Product Overview"), then "Select Product", then  "Servers & Cloud" and select the server you want to edit.
When the other panel opens up select "Networking" and "Firewall Policies" afterward, there you can modify/create your Firewall policies. When you enter the configurations you also have predefined values there as well. So you won't have to google ports etc.
This fixed all my server issues and the DNS issues.
Also, thank you for all the help, some of the comments helped a lot.


AWS STS endpoint selection in CLI

Question: When using STS to assume a role, in the AWS SDKs (Java, for example), we have shaved valuable seconds off the operation by selecting the 'local' STS endpoint for the region our code is executing in (e.g. https://sts.eu-west-2.amazonaws.com).
Is it possible to do the same from the CLI (aws sts assume-role ...?  There doesn't seem to be an option to override the default endpoint in the documentation.
Answer: Take a look at: Activating and Deactivating AWS STS in an AWS Region and enable the region endpoint you want to connect to.
--region (string)
is common for all AWS CLI commands. Once you enable additional endpoints, you can use --region (string) to override the default endpoint.
Comment: Add the AWS CLI command line option --debug. The debug output will contain the endpoint used.
Comment: Thanks, STS is definitely active in our region, and we are already using the `--region` option, so sounds like we should already be connecting to the local STS service
Comment: Check CloudTrail to make sure you are connecting to the correct region.
Comment: @JohnHanley Thanks. totally forgot about --debug.

AWS STS endpoint selection in CLI