Advantage of Logs and DBs on separate SAS HDDs on dedicated server?

Question: Is there any significant performance advantage of having log data (application + DB) and DB data on separate SAS drives (for a dedicated server running CentOS) because writes of logging and db will cause writes to be random while keeping things separate will allow more sequential writes (I might be wrong here!).
Also, logs are mostly write only, while I expect my DB to be 90/10 read/write.
Comment: It is not about how the relative number of reads and writes compare but about the absolute IOPS, nine reads per minute vs 1 write you could manage from an old floppy drive. ... 9000/1000 per second is something completely different. (IIRC a 15k SAS drive supports 200 IOPS)
Comment: Lets say we are talking about server at max capacity, because performance will be important in that situation!
Comment: `Lets say we are talking about server at max capacity` - That's a meaningless statement. What does max capacity mean in this case? How are you quantifying max capacity?
Answer: One major advantage of having separate disks, is the ability to recover data in the event of a failure.
If you take regular backups of the database, and record transaction logs to a different disk than the database, if either disk fails, you can quickly get up and running without any database data being lost (restore from the backup, and replay the transaction logs, to recreate the database at the time of the disk fail).
You are also correct about disk IO.  The more spindles you have working on parallel workloads the more performant you are.
You may however want to also consider utilising RAID.  I would much rather run a database in RAID 10, and be able to hot swap out a disk with zero downtime in the event of a failure, then split 4 disks as 2 databases and 2 logs, and have a database outage after a disk failure, even if I can recover all of the data.
RAID 10 can also give a significant boost in disk read speed, which might have a greater effect on database reads.
The best solution will differ based on the type of database you run, the number of disks available, the uptime requirements, performance requirements and other hardware restraints.
In an ideal world, you would be able to utilise all of the above techniques and do so on multiple database servers to form a redundant cluster.


Average amount of picks before re-picking

Question: I have a set of $N$ elements and I iterate the following procedure (all the elements at the beginning are not marked):

I pick an element at random.
If it is marked, I stop.
If it is not marked, I mark it and I repeat the procedure.

How many times on average do I iterate the procedure before stopping because I am picking something I have already picked?
My best shot at solving it
The probability of picking one more, having already picked one is
\begin{equation*}
p_i = \frac{N - i}{N}
\end{equation*}
The probability of picking at least $i$ is therefore:
\begin{equation*}
s_i = \frac{N!}{(N - i)! N^i}
\end{equation*}
The probability of picking exactly $i$ is
\begin{equation*}
f_i = s_i - s_{i + 1} = \frac{N!}{(N - i)!N^i}\frac{i}{N}
\end{equation*}
So far so good. Now, I use Stirling's approximation ($N$ is very large and the probability to have a large $i$ is very small) and (if I didnt' get any calculation wrong) I get
\begin{equation*}
f_i = \frac{i}{N} \left(\frac{N}{N - i}\right)^{(N - i + 1/2)}
\end{equation*}
The average number of picks $<i>$ is therefore:
\begin{equation*}
<i> = \sum_j^N \frac{j^2}{N} e^{-j} \left(\frac{N}{N - j}\right)^{(N - j + 1/2)}
\end{equation*}
But here I have no clue on how to go on. I can imagine this is a fairly known problem, but I wouldn't know where to look for, does it have a commonly known name?
Comment: The number $X_N$ of picks before getting an already marked item is such that, for every $k\geqslant1$, $$P(X_N\geqslant k)=\prod_{i=1}^{k-1}\left(1-\frac{i}N\right)$$ As long as $k^2\ll N$, the RHS is approximately $$\exp\left(-\sum_{i=1}^{k-1}\frac{i}N\right)=\exp\left(-\frac{k(k-1)}{2N}\right)$$ hence $$\frac{X_N}{\sqrt{N}}\to\xi$$ in distribution where, for every nonnegative $x$, $$P(\xi\geqslant x)=e^{-x^2/2}$$ More refined arguments show the convergence of the moments hence $$\frac{E(X_N)}{\sqrt{N}}\to E(\xi)=\int_0^\infty P(\xi\geqslant x)dx=\int_0^\infty e^{-x^2/2}dx=\sqrt{\frac2\pi}$$
Answer: This has been researched. It is a variant of the Birthday Problem. It seems you're on the right track according to Wikipedia, but your formula is a little off. Knuth gives $1+\sum_{i=1}^n\frac{N!}{(N - i)! N^i}$ as the answer. His proof is in The Art of Computer Programming. Ramanujan also offers an asymptotic approximation in the link, which is also called "Ramanujan's Q function."


Limit touches recognized on UIScrollView

Question: I'm trying to limit the number of touches recognised on a UIScrollView as it's executing with another gesture that has more than one touch required. I don't want the pan & swipe gestures to fire if the number of touches is greater than 1. But I'm having no success.
I've subclassed the UIScrollView and overridden the obvious methods, but numberOfTouches always returns 1?
-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.numberOfTouches > 1)
    {
        return NO;
    }
    return YES;
}

Answer: Perhaps you can do the following?
for(UIGestureRecognizer* gr in _scrollview.gestureRecognizers)
{
    if([gr respondsToSelector:@selector(setMaximumNumberOfTouches:)])
    {
        gr.maximumNumberOfTouches = 1;
    }
}

No need for sub-classing the scroll view, you can just do this in viewDidLoad of your view controller.
Comment: Doesn't work I'm afraid. It set's it for UIScrollViewPanGestureRecognizer but still responds to multiple touches :(


Erro de (T_Variable) no php,como resolver?

Question: Estou com um erro ao conectar no banco de dados,o php diz que não reconhece a linha.
Ele da o seguinte erro :
Parse error: syntax error, unexpected '$conexao' (T_VARIABLE) in C:\xampp\htdocs\Site\formcadastro\conexao2.php on line 6
Meu código em php :
<?PHP
$host = "localhost";
$user = "root";
$pass =  "";
$banco = "cadastrocli"
$conexao = mysql_connect($host,$user,$pass) or die(mysql_error());
mysql_select_db($banco) or die(mysql_error());

$idCad       = $_POST ['idCad'];
$nome       = $_POST ['Nome'];
$email      = $_POST ['Email'];
$senha      = $_POST ['Senha'];
$confirmar  = $_POST ['Confirmar'];
$telefone   = $_POST ['Telefone'];
$celular    = $_POST ['Celular'];
$nascimento = $_POST ['Nascimento'];
$sexo       = $_POST ['Sexo'];
$bairro     = $_POST ['Bairro'];
$cidade     = $_POST ['Cidade'];
$estado     = $_POST ['Estado'];

$sql = mysql_query "(INSERT INTO cadastrocli (idCad, Nome, Email, Senha, Confirmar, Telefone, Celular, Nascimento, Sexo, Bairro, Cidade, Estado)
VALUES ('$idCad', '$nome', '$email', '$senha', '$confirmar', '$telefone', '$celular', '$nascimento', '$sexo', '$bairro', '$cidade', '$estado');"
echo"Cadastro efetuado com sucesso;"
?>

Answer: Colocando o ; na linha anterior. Todas as linhas devem terminar assim para não afetar as demais, arrume isto:
$banco = "cadastrocli";

Embora não vai acontecer nada agora, é adequado fazer o mesmo na última linha. Não só porque vai acostumando sempre colocar o ponto e vírgula, mas também facilita se mais tarde colocar novas linhas, não terá o mesmo erro que ocorre agora.
Programação é ter atenção ao detalhes.
Veja "funcionando" no ideone. Também coloquei no GitHub para referência futura. Note que não gera nenhum erro.
Comment: Então,modifiquei mas mesmo assim o erro persiste.
Comment: Editei a resposta pra mostrar que funciona. Aí o problema é outro e específico no seu ambiente. Aí não temos como saber o que ocorre. O motivo de fechamento da pergunta permanece o mesmo, porque ou é erro de digitação ou não pode ser reproduzido. Dê uma olhada se não está fazendo algo errado, se está salvando o editado no lugar certo, se o erro mudou de lugar. Se tiver outro erro, abra outra pergunta.
Comment: No Google ao tentar rodar,continua dando o mesmo erro,não é erro de digitação pois já verifiquei,o que pode ser se for é um erro nas variáveis ao serem chamadas.
Comment: Mas o google não roda código.
Comment: Era claramente erro de digitação, se tem outro problema, abra uma nova pergunta com informações suficientes para poder ajudar. A única coisa que posso acrescentar que este código está pedindo para receber um ataque e roubar e destruir o banco de dados. E não sei o que significa Google nesse contexto. Os contextos que eu conheço, não roda mesmo, não é função dele rodar código PHP. Se quer ajuda, dê informações suficientes para ser ajudado. Jogar palavras sem nexo não vai te ajudar.


How to find IP address of a Switch that the host is connected to?

Question: I'm trying to write a script that can block a host by shutting down a switchport directly on the Switch.
I have access to the Cisco Router and the computer, how do I find out which Switch my computer is connected to?
I tried using "show arp" and "show cdp neighbors" but the interface of the host IP address just isn't written there. Or maybe I just didn't get the command.
Anyway, the Network administrator suggested that I'm just supposed to connect to the "neighbors" until eventually there aren't any and that's how I know I reached the direct Switch. But it doesn't work for me. Is there an easier way?
Answer: Cisco IOS provide this feature called port-security. You can use it to restrict access on an interface that you want limiting and identifying MAC addresses of devices that are allowed to send packet throught this port.
Also this option allows to define the reaction of the switch after detection of the violation access.
SW1(config)# interface fa 0/0
SW1(config)# switchport mode access
SW1(config-if)# switchport port-security

First login on the switch, and select the interface that you want to activate port-security in global configuration.
Depending what you try to do, you have the option of set a MAC address that have authorization to send packet on the network.
SW1(config-if)# switchport port-security mac-address cafe.dead.bad4

Ok, now you have 3 options to define how the switch will react when a violation detection occur:

protect (stop sending packet, without log)
restrict (stop sending packet + log message)
shutdown (put the interface in shutdown state)
SW1(config-if)# switchport port-security violation shutdown

When a violation occure, you can see in show command, the interface will be in err-disable.
No script is required for that


Posso utilizar "mysql_real_escape_string" em site "mysqli_connect"?

Question: posso utilizar a função mysql_real_escape_string em um site construído em mysqli_connect? E se sim faz alguma diferença ou a proteção seria menor?
Ou deveria utilizar mysqli_escape_string? Porque quando pus o mysqli_escape_string deu uns erros quando foi fazer um mysqli_query..
mysqli_escape_string() expects exactly 2 parameters, 1 given in ....
POREM  ao usar o mysql_escape_string ele retorna
mysql_escape_string(): This function is deprecated; use mysql_real_escape_string()
No cado deveria utilizar mysql_real_escape_string?
Answer: Não, não use! A função mysql_real_escape_string está obsoleta.
O certo seria usar:
$anything = mysqli_real_escape_string($conexao, $_POST['variavel']);

Comment: sempre tem que por a conexão junto? no meu caso >> `$painel_log = mysqli_real_escape_string($conn, $_POST['painel_log']);`
Comment: @PedroQuezado Quando as funções mysqli são utilizadas o primeiro argumento é "sempre" a conexão.
Comment: ahhhhh entendiiii
Comment: asauhsuhau VLWWW
Answer: Motivos pelos quais não se deve usar as funções mysql_, estão obsoletas, removidas do php7, necessita de um conexão mysql_ para funcionar e não resolve o problema de sql injections pois apenas escapas determinados caracteres, para resolver isso utilize prepared statements.

mysqli_escape_string() expects exactly 2 parameters, 1 given in

Ao utilizar o estilo procedural do mysqli QUASE SEMPRE o primeiro argumento da função é conexão.

string mysqli_real_escape_string ( mysqli $link , string $escapestr )

Leitura Recomendada:
Por que não devemos usar funções do tipo mysql_*?
Como prevenir injeção de código SQL no meu código PHP
Select com prepared statements MySQLi
Manual - mysqli_real_escape_string
Comment: sempre tem que por a conexão junto? no meu caso >>
`$painel_log = mysqli_real_escape_string($conn, $_POST['painel_log']);`
Comment: @PedroQuezado, sim sempre, a segunda linha amarela da resposta, mostra a assinatura da função e quantos parâmetros você deve passar ao chamar ela.
Answer: Cara, aprenda e utilize o PDO. Já foi lançado o PHP 7, que tornou obsoletas todas as funções mysql_*, tornando incompatível códigos legados. Uma hora você vai ter que lidar com esse problema. O PDO tem um método chamado bindValue que resolve esse problema facinho pra você.


Viewing a closed point as a scheme

Question: If $P$ is a closed point of a scheme $X$, then pullback of the structure sheaf $\mathscr{O}_X$ is $k(P)$. This really baffles me - by definition, this pullback is just $P \mapsto \lim_{U \supset P}\mathscr{O}_X(U)$, which is the stalk of $\mathscr{O}_X$ at $P$. So why isn't the pullback the local ring $\mathscr{O}_{X,P}$ instead of the residue field?
Answer: It looks like you are confusing the functors $i^*$ and $i^{-1}$, where $i$ is the inclusion morphism $\operatorname{Spec} k(P)\to X$.  You are right that $i^{-1}(\mathscr{O}_X)$ is the sheaf with value $\mathscr{O}_{X,P}$.  However, the definition of $i^*$ is different: for any sheaf $F$ on $X$, $i^*F=i^{-1}F\otimes_{i^{-1}(\mathscr{O}_X)}\mathscr{O}_{\operatorname{Spec} k(P)}$.  In particular, this means $i^*\mathscr{O}_X$ is $\mathscr{O}_{\operatorname{Spec} k(P)}$, which has value $k(P)$.
Comment: Well, $\operatorname{Spec} \mathscr{O}_{X,P}$ usually has more than one point, for one thing.
Comment: I guess my real question is when you view $P$ is a scheme, why is it Spec $k(P)$ rather than Spec $\mathscr{O_{X, P}}$? That should be $i^*\mathscr{O}_X$, right?
Comment: Using $k(P)$ is just taking the usual reduced closed subscheme structure on the closet set $\{P\}$.  This is the "default" way to consider any closed subset as a subscheme.
Answer: Just see that $\{P\}$ is, as closed subscheme, $\textrm{Spec }k(P)$. Take $U=\textrm{Spec }A$ an affine open containing $P$. Hence $P$ corresponds to a maximal ideal $\mathfrak{m}$ in $A$ and $$A/\mathfrak{m}\cong A_{\mathfrak{m}}/\mathfrak{m}A_{\mathfrak{m}}=k(P).$$

Viewing a closed point as a scheme


Given a schedule find all conflicting appointments for a doctors office

Question: You are given 'n' appointments. Each appointment contains startime and  endtime. You have to retun all conflicting appointments efficiently starttime and endtime can range from a few min to few years. I saw the post: FInd overlapping appointments in O(n) time? which is very similar to this. But a doubt remains.
My question is that if we have a sorted schedule given, say : (6:30-6:35), (6:40-7:10) (7:25-7:40), (7:35-7:50) and so on.
Can we not traverse the schedule list and make sure that the next appointment should begin ONLY after the previous one is over? In that case we're applying a very tight bound on the possible time for scheduling an appointment. In this example, we know that the appointment beginning at 7:35 is before last appointment ends (7:40) so it is a conflict. Do we really need to complicate the solution by creating a tree or hash map as mentioned in the most rated solution in link for similar question?
Please point out cases which can bypass this check and prove this condition invalid.
Comment: Thank you for the quick response. I wanted to make sure because the solution stated that, "The algorithm basically involves checking whether the next appointment is overlapped by _**any**_ previous ones."
Comment: You do have to check *any* previous ones. The appointment doesn't necessarily overlap the one immediately prior, eg: `(0, 5), (2, 3), (4, 8)` The third appointment overlaps the first one but not the second. However, you don't actually have to compare each appointment to every other appointment to achieve this, you can just keep track of the latest end time you have seen so far.
Comment: But if we just need to find out if there are any overlaps at all, we'll stop at the second one itself. You are right when you say, "The third appointment overlaps the first one but not the second. " but second one begins before first has ended so we never really go to the third.
Comment: Correct, however your question title is "find **all** conflicting appointments", not find the first one. :)
Answer: In the linked answer, the list appointments is not sorted, hence the more complicated solution. You are correct that if the appointments are sorted you can just traverse the list and keep track of the latest end time seen so far.
Also, note that sorting the list is O(n lg n), so you can't just sort it and then traverse it if you want an O(n) solution.
Answer: Of course the solution can be performed in O(n) time if as you say "we have a sorted schedule given." The question you referenced is assuming the times are NOT sorted.


Array cell reference in where clause of query

Question: Google Sheets sample file:
https://docs.google.com/spreadsheets/d/1WqqiysWdYMAop5uQXZnisuX291wY2PFmAMEKZhya2IM/edit?usp=sharing
I am trying to calculate the average value of each person for each month. My two variables to match are the names and month of the date. Currently I am able to get the correct values if I am applying the formula to each cell using this formula:
=IFERROR(QUERY(Sheet2!A:C,"Select avg(C) where A = '"&A2&"' and month(B) = month(date '"&TEXT(DATE(2021,MONTH(DATEVALUE($A$1&"1")),1),"yyyy-mm-dd")&"') label avg(C) '' "),"-")
What I want to do is be able to do an arrayformula instead so I will only need to input the formula once and wont have to worry about the number of names entered. I tried using this formula:
=ARRAYFORMULA(IFERROR(QUERY(Sheet2!A:C,"Select avg(C) where A = '"&A2:A&"' and month(B) = month(date '"&TEXT(DATE(2021,MONTH(DATEVALUE($A$1&"1")),1),"yyyy-mm-dd")&"') label avg(C) '' "),"-"))
, but it only calculates the average for that row.
If possible, the solution should also be using query since in the data I will be using it on I am not able to use sumifs/averageifs for some reason.
Answer: try:
=QUERY('data source'!A2:C,
 "select A,avg(C)
  where month(B)+1 = "&MONTH(A1&1)&"
  group by A
  label avg(C)''")

=ARRAYFORMULA({SORT(UNIQUE(FILTER('data source'!A2:A, 'data source'!A2:A<>""))),
 IFNA(VLOOKUP(SORT(UNIQUE(FILTER('data source'!A2:A, 'data source'!A2:A<>""))),
 QUERY('data source'!A2:C, "select A,avg(C) where month(B)+1 = "&
 MONTH(A1&1)&" group by A label avg(C)''"), 2, 0), "-")})

Comment: Issue addressed as needed! The main part of the solution given that fixed the problem is the addition of the vlookup after the query. @player0 Thank you very much again for the quick and elegant solution!


Force new articles to have tags (term + subterm) associated with it

Question: previous question
I have a site where articles need to be classified as, apple, banana, cranberry, etc....
Each category has sub-cats like apple - 1, apple - 2, ... banana - 1, banana - 2 ...
Now apples can have 10 subs and banana can have 200 or something like that.
I already make a vocabulary using taxonomy of all the terms and subterms.
What I need to do is have it so that users submit articles and it must have a category and sub-cat associated with it.
I want to do it this way so that I can have an index page of all apple articles, or just apple - 1, or banana - 2's ... etc.
Answer: What you are seeking to do is very basic and one of the early things you learn how to do in Drupal.  The simplest way to answer your question is to recommend you get a book such as Drupal 7 by Tom Geller or any of the other introductory Drupal books. Lynda.com also has a video series that can fill you in on how to use Drupal.  You can accomplish want you seek by modifying or creating a content type and adding field s linked to taxonomy terms. You can make it a requirement to add a value for each new entry.  Eventually you will want to master the Views module to find your content and display it.
Before you start working on the design of a site, yuo may want to spend some time studing Drupal basics. Drupal has a steep learning curve in the beginning and you will have to cover a lot of ground before it starts clicking and you will feel confident diving into a project.
Comment: I have 6 thousand terms or so. That would be a lot of checkboxes, I need something that repopulates the sub-categories after selecting the main category.
Comment: No checkboxes needed.  See my next response.
Answer: RE: No checkboxes
The views module can filter your content based upon the URl using contextual filters to sort through the hierarchy and control what is displayed at each level.  Views can take the input from the URL (or panel module arguments) to determine what to display.
Path auto module would create the proper path aliases for each content entry.
I am currently working on a similar navigation problem and attempting to access the content through a menu generated using Taxonomy Menu  that has arranged all the terms in a hierarchical menu. (There is a bug in the design I have not yet solved, so I cannot guarantee it works from personal experience...yet.)
Comment: I first need it for authors to be able to select the correct tags first. Views can't really help with that
Comment: See my comment Re: Correct Tags.
Answer: Re: Correct Tags comment:
I am not certain I understand what your concern is. :)
Two possible considerations:
1.  You can make the selection of the field mandatory when the content is submitted.
2.  You can expose the field in the view display to allow the user to make a selection
Comment: good enough thanks. I got hierarchical select plugin.


sum of arctangent

Question: Here is an interesting topic.  It comes from evaluating $$\sum_{k=1}^{\infty}\tan^{-1}\left(\frac{1}{k^{2}}\right)$$
I managed to dig up an old paper I have on the sum of arctans by Boros and Moll.  It is called the Method of Zeros.  It is located here:
http://www.mat.utfsm.cl/scientia/archivos/vol11/Art2.pdf  on page 6-7
I will post, verbatim, what it says.  Perhaps someone can figure out how they arrive at the solution.
They skip over the details and I do not know how they arrived at the general form they establish in [2].
"Based on the factorization of the product  $$p_{n}:=\prod_{k=1}^{n}(a_{k}+ib_{k}), \;\ a_{k},b_{k}\in R$$
The argument of $p_{n}$ is given by $$\text{arg}(p_{n})=\sum_{k=1}^{n}\tan^{-1}\left(\frac{b_{k}}{a_{k}}\right)$$
up to an integral multiple of $\pi$.
This can be applied to the case of a polynomial with real coefficients given by
$$p_{n}(z)=\prod_{k=1}^{n}(z-z_{k})$$
Then,  $$\text{arg}(p_{n}(z))=\sum_{k=1}^{n}\tan^{-1}\left(\frac{x-x_{k}}{y-y_{k}}\right)$$
up to an integral multiple of $\pi$.
The special case $$p_{n}(z)=z^{n}-1$$ has roots at
$$z_{k}=\cos(\frac{2\pi k}{n})+i\sin\left(\frac{2\pi k}{n}\right),$$  so we get:
$$\text{arg}(z^{n}-1)=\sum_{k=1}^{n}\tan^{-1}\left(\frac{x-\cos\left(\frac{2\pi k}{n}\right)}{y-\sin\left(\frac{2\pi k}{n}\right)}\right)$$
The classical factorization  $$\sin(\pi z)=\pi z\prod_{k=1}^{\infty}\left(1-\frac{z^{2}}{k^{2}}\right) \tag{1}$$
shows that one can think of $\sin(\pi z)$ as a polynomial in $z$ of infinite degree.
Euler than derived $$\sum_{k=1}^{\infty}\frac{1}{k^{2}}=\frac{{\pi}^{2}}{6}$$ by comparing the cubic terms of (1).
This now yields $$\sum_{k=1}^{\infty}\tan^{-1}\left(\frac{2xy}{k^{2}-x^{2}+y^{2}}\right)=\tan^{-1}(y/x)-\tan^{-1}\left(\frac{\tanh(\pi y)}{\tan(\pi x)}\right) \tag{2}$$
That is it. They mention Euler's famous sum of reciprocal of squares then just skip to "this then yields...."
Does anyone see how? Besides that, didn't Euler compare the square terms and not the cubic ones?
So, for the problem at hand, we would let $x=y=\frac{1}{\sqrt{2}}$ and arrive at:
$$\sum_{k=1}^{\infty}\tan^{-1}\left(\frac{1}{k^{2}}\right)=\frac{\pi}{4}-\tan^{-1}\left(\frac{\tanh\left(\frac{\pi}{\sqrt{2}}\right)}{\tan\left(\frac{\pi}{\sqrt{2}}\right)}\right)\approx 1.42474......$$
Comment: I think it means the "cubic terms" of the power series in $z$ gotten from $[1]$ to get the sum of the square inverses.  Basically, what is the coefficient of $z^3$ on either side of $[1]$?  (Note, there is no $z^2$ term in the expansion of the right side of $[1]$.
Answer: Here is a slightly different approach.
Note that
$$
\log(1+ix)=\tfrac12\log(1+x^2)+i\tan^{-1}(x)\tag{1}
$$
So, applying $(1)$ yields
$$
\sum_{k=1}^\infty\tan^{-1}\left(\frac{1}{k^2}\right)=\Im\left(\log\left(\prod_{k=1}^\infty\left(1-\frac{\alpha^2}{k^2}\right)\right)\right)\tag{2}
$$
where $\alpha  =\frac{1}{\sqrt{2}}-\frac{i}{\sqrt{2}}$, so that $\alpha^2=-i$.
Furthermore, the sinc function has the following product expansion
$$
\prod_{k=1}^\infty\left(1-\frac{\alpha^2}{k^2}\right)=\frac{\sin(\pi\alpha)}{\pi
\alpha}\tag{3}
$$
We also have
$$
\begin{align}
\frac{\sin(x+iy)}{x+iy}
&=\frac{\sin(x)\cosh(y)+i\cos(x)\sinh(y)}{x+iy}\\
&=\frac{x\sin(x)\cosh(y)+y\cos(x)\sinh(y)}{x^2+y^2}\\
&+\;i\frac{x\cos(x)\sinh(y)-y\sin(x)\cosh(y)}{x^2+y^2}\tag{4}
\end{align}
$$
Combining $(2)$, $(3)$, $(4)$, and using the identity $\tan(\pi/4-x)=\frac{1-\tan(x)}{1+\tan(x)}$ yields
$$
\begin{align}
\sum_{k=1}^\infty\tan^{-1}\left(\frac{1}{k^2}\right)
&=\Im\left(\log\left(\frac{\sin(\pi\alpha)}{\pi\alpha}\right)\right)\\
&=\tan^{-1}\left(\frac{x\cos(x)\sinh(y)-y\sin(x)\cosh(y)}{x\sin(x)\cosh(y)+y\cos(x)\sinh(y)}\right)\\
&=\tan^{-1}\left(\frac{\tan(\frac{\pi}{\sqrt{2}})-\tanh(\frac{\pi}{\sqrt{2}})}{\tan(\frac{\pi}{\sqrt{2}})+\tanh(\frac{\pi}{\sqrt{2}})}\right)\\
&=\frac{\pi}{4}-\tan^{-1}\left(\frac{\tanh(\frac{\pi}{\sqrt{2}})}{\tan(\frac{\pi}{\sqrt{2}})}\right)\tag{5}
\end{align}
$$
Comment: Very nice.  Thanks RobJohn.  You always have ingenious solutions.
Comment: @RandomVariable: yes, that is true, but since $|\tan^{-1}(x)|\le|x|$ and $\sum_{k=1}^\infty\frac{1}{k^2}=\frac{\pi^2}{6}$, the sum in question is less than $\frac{\pi^2}{6}<\pi$.
Comment: The underlying assumption is that you remained on the principal branch of the logarithm.
Answer: I don't understand why you have $x$ in the numerator and $y$ in the denominator in some of the upper equations. However, in $[2]$ they're the right way around. The left-hand side is minus the sum of the arguments of $1-z^2/k^2$, the first term on the right-hand side is the argument of $z$, and the second term on the right-hand side is minus the argument of $\sin(\pi z)$:
$$
\begin{eqnarray}
\sin(\pi z)
&=&
\frac{\mathrm e^{\mathrm i\pi z}-\mathrm e^{-\mathrm i\pi z}}{2\mathrm i}
\\
&=&
\frac{\mathrm e^{\mathrm i\pi (x+\mathrm iy)}-\mathrm e^{-\mathrm i\pi (x+\mathrm iy)}}{2\mathrm i}
\\
&=&
\frac{\mathrm e^{-\pi y}(\cos(\pi x)+\mathrm i\sin(\pi x))-\mathrm e^{\pi y}(\cos(\pi x)-\mathrm i\sin(\pi x))}{2\mathrm i}
\\
&=&
\sin(\pi x)\cosh (\pi y)+\mathrm i\cos(\pi x)\sinh(\pi y)\;.
\end{eqnarray}
$$
By the way, a lot of your parentheses are undersized.
Comment: Thanks for the response.  Nice observation. I do not know why the y's and x's are swapped either. It comes from the paper in the link. I noticed that as well. Perhaps they are typos. Earlier in the paper they bring up $$\sum_{k=1}^{n}tan^{-1}h(k)=tan^{-1}(f(n+1))-tan^{-1}(f(n))$$ where $$h(k)=\frac{f(x+1)-f(x)}{1+f(x+1)f(x)}$$.  Perhaps they are using that in some respect.  I played around and got close, but did not quite get the $$\frac{2xy}{k^{2}-x^{2}+y^{2}}$$ they obtained.
Comment: @Cody: That last expression is the argument of $1-z^2/k^2$, which is the argument of $(k^2-z^2)/k^2$, which is the argument of $k^2-z^2$.
Comment: Joriki, if you don't mind,  may I ask how you get the arguments of $1-\frac{z^{2}}{k^{2}}$?.  I guess I am too stupid to see it. Perhaps I should just forget about it, but I hate it when they skip steps like this. The rest of the paper I understand.
Answer: I see now. Thanks for the pointers, Joriki.
The roots of $1-\frac{z^{2}}{k^{2}}$ are $-k$ and $k$.
This gives $$\frac{\frac{x-k}{y}+\frac{x+k}{y}}{1+\frac{x-k}{y}\frac{x+k}{y}}$$
$$=\frac{2xy}{k^{2}-x^{2}+y^{2}}$$.
Comment: That's a lot more complicated than necessary. You can get the argument directly from the standard formula. The numerator is the imaginary part of $k^2-z^2$, and the denominator is the real part of $k^2-z^2$.
Comment: Wow, thanks, Joriki.  A case of not seeing the forest for the trees. I should have seen that. *blush*   I was making it too complicated. Thanks a lot for your help and take care.  Your help was insightful and valued.

sum of arctangent


Why does the series not converge to its actual value?

Question: I am uncertain why does the taylor series expansion of $\ln(x)$ $$\sum^{\infty}_{n=1} \frac{(-1)^{n+1}(x-1)^n}{n}$$ at $x = 2$ has almost the same value with the actual value of $\ln(2)$. However, the sum of the taylor series expansion of $\log_3(2x-1)$ which is $$\sum^{\infty}_{n=1} \frac{(-1)^{n+1}(2^n)(x-1)^n}{(n)(\log3)}$$ at $x = 2$ is not even almost equal to the value of $\log_3(3)$. The actual value is $1$, but the value of $$\sum^{10}_{n=1} \frac{(-1)^{n+1}(2^n)(x-1)^n}{(n)(\log3)}$$ is around $-100$. The sum, a negative value, increases as the order of the summation increases. What is the reason behind this?
Answer: It being $\log_3$ is irrelevant, you can forget about that part. The point is that the expansion of $\ln(2x-1)$ about $x=1$ evaluated at $x=2$ is the same series as for the expansion of $\ln(y)$ about $y=2 \cdot 1 - 1 =1$ evaluated at $y=2 \cdot 2-1=3$, which is outside the interval of convergence of the series, which is to say $(0,2]$.


Mudar a fonte de section

Question: Tenho o seguinte trecho:
\section{Referencial teórico}

Quero alterar a fonte para 14pt como fazer sem alterar o restante do texto que se encontra com fonte 12pt
Comment: Não vás por aí! em LaTeX a vantagem é não pensar em tamanhos nem fontes -- só em conceitos.
Answer: Você tem a opção de pelo menos dois pacotes para mudar a fonte das seções e subseções.
Pacote sectsty:
\documentclass{article}
\usepackage{sectsty}

% Para definir a fonte da seção
\sectionfont{\fontsize{14}{15}\selectfont}

\begin{document}

\section{Test Section}
test \newline
\fontsize{12}{15}\selectfont test \newline
\fontsize{14}{15}\selectfont test

\end{document}

Pacote titlesec:
\documentclass{article}
\usepackage{titlesec}

% Para definir a fonte da seção
\titleformat{\section}
  {\normalfont\fontsize{14}{15}\bfseries}{\thesection}{1em}{}

\begin{document}

\section{Test Section}
test \newline
\fontsize{12}{15}\selectfont test \newline
\fontsize{14}{15}\selectfont test

\end{document}

Fonte: https://tex.stackexchange.com/a/103290
Para mais detalhes dependendo da classe do documento: https://tex.stackexchange.com/a/59727

Mudar a fonte de section


How did Baroque music come to be associated with Christmas?

Question: I was introducing Baroque music to a friend, and trying to make it less intimidating, I jokingly said, "You've heard this before, Christmas shopping at Macy's." My friend laughed, but I started to wonder why that association existed.
Is it just me, or is the association real? I didn't find much online. The Worcester Chamber Music Society says, advertising a now-past program, "Two of Bach's Brandenburg Concertos raise the Christmas spirits as only Bach can!" An event listing site called Early Music America includes a listing that says, "Nothing says Christmas like a beautiful package of Baroque musical jewels." But that's just evidence of the association, and not very much evidence at that.
Comment: I have never associated Baroque music with Christmas and neither did I know that any other person would have such an association. Anyway if someone has such an association it would obviously be real for that person, but only as a subjective reality.
Answer: At least in Germany, you'll find some performance of Bach's Christmas oratorio in basically any larger town during the holiday time.  There'll also be some lesser known variants, like the Christmas oratorio of Heinrich Schütz.
The special case of a Christmas oratorio did not gather a whole lot of traction in times after the Baroque, so the usual season-specific performances will tend to be in the baroque spirit.
It's also the season of Eastern European street musicians who interrupt their music professorships to come scare the heebie bejeebies out of the local performers in the West.  A cultural common denominator for small ensembles with classical instruments playing "pleasing" music does happen to be Baroque music.  The conservatories in Russia certainly have Bach in their curricula.
Regarding Christmas season music, instrumental music tends to work better than singing for busking since you don't get shooed away as fast and are less obtrusive.
Answer: Baroque music is for life, not just for Christmas.
Your association of baroque music with Christmas is probably because of the increased prominence of church music in the mainstream listening palette at that of year, although unaccompanied sacred vocal music spans a far wider time period than the period usually referred to as the baroque.
Bach's Christmas Oratorio and Handel's Messiah are deservedly popular at that time of year which may have also created the association.
Comment: I associate Handel's Messiah with Easter. Well, actually a stronger association I have with this work is some movements with violin parts that I love to play. I have participated in many performances of this work always with all three parts. Sometimes at Christmas time someone makes a permance that ends with the Hallelujah Chorus which is the end of the second part. But then you miss the Bass Air: "The Trumpet shall sound" (sometimes referred to as "The Trumpet Air") and the great Amen Chorus, well the whole third part.
Answer: One aspect not yet mentioned is, that some of the instruments easily associated with the sheperds of the Christmas story, such as recorder or traverse flute (not the modern concert flute, but the wooden predecessor without any keys) fell out favour in the late baroque era and had to be rediscoverd for some different than children learners in the second half of the twentieth century.
France had special Noëls, played e.g. by the organ during christmas mass, from which some baroque examples are well-known (as thos from d'Aquin).
While appropriatness for sheperds would also apply to hurdy-gurdy and bagpipe (which had their peak during Renaissance), there is little to none classical repertoire for them.
Comment: Agreed that the recorder fell out of use after the baroque period, but the transverse flute has been a constant presence throughout the classical repertoire both as the soloist in concertos and as a part of the woodwind section of the classical orchestra.
Comment: The transverse flute continues to have a prominent role in 20th-21st-century concert band music (both compositions and arrangements of more famous works) to boot.
Answer:
Is it just me, or is the association real?

Perhaps there is some association, but it seems more like Baroque is just one of several options for Christmas background music.
You can also find rock and roll Christmas  and jazz Christmas soundtracks. Similarly, Baroque music gets used as a soundtrack for just about anything needing a sense of propriety, high-culture, tradition, etc.
You could swap out the Baroque with lesser known Mozart works and almost no one would notice the difference.
I suppose there is a certain abstractness to Baroque music - compared with the symbolism and tone poem type stuff of later styles - which lends it to work as unobtrusive background music. But not exclusively Christmas background music.


How to read second point of Axiom of Induction

Question: I have two questions:

How do you read the following expression in words: (here is $A\subseteq \mathbb{N}$)

$\forall k\in \mathbb{N}(k\in A\implies k+1\in A)$?

What I would translate it as is: for all $k\in \mathbb{N}$, we have $k+1\in A$ whenever $k\in A$. Not sure if it makes sense. Are there alternate translations?

How do you prove a statement using the expression above?

What I would do is: Let $k\in \mathbb{N}$ be given. Assume $k\in A$. Then, I use this assumption to prove that $k+1\in A$. Is this correct? I feel like if first two sentences "Let $k\in \mathbb{N}$ be given. Assume $k\in A$." are mentioned in the same line, it seems a bit superfluous. Can I say: "Let $k\in \mathbb{N}$ be given with $k\in A$", or simply "Let $k\in A$ be given", where I omit saying "let $k\in \mathbb{N}$ be given" in the beginning?
Answer: Your interpretation of this part of the induction axiom is true. But note that this is not the whole induction axiom. The induction axiom says that if the mentioned statement is true for some set A then A is equal to the set of natural numbers.
Thus if you have a set A containing zero and you can say that if k is in A then k+1 is also in A then A is equal to N.
Comment: I know that I haven't included the whole part of induction of axiom. What I am asking for is: how to read the particular point - that is written in propositional logic - into words, and how to prove using that point. What you are suggesting is omitting "$\forall k\in \mathbb{N}$" in the second point. Is it because that they mean the same thing, since $A\subseteq \mathbb{N}$?
Comment: I am sorry if I didn't understand your question. The universal quantifier you are asking about just means we are talking about natural numbers. If I have understood your question correctly then yes you can omit it for the exact reason you mentioned.


Adding extra buying option to product

Question: I need to add extra buying option with some price in Create Product (Add a product). If a user checks on extra buying option then they need to add the price and that price will be again added to product price. I am trying to achieve this using commerce pricing attributes but no success so far.
Any suggestions?
Answer: use Product Attributes & Variations.
full documentation is here:
https://drupalcommerce.org/user-guide/product-attributes-variations
Answer: I have used Commerce Product Add-on and it worked like a charm

Adding extra buying option to product


How can I get an absolute path to a theme?

Question: Is there a Drupal function that returns the absolute theme path? Or is there a canonical / base practice way of doing this correctly returning the theme path?
What I've found so far is this:
<?php
// @file template.php
$template_path = DRUPAL_ROOT . drupal_get_path('theme', 'foo');

I'm looking to require_once the template path in a template.php file like so:
<?php
$template_path = DRUPAL_ROOT . drupal_get_path('theme', 'coo');
// ...
// Check file exists etc
require_once $template_path;

Answer: The base_path() function would return the base bath of the Drupal installation

Returns the base URL path of the Drupal installation. At the very
  least, this will always default to /.

and path_to_theme() will return the path to the current theme.

Return the path to the current themed element.
It can point to the active theme or the module handling a themed
  implementation. For example, when invoked within the scope of a
  theming call it will depend on where the theming function is handled.
  If implemented from a module, it will point to the module. If
  implemented from the active theme, it will point to the active theme.
  When called outside the scope of a theming call, it will always point
  to the active theme.
Comment: Beware using the `path_to_theme()`, in case of subtheme your path will be broken, because it will point to your subtheme instead of the main theme! And subtheme doesn't need to have the same files and structure as the main theme. So if you need to create your theme's a subtheme, don't use `path_to_theme()`.
Answer: Mohammed Shameem's answer is correct, but if you're really looking for the correct way (the Drupal way) to render a custom template, do not use include() or require_once(). Instead, use the Drupal theme system. Changing the output of something that already has a template is easy, see Overriding themable output to learn how to override a template. If there is no template yet, you would have to learn about hook_theme, registering your own templates, and render arrays.
Answer: You can try this module: System stream wrapper
It provides wrappers(examples from module's site) :

module://file/icons/text-plain.png
theme://bartik/screenshot.png
theme://default/screenshot.png
profile://minimal/minimal.info
profile://current/standard.info (profile://current expands to the
active profile for the site)
library://ckeditor/images/spacer.gif (works only if the Libraries
module is enabled)


How many ways are there to put seven white and two black billiard balls in nine pockets? Some of the pockets may remain empty and the pockets are cons

Question: How many ways are there to put seven white and two black billiard balls in nine pockets? Some of the pockets may remain empty and the pockets are considered indistinguishable.
Well, my solution goes like this:

We have $7$ white balls and $2$ black balls . We can distribute this $9$ pockes . So, we can represent this as:
$x_1+....+x_9=9$ . Each of the integers $x_i$ denotes the number of balls in the ith packet(where $i=\{1,2,...,9\}$ ) . Now the number of solutions of the equation is $17\choose 8$ .

However, if we do it in the following method:

We first find the result for black and white balls. The number of ways of putting $7$ white balls in $9$ packets is $15\choose 8$ and the number of ways of putting $2$ black balls in $9$ packets is $10\choose 8$ . So, the total number of ways is $15\choose 8$$10\choose 8$.

However, both should give the same answer. Which method is valid? Why is the other one not valid? I am not getting it...
Comment: I only indicated the placement of the black balls.  The placement of the white balls follows from that.  If, say, you put both black balls in the first pocket then that means you must have three white ones in the first, and four white ones in the second.
Comment: It is said that the pockets are indistinguishable , so you cannot use stars and bars method. You need to use partition method.
Comment: The first method is wrong even if the pockets were distinguished.  In that case, you will need to distinguish between the black and white balls.
Comment: Assuming the pockets were distinguished:  Suppose $x_1=5, x_2=4$.  that's one case according to your method $1$.  But we could achieve that by having both black balls in the first pocket, one black ball in each of the first two pockets, or both in the second pocket.  So that ought to have been $3$ cases.
Comment: @lulu Thanks a lot! I do get it now...Thanks!
Comment: @lulu Otherwise some cases are missed isnt it?...But can u please explain which cases are missed in the 1st method?...
Comment: @lulu I am not quite getting it.. if $x_1=5$ and $x_2=4$ .This means 1st pocket has $5$ balls and 2nd pocket has $4$ balls . The case ur talking about are :when two balls in 1st pocket, one black ball in each of the 1st two pockets and  both black balls in 2nd pocket. But that is counted once in the solution ,isn't it? That's the problem, right? The main idea is that the balls are distinguishable ....
Comment: I am, of course, assuming that the order within a pocket is irrelevant.
Answer: Personally, I regard the problem as complicated enough, and the numbers as small enough, and my knowledge of partitions non-existent enough, that my approach is to simply take off my shoes (and count).
I will divide up the situation into disjoint cases, form an enumeration for each case, and then add up all of the enumerations.
I will use the symbols $a-b-0 ~: ~a + b = 7$ to symbolize that $a$ white balls go in one pocket, $b$ white balls go in some other pocket, and none of the other pockets receive a white ball.

$\underline{\text{Preliminary Results}}$
First, I will list all of the possible (distinct) types of white ball distributions.  Then, I will re-organize them into groups, where the enumeration for each element in a group is identical.
$a01: ~7-0.$
$a02: ~6-1.$
$a03: ~5-2.$
$a04: ~5-1-1.$
$a05: ~4-3.$
$a06: ~4-2-1.$
$a07: ~4-1-1-1.$
$a08: ~3-3-1.$
$a09: ~3-2-2.$
$a10: ~3-2-1-1.$
$a11: ~3-1-1-1-1.$
$a12: ~2-2-2-1.$
$a13: ~2-2-1-1-1.$
$a14: ~2-1-1-1-1-1.$
$a15: ~1-1-1-1-1-1-1.$
So, there are $15$ distinctive distributions of the white balls, and for each distribution, the number of distinct distributions of the black balls must be computed.
Since only $2$ black balls are to be distributed, the enumeration for each of the $15$ distributions listed above is not that bad.  For a specific white-ball-distribution, the enumeration will depend on $2$ factors:

How many kinds of pockets are involved.
For example, in $a01$ there are only $2$ kinds, a $[7]$ and a $[0]$.
In contrast, in $a10$ there are $4$ kinds, a $[3],[2],[1],$ and $[0]$.

How many of the kinds of pockets are singletons.
For example, although $a02$ and $a04$ each have $3$ kinds of pockets, their enumerations will be different.  This is because $a02$ has $2$ singletons, and $a04$ has only $1$ singleton.

I will divide up the distributions into cases.
I will let $T_k$ denote the enumeration for case $k$.
In general, within each case, there will be two subcases.
Either the $2$ black balls are together in the same pocket, or they are not.
I will use $T_{ka}$ to denote the enumeration where the $2$ black balls are together in the same pocket.
I will use $T_{kb}$ to denote the enumeration where the $2$ black balls are not together in the same pocket.
It is probably best to supply the formulas that will pertain, if a Case involves $r$ different types, where $s$ of the types are non-singletons.  Here, it is assumed that $r,s \in \Bbb{Z^+}$, with $s \leq r$.
For $T_{ka}$, any one of the $r$ types might receive both balls into the same pocket. So, $T_{ka} = r.$
For $T_{kb}$, you start by pretending that you must select $2$ of the $r$ types, sampling without replacement.  Then, since you are assuming that there are $s$ non-singletons, you have to increment by $s$ to accommodate the $s$ possibilities that the $2$ black balls might go into different pockets of the same type, where there are $s$ such (non-singleton) types.
So, $\displaystyle T_{kb} = \binom{r}{2} + s.$
So, the computation for Case $k$ will be
$$r + \binom{r}{2} + s.$$

$\underline{\text{Case 1 : 2 types, 1 of which is a singleton}}$
The only distribution that fits in this group is $a01$.
$$T_1 = 2 + \binom{2}{2} + 1 = 4.$$

$\underline{\text{Case 2 : 2 types, 0 singletons}}$
The only distribution that fits in this group is $a15$.
$$T_2 = 2 + \binom{2}{2} + 2 = 5.$$

$\underline{\text{Case 3 : 3 types, 2 singletons}}$
This includes $a02, a03,$ and $a05$.
$$T_3 = 3 + \binom{3}{2} + 1 = 7.$$

$\underline{\text{Case 4 : 3 types, 1 singleton}}$
This includes $a04, a07, a08, a09, a11, a12$ and $a14$.
$$T_4 = 3 + \binom{3}{2} + 2 = 8.$$

$\underline{\text{Case 5 : 3 types, 0 singleton}}$
This includes $a13$.
$$T_5 = 3 + \binom{3}{2} + 3 = 9.$$

$\underline{\text{Case 6 : 4 types, 3 singletons}}$
This includes $a06$.
$$T_6 = 4 + \binom{4}{2} + 1 = 11.$$

$\underline{\text{Case 7 : 4 types, 2 singletons}}$
This includes $a10$.
$$T_7 = 4 + \binom{4}{2} + 2 = 12.$$

Final Computation:
$$\sum_{k=1}^7 T_k \times f(k),$$
where $f(k)$ denotes how many of the $15$ distributions are represented by Case $k$.
$$(4 \times 1) + (5 \times 1) + (7 \times 3) + (8 \times 7)$$
$$+ ~(9 \times 1) + (11 \times 1) + (12 \times 1)$$
$$=~ 118.$$


Is an Elegant Solution Preferred over a Brute-Force Solution?

Question: Is it an unwritten rule at the heart of mathematics to always look for an "elegant" solution and always look at brute force computation as sort of tarnishing the mathematical beauty?
Take for example there is some group theory question about a group of order $k$. And someone solves it theoretically while someone explicitly finds all groups of that order and then does case-by-case computation. Is the second method always frowned upon?
And in cases where there is already a brute force solution but no "elegant" solution, are mathematicians always secretly hoping for an elegant solution in spite of there already being a solution?
Comment: Relevant links: [Mathematical Beauty (wikipedia)](https://en.wikipedia.org/wiki/Mathematical_beauty), [Proofs from 'The Book' (Aigner, Ziegler)](https://www.emis.de/classics/Erdos/textpdf/aigzieg/aigzieg.pdf), [Proof by exhaustion (Wikipedia)](https://en.wikipedia.org/wiki/Proof_by_exhaustion).
Comment: Here is another funny (I think, atleast) little link: https://en.wikipedia.org/wiki/List_of_mathematical_jargon#elegant
Answer: Yes, elegant solutions are preferred. The most compelling reason for this preference is that an elegant answer to a question provides insight into why it would be the answer, whereas a brute force solution gives us only the answer without the insight. Mathematicians typically want understanding over results. It's about the journey, not the destination ;)
But also, the understanding usually gives you the results that a brute force solution would find anyways, but more compactly. For example, say you want to find (up to isomorphism) all abelian groups of order $27$. A brute force approach would eventually find that there are three of them, and you could write down their operation tables and point to them. But if you know the elegant, more general solution, the classification theorem of finite abelian groups, you can (1) immediately say that there are three of them, (2) write them down more compactly as $\mathbf{Z}_{27}$, $\mathbf{Z}_{3}\times \mathbf{Z}_{9}$, and $\mathbf{Z}_{3} \times \mathbf{Z}_{3} \times \mathbf{Z}_{3}$, and (3) by writing them down more compactly you can see their structure better than you could from the operation table.
To address your other questions directly:

A brute force solution certainly doesn't tarnish anything. Sometimes finding an elegant solution is tough, getting the results we want by brute force can give mathematicians the raw data to look at to reverse engineer a more elegant thought.
I wouldn't say a brute force solution is frowned upon in the face of an elegant solution, but instead is made obsolete by an elegant solution.


Problem with Loop through nested sass maps

Question: I have a simple sass map with colors. I loop through it and generate css vars. Works great so far.
<code>$colors: (
  primary: red,
  secondary: blue,
)

@each $color, $value in $colors {
    --#{$color}: #{$value};
}
</code>
Then I extended this map with themes. There I loop through again per theme and create the css vars. This also works great.
<code>$colors2: (
  theme-1: (
    primary: red,
    secondary: blue,
  ),
  theme-2: (
    primary: yellow,
    secondary: pink,
  )
)

@each $theme, $colors in $colors2 {
    &[data-theme="#{$theme}"] {
        @each $color, $value in $colors {
            --#{$color}: #{$value};
        }
    }
}
</code>
But now I need to find a way to combine the two. Unfortunately I haven't found a way so far to loop through the following list, create the individual css vars and the data-attributes + css vars.
<code>$colors3: (
  primary: green,
  secondary: purple,
  theme-1: (
    primary: red,
    secondary: blue,
  ),
  theme-2: (
    primary: yellow,
    secondary: pink,
  )
)
</code>
Does anyone of you maybe have an idea how I can do this? In the end something like this should come out:
<code>:root {
  --color-primary: green;
  --color-secondary: purple;

  &[data-theme="theme-1"] {
  --color-primary: red;
  --color-secondary: blue;
  }
  &[data-theme="theme-2"] {
  --color-primary: yellow;
  --color-secondary: pink;
  }
 }
</code>
Thank you very much for your help!
Kind regards
Marco
Comment: Would that be acceptable for you to move down one level your root variable in your map ? Then you could have a condition in your mixin and do something like `if theme == base {} else {}`
Comment: nope, i need this structure. but i found a way :)
Answer: i found a way to get it to work :)
here is my solution just in case, someone else needs it.
<code>:root {
    @each $key, $value in $colors {
        @if type-of($value) == map {
            &[data-theme="#{$key}"] {
                @each $theme-key, $theme-value in $value {
                    --color-#{$theme-key}: #{$theme-value};
                }
            }
        } @else {
            --color-#{$key}: #{$value};
        }
    }
}
</code>


How do I get Rules to see my custom entity?

Question: From what I've read in the past few days, Rules will gather all information it needs from hook_entity_info.  I still can't get my custom entity to appear in the data selector to make things work though.  Here is my implementation of hook_entity_info:
function badge_entity_info() {
  $info = array();

  $info['badge'] = array(
    'label' => t('Badge'),
    'base table' => 'badge',
    'class' => 'DrupalDefaultEntity',
    'controller class' => 'DrupalDefaultEntityController',
    'entity keys' => array(
      'id' => 'bid',
      'label' => 'name',
    ),
    'module' => 'badge',
    'access callback' => 'badge_access',
    'admin ui' => array(
      'path' => 'admin/structure/badge',
      'file' => 'badge.admin.inc',
    ),
    'uri callback' => 'badge_uri',
  );

  return $info;
}

Everything else is working perfectly, I just need to understand how to make Rules recognize my custom entity.
Answer: Individual rules can have a type associated with them. Most rules work with Nodes but an Entity is 1 object up in the type hierarchy of Drupal. therefore rule(s) defined with the Rules module must be made aware that they are compatible with your custom entity type.
You would do this with an alter hook for Rules, or providing property information for your Entity:
I can't set a data value using rule on a custom entity


Disadvantages of representing VAR(p) process as VAR(1) process (vector autoregression)

Question: It is obvious that representation of VAR(p) process as VAR(1) process has a couple of advantages:

This representation(VAR(1)) is much more compact
Easy to check if process is stable (only looking at eigenvalues of $A_1$)

But my question is: are there any disadvantages of representing VAR(p) process as VAR(1)?
Answer: There is a tradeoff between dimensionality and lag order:

in VAR($p$) you have a potentially high lag order $p$ but low dimensionality (the number of time series) $K$;
in the corresponding VAR($1$) (the companion form) you have low lag order $1$ but potentially high dimensionality $p\times K$.

Sometimes manipulating $p$ small coefficient matrices of size $K\times K$ can be easier than manipulating one large matrix of size $pK\times pK$.
Also, it is more natural to think about VAR($p$) than the companion VAR($1$). It is no coincidence that the companion form is only introduced in textbooks when it is needed for proofs, but not for general exposition.
Comment: @Ferdi, thanks! I think the dataset size and lag order are only partly relevant here as we are considering two representations of the same model. Thus a $pK$-dimensional VAR(1) is still the same model as the $K$-dimensional VAR(p). Therefore, the VAR(p) is neither more nor less appropriate than its companion VAR(1) for any given data sample.
Comment: @DanielYefimov, you are welcome! There could also be other nuances, but these were the obvious ones for me.
Comment: Great answer. Also not that VAR is usually applied to small macreconomic datasets. Therefore including too many lags may not be appropriate.


JMH - why do I need Blackhole.consumeCPU()

Question: I'm trying to understand why it is wise to use Blackhole.consumeCPU()?
Something I found about Blackhole.consumeCPU() on Google

Sometimes when we run run a benchmark across multiple threads we also
want to burn some cpu cycles to simulate CPU business when running our
code. This can't be a Thread.sleep as we really want to burn cpu. The
Blackhole.consumeCPU(long) gives us the capability to do this.

My example code:
    import java.util.concurrent.TimeUnit;

    import org.openjdk.jmh.annotations.Benchmark;
    import org.openjdk.jmh.annotations.BenchmarkMode;
    import org.openjdk.jmh.annotations.Level;
    import org.openjdk.jmh.annotations.Measurement;
    import org.openjdk.jmh.annotations.Mode;
    import org.openjdk.jmh.annotations.OutputTimeUnit;
    import org.openjdk.jmh.annotations.Scope;
    import org.openjdk.jmh.annotations.Setup;
    import org.openjdk.jmh.annotations.State;
    import org.openjdk.jmh.annotations.Warmup;
    import org.openjdk.jmh.infra.Blackhole;
    import org.openjdk.jmh.runner.Runner;
    import org.openjdk.jmh.runner.RunnerException;
    import org.openjdk.jmh.runner.options.Options;
    import org.openjdk.jmh.runner.options.OptionsBuilder;

    @State(Scope.Thread)
    @OutputTimeUnit(TimeUnit.NANOSECONDS)
    public class StringConcatAvgBenchmark {

    StringBuilder stringBuilder1;
    StringBuilder stringBuilder2;

    StringBuffer stringBuffer1;
    StringBuffer stringBuffer2;

    String string1;
    String string2;

    /*
     * re-initializing the value after every iteration
     */
    @Setup(Level.Iteration)
    public void init() {
        stringBuilder1 = new StringBuilder("foo");
        stringBuilder2 = new StringBuilder("bar");

        stringBuffer1 = new StringBuffer("foo");
        stringBuffer2 = new StringBuffer("bar");

        string1 = new String("foo");
        string2 = new String("bar");

    }

    @Benchmark
    @Warmup(iterations = 10)
    @Measurement(iterations = 100)
    @BenchmarkMode(Mode.AverageTime)
    public StringBuilder stringBuilder() {
        // operation is very thin and so consuming some CPU
        Blackhole.consumeCPU(100);
        return stringBuilder1.append(stringBuilder2);
        // to avoid dead code optimization returning the value
    }

    @Benchmark
    @Warmup(iterations = 10)
    @Measurement(iterations = 100)
    @BenchmarkMode(Mode.AverageTime)
    public StringBuffer stringBuffer() {
        Blackhole.consumeCPU(100);
        // to avoid dead code optimization returning the value
        return stringBuffer1.append(stringBuffer2);
    }

    @Benchmark
    @Warmup(iterations = 10)
    @Measurement(iterations = 100)
    @BenchmarkMode(Mode.AverageTime)
    public String stringPlus() {
        Blackhole.consumeCPU(100);
        return string1 + string2;
    }

    @Benchmark
    @Warmup(iterations = 10)
    @Measurement(iterations = 100)
    @BenchmarkMode(Mode.AverageTime)
    public String stringConcat() {
        Blackhole.consumeCPU(100);
        // to avoid dead code optimization returning the value
        return string1.concat(string2);
    }

    public static void main(String[] args) throws RunnerException {

        Options options = new OptionsBuilder()
                .include(StringConcatAvgBenchmark.class.getSimpleName())
                .threads(1).forks(1).shouldFailOnError(true).shouldDoGC(true)
                .jvmArgs("-server").build();
        new Runner(options).run();
    }
    }

Why are the results of this Benchmark better with the blackhole.consumeCPU(100) ?

UPDATE:
Output with blackhole.consumeCPU(100):
    Benchmark                      Mode  Cnt    Score    Error  Units
    StringBenchmark.stringBuffer   avgt   10  398,843 ± 38,666  ns/op
    StringBenchmark.stringBuilder  avgt   10  387,543 ± 40,087  ns/op
    StringBenchmark.stringConcat   avgt   10  410,256 ± 33,194  ns/op
    StringBenchmark.stringPlus     avgt   10  386,472 ± 21,704  ns/op

Output without blackhole.consumeCPU(100):
    Benchmark                      Mode  Cnt   Score    Error  Units
    StringBenchmark.stringBuffer   avgt   10  51,225 ± 19,254  ns/op
    StringBenchmark.stringBuilder  avgt   10  49,548 ±  4,126  ns/op
    StringBenchmark.stringConcat   avgt   10  50,373 ±  1,408  ns/op
    StringBenchmark.stringPlus     avgt   10  87,942 ±  1,701  ns/op

I think I know now why they used this, because the benchmarks are too quick without some delay.
With blackhole.consumeCPU(100) you can measure each benchmark better and receive more significant results.
Is that right ?
Comment: Define "better"? I don't see any comparison in your question.
Answer: Adding artificial delay would not normally improve the benchmark.
But, there are some cases where the operation you are measuring is contending over some resources, and you need a backoff that only consumes CPU, and hopefully does nothing else. See e.g. the case in :
 http://shipilev.net/blog/2014/nanotrusting-nanotime/
The benchmark in original question is not such a case, therefore I'd speculate Blackhole.consumeCPU is used there without a good reason, or at least that reason is not called out specifically in the comments. Don't do that.


Agrupar períodos de datas

Question: Preciso fazer uma query que retorne todos os registros agrupados em determinados períodos. A tabela contem um tipo date e deve produzir uma saída semelhante a isto:
   | Hora  | Quantidade |
-------------------------
01 | 08:00 | 30         |
02 | 08:05 | 28         |
03 | 08:10 | 32         |
04 | 08:15 | 53         |

Ou seja:
Na linha 1 foram encontrados 30 registros com a coluna date entre 08:00:00 e 08:04:59, na linha 2 foram encontrados 28 registros com a coluna date entre 08:05:00 e 08:09:59, assim sucessivamente.
Tem alguma forma de agrupar a data por período da forma como descrita na tabela?
PS: O SGBD é Oracle.
Answer: Para agrupar por um intervalo, trunque a data na unidade desse intervalo (minuto, no seu caso), divida pelo total de um dia e some com a data e hora:
(trunc(current_date, 'hh')+trunc(to_char(current_date,'mi')/5)*5/1440)

Neste SQL Fiddle eu criei uma tabela com alguns timestamps para teste, na coluna de nome d:
> select * from datas;

|                     D |
|-----------------------|
| 2017-10-01 08:00:00.0 |
| 2017-10-01 08:01:00.0 |
| 2017-10-01 08:03:00.0 |
| 2017-10-01 08:07:00.0 |
| 2017-10-01 08:08:00.0 |
| 2017-10-01 08:09:59.0 |
| 2017-10-01 08:11:00.0 |
| 2017-10-01 08:11:15.0 |
| 2017-10-01 08:13:00.0 |
| 2017-10-01 08:17:00.0 |

Para essa tabela aplico o método acima, tanto para obter o período de cinco minutos quanto para a cláusula GROUP BY e para uma janela, a fim de obter o numerador de registros que aparece na sua pergunta:
select
  row_number() over (order by (trunc(d, 'hh')+trunc(to_char(d,'mi')/5)*5/1440)) as " ",
  to_char((trunc(d, 'hh')+trunc(to_char(d,'mi')/5)*5/1440), 'HH24:MI') as "Hora",
  count(*) as "Quantidade"
from datas
group by (trunc(d, 'hh')+trunc(to_char(d,'mi')/5)*5/1440);

|   |  Hora | Quantidade |
|---|-------|------------|
| 1 | 08:00 |          3 |
| 2 | 08:05 |          3 |
| 3 | 08:10 |          3 |
| 4 | 08:15 |          1 |

Answer: Uma forma eficiente de fazer isso é obtendo os valores por coluna em vez de linhas, uma vez que você já sabe previamente o intervalo de horas desejado.
Dessa forma a consulta fica rápida, pois será passado uma vez só em cada registro. De outra forma (por linha) você precisaria fazer uma subquery e retornar as linhas filtrando cada intervalo de hora em separado, ficando bem mais lento e muito maior o seu select.
select
 sum(case when to_char(campodata, 'hh:mm:ss') between '08:00:00' and '08:04:59' then 1 else 0 end) as "08:00"
,sum(case when to_char(campodata, 'hh:mm:ss') between '08:05:00' and '08:09:59' then 1 else 0 end) as "08:05"
,sum(case when to_char(campodata, 'hh:mm:ss') between '08:10:00' and '08:14:59' then 1 else 0 end) as "08:10"
,sum(case when to_char(campodata, 'hh:mm:ss') between '08:15:00' and '08:19:59' then 1 else 0 end) as "08:15"
from tabela

Answer: select Sum(campodata), compodata from tabela group by campodata;

o sum vai te dar a soma e o group by vai agrupar;
Comment: http://stackoverflow.com/questions/19309959/oracle-plsql-truncate-datetimes-to-15-min-blocks    uma combinação de trunc e outras functions.
Comment: Mas e como eu agrupo o campodata a cada 5 minutos por exemplo?, esse select somente vai agrupar datas exatamente iguais
Comment: o group by vai agrupar sim datas exatamentes iguais
Comment: Sim, mas eu quero agrupar datas por período, e não exatamente iguais. dessa forma não vai retornar o que preciso

Agrupar períodos de datas


Cross domain ajax in a multisite setup

Question: I have a drupal multisite install so that two sites can share the same codebase. In a custom module that both sites use, the ajax works on one site but with the other site it returns the error status 200. What my module does is that it creates a new "article" node programmatically.
I read somewhere that this is a crossdomain ajax problem, even though both sites are really on the same hard drive of the same server.
The views module, which also uses ajax, works on both sites with no problem.
How can I make the ajax work? I'll give up the multisite way if it creates more problems than it solves
Update: here is the jquery code :
(function ($) {
    Drupal.behaviors.addArticle = {
        attach: function (context, settings) {
            var addstuffAjaxLink = $(".addsomething");
            addstuffAjaxLink.click(function(e) {
                var ajaxpath = 'addstuff/ajax';
                $.ajax({
                    type: "POST",
                    url: ajaxpath,
                    data: {'from_js': true},
                    dataType: "json",
                    success: function (data) {
                        if (data.message) {
                            var message= data.message;
                            alert(message);
                        }
                    },
                    error: function (xmlhttp) {
                        alert('An error occured: ' + xmlhttp.status);
                    }
                });
            });
        }
    };
})(jQuery);

and this is the custom module php code:
<?php
/**
 * Implements hook_menu().
 */
function addstuff_menu() {
  $items = array();

  $items['addstuff/ajax'] = array(
   'title' => 'Add Stuff',
    'page callback' => 'addstuff_callback',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}
/**
 * Menu callback.
 */
function addstuff_callback() {
    if ($_POST['from_js']) {
        global $user;

        $newnode = new stdClass();
        $newnode->uid = $user->uid;
        $newnode->name = $user->name;
        $newnode->language = LANGUAGE_NONE;
        $lan=$newnode->language;
        $newnode->status = 1;
        $newnode->promote = 0;
        $newnode->sticky = 0;
        $newnode->created = timestamp;
        $newnode->title = 'New Article';
        $newnode->type = 'article';

        $newnode->field_body = array(
            $lan => array(
                array(
                    'value' => 'Click HERE to add some text.',
                    'format'=> 'full_html',
                    'safe_value' => 'Click HERE to add some text.',
                )
            )
        );
        node_save($newnode);
        $response = array(
            'message' => 'Article Created',
        );
        return drupal_json_output($response);
        exit;
    } else {
        $response = array(
            'message' => 'There was an error',
        );
        drupal_json_output($response);
        exit;
    }
}
/**
 * Implements hook_init().
 */
function addstuff_init() {
  drupal_add_js(drupal_get_path('module', 'addstuff') . '/addstuff.js');
}

Comment: I'm afraid we would need more information. Possibly, the code snippet that you are trying to get to work and the context it is being run from and what "works from the other site" actually means.

From what I understand, I doubt if it has anything to do with the multi-site setup and cross-domain in its simplest form, means "accessing data of a host from a client on a different host" - it doesn't depend on *where* your site is being served from, actually.
Comment: I guess, you are using jquery for you ajax calls. If yes, than check your dataType. It should be "jsonp"
Comment: check these urls. http://stackoverflow.com/questions/3506208/jquery-ajax-cross-domain and http://stackoverflow.com/questions/5133864/ajax-cross-domain-problem
Comment: I added the code. I'll try to give more details : on domain1.com and on domain2.com there is a button with the class "addsomething". When the user clicks on that button, it runs the jquery code, which in turns fires the php code, to add an article node. Clicking on the button on domain1.com should add the node in the database of domain1, whereas clicking on the similar button on domain2.com should create the node in domain2's database, but instead it gives an xmlhttp error 200.
Answer: The first thing I'd probably do is to change the url option of $.ajax to something like:
$.ajax({
  // your code goes here
  url: Drupal.settings.basePath + 'addstuff/ajax',
  // more of your code goes here
});

So, what could be happening (assuming of course, that you have clean URLs enabled on both sites) is that when you are on a page on your site with the Drupal path, say, node/add and click on your link, the AJAX request to addstuff/ajax without the leading slash (base path) goes to node/addaddstuff/ajax which will return HTML and not JSON as expected. Hence, jQuery throws a parseerror and Drupal calls its error handler. You can check this by inspecting the XHR requests being sent out from the Network tab of your browser's developer console.
However, this doesn't explain how your code works as expected on one site but not the other.
Comment: That makes sense, I'll give it a shot

Cross domain ajax in a multisite setup


Warning: Illegal offset type in drupal_add_js() (line 4184 of C:\EasyPHP-220.127.116.11\www\lfp\includes\common.inc)

Question: I am using D7. I am getting the above error when I created a js file with the code below and then included it in the .info file. What is wrong?
<code>(function($) {
Drupal.behaviors.userLoginChanges = {
    attach: function(context) {
        $("#user-login-form").attr("placeholder", "Username");

    }
}
}) (jQuery);
</code>
Comment: No harm in putting that as an answer, could help someone in the future :)
Comment: Ignore this question: I realized the issue - In the info file I was writing scripts[all][] = filename, the same way you do it with css files. The correct syntax is scripts[] = filename.
Answer: I realized the issue - In the info file I was writing scripts[all][] = filename, the same way you do it with css files. The correct syntax is scripts[] = filename.

Warning: Illegal offset type in drupal_add_js() (line 4184 of C:\EasyPHP-5.3.8.1\www\lfp\includes\common.inc)


Is there any trick to create a symmetrical table in c using unicode symbol

Question: Hey guys i am trying to create a table like structure in c language using box generating symbol of unicode but right side is not symmetrical like a left one what should i do, is there any trick or function for fix this...
This is the code
<code>#include <stdio.h>

 int main()
{
 int R=89;
 printf("\n┏");
 for(int i=0;i<42;i++)
{
 printf("━");
}
 printf("┓\n");
 printf("┃ SUBJECT   ┃
  MAX/MIN  ┃ TERM 1 ┃ TERM
  2 ┃ TERM 3 ┃");
  printf("\n┃");
  for(int i=0;i<42;i++)
  {
  printf("━");
  }
 printf("┃\n");
 printf("┃ ENGLISH   ┃
  100/33  ┃  %3d   ┃  %3d
  ┃  %3d   ┃",R,R,R);
  printf("\n┃");
  for(int i=0;i<42;i++)
 {
  printf("━");
 }
  printf("┃");
 }
</code>
This is a output image:
Comment: Welcome to Stack Overflow. You should use a fixed width font to display the text. Also, you should remove the `python` tag from the question.
Answer: Your code looks OK.
To track down the actual cause of the misaligned output, make the output of your code simpler and simpler, until the problem disappears. By doing this you will learn where the crucial difference is.
It may be the font, or some spaces, or something else.


Regex - Most efficient expression for matching after start of line OR after specific character

Question: I am trying to find the most efficient way to match characters after the start of the line OR after another character.
Match criteria
ad([sxv])?[0-9]*[-_.] - Matches from this need to be found immediately after ^, or after [-_.]
Note: I am not 100% sure which flavour of regex the processor uses, but it doesn't seem to support non-capturing groups.
Scenario:
User tries to access a domain which is then checked against several regex expressions (including this example). If no match is found, access is permitted.
Sample user inputs (to be blocked):
ad.dailymail.co.uk
asdsa.adasdsa.dasdasd.asdasdasd.dasdasdsa.ad.test.com

Regex tests:
ad.dailymail.co.uk

(^|[-_.])ad([sxv])?[0-9]*[-_.] - 13 steps
^(.*[-_.])?ad([sxv])?[0-9]*[-_.] - 36 steps
^([a-z0-9]([a-z0-9-]*[a-z0-9])?[-_.])*ad([sxv])?[0-9]*[-_.] - 69 steps

asdsa.adasdsa.dasdasd.asdasdasd.dasdasdsa.ad.test.com

(^|[-_.])ad([sxv])?[0-9]*[-_.] - 151 steps
^(.*[-_.])?ad([sxv])?[0-9]*[-_.] - 28 steps
^([a-z0-9]([a-z0-9-]*[a-z0-9])?[-_.])*ad([sxv])?[0-9]*[-_.] - 86 steps

So far, it's looking as if ^(.*[-_.])?ad([sxv])?[0-9]*[-_.] is most efficient, but is there another way to check that may be faster?
Also, can anybody tell my why(^|[-_.]) consumes so many more steps than the other expressions?
Comment: You are comparing apples to oranges, `(^|[-_.])ad([sxv])?[0-9]*[-_.]` is not equal to `^(.*[-_.])?ad([sxv])?[0-9]*[-_.]` and `^([a-z0-9]([a-z0-9-]*[a-z0-9])?[-_.])*ad([sxv])?[0-9]*[-_.]`. Are you only looking for a single match in each string? Or multiple?
Comment: I know they are not necessarily equal, but I am just trying to find the best method that will return a true or false to the match criteria. Only a single match in each - One of the two possibilities.
Comment: Ok, but note that most probably your tests are not valid since at regex101 you are using `g` modifier, and it might not be used in the actual app. Do not use regex101 to test real performance, you need to test it in the target environment.
Comment: @WiktorStribiżew noted, thanks.
Answer: You could modify the second regex to use a ?? modifier for the first group. So it will be lazy and stop at 0 times if you already find "ad..." at the beginning.
Demo
It has even less steps than the first regexp (which was the fastest) (9 vs 10 steps)
The downside is that it may get a little worse (0-2 extra steps) for any "not starting by ad" urls. It will also depend if it matches or not. If it does not match, both regexes have same steps. If they match, It may have 1-2 extra steps.
You may do your maths and compute the number of urls of such types and decide according to the probability
Finally, I made a table withh all the results:
Comment: `\bad[sxv]?[0-9]*\b[-_.]` seems to be a lightly optimized version of Regex1. It behabes the same way. About lazy `?`: consider the string `ab` and the regexp `a??`: It will match: `nothing`, `a`, `nothing`, `nothing`. However, the regex `a??b` will just match `ab` because the extra b at the end forces the lazy `?` to match `a` 1 time. When a lazy `?` is found, 0 to 1 occurrences are possible (with 0 preferred). So if the only option to match is to find 1 occurrence, it will be matched if 0 does not match. See https://regex101.com/r/PxnBYB/4 and https://regex101.com/r/PxnBYB/5
Comment: Thanks for your reply, and for going the extra mile with the table. How does the lazy quantifier work on an optional group? I understand it in the context of shortening a greedy match, but I can't quite wrap my head around how it changes the matching process in this scenario.
Comment: Actually, I wonder whether something like `\bad[sxv]?[0-9]*\b[-_.]` could even be suitable?


Pagination in apache solr search page

Question: To control the number of search results showing in a solr site search page there is a text field in admin/config/search/apachesolr/search-pages/core_search/edit
In advanced option tab, there is an option called Results per page to specify its count. but I need to alter the pagination displayed in search page. It displays 1 to 9 pagers by default I want them to be 5. what should I alter??
Comment: You could try overriding theme_pager() if you don't mind all pagers on your site changing to 5.
Answer: This could be done by using theme_pager in TEMPLATE.PHP and by applying some if condition to be specific on just the search page
<code>if(arg(0) == "search" && arg(1) == "site") {

$variables['quantity'] = 5;

}
</code>
These two lines did the magic !!!
Comment: Generally a better solution in this case would be to move that same code into THEMENAME_preprocess_pager($variables) in your template.php since you are only modifying one of the variables.
Comment: yep..thats what I did :)
Comment: Your answer mentions theme_pager though not HOOK_preprocess_pager
Comment: Do you want me to use preprocess_pager instead of theme_pager.. May I know why you say so?
Comment: You can do it either way however the preprocessor way uses less code and what you are doing is not actually changing the output code of the theme function but changing the variable used in the theme function. It keeps things consistent with the rest of Drupal themeing. There is a line on https://www.drupal.org/node/173880 that says "To customize the variables inside templates, see the sub-page on Preprocess functions.", which is https://www.drupal.org/node/223430

Pagination in apache solr search page


$R$ is a ring. $\forall 0\ne a\in R \exists ! b\in R; aba=a$. Can I conclude that $R$ is a ring with identity? How?

Question: $R$ is a ring, containing more than one element, such that
 $\forall 0\ne a\in R \exists ! b\in R; aba=a$.
Here's what I did in the very first place:
$(aba)a^{-1}=aa^-1 \text{ and } a^{-1}(aba)=a^{-1}a\Longrightarrow \left\{ \begin{array}{rl} ab=1 & \forall0\ne a\in R \exists !b\in R \\ ba=1 & \forall0\ne a\in R \exists !b\in R \end{array} \right.$
Therefore, since $ab\in R\Longrightarrow 1\in R$. So $R$ is a ring with identity.

But then I realized, how one can say $aa^{-1}=1$ when one doesn't know whether $R$ is a ring with identity.
Comment: @Brenin I think OP just means the ring contains more than one element (it is non-trivial.) The "such that" modifies the ring, not the elements.
Comment: In a ring, if you don't know it has an identity, you definitely don't know it has multiplicative inverses - $a^{-1}$ is meaningless.
Comment: Silly me! right, I'll delete my comment
Comment: I'll add commas to make it clearer.
Answer: Try to first show $R$ has no zero divisors (see below), and having that, it follows that $bab=b$.
With this in hand, let $c\in R$. Then $aba=a$ implies $caba=ca$, so cancelling the nonzero $a$, $cab=c$.
On the other hand, $bab=b$ implies $bc=babc$, so cancelling the nonzero $b$ yields $c=abc=cab$. That is, $c=(ab)c=c(ab)$ for any $c\in R$. So $ab$ satisfies the properties of $1$, so $ab=1$.

To see there are no zero divisors, assume $a\neq 0$. Let $b$ be the unique $b$ such that $aba=a$. Suppose $c$ is such that either $ca=0$ or $ac=0$. Then
$a(b+c)a=aba+aca=a$ so by uniqueness, $b=b+c$, or $c=0$.
Comment: I can see no reason.
Comment: @Milad You're cancelling by the fact that $R$ has no zero divisors, not by assuming an inverse of $a$. The reasoning is $caba=ca$ implies $caba-ca=0$ implies $(cab-c)a=0$. Since $a\neq 0$ and there are no zero divisors, necessarily $cab-c=0$, so $c=cab$.
Comment: That's right, @BenWest . $R$'s being an integral domain is what I miss. Problem solved and thank you.
Comment: Any reason for the downvote?
Comment: I'm a bit confused here @BenWest .
In the second line, how can we cancel the element $a$ when we don't know whether a $1_R$ exists such that
$caba=ca\Rightarrow caba(a^{-1})=ca(a^{-1}) \Rightarrow cab(1)=c(1)$.
Do I miss anything?
Comment: @BenWest In proving that there are no zero divisors, correct this:
$a(b+c)a=aba+aca$
Answer: $a = aba = abababa = ... = (ab)^n a \quad \forall n$
Therefore $a=(ab)a$ and $a=a(bab)a$.
But $\exists ! b$. So $b=bab$. So if $a\mapsto b$ by that rule, $b\mapsto a$.
Now $ab$=$abab$=$(ab)^n \forall n$
So $\forall c \in R, \quad ab c=(ab)^2c=(ab)^n c$
If $c \neq (ab)c$, then since $(ab)\neq 0$
$(ab)c\neq (ab)^2 c$. But this is false, so $c=(ab)c$ for all $c$, therefore $ab=1$
Comment: I'd say in the last step, "therefore $ab$ is a left-identity." $=1$ is meaningless.
Answer: aba = a
aba - a = a - a
aba - a = 0
EDIT:
aba - aba = 0
baba - baba = 0
baba - ba = 0
a(bab - b) = 0
b = bab
Now since b = bab let c be any element in R
since bc = babc we see that c = (ab)c
we also have ca = caba
thus c = c(ab)
Therefore ab must be a an identity in R
Comment: @Milad It comes from the fact that there are no Zero divisors. Since a != 0 and c != 0 we have the equation bc = babc which is equivalent to saying b(abc - c) = 0. This shows that abc = c and hence why (ab) = 1.
Comment: Where does $c$ comes from?
Comment: when you factor out the a its quite obvious that the c has to be 1 but for generality I'm assuming that some ac = a there.
Comment: I can't see what you mean with $aba-a=a(ba-c)$: you are assuming the existence of $1$, in order to do it. Where are you using the uniqueness of the pseudoinverse $b$, which is necessary for concluding the existence of $1$? There are examples of von Neumann regular rings without $1$.
Comment: I'm not assuming the existence of 1. I will edit my post for clarity.
Comment: Yes, you are; think about it. The only $c$ you are allowed to use there, unless you prove other facts, is $c=ba$, which doesn't help much, does it?
Comment: Fixed it for ya.
Comment: How do you go from $a(bab-b)=0$ to $bab=b$?
Comment: How do you see from the equation $bc = babc$, the equation $c = (ab)c$? We don't know whether $1_R$ exists, so, can we move on saying:
$bc=babc\Rightarrow (b^{-1})bc=(b^{-1})babc \Rightarrow (1)c=1(abc) \Rightarrow c=abc.$
Comment: @Ben West: a(bab - b) = 0 goes to bab = b because since a != 0 we must have that bab - b = 0 Hence bab = b.
Comment: Yes, I agree, but nowhere in your answer have you proven there are no zero divisors.


Root Guess For a Function (Yield Calculation of a Bond)

Question: The price of a bond is given by the formula :
$$P(y) = Re^{-yt_N}+\sum_{i=1}^{N}C_ie^{-yt_i}$$
Where :
$R$ is the redemption price (usually equals 1)
$y$ is a constant (yield) (it ranges between say -0.2 and 0.3)
$C$ is a coupon (ranges from 0 to 0.2)
Using Newton Raphson algorithm, I can get the root $y$ for $P(y)=Pm$ where $Pm$ is a given constant
However, I have a lot of data, the computation time is a little big. Seeing the problem from a mathematical or a Financial view, what would be the best starting point for the algorithm? (I mean the guess value for $y$)? Thank you
NB : I gave the ranges for the variables just to give an idea for the those not familiar with bond maths. These values can off course be out of the ranges given
Comment: Are you sure the coupon terms are $t_iC_ie^{-yt_i}$ and not just   $C_ie-^{yt_i}$? And what is the range of the $t_i$? May we assume $0 < t_1 < \dots < t_N = 1$?
Comment: Sorry. Edited now
Comment: Are you sure about the range $-0.2$ to $0.3$ for $y$? You are using continuous compounding and $y=-0.2$ is roughly equivalent to a yearly rate of interest of $-18\%$.
Answer: As a guess for y to feed to the algorithm i would do this:
$$\bar{t}=\frac{1}{N}\sum_{i=1}^N t_i$$
$$\bar{C}=\frac{1}{N}\sum_{i=1}^N C_i$$
and replace all quantities in the formula by their mean value:
$$
P_{simp}(y) = Re^{-y \bar t}+\sum_{i=1}^{N}\bar C e^{-y \bar t}= (R+N\bar C) e^{-y \bar t}
$$
now solve $P_{simp}(y)=Pm$ for y:
$$
y_{guess}=-\frac{1}{\bar t}\log\frac{Pm}{R+N\bar C}=\frac{1}{\bar t}\log\frac{R+N\bar C}{Pm}
$$
this could work really well as a starting point, but you have to try to know if indeed it does.

Adaptive Newton Method
1) $\lambda \to 1$
2) $x_{n+1}=x_n-\lambda\frac{P(x_n)-Pm}{P'(x_n)}$
3) $\lambda\to\lambda\left\{1+\frac{Pm-P(x_{n+1})}{P(x_{n+1})-P(x_{n})}\right\}_{0.2}^{1.8}$
4) until convergence go to 2)
those numbers on the right graph on (2) are a lower limit and a upper limit for the coefficient between graphs that multiplies $\lambda$.
I devised this algorithm in a simulation that required really fast convergence since executing the simulation was really costly and it worked nice.
Comment: Ok great.  I let you know about the results
Comment: Looks intuitive. I tried it but it has some unexpected behaviour. Maybe I need to go for another algorithm to go faster?
Comment: hmm i see... to be honest the problem of slow convergence is not to be solved by better choosing a starting point, but by implementing an adaptive step size. i'm about to post a formula for that.
Comment: added adaptive newton algorithm
Comment: Going to try it. What do you mean by 1.8 and 0.2? How am I supposed to use them? Again thanks
Comment: see in the update rule for lambda, lambda gets multiplied by 1+..., that coefficient must be clamped between 0.2 and 1.8 so that lambda never becomes null or grows too fast.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/43864/discussion-between-francesco-alem-and-dave-ddd).
Answer: Since this is a convex decreasing function of $y$, the starting value does not matter. The Newton-Raphson iteration will converge globally. By choosing a good starting value you may be able to save yourself one or two steps.
So you can start at $y_0 = 0$. Use $R =0$ (since the bond redemption is just another coupon and is paid at the same time). Then the first Newton-Raphson step leads to
$$
y_1 = \frac{\sum_{i=1}^N C_i - P_m}{\sum_{i=1}^N t_iC_i}
$$
and that could be your starting value.


XMLHttpRequest - response em branco

Question: Tenho um arquivo no servidor que, caso encontre o login e senha informados, retorna 1 ou 0 caso nada seja achado. Porém, não estou conseguindo receber essa informação usando XMLHttpRequest. No PHP, uso echo (json_encode($)) para passar o valor, mas não sei como pegar esse valor.
Aqui está meu Javascript:
function logar()
{
    var request = new XMLHttpRequest();
    var url = "http://clleyton.hostoi.com/form_login.php/?login=" + document.getElementById("login").value + "&senha=" + document.getElementById("senha").value;
    console.log(url);
    request.open("GET", url, true);
    request.onreadystatechange = function() {
        if (request.readyState == 4)
        {
            if (request.status == 200 || request.status == 0)
            {

                console.log(request.responseText);
                console.log(request.response);
            }
        }
    }

}

Comment: Parece haver um erro de formação da URL:

`var url = "...hostoi.com/form_login.php/?login="...`

Provavelmente o que você quer usar é `form_login.php?login` tente tirar o `/`
Answer: Confesso que não tenho experiência com XMLHttpRequest e não tenho como lhe dar uma resposta exata sobre como resolver o problema da forma que precisa. Mas recomendo a utilização do fetch para comunicação entre client <-> server.
De forma simples irá conseguir fazer o request (GET) que precisa e controlar a resposta através de Promises.
Sei que pode parecer demais utilizar um polyfill para seu problema, mas em contexto geral acho válido avaliar que se trata de uma tecnologia nova e com especificação nativa no javascript. Estará apenas antecipando o que um dia será comum no dia a dia. Bem mais elegante e simples do que esse tal de  XMLHttpRequest ;)

XMLHttpRequest - response em branco


localhost:3000 ERR_CONNECTION_REFUSED returned when trying to run a node/express app

Question: I am trying to run a simple express app and I can't seem to figure out why I can't view my app in a web browser, or in postman. Looking into my system port 3000 does not appear to be in use, I have also tried several different ports and receive the same error. There is nothing in console logs, and this is the ERR_CONNECTION_REFUSED is the only error code present across all apps.  Below is my JS code, there is a separate .env file with PORT = 3000.
require('dotenv').config()
const express = require("express");
const app = express();

app.use('/places', require('./controllers/places'))

app.get("/", (req, res) => {
  res.send("Hello World!");
});

app.get('*', (req, res) => {
    res.status(404).send('
404 Page
')
})

app.listen(process.emitWarning.PORT);
const PORT = process.env.PORT;

app.listen(PORT, () => {
  console.log("app running on port 3000");
});

I have run npm install, npm innit, and when I run nodemon the server starts fine with "app running on port 3000" logged into the terminal.Attempting to run the app in different browsers creates the same outcome. I have completely disabled my firewall, flushed my DNS, and cleared my browser cache across all browsers and the same issue persists. If anything else is needed please let me know! Thanks for any advice, it is greatly appreciated.
Comment: `app running on port 3000` is just a `console.log(...)` - you can put everything on it what ever you want, but it does not tell you on which port your app is running.
Answer:
check environment variable process.env.PORT

const PORT = process.env.PORT || 3001
3000: correct, process.env.PORT is set
3001: wrong,   process.env.PORT is not set

print the value of PORT in app.listen

console.log("app running on port 3000");    // wrong
console.log(`app running on port ${PORT}`); // correct

call app.listen once, not twice with different ports

app.listen(process.emitWarning.PORT); // wrong
app.listen(PORT, () => {});           // correct

Your minimal code should be:
require('dotenv').config()
const express = require("express");

const app = express();

app.get("/", (req, res) => {
  res.send("Hello World!");
});

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`app running on port ${PORT}`);
});

You can add everything else afterwards.


ValueError: No closing quotation While building nativescript app

Question: I am developing ios and android applications using native script-angular.When I created a new native script angular application and build that application it caused the error like
<code> File "./build-step-metadata-generator.py", line 40, in <module>
    header_search_paths_parsed = map_and_list((lambda s: "-I" + s), shlex.split(header_search_paths))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 279, in split
    return list(lex)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 269, in next
    token = self.get_token()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 96, in get_token
    raw = self.read_token()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 172, in read_token
    raise ValueError, "No closing quotation"
ValueError: No closing quotation
</code>
How to fix the issue?
Comment: My Header search paths value:HEADER_SEARCH_PATHS=/Users/admin/Documents/copied/MyNativeScriptPoc's/MyGraphPoc/platforms/ios/build/Debug-iphonesimulator/include  "/Users/admin/Documents/copied/MyNativeScriptPoc's/MyGraphPoc/platforms/ios/internal" "/Users/admin/Documents/copied/MyNativeScriptPoc's/MyGraphPoc/platforms/ios/internal/TKLiveSync/include" "/Users/admin/Documents/copied/MyNativeScriptPoc's/MyGraphPoc/platforms/ios/../../App_Resources/iOS/src" "/Users/admin/Documents/copied/MyNativeScriptPoc's/MyGraphPoc/platforms/ios/../../node_modules/tns-core-modules/platforms/ios/src"
Comment: Probably the HEADER_SEARCH_PATHS variable in your project is corrupted (unbalanced quotes). Can you verify its value?

You can add `printenv | sort` to your `platforms/ios/internal/nsld.sh` after `source ./.build_env_vars.sh` and build with `--log debug` to see it in the build output.
Comment: Ok i will try thanks for your response.
Comment: The file you have mentioned does not exist in the platforms/ios/internal/ folder.
Comment: nsld.sh is present from email@example.com onwards. I guess you are using an earlier version. In this case you can add the same line to `platforms/ios/internal/nativescript-pre-build`
Comment: ok i will check.
Comment: Are you using any specific plugins in your project? Can you post your `package.json`?
Answer: It seems like the apostrophe in the path breaks shlex.split. As a workaround I suggest that you rename the directory of your project to not have an '


How do I prove that $ f(n) = (n + 1)! - 1 $ is an injective function?

Question: I have this problem:

Consider the function $f : \mathbb{N} \rightarrow \mathbb{N}$ defined, for every $n \in \mathbb{N}$, by
$$f(n) = (n+1)! - 1$$
Prove that $f$ is injective.

How do I solve this problem?
Answer: The easiest way probably to prove this is by proving that $f$ is strictly increasing. You can do that quite easily using induction.
Answer: Suppose $f(n)=f(m)$.  Then $(n+1)!-1=(m+1)!-1$.  Adding $1$ to each side we conclude that $(n+1)!=(m+1)!$.  We assume without loss of generality, by swapping the names of $m,n$ if necessary, that $n\ge m$.  We now divide both sides by $(m+1)!$ to conclude $$1=\frac{(n+1)!}{(m+1)!}=\frac{(m+1)!(m+2)(m+3)\cdots(n+1)}{(m+1)!}=(m+2)(m+3)\cdots (n+1)$$
If there is even one term on the right, that term is $n+1>1$, which  is a contradiction.  Hence there are no terms on the right, i.e. $n=m$.


Interactive share through JS not rendering

Question: Can someone explain to me why the following code isn't working? I have copied the code from Google and I need the "onshare" facility which I don't believe is available through the standard HTML. There are no JS errors - and nothing renedered:
            <!DOCTYPE html>

                            <title>Title of the document</title>

google_test

After some investigation (5/1/15) I discovered that in the response (net panel in firebug) I was getting an error back in a hidden text box. This was because my origin url was wrong, but now I get the following:
<input type="hidden" id="error" value="true" />
<input type="hidden" id="response-form-encoded" value="state=887621045%7C0.2365188186&error=immediate_failed&num_sessions=1&session_state=MY_SESSION_ID" />

Any idea what this might mean?
Answer: You load Google api with async defer. Therefore it is not ready when you create the share link.
Either you should render the share link only after the page is loaded ( using the domready event ), or remove the 'async defer' attributes.
Comment: Removed the async defer and nothing I'm afraid.
Answer: The answer is so simple - thanks to http://wheresgus.com/iodemos/demotargetipost/ for helping me see it. In the example above,

Simply needs a content such as this:

<button>hello world</button>

In fact you don't even need the button!! Why on earth the documentation doesn't have this I don't know - so have reported the documentation as not being great. Additionally you should note that the callbackurl and calltoactionurl both need the same protocols - again their examples differ.


Chamar script PYTHON através do PHP

Question: Quero que o PHP mostre o resultado do código PYTHON
PYTHON
x = 4 * 5
print(x)

PHP
<?php
$teste = shell_exec('python codigopython.py 2>&1');
echo $teste; ?>

O Resultado que estou recebendo é:

'python' não é reconhecido como um comando interno ou externo, um
  programa operável ou um arquivo em lotes.

Mas se eu executo o código python no CMD, funciona normalmente
Comment: Caio, acredito que a pergunta era se o seu interpretador de Python é acessível, não se o seu script escrito em Python é acessível.
Comment: E onde está seu Python? está onde pode ser acessado universalmente pelo sistema operacional?
Comment: está junto com o index.php no caminho: C:\wamp64\www\teste-php-python\codigopython.py
já tentei usar o 'shell_exec' com o caminho, mas da o mesmo resultado.
shell_exec('python C:\wamp64\www\teste-php-python\codigopython.py 2>&1');

'python' não é reconhecido como um comando interno ou externo, um programa operável ou um arquivo em lotes.
Comment: user140828, acho que sim, pois o 'shell_exec' está conseguindo ir até o código em python, mas na hora de executar, não está dando certo.
Comment: Se deu o erro citado, o Windows não está localizando o interpretador Python na sua máquina - então ele nem "chega ir até o código". Verifique se o executável do Python está na sua variável de ambiente PATH ou execute passando o caminho absoluto do interpretador.
Comment: Obrigado Anderson Carlos Woss, o PATH está correto, mas só funcionou passando o caminho absoluto do interpretador.
Answer: Use isso
<?php

$comando = escapeshellcmd('./ficheiro_python.py');
$cmdResult = shell_exec($comando);
echo $cmdResult;

?>

Como linha "shebang" deverás ter o seguinte no ficheiro python:
#!/usr/bin/env python

Também deverás ter permissões para executar esse ficheiro.
Testado com sucesso com o Ubuntu 16, PHP7.0 e python 2.7.

Chamar script PYTHON através do PHP


Relationship Between Topological Closure and Group Generation

Question: Let $X\subset G$ be a subset of a topological group $G$.  How are $cl(\langle X\rangle)$ and $\langle cl(X)\rangle$ related in general?  Are there results giving conditions on equality of the two?
Here $\langle X\rangle $ is the subgroup generated by $X$ and $cl(X)$ is the (topological) closure of $X$ in $G$.
Comment: From https://en.wikipedia.org/wiki/Topological_group#Properties since $$ is the smallest sub-group of $G$ containing $X$ and since the closure of a top-sub-grp is a top-sub-grp then if $X$ is not closed then $\subset cl()$ strictly...  Not sure if this helps..
Comment: Thanks, this I know but it doesn't really help (at-least I don't see how)
Answer: I don't quite understand what condition you're looking for, but I can give a good example in which these groups are the "least equal" as possible. Note that always $\left<X\right>\subseteq \left<\text{Cl}(X)\right>\subseteq \text{Cl}(\left<X\right>)\subseteq G$. Below is an example in which the first and last inclusions are equalities.
Take $G = S^1 = \{z\in\mathbb{C}:|z|=1\}$ with the multiplication from $\mathbb{C}$ and $X=\{e^{2\pi i \alpha}\}$ a point, for some irrational number $\alpha\in\mathbb{R}$.
In this case $\text{Cl}(X) = X$ and since $\left <X\right>$ is a dense subgroup of $S^1$ the closure is everything. In other words, on the left side you get just the subgroup generated by $X$ and on the right side you get the entire group.
Comment: @New_Topologist_On_The_Block I don't think there's something like that for general topological groups. I mean, you can use this one but it's probably not so interesting: The group $N\leq G$ is dense, if and only if for every group $H$ and every continuous homomorphism $f:G\rightarrow H$ which is trivial on $N$ is trivial on $G$. (The proof is simple, because the quotient map $\pi:G\rightarrow G/\text{Cl}(N)$ is a continuous homomorphism). If you know more about the group it might help (for instance if $G$ is locally compact and abelian you can assume that $H=S^1$ - using pontryagin dual)
Comment: Are there general conditions for a topological subgroup to be dense?  (Something like Stone-Weirestrass but without assuming TVS structure or the structure of an algebra)?