É possível desenvolver sites com C/C++?

Question: Eu sei um pouco de PHP, mas vejo que em sites de conteúdo, as vezes dá umas travadas e etc.
Pesquisando, vi relatos (bem superficiais) de que é possível desenvolver aplicações web com C/C++, e que essas, por sua vez, teriam muito mais performance do que as php, que são de linguagem interpretada.
Gostaria de saber se isso é verdade. Caso alguém possa ajudar, por favor, grato.
Comment: Você pode desenvolver sites em C/C++ mas vai exigir muito mais esforço do que se você usar uma linguagem mais adequada a esse tipo de desenvolvimento.
Comment: Voce pode fazer qualquer coisa com c++, drivers, sistemas operativos, aplicacoes. Aplicacoes web nao sao excepcao. Se sao mais eficientes? Isso é baseado em opinioes
Comment: @Haroldo_OK Isso também é baseado em opinioes. Há semelhanca de outras linguagens, também existem bibliotecas em c++ que facilitam o desenvolvimento de servidores, seguindo até por exemplo o padrao MVC
Comment: https://github.com/ipkn/crow
Answer: Sim, é possível sim. Mas quase ninguém faz. Geralmente o ganho não vale o esforço, que é muito maior.
E mais, se a pessoa não dominar todo processo de desenvolvimento, dominar cada minúcia da linguagem, pode ter um resultado bem pior. Linguagens não fazem milagres. Elas podem permitir que o programador obtenha o resultado desejado, se ele souber o que está fazendo.
Todas as linguagens de programação mainstream podem ser usadas para desenvolver websites, já que o que chamamos de sites são páginas de textos. Toda linguagem pode gerar textos. Esses textos precisam ser usados por um servidor HTTP. Todo servidor HTTP pode chamar um executável e obter esse texto de alguma forma. Claro que se a linguagem puder se comunicar de forma mais eficiente com esse servidor, melhor. Existem bibliotecas para C/C++ que ajudam nisso. Note que é comum esses servidores HTTP serem escritos em C ou C++.
A linguagem de programação não é o problema.
Travadas
É possível que essas travadas estejam relacionadas com seu problema que é bem complexo. Mas também é possível que seja porque não está usando o PHP de forma adequada. Aí mudar de linguagem não resolverá qualquer problema, pode até ocorrer o contrário. O PHP é muito fácil, é mais difícil fazer algo errado nele. Mas vejo que muita gente faz. PHP é uma das linguagens mais usadas para desenvolver sites, fazem coisas complexas, e não trava.
Eu até tenho críticas ao PHP, mas quase tudo para web dá para desenvolver com ele. Nem sempre será a linguagem mais adequada, mas em coisas simples costuma ser. Mesmo que não seja a mais adequada, ainda será razoavelmente adequada.
O que muitas vezes as pessoas fazem quando precisam de performance extrema é passar para Java ou C# que são quase tão fáceis quanto o PHP e com performance muito melhor.
Eu poderia sugerir uma série de coisas que poderia fazer no próprio PHP para melhorar a performance, mas nem isso deve ser o problema. Deve ser algo relacionado ao algoritmo adotado. Então perguntas mais específicas sobre um problema pontual pode ser útil para achar o que está ocorrendo.
Mas reforço, que se não souber fazer tudo muito bem, não entender cada aspecto da computação, não obterá resultados bons em linguagem alguma. Talvez o caminho seja melhorar nesse ponto.
Coloquei no GitHub para referência futura.
Comment: Interessante explicação, me lembrou um professor de faculdade que dizia que tudo no desenvolvimento é possível, a questão é se é viável.
Answer: Sim programação web em C/C++ é possível, isso inclusive remete ao início das aplicações dinâmicas na web. Nos anos 90 CGI com Perl para manipulação de texto e C/C++ para "processamento pesado" eram a norma.
A linguagem de programação, em média, não é o primeiro gargalo de um website. Latência de rede, IO, etc são fatores que pesam muito mais do que a linguagem na grande maioria dos casos.
É claro que o custo do processamento existe, bem como o custo de escalar um website para lidar com milhares / milhões de requests simultâneos... Além disso, com estudos indicando que um atraso de um segundo pode impactar vendas em 7%, há incentivo econômico para otimização de performance.
Vamos assumir que você tenha um problema em que a linguagem de programação realmente se tornou relevante em relação aos demais gargalos de performance e escalabilidade. Mesmo nesse Universo as coisas não são tão binárias; a decisão não precisa ser entre linguagens puramente interpretadas vs puramente compiladas. De fato, o sweetspot para soluções web parece estar em máquinas virtuais com compilação just-in-time. Essa foi a solução do Facebook para o PHP (veja HHVM), de grande parte do desenvolvimento enterprise para grandes web sites (Java, .NET, etc) e mesmo para JavaScript (veja V8).
Você não precisa expor desenvolvedores às idiossincrasias do C/C++ para obter um ganho significativo de performance. De fato, mesmo partindo do pressuposto que uma solução em C/C++ devidamente otimizada sempre será mais rápida (o que não é verdade), a lei dos rendimentos decrescentes faz com que extrair essas últimas gotas de performance da linguagem em um mundo com tantos outros fatores dificilmente valha a pena.
Na grande maioria dos casos, acaba não sendo viável abrir mão de anos e anos de evolução das linguagens, ferramentas, técnicas e conhecimento acumulado pelas diversas comunidades especializadas em desenvolvimento web para escrever uma solução em C/C++. Frameworks para desenvolvimento web em C++ como CppCMS e Wt, independentemente de méritos técnicos, simplesmente não possuem a mesma tração de tecnologias em ecossistemas mais recentes.
Dessa forma, eu diria que desenvolvimento web em C/C++ é possível e existem aplicações em determinados nichos. Dito isso, vejo pouca chance desses tipo de desenvolvimento se tornar mainstream. O argumento do ganho de performance com C/C++ para "evitar travadas" não se sustenta e é bem difícil pensar em um bom motivo para escrever aplicações web em C/C++ em 2016.
Answer: Como o @Maniero comentou, possível é, mas quase ninguém faz.
Isso é simples de entender: o C/C++ não tem esse foco de ser uma linguagem para Web.
Seria como tentar desenvolver um site com Pascal, COBOL ou outra linguagem com propósito diferente.
O C/C++ é uma linguagem que permite desenvolver qualquer coisa, mas existem linguagens mais indicadas para certos propósitos, assim como temos SQL para interação com banco de dados, e R para cálculos que auxiliam Big Data, há linguagens com suporte para o desenvolvimento Web, como PHP, Java e ASP/ASP.NET usando C# por exemplo.
No geral, você pode, mas teria que programar ou encontrar bibliotecas para coisas básicas que essas outras linguagens acima já tem.
Agora, sobre o seu problema de performance, culpar a linguagem é prematuro. Existem sites em ASP/VB que funcionam muito bem até hoje. Seu problema pode ser de rede, acesso a arquivo, tráfego, banco de dados, etc, uma monte de coisas que, independente da linguagem, vão deixar seu site lento.
Sugiro pesquisar mais a fundo e identificar onde está o problema. Muito provavelmente você vai conseguir resolver usando PHP e seu site vai ter uma boa performance.
Answer: Recomendo usar o C#. Eu comecei agora a estagiar numa empresa de programação web e estou a usar o ASP.NET e C#. Na faculdade aprendi C/C++, e C# é muito parecido e fáci aprender e o melhor é que poupa muito trabalho, pois há livrarias para tudo, incluindo para aplicações web, e o melhor é que podes usar o mesmo código para desenvolver para várias plataformas (ex. Android ou iOS) usando Visual Studio, que é grátis na versão comunitária.
Comment: Não gosto do C# mas é digno de nota que o Stack Overflow é escrito em C#.
Answer: O componente crítico, que é o servidor Web em si, já é escrito em C ou C++.
Quanto ao código de aplicação, você vai gastar 100 vezes mais para desenvolver em C do que em PHP ou Javascript. De fato a página vai ter umas 3x mais performance em termos de CPU. Basta pegar uma máquina melhor na nuvem, por alguns dólares a mais por mês, para empatar a performance.
Só por este raciocínio já fica difícil justificar o gasto adicional. Mas tem mais.
O principal gargalo da performance Web é a rede (internet). Velocidade e principalmente a latência. Trabalhar o acesso de rede, usar CDN, usar cache para objetos estáticos, tudo isso vai dar resultados muito mais expressivos num primeiro momento.
Certamente sua aplicação Web usa um banco de dados. A performance desse banco vai ser um gargalo de performance muito antes do código da sua própria aplicação. Num site grande e movimentado, é aqui que você vai gastar o grosso do seu orçamento.
Um site Web costuma ser muito dinâmico, mudanças todo dia, desenvolvimento contínuo. E isso  não combina com C/C++, combina com linguagem interpretada, que você não vai usar só porque é facinha ou porque tem programador barato no mercado; vai usar porque ela é produtiva, porque ela vai permitir que você largue o trabalho à noitinha em vez de ter de virar noite.

É possível desenvolver sites com C/C++?


mongoose .save() method don't insert the data to MonogoDB

Question: i do these steps in console

node
.load app.js
Massage.save()

then in mongoDB shell

use test
db.test.find()

and when i check the data base, it's empty
const express = require("express");
const app = express();
const port = 3000;

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/test", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const movieSchema = mongoose.Schema({
  title: String,
  year: Number,
  score: Number,
});

// Models
const Movie = new mongoose.model("Movie", movieSchema);

const Massage = new Movie({
  title: "The Massage",
  year: 1976,
  score: 92,
});

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

app.listen(port, (req, res) => {
  console.log(`http://localhost:${port}`);
});

Answer: The problem is that I did not set a collection in the model
so instead of
const Movie = new mongoose.model("Movie", movieSchema);

it should be
const Movie = new mongoose.model("Movie", movieSchema, collectionName);

when you want to extract the data from database
use database // go to the database u want

db.collection.find() // extract the data from the collection

Answer: You missed the most important part:
const Massage = await new Movie({
  title: "The Massage",
  year: 1976,
  score: 92,
}).save();

Comment: how to fix this error? Uncaught SyntaxError: await is only valid in async function
Comment: Wrap the function with async


Three20: How to access the model in the next ViewController?

Question: The Situation
I populate my TTTableViewController with a TTListDatasource(with TTModel).
My didSelectObject methods opens a TTViewController.
The Question
I d like to show more informationen in the TTViewController.
1.Question: Should i hand over the datasource (and run a new query) or should i hand over a specific VO (with all information)?
2.Question: How do I acces the datasour in the new TTViewController?
thanks,
Answer: In your TTTableViewController's didSelectRowAtIndexPath: definition, use your TTListDatasource to grab a reference to the corresponding object. Then pass it to your TTViewController. This is best accomplished by using a property of the TTViewController so that you don't have to worry about retain/releasing'ing.
<code>@property (nonatomic, retain) TTModel *model;
</code>
and then in the didSelectRowAtIndexPath:
<code>TTModel *model = //get the correct model
TTViewController *vc = [[TTViewController alloc] initHoweverYouWant];
vc.model = mode;
</code>
A few tips: TTViewController doesn't sound terribly descriptive, since you're (correctly) prefixing your classes. Maybe TTPhotoViewController or something may be more descriptive. Always err on the side of verbosity :)
Additionally, I find it pretty useful to just have my UITableViewController subclass implement the UITableViewDataSource protocol instead of creating a separate object, unless the exact same datasource is going to be used elsewhere for the exact same reason. This works more nicely with NSFetchedResultsController if you're using core data, as well.


Grep Multiple words using a pattern

Question: I ahve a requirement where i need to grep multiple strings from a log file if the pattern is matched
below is the log snapshot:access.log
126.96.36.199 - RMC1 [06/Jul/2016:07:34:17 -0700] "GET /identity/afr/partition/ie/n/default/opt/grid-188.8.131.52.0-5358.js HTTP/1.1" 200 9318
220.127.116.11 - BMC1 [06/Jul/2016:07:34:17 -0700] "GET /identity/ HTTP/1.1" 200 6788
220.127.116.11 - RMC1 [06/Jul/2016:07:34:17 -0700] "GET /identity/afr/partition/ie/n/default/opt/status-188.8.131.52.0-5358.js HTTP/1.1" 200 2297
220.127.116.11 - RMC1 [06/Jul/2016:07:34:17 -0700] "GET /identity/afr/partition/ie/n/default/opt/poll-220.127.116.11.0-5358.js HTTP/1.1" 200 2098
18.104.22.168 - RMC1 [06/Jul/2016:07:34:18 -0700] "GET /identity/afr/alta-v1/overflow_right_ena.png HTTP/1.1" 200 1082
22.214.171.124 - RMC1 [06/Jul/2016:07:34:18 -0700] "GET /identity/ HTTP/1.1" 200 6749
22.214.171.124 - RMC1 [06/Jul/2016:07:34:18 -0700] "GET /identity/afr/alta-v1/conv_l_ena.png HTTP/1.1" 200 1161
188.8.131.52 - RMC1 [06/Jul/2016:07:34:24 -0700] "GET /identity/ HTTP/1.1" 200 6799
22.214.171.124 - RMC1 [06/Jul/2016:07:34:27 -0700] "GET /identity/images/Dashboard/myAccess_s2.png HTTP/1.1" 200 6885
188.8.131.52 - SSS1 [06/Jul/2016:07:34:24 -0700] "POST /identity/faces/home?_adf.ctrl-state=o9l9q161v_5 HTTP/1.1" 200 41776

want to grep the username and time fields if the pattern matches /identity /HTTP/1.1  in the log file
so my output will be:
BMC1 06/Jul/2016:07:34:17
RMC1 06/Jul/2016:07:34:18
RMC1 06/Jul/2016:07:34:24

Tried:
grep -E '/identity/ HTTP/1.1' *.log

But it is giving whole line.
Please assist
Answer: Using awk
$ awk -F'[][ ]+' '/\/identity\/ HTTP\/1[.]1/{print $3,$4}' access.log
BMC1 06/Jul/2016:07:34:17
RMC1 06/Jul/2016:07:34:18
RMC1 06/Jul/2016:07:34:24

How it works:

-F'[][ ]+'
This sets the field separator to be any combination of [, ], or space.
/\/identity\/ HTTP\/1[.]1/{print $3,$4}
This selects the lines of interest and prints just the third and fourth fields.

Using sed
$ sed -n '\|/identity/ HTTP/1[.]1|{s/^.* - //; s/[[]//; s/[]].*//; p;}' access.log
BMC1 06/Jul/2016:07:34:17 -0700
RMC1 06/Jul/2016:07:34:18 -0700
RMC1 06/Jul/2016:07:34:24 -0700

How it works:

-n
This tells sed not print anything unless we explicitly ask it to.
\|/identity/ HTTP/1[.]1|
This selects the lines of interest.
s/^.* - //; s/[[]//; s/[]].*//
For the selected lines, these three substitution commands remove the unwanted parts from the line.
p
This tells sed to print what is left of the selected lines after our substitutions were made.

Using grep -P
If your grep supports the -P flag:
$ grep -oP '(?<= - ).*(?= "GET /identity/ HTTP/1\.1)' access.log
BMC1 [06/Jul/2016:07:34:17 -0700]
RMC1 [06/Jul/2016:07:34:18 -0700]
RMC1 [06/Jul/2016:07:34:24 -0700]

If it is important to get rid of [ and ], we can use:
$ grep -oP '(?<= - ).*(?=] "GET /identity/ HTTP/1\.1)' access.log | tr -d '['
BMC1 06/Jul/2016:07:34:17 -0700
RMC1 06/Jul/2016:07:34:18 -0700
RMC1 06/Jul/2016:07:34:24 -0700

Comment: @sps Good point.  I just added a `grep+tr` solution to handle that.
Comment: +1 for good answer, but just a note though, your `grep` answer isn't producing what OP wanted. OP did not want `[` and `]` characters.
Comment: You need to escape `.` in the pattern, it will match any char now between two 1s (e.g. 1x1, 131 etc.) not that it's realistic in this scenario.
Comment: @karakfa Yes, thanks, I missed that a couple places.  Answer updated.

Grep Multiple words using a pattern


How many $3$-digit numbers are there whose sum of digits is $10$?

Question: I did just counted all in gap of every $100$ numbers. Like in $100-200$, there are $10$ nos.($109,118,127, \ldots,181,190$). And then $9$ nos. in $200-300$, $8$ in $300-400$ ... and so on. By this I am getting $10+9+...3+2=54$, but answer given in India's JEE Mains exam is $55$. Am I missing one or the answer given is wrong and I'm right? Please help.
Comment: hmm...  For $a**$ we have $**$ must add to $10-a$ and go from $0$ to $10-a$ so there are $11-a$ of them ..... yep, I get the same result as you do.  $10+9+8+....+3+2=54$.
Comment: Sometimes texts and proof readers make mistakes.
Comment: I m not able to read this...it is showing $a**$ and $**$..please help
Comment: Your answer is correct. [Verified by C program.](https://tio.run/##JY1BDsIgEEXXcIpJTRMIVYc1pXcxIDqJgql0ZTw7nbab//Ink/fD@RFCO1EOryXeYfzWSOXynBrlCu8bZaXlT4qthbLkOpCTIpUZFHmL6GjkZBijpRCU@N5bBHMQ9XUvxEDwHixub2JXGcOqz8zqpLo@dsOxoJ38t7YC)
Comment: @fleablood so this is correct .. isn't it..54...actually it was in JEE Mains exam (India) and my institute gave answer as 55(but it was just by memory based ques so may be some student have given wrong ques)...
Comment: @player3236 thnx
Comment: "I m not able to read this...it is showing a∗∗ and ∗∗..please help"  That was what I meant to type.  It's a number whose first digit is $a$ and the other two digits are left blank.  The two blanks must add to $10-a$ and so the first blank can go from $0$ to $10-a$ and the other blank is whatever is left.  From $0$ to $10-a$ is $11-a$ options where $a$ can be $1,2,3,....9$ and so the total number is $10 + 9+ 8 + ...... + 2=54$.
Comment: @fleablood ohh...ohk...got the point... actually in my phone it is showing dollar sign before and after a** ...so I got confused .. it is because of some coding... isn't it. I got confused because of many dollar signs in it..
Comment: Welcome to MathSE.  This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Comment: I have already asked this yesterday. You can see this for more methods https://math.stackexchange.com/questions/3812972/
Comment: Ah... well... The dollar signs are symbol coding.  YOu must have a version that doesn't render the math code in comments.  To write math code you put them between dollar signs.
Answer: This problem is equivalent to partitioning ten items to three boxes.
For example $433$ whose sum of digits is 10. $433$ can be represented as partition of items as below:
$$\circ \circ \circ \circ \mid \circ \circ \circ \mid  \circ   \circ  \circ$$
More examples:
$109$
$$\circ \mid \mid \circ \circ \circ \circ \circ \circ \circ   \circ  \circ$$
$019$, this is not a 3-digit number.
$$\mid \circ \mid \circ \circ \circ \circ \circ \circ \circ   \circ  \circ$$
$190$
$$ \circ \mid \circ \circ \circ \circ \circ \circ \circ   \circ  \circ \mid$$
Now we calculate the Number of three digit number with following three mutually exclusive cases.
Case I: Zero is not one of the digits.
Here we need to choose partition from the $9$ spaces between the items.
This is $= \binom{9}{2} = 36$
Case II: One of the digit except the last digit is zero. (Eg: 109)
Both the partitions occupy the same position.
Number of choices = $\binom{9}{1} = 9$
Case III: The last digit is zero but other digits are non-zero. (Eg: 190)
One of the partitions is at the end and other partition can be chosen from one of the 9 places. The number of choices = $\binom {9}{1} = 9$
Therefore total number of 3-digit numbers whose sum of digits is $10 = 36 + 9 + 9 = 54$.
NOTE: $100, 200, \cdots, 900$ digits with two zeros are not included in any of these cases. All these numbers have a digit sum less than 10.
Answer: Your solution is correct.
Let $h$ denote the hundreds digit, $t$ denote the tens digit, and $u$ denote the units digit.  Then
$$h + t + u = 10 \tag{1}$$
where $1 \leq h \leq 9$, $0 \leq t \leq 9$, and $0 \leq t \leq 9$.
If we let $h' = h - 1$, then $h'$ is a nonnegative integer such that $0 \leq h' \leq 8$.  Substituting $h' + 1$ for $h$ in equation 1 yields
\begin{align*}
h' + 1 + t + u & = 10\\
h' + t + u & = 9 \tag{2}
\end{align*}
which is an equation in the nonnegative integers.
A particular solution of equation 2 corresponds to the placement of $3 - 1 = 2$  addition signs in a row of $9$ ones.  For instance,
$$1 1 1 1 + 1 1 1 + 1 1$$
corresponds to the solution $h' = 4, t = 3, u = 2$ of equation 2 and $h = 5, t = 3, u = 2$ of equation 1.  The number of solutions of equation 2 in the nonnegative integers is
$$\binom{9 + 3 - 1}{3 - 1} = \binom{11}{2} = 55$$
since we must which two of the eleven positions required for nine ones and two addition signs to be filled with addition signs.  This is presumably how the authors of the official solution arrived at the answer $55$.
However, we have not dealt with the restriction that $h' \leq 8$.  There is one solution of equation 2 which violates this restriction, namely $h' = 9, t = 0, u = 0$, which corresponds to the solution $h = 10, t = 0, u = 0$ of equation 1 in the nonnegative integers.  However, if $h = 10$, then we are counting $1000$ as a three-digit integer, which is nonsense.  Subtracting this case, we obtain
$$\binom{9 + 3 - 1}{3 - 1} - 1 = 55 - 1 = 54$$
three-digit positive integers with digit sum $10$, as you found.
Answer: Consider the numbers betweeb $a00$ and $a99$.
Such a number is $ajk$ and $j+k= 10 -a$.  Now $j$ may be anything from $0$ to $10-a$.  That is $11-a$ choices.  $j$ must bue $10-a-j$ and is fixed for us.
(For example:  for then numbers between $600$ and $699$ the number $6jk$ must be that $j+k =4$ and that $j$ may be $0$ to $4$ and there are $5$ such options.  That is $j = 0,1,2,3,4$ and $k= 4,3,2,1,0$.)
So for $a =1......9$ we will have $11-a$ options in that range and so $10+9+ 8+......+2=54$  (the very last case is the numbers between $900$ and $999$ where $9jk$ can have $j = 0,1$ and $k =1,0$.
I think the answer given was careless and accidently included the number $(10)00$ where the first "digit" $a$ is $10$ and $j$ can go from $0$ to $0$.
If you are doing a sum, its easy to think you must go all the way down to $1$.


Explicit partition of $\mathbb{N}$ to demonstrate that $\{x,y,3x-y\}$ is not a Ramsey family

Question: Let $k, s \in \mathbb{N}$, and let $f_{1}, \ldots, f_{k}: \mathbb{N}^{s} \rightarrow \mathbb{Z}$. We call $\left\{f_{1}, \ldots, f_{k}\right\}$ a Ramsey family if for any finite coloring $\mathbb{N}=C_{1} \cup \cdots \cup C_{r}$, there exist $\mathrm{x} \in \mathbb{N}^{s}$ and $i \in\{1, \ldots, r\}$ such that $\left\{f_{1}(\mathrm{x}), \ldots, f_{k}(\mathrm{x})\right\} \subset C_{i}.$ For example $\{x,x+1\}$ is not a Ramsey family because the partition to odd and even naturals would be a counter example. By Rado's theorem we know that $\{x,y,3x-y\}$ is not a Ramsey family but I have been unable to construct an explicit partition of $\mathbb{N}$ to demonstrate this. Is there a way to do it?
Answer: Suppose you have a coloring of $\mathbb N$ with the property that whenever $x,y \in \mathbb N$ and $1.5x \le y \le 3x$, $x$ and $y$ are a different color.  In such a coloring, a triple $\{x, y, 3x-y\}$ can never be monochromatic: both $y$ and $3x-y$ are at most $3x$, and the larger of them must be at least $1.5x$.
Can we find such a coloring? Yes! Define a sequence $(a_n)$ by the recurrence relation $a_n = \lceil \frac32 a_{n-1}\rceil$, with $a_1=1$. This sequence begins $1, 2, 3, 5, 8, \dots$ and it's not the Fibonacci numbers because the next term is $12$: it is sequence A061419 in the OEIS.
Now color the intervals $[a_n, a_{n+1})$ by cycling through four different colors. If $x \in [a_n, a_{n+1})$ and $1.5x \le y \le 3x$, then either $y \in [a_{n+1}, a_{n+2})$ or $y \in [a_{n+2}, a_{n+3})$ or $y \in [a_{n+3}, a_{n+4})$, because $a_{n+4} > 3a_{n+1}$. So $y$ is in an interval of a different color from $x$.


Verificar se input file está preenchido

Question: Estou com uma dificuldade que não estou conseguindo resolver, mesmo sendo uma situação simples. Estou tentando validar um campo input file, o campo precisa ser preenchido, o que tenho:
Formulário:
<form enctype="multipart/form-data" class="form-horizontal" id="frmDoc" method="post">

<legend>Selecione o PDF</legend>

  Arquivo

    <input name="Arquivo" type="file" class="btn btn-default" id="Arquivo">

 Extensão permitida PDF.

Tentativa de validação:

if (!isset($_FILES)):
    $retorno = array('codigo' => 0, 'mensagem' => ' Informe o arquivo para Upload');
    echo json_encode($retorno);
    exit();
endif;

O script está sendo executado mesmo sem informar o arquivo.
Answer: Podes fazer assim:
if ($_FILES['Arquivo']['error'] == 4):
    $retorno = array('codigo' => 0, 'mensagem' => ' Informe o arquivo para Upload');
    echo json_encode($retorno);
    exit();
endif;

O problema estava na verificação, pois isset($_FILES) é sempre verdade, $_FILES existe sempre, mesmo que esteja vazio. O que fiz em cima foi verificar se dentro dentro desse array existe o Arquivo definido no form.
Mais sobre erros de upload
Também aconselho a fazer uma verificação do lado cliente, com required:
<input name="Arquivo" type="file" class="btn btn-default" id="Arquivo" required>

Comment: Olá @Miguel, agora mesmo informando o arquivo a mensagem de erro está sendo exibida, valeu pela dica.
Comment: Como @adventistapr ? Se fizezeres o upload ficas com a mensagem de erro? O campo file chama-se, tem o `name` "Arquivo" certo? Não está a fazer bem o esperado?
Comment: Peço desculpa @adventistapr, foi um lapso meu, coloquei de maneira correta agora
Comment: Então, fiz a alteração como você indicou e o estranho é isso, mesmo com o campo preenchido minha mensagem é exibida, o campo do input está correto.
Comment: @adventistapr , no form não devia post? `...method='POST'`
Comment: Corrigido @adventistapr , desculpa, foi erro meu
Answer: Você pode verificar o tamanho do arquivo.
Se for igual a 0 é porquê não teve upload.
if ($_FILES['Arquivo']['size'] == 0)

Verificar se input file está preenchido


Convert cm to mm using Regex.Replace()

Question: I want to take the following input <tag>30.234234cm</tag> and get the following output <tag>302.34234mm</tag>. Where the value between the tags is a value in centimetres that may be decimal or integer, and the goal is to convert that value to millimetres.
var input = "<tag>30.234234cm</tag>";
input = Regex.Replace(input, @"(\d+(\.\d+)?)cm", (double.Parse("$1") * 10).ToString() +
    "mm", RegexOptions.IgnoreCase);

I am using the expression (\d+(\.\d+)?) for the first capture group. However, $1 will not work in the context of double.Parse($1). How can I get the value of the unit, convert it and replace it in the example string provided?
Answer: Well,
  double.Parse("$1")

tries to parse "$1" constant string and fails. I suggest using lambda:
  var input = "<tag>30.234234cm</tag>";

  input = Regex.Replace(
      input,
     @"(\d+(\.\d+)?)cm",
      match => (double.Parse(match.Groups[1].Value) * 10).ToString() + "mm",
      RegexOptions.IgnoreCase);

Here match.Groups[1].Value is a value of the captured group (30.234234 in the example)
Comment: Note this is using the `Regex.Replace` overload that takes a `System.Text.RegularExpressions.MatchEvaluator` as the third arg, in case that's not clear.
Comment: Thank you, this worked with no problems. You're right about `"$1"` being passed as a constant. The lambda is quite elegant.
Answer: You're using "(\d+(\.\d+)?)cm" with "cm" as a capture, because of that you can't perform `double.Parse("$1")
Comment: I don't think `cm` is the reason it can't be parsed. It's that `$1` itself cannot be parsed.
Comment: Omitting the unit "cm" from the string will still throw an exception.

Convert cm to mm using Regex.Replace()


O que é o travamento otimista e pessimista?

Question: Como se diferenciam optimistic e pessimistic locking no contexto de banco de dados?
Todos os produtos possuem isto?
Answer: O travamento pessimista é muito mais simples de entender porque você efetivamente coloca uma trava (lock), ou seja, você diz que vai mexer em uma parte do banco do banco de dados e ninguém mais pode mexer nele até você terminar e destravar.
Isso tem a desvantagem de impedir o prosseguimento de outros acessos em algumas circunstâncias e exige uma atitude correta por parte da aplicação para lidar com isso e para lidar com os deadlocks possíveis causados pelos travamentos. Dependendo da tecnologia adotada o travamento pode ser o banco de dados todo.
Ele considera que algo dará errado e toma a decisão mais garantida para impedir colisão de acesso.

O travamento otimista costuma escalar melhor porque ele não é um travamento de verdade, ele permite que outros acessem ao mesmo tempo. Ele é mais complexo de implementar em um sistema gerenciador de banco de dados e pode ser menos eficiente já que precisa garantir que não houve alterações no meio do processo quando começou o processo de manipulação e quando terminou de fazer, tendo que tomar alguma providência se houve alterações, muitas vezes abortando a transação e tendo que começar de novo, o que não é um problema se raramente acontece um conflito, e o padrão da maioria das aplicações é ser raro mesmo. A aplicação precisa saber manipular uma falha de transação.

Note que mesmo o travamento pessimista pode ocorrer automaticamente pelo SGBD e você não precisaria se preocupar. Em alguns casos é feito o otimista automaticamente e o pessimista fica a critério do usuário que fará o acesso.
Cada produto entrega a forma que acha mais conveniente, pode ter ambos, um deles ou nenhum. Uma forma muto simples e eficiente é não permitir escritas concorrentes, só permite a serialização completa. Boa parte dos problemas não precisam disso e alguns bancos de dados mais nichados adotam esta forma, pode ser mais efetivo do que parece, mas obviamente não atende 100% das necessidades, quem sabe 99 ou 99,9%.
Coloquei no GitHub para referência futura.
Comment: Só pode fazer uma transação de cada vez. Ele faz a transação completa, termina e vai para a próxima. Não tem concorrência verdadeira. Isso evita um monte de problemas e altamente eficiente. Em muitos cenários é uma maravilha, o problema dela é que se tiver uma transação demorada, todas as outras terão que esperar, mas esse não é um cenário comum na maioria dos problemas e na média ele é muito mais rápido, ele só tem alguma dificuldade nos raros picos que podem ser administrados ou em problemas que tenham muitas transações longas. Note que isso é só para escrita, a leitura está sempre livre.
Comment: O que significa serialização completa nesse contexto de bancos?


Proof of convergence implication

Question: I am trying to show that if $(Z_t)_{t> 0}$ is a stochastic process the following implication holds
$$
P(sup_{0<s\le t} |Z_s| > \alpha ) \stackrel{t\to 0}{\to} 0 \Rightarrow Z_t \stackrel{t\to 0}{\to} 0 \ a.s.
$$
 I am really clueless. Any hint / help is appreciated.
Comment: As stated, it is not true, as $Z_t$ can remain larger than $\alpha/2$ for ever and ever without violating the assumption yet without getting the result. You should take more care in copying your homework problems if you want other people to solve them for you.
Answer: Okay, so we can deduce there exists a deterministic sequence $t_n$ for which the following holds:
$$
P(\underbrace{\sup_{0\le s\le t_n}|Z_s|}_{X_n}>\tfrac{1}{n})\le \tfrac{1}{n^2}
$$
Now, Borel Cantelli yields that almost surely $X_n\le \tfrac{1}{n}$ for $n$ big enough. That should do that job, I think...
Comment: ..like a boss !

Proof of convergence implication


Repetição de Código

Question: Estou tendo problema com a repetição de código na minha classe de conexão CURL, a classe está sendo declarada da seguinte forma:
<?php
if (!defined("ROOT_PATH")) define("ROOT_PATH", dirname(__FILE__, 2));

require_once ROOT_PATH."/helpers/Helper.php";

class PhabricatorModel
{
    const TOKEN = "api.token=api-...";

    public function add($parameters)
    {
        $channel = curl_init();
        curl_setopt($channel, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded"));
        curl_setopt($channel, CURLOPT_URL, "https://pb-dc.com/api/maniphest.edit");
        curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($channel, CURLOPT_POSTFIELDS, self::TOKEN.$parameters);
        curl_setopt($channel, CURLOPT_POST, 1);
        $result = curl_exec($channel);
        if (curl_errno($channel)) {
            return false;
        }

        curl_close($channel);

        return $result;
    }

    public function consultProject($project)
    {
        $channel = curl_init();
        curl_setopt($channel, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded"));
        curl_setopt($channel, CURLOPT_URL, "https://pb-dc.com/api/project.query");
        curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($channel, CURLOPT_POSTFIELDS, self::TOKEN."names[]=".$project);
        curl_setopt($channel, CURLOPT_POST, 1);
        $result = Helper::convert_array(json_decode(curl_exec($channel)));
        if (curl_errno($channel)) {
            return false;
        }

        curl_close($channel);

        return $result;
    }

    public function consultStory($story)
    {
        $channel = curl_init();
        curl_setopt($channel, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded"));
        curl_setopt($channel, CURLOPT_URL, "https://pb-dc.com/api/maniphest.query");
        curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($channel, CURLOPT_POSTFIELDS, self::TOKEN."status=status-open&fullText=".$story);
        curl_setopt($channel, CURLOPT_POST, 1);
        $result = Helper::convert_array(json_decode(curl_exec($channel)));
        if (curl_errno($channel)) {
            return false;
        }

        curl_close($channel);

        return $result;
    }
}

Se notar o mesmo item de curl_init nos 3 métodos e eu queria remover essa repetição, não só no curl_init mas também em outras partes.
Comment: Crie um novo método para inicialização, assim `$channel` virará `$this->channel` e coloque lá CURLOPT_HTTPHEADER, CURLOPT_RETURNTRANSFER e CURLOPT_POST que são iguais nos três casos (mas você ainda pode alterá-los dentro do método sempre que precisar). Vou colocar um exemplo disto aqui nas respostas.
Comment: maioria dos casos o curl não resulta em nada se não utilizar `CURLOPT_SSL_VERIFYPEER, false`. tenho conhecimento básico. talvez seja isso
Comment: @Guilherme não entendi muito bem o que você quis me passar, poderia me explicar mais ?
Comment: Teus três métodos são muito parecidos em estrutura, você poderia fazer um método único e utilizar a estrutura de switch/case para tratar as partes que são diferentes.
Comment: @GiovanniNunes a ideia é que com o tempo esse código seja evoluído, e para leitura e entendimento um switch/case não ficaria legal pra isso.
Answer: Trate a variável $channel como um atributo da classe e crie um método privado específico para inicializá-la com os valores que já se repetem lá dentro, algo assim:
class PhabricatorModel
{
        const TOKEN = "api.token=api-...";

        // o que é comum fica aqui...
        private function curl_init(){
            $this->channel = curl_init();
            curl_setopt($this->channel, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded"));
            curl_setopt($this->channel, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($this->channel, CURLOPT_POST, 1);
        }

        // o que é específico fica num método próprio...
        public function add($parameters) {
            $this->curl_init();
            curl_setopt($this->channel, CURLOPT_URL, "https://pb-dc.com/api/maniphest.edit");
            curl_setopt($this->channel, CURLOPT_POSTFIELDS, self::TOKEN.$parameters);
            if (curl_errno($this->channel)){
                $result = false;
            } else {
                $result = curl_exec($this->channel);
            }
            curl_close($self->channel);
            return $result;
        }
        // alterei a lógica no final para evitar surpresas.

        // ...

E a mesma coisa seria feita nos outros métodos.
Answer: Extração de método
Tente criar um novo método que contém a parte que se repete e passe como parâmetro os valores que variam nas chamadas da biblioteca curl.
     private function configCurl($url, $token)
     {

        $channel = curl_init();
        curl_setopt($channel, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded"));
        curl_setopt($channel, CURLOPT_URL, $url);
        curl_setopt($channel, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($channel, CURLOPT_POSTFIELDS, $token);
        curl_setopt($channel, CURLOPT_POST, 1);

        return $channel;

     }

Depois basta usar o método no lugar do código repetido e trabalhar com a referência de curl (agora retornada pelo método), assim como você está fazendo.

Repetição de Código


AutoCompletetextView with CursorLoader

Question: I´m changing my application to use CursorLoader instead of startManagingCursor....
And I have one AutoCompleteTextView, SimpleCursorAdapter and in my setFilterQueryProvider  implementation, in "runQuery" method I have
<code>    mProdutoAdapter.setFilterQueryProvider(new FilterQueryProvider() {
        @Override
        public Cursor runQuery(CharSequence constraint) {

            Cursor cursor = mVendasDb.getProdutos(constraint.toString());
            startManagingCursor(cursor);
            return cursor;
        }
    });
</code>
How can I change this part to make it works with CursorLoader?
Should I discard  setQueryFilterProvider and use TextWatcher in the AutocompleteTextView and then call getLoaderManager().restartLoader(0, bundleFilter, this)???  I have no idea how to proced!
bundleFilter would have the text came from textwatcher.
Is it ok using this aproach? Is it the best to do in this case?
Answer: This is a fine approach, according to the android developer website :
Restarting a Loader :

To discard your old data, you use restartLoader(). For example, this implementation of SearchView.OnQueryTextListener restarts the loader when the user's query changes. The loader needs to be restarted so that it can use the revised search filter to do a new query:
Comment: So, how would you use a Loader to return a Cursor from the OP's `runQuery()` method?

AutoCompletetextView with CursorLoader


Is a negative OOB score possible with scikit-learn's RandomForestRegressor?

Question: I'm currently implementing scikit-learn's RandomForestRegressor in Python and am scratching my head over why I have occasionally wound up with negative out-of-bag scores from it. As far as I can tell from the given description of the attribute "_oob_score" ("Score of the training dataset obtained using an out-of-bag estimate") and everything I've read so far, the out-of-bag score should be a positive value.
Extra info:

All of the scores I have been getting, both positive and negative, are very small in magnitude (< 0.001; many are < 0.0001). I am also not sure if this is normal, but in general the responses are also small.
I'm using 500 trees, and varying min_samples_leaf and max_features. I seem to get the negative values when min_samples_leaf is over ~500.
There are about a hundred Boolean columns that were created to deal with categorical data (that are therefore fairly sparsely populated). In contrast, there are about 10 other, numerical columns. Null values have been filled in with a large negative number as a numerical placeholder.
My data size is about 1,000,000 rows, with 65% being used for training data and the remainder for testing.
(Any other info I can give to help out?)

Is there a statistical interpretation/definition of the out-of-bag score for a random forest for which one would expect a negative score as a possibility, or is this more likely to be a quirk of the program?
Comment: It's hard for someone who doesn't use this software to be clear whether you have (1) a general statistical question or (2) a question specific to the software. Which is it? (2) would usually be off-topic here.
Comment: Thanks for the help, @NickCox! I guess the problem is that I don't know (or, that is what I am trying to find out) -- are there any statistical interpretations of out-of-bag scores of a random forest that would allow for a negative score? If not, I am guessing my issue is more in the realm of (2) and I will ask elsewhere, but I suppose I am hoping it is (1) and there is simply something I'm not understanding about the meaning of the term or how it might be applied here. I will edit my question a bit to clarify.
Answer: RandomForestRegressor's oob_score_ attribute is the score of out-of-bag samples. scikit-learn uses "score" to mean something like "measure of how good a model is", which is different for different models. For RandomForestRegressor (as for most regression models), it's the coefficient of determination, as can be seen by the doc for the score() method.
This is defined as $(1 - u/v)$,
where $u$ is the regression's sum squared error $u = \sum_i (y_i - \hat{y}_i)^2$,
and $v$ is the sum squared error of the best constant predictor $v = \sum_i (y_i - \bar{y})^2$ (where sums range over the test instances).
This measure can indeed be negative, if $u > v$, i.e. your model is worse than the best constant predictor. This means your model kind of sucks; usually models get positive scores. The score of .0001 or whatever means that your model is only just barely better than the best constant predictor.
Comment: Thanks so much for the help; the meaning of the score is much clearer to me now. Given the very skewed nature of the data in question and now knowing the oob_score_ is $R^2$, I suppose it's not really a surprise that the score would be that low. We have been able to get reasonable AUCs with the model, though. I wonder if it's justifiable to give more weight to the AUC when deciding whether the model is good, or if the bad $R^2$ indicates a deeper problem that the AUC masks that still needs to be addressed.


Proving the language is regular or not?

Question: I was trying to solve these two questions for a while, can I know how can I use pumping lemma to solve them?
a) $\{a^i b^j \mid i, j \geq 0 \text{ and }i + j = 5\}$.
b) $\{w = xy \mid x, y \in \{a, b\}^* \text{ and } |x| = |y| \text{ and } \#a(x) \geq \#a(y) \}$.
and thanks
Comment: Welcome to SE network, please visit [Help Center](http://math.stackexchange.com/help)
Comment: Did you really try seriously to solve a) ?
Comment: @J.-E.Pin I did try and I solve it, I found similar question but with (i doesn`t equal j)
Answer: Language a) is regular.
To see this, observe that there are only finitely many strings in this language (all strings of length $5$ such that the string is composed of zero or more $a$s followed by zero or more $b$s). Thus, we can compose a DFA, which has a finite number of accepting states corresponding to these strings, and all other states are not accepting. In general, any finite language is regular.
Language b) is not regular.
To see this, we need to use the pumping lemma.
Suppose language b) was regular, and was the language corresponding to some DFA $D$, which has $N$ states. The pumping length of this language must be $\leq N$.
Clearly, $w = b^{N+1}ab^{N+1}a$ is part of this language. Using the pumping lemma on $w$, we need to decompose $w=xyz$, where $|xy|\leq N$ and $|y|\geq 1$. The only way this can happen is if $y=b^i$ for some $i\geq 1$. Then, by pumping $w$, we see that $xy^2z=b^{N+1+i}ab^{N+1}a$ must be in this language, but it is not as the first half of the language contains only $b$s but the second half has at least one $a$.
This is a contradiction, and hence the assumption that language b) was regular is false.
Comment: can you help me in composing the dfa? because I should use pumping lemma first to prove then draw the dfa if it`s possible
Comment: + isn`t this the same as my question, L = {a^ib^j: i, j >= 0 and i not equal j}

Proving the language is regular or not?


Show that there exists $c\in[a,b]$ such that $f(c)=\frac{1}{n} ( f(x_1)+f(x_2)+...f(x_n))$

Question:
Given $f$ a continuous function on $(a,b)$ such that $x_1,x_2,...,x_n$ $n$ elements of $(a,b)$, show that it exists $c\in[a,b]$ such that $f(c)=\frac{1}{n} ( f(x_1)+f(x_2)+...f(x_n))$

That equals to show that : $f(c)+f(c)+...+f(c) ( \text{n times})=f(x_1)+f(x_2)+...+f(x_n)$
There we assume the function $h(x)=f(x)-f(x_1)+f(x)-f(x_2)+...+f(x)-f(x_n)$
Its there in my mind to use the IVT but I don't know how in such serie function like that
Comment: Hint: a mean is always between (i.e. intermediate) its min and its max.
Answer: Without loss of generality, let
$$ x_1<x_2<\cdots<x_n. $$
Since $f(x)$ is continuous in $[x_1,x_n]$, $f(x)$ reaches its minimum and maximum. Let
$$ m=\min_{x\in[x_1,x_n]}f(x), M=\max_{x\in[x_1,x_n]}f(x). $$
Clearly
$$ m\le\frac{1}{n}(x_1+x_2+\cdots+x_n)\le M.$$
By the IMVT, there is $c\in[x_1,x_n]$ such that
$$ f(c)=\frac{1}{n}(x_1+x_2+\cdots+x_n). $$
Answer: Find $l,h \in \{1,2,\ldots ,n \}$ such that $f(x_l)\leq f(x_i)$ for all $i \in \{1,2,\ldots ,n \}$ and $f(x_h)\geq f(x_i)$ for all $i \in \{1,2,\ldots ,n \}$. Clearly such $l$ and $h$ exist. Now if $f(x_l)=f(x_h)$, then all $f(x_i)$ are equal so there is nothing to prove. So $f(x_l)<f(x_h)$ and so now assume WLOG  $x_l<x_h$. Now consider the function $f(x) - \frac{1}{n}(f(x_1)+ \ldots f(x_n))$ in the interval $[x_l,x_h]$. Clearly $f(x_l) \leq 0$ and $f(x_h)\geq 0$, hence by IMVT $\exists c \in [x_l,x_h]$ with $f(c) - \frac{1}{n}(f(x_1)+ \ldots f(x_n)) = 0$.


How to find inverse Laplace transform of $\frac{\sqrt{s} \sqrt{a+s}}{b+s}$

Question: How to find inverse Laplace transform of
$$\frac{\sqrt{s} \sqrt{a+s}}{b+s}$$
where $a$ and $b$ constants, ${a,b}>0$
I tried to solve it, but I couldn't.
EDITED.
Numerical solution for $a=1,b=1$.
Plot:
Comment: It have to satisfy $\lim_{s\to\infty}F(s)=0$.
Comment: Why do you need to find it and what are your actual attempts? It has a distributional part due to MyGlasses' remark.
Comment: @JackD'Aurizio ,I tried with  convolution teorem,but checking numericall dosen;t work.,I tried with expanding with infinite sum,but could not find closed sum.I tried with Bromwich Integral ,but I not succeed....,I tried with Mellin Transform, but could not find inverse..
Comment: @JackD'Aurizio. Mathematica ,Maple can't  find solution.I searched in the Tables but I not succeed.
Answer: One method of consideration may be applied to the following. By using the series expansion
$$\sqrt{1-x} = 1 - \sum_{k=1}^{\infty} \frac{(2k-2)! \, x^{k}}{2^{2k-1} \, k! \, (k-1)!}.$$
Now the fraction in question becomes:
\begin{align}
\frac{\sqrt{s \, (s+a)}}{s+b} &= \frac{\sqrt{\left(s+ \frac{a}{2}\right)^{2} - \frac{a^{2}}{4}}}{s+b} = \frac{s + \frac{a}{2}}{s+b} \cdot \sqrt{1 - \frac{a^{2}}{4 \, \left(s + \frac{a}{2}\right)^{2}}} \\
&= \frac{s + \frac{a}{2}}{s+b} - \sum_{k=1}^{\infty} \frac{(2k-2)! \, \left(\frac{a}{2}\right)^{2k}}{2^{2k-1} \, k! \, (k-1)!} \cdot \frac{1}{(s+b) \, \left(s + \frac{a}{2}\right)^{2k-1}}.
\end{align}
By using the convolution theorem it is developed into:
\begin{align}
\frac{(2k-2)!}{(s+b) \, \left(s + \frac{a}{2}\right)^{2k-1}} &\Doteq \int_{0}^{t} e^{-b (t-u)} \, u^{2k-2} \, e^{- \frac{a u}{2}} \, du \\
&\Doteq \frac{e^{-bt}}{\left(\frac{a}{2} - b\right)^{2k-1}} \, \int_{0}^{\left(\frac{a}{2} - b\right) \, t} e^{-x} \, x^{2k-2} \, dx \\
&\Doteq \frac{e^{-bt}}{\left(\frac{a}{2} -b\right)^{2k-1}} \, \gamma\left(2k-1, \left(\frac{a}{2} - b\right) \, t \right),
\end{align}
where $\gamma(a,x)$ is the incomplete Gamma function. Putting all the components together yields
$$\frac{\sqrt{s \, (s+a)}}{s+b} \Doteq \delta(t) + \left(\frac{a}{2} - b\right) \, e^{-b t} \, \left[1 - 2 \, \sum_{k=1}^{\infty} \frac{\left(\frac{a}{2 \, (a-2b)}\right)^{2k} \, \gamma\left(2k-1, \left(\frac{a}{2} -b\right) \, t \right) }{ k! \, (k-1)!} \right]. $$
Notice that if $b = \frac{a}{2}$ then this reduces to
$$\frac{\sqrt{s \, (s+a)}}{s+\frac{a}{2}} \Doteq \delta(t) - \frac{a^{2} \, t}{8} \, e^{- \frac{a \, t}{2}} \, {}_{1}F_{2}\left(\frac{1}{2}; \frac{3}{2} , 2; \frac{a^{2} \, t^{2}}{16} \right).$$
Comment: Yours answer is wrong.If I put $a=1,b=1,t=1$ in yours formuła I get $Infinity$.It should be approximately: $-0.2443072$.I checked numericall in Mathematica.
Comment: I corrected yours mistake and Yours answer is useful to me.It should be:$\delta (t)+\left(\frac{a}{2}-b\right) \exp (-b t)-\exp (-b t) \sum _{k=1}^{\infty } \frac{4^{-k} a^{2 k} (a-2 b)^{1-2 k} \left(\Gamma
   (-1+2 k)-\Gamma \left(-1+2 k,\frac{1}{2} (a-2 b) t\right)\right)}{k! \Gamma (k)}$
Comment: @MariuszIwaniuk Good catch of the error. Starting with an incorrect term in the convolution leads to an extension of said error.


HttpContext.Current.Request.ApplicationPath is empty on production

Question: On my development server HttpContext.Current.Request.ApplicationPath correctly returns the path, but on production it returns empty.
Why woudld this be?
I am using this to build URL's, and now in production a link doesn't work as it looks like:
http://section/page1.aspx

but it should be:
https://www.example.sub.com/section/page1.aspx

What could be causing this?
Comment: I don't think it should return the host name at all. [According to MSDN](http://msdn.microsoft.com/en-us/library/system.web.httprequest.applicationpath.aspx), ApplicationPath returns the virtual path of the application. Which doesn't include the host.
Comment: @Vlad you are right, strange how it works on my development server (it doesn't appear to be using a virtual path).
Answer: The ApplicationPath property returns the path to the folder where the application is, and it doesn't include the domain name.
I imagine that you have put the application in a folder with the same name as the domain name in your development server. The property then returns the name of the folder, not the actual domain.
Answer: pls try this
public static string RootURL {
get {
    var _with1 = System.Web.HttpContext.Current.Request;
    return _with1.Url.Scheme + "://" + _with1.Url.Host + _with1.ApplicationPath;
}

}
use this function when you need root url with application path
please try and let me know if you have problem.......


Post hoc test in a 2x3 mixed design ANOVA using SPSS?

Question: I have two groups of 10 participants who were assessed three times during an experiment. To test for differences between groups and across the three assessments, I ran a 2x3 mixed design ANOVA with group (control, experimental), time (first, second, three), and group x time.
Both time and group resulted significant, besides there was a significant interaction group x time.
I don't know very well how to proceed to further check for the differences between the three times of assessments, also respect to group membership. In fact, at the beginning I only specified in the options of the ANOVA to compare all the main effects, using the Bonferroni's correction. However, then I realized that this way they were compared the differences in time of the total sample, without group distinction, am I right?
Therefore, I searched a lot on the internet to find a possible solution, but with scarce results. I only found 2 cases similar to mine, but their solutions are opposite!

In an article, after the mixed design, the authors ran 2 repeated measures ANOVA as a post-hoc, one for each group of subjects. This way, the two groups are analysed separately without any correction, am I right?
In a guide on the internet, they say to add manually in the SPSS syntax COMPARE(time) ADJ(BONFERRONI), just after /EMMEANS=TABLES(newgroup*time), while running the mixed ANOVA. This way, the three times are compared separately for each group, with Bonferroni correction, am I right?

What do you think? Which would be the correct way to proceed?
Comment: http://stats.stackexchange.com/questions/575/post-hocs-for-within-subjects-tests
Comment: Winer (1962)'s master text on stats. provides formulae for the errors terms to be used in post hoc comparisons following many kinds of ANOVA, including this one.
Comment: Hi @StuartMcKelvie, could you give more details? As it stands, your answer is hardly usable by the OP *or* future visitors. (Plus, you don't provide a reference for Winer [1962], and since it's so old, it might not be easy to find.)
Comment: I found this free chapter from IBM SPSS Statistics (18&19): Workbook http://www.psychtestingonline.com/PDFDownloader.aspx?pdf=3 It's exactly about your case
Comment: I'm having exactly the same issue. Did you decide on a particular method in the end? Thank you.
Answer: Answer edited to implement encouraging and constructive comment by @Ferdi
I would like to:

provide an answer with a full contained script
mention one can also test more general custom contrasts using the /TEST command
argue this is necessary in some cases (ie the EMMEANS COMPARE combination is not enough)

I assume to have a database with columns: depV, Group, F1, F2. I implement a 2x2x2 mixed design ANOVA where depV is the dependent variable, F1 and F2 are within subject factors and Group is a between subject factor. I further  assume the F test has revealed that the interaction Group*F2 is significant. I therefore need to use post hoc t-tests to understand what drives the interaction.
MIXED depV BY Group F1 F2
  /FIXED=Group F1 F2 Group*F1 Group*F2 F1*F2 Group*F1*F2 |  SSTYPE(3)
  /METHOD=REML
  /RANDOM=INTERCEPT | SUBJECT(Subject) COVTYPE(VC)
  /EMMEANS=TABLES(Group*F2) COMPARE(Group) ADJ(Bonferroni)
  /TEST(0) = 'depV(F2=1)-depV(F2=0) differs between groups'
    Group*F2 1/4 -1/4 -1/4 1/4
    Group*F1*F2 1/8 -1/8 1/8 -1/8 -1/8 1/8 -1/8 1/8
  /TEST(0) = 'depV(Group1, F2=1)-depV(Group2, F2=1)' Group 1 -1
    Group*F1 1/2 1/2 -1/2 -1/2
    Group*F2 1 0 -1 0
    Group*F1*F2 1/2 0 1/2 0 -1/2 0 -1/2 0 .

In particular the second t-test corresponds to the one performed by the EMMEANS command. The EMMEANS comparison could reveal for example that depV was bigger in Group 1 on the condition F2=1.
However the interaction could also be driven by something else, which is  verified by the first test: the difference depV(F2=1)-depV(F2=0) differs between groups, and this is a contrast you cannot verify with the EMMEANS command (at least I did not find an easy way).
Now, in models with many factors it is a bit tricky to write down the /TEST line, the sequence of 1/2, 1/4 etc, called L matrix. Typically if you get the error message: "the L matrix is not estimable", you are forgetting some elements. One link that explains the receipt is this one: https://stats.idre.ucla.edu/spss/faq/how-can-i-test-contrasts-and-interaction-contrasts-in-a-mixed-model/
Comment: What a great answer. You can make it even better if you 1. summarise the content of your link and 2. explain what you are doing statistically
Answer: I don't know SPSS syntax particularly well, but, if I understand your situation correctly, the significant interaction means that, in order to adequately assess the significance of your main effects, you'll need to do separate analyses. I think the best way to proceed is to do separate repeated measure analyses for each level in your grouping factor. Perhaps someone else can speak better to the question of how to handle correcting for multiple comparisons during post-hoc analysis, but I'm pretty sure you still need to use a correction. You might try Tukey's, as a multiple comparison correction!
Comment: Thank you for your answer. If I understood correctly, you suggest the solution 1), to conduct two separate repeated measures ANOVAs, one for each group, with time as the within subjects indipendent variable (3 levels) and then, if significant, compare the main effects with Tukey's correction (or Bonferroni, I guess, isn't it ok?). Have I understood correctly?
Comment: In this case, using SPSS I selected "Data/Split file..." and entered the grouping variable. Is this correct? This way, I found a slightly significant ANOVA (p = 0.044) for the control group, but Bonferroni (it doensn't allow me to do Tukey) comparisons are all non significant... How should explain this? Is the ANOVA result a I type error?
Answer: In short.  There is no globally accepted convention for these situations.  Some will use Bonferroni corrections.  Some will force the Tukey HSD framework to dance for them (e.g. Maxwell & Delaney).  In contrast...
COMPARE(time) ADJ(BONFERRONI)", just after "/EMMEANS=TABLES(newgroup*time)

... does seem to use the Bonferroni correction.  However, this approach is likely conservative, especially in the face of Holm-Sidak style corrections.  (ESPECIALLY if you don't use the MSW as the error term for your post-hoc comparisons).


The famous counter module "counter" is marked unsupported

Question: The famous counter module "Counter" is marked unsupported.  Is there another good choice for counter?
Answer: The Visitors module is pretty good option for the counter module.
Reports provided by the module:

View pages that have recently been visited.
View pages that have been hit frequently.
View pages count per month.
View pages count per day of month.
View pages count per day of week.
View pages count per hour.
View pages count per host.
View access log.
View user activity report (hits, nodes, comments).
View referrer list.
Comment: Do you know how to reset the counter to zero?


A question of random points in a square and probability of intersection of their line segments

Question: The following is a problem from PUMaC 2007:

Take the square with vertices $(0,0)$, $(1,0)$, $(0,1)$, and $(1,1)$. Choose a random point in this square
and draw the line segment from it to $(0,0)$. Choose a second random point in this square and draw
the line segment from it to $(1,0)$. What is the probability that the two line segments intersect?

I tried to find the probability by taking the general point $(x,y)$ and finding the region in which the second point should lie so that the line segments intersect, however, I am stuck in this step. My idea was to find the area of the region, divide by area of the square to get probability and then double integrate wrt y and x to get probability.  I have failed at this after multiple attempts, If the region is a triangle (which is erroneous) I got the answer as $3/8$ , and if I try to do the general case, I find that the integral does not converge.
(Do note, over here vertices are adjacent, not opposite)
Comment: At first I misread the question; I thought it was asking for the probability that the extended line segments intersect inside the square. The answer to that question turns out to be $7/8$. (There is a nice intuitive explanation, like @Empy2's answer.)
Comment: Your integration method should work, but it's tedious. I think there's a "clever" way. Calling A and B the two square corners (0,0) and (1,0) and calling X and Y the two random points, there are three possible (disjoint) events: (E1) [AX] and [BY] intersect; (E2) [AX] and [BY] don't intersect, but [AY] and [BX] intersect; (E3) [AX] and [BY] don't intersect and [AY] and [BX] don't intersect either. I think we should have P(E1) = P(E2) = P(XY has slope < 1) / 2 = 1/4.
Comment: I have fleshed out my previous comment [here](https://math.stackexchange.com/q/4813364/398708).
Answer: Let the square be $ABCD$ and the points $P$ and $Q$.
Consider the bent lines $APC$ and $BQD$.  They intersect once, so by symmetry the chance that $AP$ and $BQ$ cut is $1/4$.
Comment: Upvoted for the extreme simplicity
Answer: This is basically the same solution the Stef presented in the comments, but completing the final step.
Let $A=(0,0)$ and $B=(1,0)$. Pick random points $P$ and $Q$ and draw the line $l$ through $P$ and $Q$.
There is a probability $1/2$ that $l$ intersects the line segment $AB$. One way to see this is that it intersects two of the sides of the square (ignoring the probability zero case of it passing through one of the corners), and by symmetry (the four rotations of the square), all sides are equally likely.
If $l$ intersects the line segment $AB$, the line segments $AP$ and $BQ$ will be on separate sides of the line $l$ and therefore not intersect.
If $l$ does not intersect the line segment $AB$, then the points $A$, $B$, $P$, $Q$ are the corners of a convex quadrilateral. The quadrilateral with points in order will be either $ABQP$ or $ABPQ$ depending on which of the points $P$ and $Q$ share a side of the quadrilateral with $A$ and $B$. If the quadrilateral is $ABQP$, then $AP$ and $BQ$ do not intersect; if the quadrilateral is $ABPQ$, then $AP$ and $BQ$ intersect. Since $P$ and $Q$ are picked independently, these two cases are equally likely.
So, the likelihood that $AP$ and $BQ$ intersect is $1/2\times1/2=1/4$: first that $l$ does not intersect $AB$, and then the order of $P$ and $Q$ on the convex quadrilateral.
Answer: Your integration method should work, but it's tedious.
I think there's a "clever" way.
Call A (0,0) and B (1,0) the two square corners. Call X and Y the two random points.
There are three possible (disjoint) events:

(E1) := [AX] and [BY] intersect;
(E2) := [AX] and [BY] don't intersect, but [AY] and [BX] intersect;
(E3) := [AX] and [BY] don't intersect and [AY] and [BX] don't intersect either.

By symmetry we have $P(E1) = P(E2)$. Geometrically we can also see: $E_1 \cup E_2$ if and only if XY has slope < 1.
By symmetry P(XY has slope < 1) = P(XY has slope > 1) = 1/2.
Hence P(E_1) = P(XY has slope < 1) / 2 = 1/4.
Comment: What if we take X (0.5, 0.1) and Y (0.9, 0.3)? Then XY has slope 1/2, but it's E3.
Answer: This answer extends what the OP has tried.
Let $O=(0,0)$ and $P=(1,0)$, $U = (U_1,U_2)$, $V = (V_1,V_2)$ with $U_1,U_2,V_1,V_2$ iid $\mathcal U([0,1])$.
We look for $P(OU\cap PV\neq \emptyset) = E[E[1_{OU\cap PV\neq \emptyset}|U]]$. We fix a point $A=(a_1,a_2)$ in the square and we compute the conditional expectation $E[1_{OU\cap PV\neq \emptyset}|U = A]$.
Since $U$ and $V$ are independent, this is the same as $P(OA\cap PV\neq \emptyset)$.
Let $I$ denote the point where the line $PA$ intersects the square. Let $\mathcal R$ denote the region of the square located "behind" the points $O,I,A$.  Your mistake is in thinking that $\mathcal R$ is always a triangle. When $a_2>1-a_1$, this region has $4$ sides.
Note that the line $PA$ has equation $y= \frac{a_2}{1-a_1}(1-x)$.
Case 1:  $a_2\leq 1-a_1$. The region $\mathcal R$ is a triangle with base $OI$, hence with length $\frac{a_2}{1-a_1}$, and height $a_1$, thus with area $\frac{a_1a_2}{2(1-a_1)}$.
Case 2: $a_2> 1-a_1$. The region $\mathcal R$ has 4 sides and it is more convenient to compute the area of the complement, which is the disjoint union of two triangles. One has area $\frac{1-a_1}{2a_2}$ and the other $\frac{a_2}2$.
Thus $P(OA\cap PV\neq \emptyset) = P(V\in R) = 1_{a_2\leq 1-a_1}\frac{a_1a_2}{2(1-a_1)} + 1_{a_2> 1-a_1}[1-\frac 12(\frac{1-a_1}{a_2} + a_2)]$.
Finally, the probability $P(OU\cap PV\neq \emptyset)$ is
$$E\Big[1_{U_2\leq 1-U_1}\frac{U_1U_2}{2(1-U_1)} + 1_{U_2> 1-U_1}[1-\frac 12(\frac{1-U_1}{U_2} + U_2)] \Big].$$
The Mathematica command
<code>Integrate[
 1/2*(x*y)/(1 - x), {x, y} \[Element]
  ImplicitRegion[y <= 1 - x && 0 < x < 1 && 0 < y < 1, {x, y}]]
+
 Integrate[(1 - 1/2*((1 - x)/y + y)), {x, y} \[Element]
   ImplicitRegion[y > 1 - x && 0 < x < 1 && 0 < y < 1, {x, y}]]
</code>
yields an answer of $\frac 14$.


A good method of mapping our AWS server infrastructure

Question: Small company. We have an fairly robust application we built that runs on AWS that serves many clients. Our Sys Admin / Lead Developer has left the company and took with him knowledge we didn't all share.
Our other developers easily picked up the coding.
As the project manager I have picked up on how to generally manage the server deployments using both Laravel Forge and AWS as needed. Having worked at a general level in AWS for a number of years, I know the basics.
I have a high level understanding of the architecture but I do not fully understand all of the relationships between the elements.
I want to document the instances, IP'S, volumes, security groups, KEYS, etc, used and how the are related. Visually if possible, or at least in table form.
I'm slowly figuring out how to find everything.
Does anyone have any suggestions on a good way to create easy to understand documentation for a system?
I'm flogging this in Excel and Powerpoint, Gliphy etc. and I find myself starting over and reworking the layouts as I see there is a new relationship that I had not previously understood.
Any tips would be appreciated.
Comment: https://cloudcraft.co/ is great for AWS diagrams.
Comment: Thanks! Checking it now!
Answer: I haven't found a tool that does good, useful AWS diagrams automatically yet. I have a few tools I use if I want a list of resources:

AWS Tag Editor : built into AWS, just provides a list that you can export
Cloudockit : haven't used it but looks like it could be useful
CloudCraft.co : useful for lists and diagrams, but not as good at diagrams as I'd hoped
AWS Retriever : provides a list of AWS resources, but seems like beta software

I find draw.io or their offline client very effective for creating AWS diagrams.
Comment: Thanks Tim. Cloudockit is like what I was thinking too. I'm checking these out. Thanks both of you. This is good info.


Install and use independent node.js environments in different project directories

Question: I really like virtual environments in Python, where you can put a whole Python environment including the interpreter into a project directory. If you dig out an old project after years you can just activate the environment and you are ready to go - this is awesome.
What is the node.js way of doing this?
Comment: Possible duplicate of [is there an virtual environment for node.js?](http://stackoverflow.com/questions/3653495/is-there-an-virtual-environment-for-node-js)
Answer: Usually you mark down the package versions and Node.js version that your code supports in the appropriate package.json directive. This means that distributed versions of your projects import the same modules. Locally, this doesn't matter as npm installs your packages in the project directory by default.
However, for managing your local Node versions more efficiently, a tool such as Node Version Manager will do the trick. NVM specifically supports a <code>.nvmrc</code> file in the project directory to mark down the Node version.


SMS Reminders for Course Signup module

Question: I am using Drupal 7 version of Signup module. It send email reminders before the course starts X number of days. Is it possible to send SMS reminders using another module. If not then where i should be looking in the code ?
thanks
Answer: You can use any sms integration api. I personally like Twilio.
There is a module for twilio integration as well: link
You will need to find a place from where the email has been sent, it would be in the code or possibly through Rule module, in either case you need to add a line of code which should utilize twilio api and send sms to the destined users.

SMS Reminders for Course Signup module


await for indexdb event in async function

Question: I'm trying to return a custom object from a async function that works as wrapper for a put using indexdb.
Using Promises this is easy.
However, using async/await became more challenging...
const set = async (storeName, key, value) => {

    if (!db)
        throw new Error("no db!");

    try {

        const result = {};

        let tx = db.transaction(storeName, "readwrite");
        let store = tx.objectStore(storeName);
        let r = store.put({ data: key, value: value });

        console.log(r);

        r.onsuccess = async () => {
            console.log('onsuccess');
            result.something = true;
        }
        r.onerror = async () => {
            console.log('onerror');
            result.something = false;
        }

        await r.transaction.complete;  // ok... this don't work

        // how can I await until onsuccess or onerror runs?

        return result;

    } catch (error) {
        console.log(error);
    }
}

The ideia is to return a composed object... however all my attemps fails as onsuccess runs after returning the result.
I googled a lot and could't find a way to proper await for onsuccess/onerror events.
I know that returning a Promise is more easy as resolve(result) would end returning what I want... but i'm trying to learn to make same code using async/await.
Thank you so much,
Answer: Try this:
function set(db, storeName, key, value) {
  return new Promise((resolve, reject) => {
    let result;
    const tx = db.transaction(storeName, 'readwrite');
    tx.oncomplete = _ => resolve(result);
    tx.onerror = event => reject(event.target.error);
    const store = tx.objectStore(storeName);
    const request = store.put({data: key, value: value});
    request.onsuccess = _ => result = request.result;
  });
}

async function callIt() {
  const db = ...;

  const result = await set(db, storeName, key, value);
  console.log(result);
}

Edit, since you insist on using the async qualifier for the set function, you can do this instead. Please note I find this pretty silly:
async function set(db, storeName, key, value) {
  // Wrap the code that uses indexedDB in a promise because that is
  // the only way to use indexedDB together with promises and
  // async/await syntax. Note this syntax is much less preferred than
  // using the promise-returning function pattern I used in the previous
  // section of this answer.
  const promise = new Promise((resolve, reject) => {
    let result;
    const tx = db.transaction(storeName, 'readwrite');
    tx.oncomplete = _ => resolve(result);
    tx.onerror = event => reject(event.target.error);
    const store = tx.objectStore(storeName);
    const request = store.put({data: key, value: value});
    request.onsuccess = _ => result = request.result;
  });

  // We have executed the promise, but have not awaited it yet. So now we
  // await it. We can use try/catch here too, if we want, because the
  // await will translate the promise rejection into an exception. Of course,
  // this is also rather silly because we are doing the same thing as just
  // allowing an uncaught exception to exit the function early.
  let result;
  try {
    result = await promise;
  } catch(error) {
    console.log(error);
    return;
  }

  // Now do something with the result
  console.debug('The result is', result);
}

Comment: Thank you Josh. Lots of documentation refer to async/await as a new es6 way to implement promise based solutions.
I agree that using async qualifier to wrap a promise looks a little silly. However, the goal was not returning the indexedDB result as is, but a new object based on the result and adding some extra logic triggered by oncomplete and onerror events.
Comment: @dfelix async and await are how you *use* promises, but not how you create them. An async function return value is a promise. Even when you return a primitive number, it is wrapped in a promise. This is is why all async functions must be awaited if you want the settled value of the promise. You are making a distinction where one does not exist.
Answer: Ultimately you'll end up wrapping IDB in a promise-friend library, but for your specific need, you could use something like this:
function promiseForTransaction(tx) {
  return new Promise((resolve, reject) => {
    tx.oncomplete = e => resolve();
    tx.onabort = e => reject(tx.error);
  });
}

And then in your code you can write things such as:
await promiseForTransaction(r.tx);

... which will wait until the transaction completes, and throw an exception if it aborts. (Note that this requires calling the helper
before the transaction could possibly have completed/aborted, since
it won't ever resolve if the events have already fired)
Answer: I can't confirm it right now but I think it should be await tx.complete instead of await r.transaction.complete;.
But a general solution that would work even if the API would not support Promises directly would be to wrap a new Promise around the onsuccess and onerror and use await to wait for that Promise to resolve, and in your onsuccess and onerror you then call the resolve function:
const set = async (storeName, key, value) => {

  if (!db)
    throw new Error("no db!");

  try {

    const result = {};

    let tx = db.transaction(storeName, "readwrite");
    let store = tx.objectStore(storeName);
    let r = store.put({
      data: key,
      value: value
    });

    console.log(r);

    await new Promise((resolve, reject) => {
      r.onsuccess = () => {
        console.log('onsuccess');
        result.something = true;
        resolve()
      }

      r.onerror = () => {
        console.log('onerror');
        result.something = false;
        // I assume you want to resolve the promise even if you get an error
        resolve()
      }
    })

    return result;
  } catch (error) {
    console.log(error);
  }
}

I would furhter change it to:
try {
  await new Promise((resolve, reject) => {
    r.onsuccess = resolve
    r.onerror = reject
  })

  console.log('success');
  result.something = true;
} catch(err) {
  console.log('error');
  result.something = false;
}

Comment: Resolving the promise on request success is premature. In the case of a write transaction, the promise should settle only when the transaction completes.


Using mongoclient I am unable to add a key of type BinData in mongo collection from python

Question: When I run this query in console it works fine:
db.testColl.updateMany({},{ "$set": {"__class" : BinData(128, "QXRzXFF1b3RlXE1vZGVsXFF1b3Rl")} })

But when I try to do the same from a python program it says 'BinData is not defined'
python code:
import pymongo
from pymongo import MongoClient
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["test"]
mycol = mydb["testColl"]

mycol.update_many({},{ "$set": {"__bclass" : BinData(128, "QXRzXFF1b3RlXE1vZGVsXFF1b3Rl")} })

Error I get is:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'BinData' is not defined

Answer:
python program it says 'BinData is not defined'

You're seeing this error message because BinData is a mongo shell utility to represent BSON Type Binary Data.
In Python this is represented differently using PyMongo. If you're using Python3 then you can just use the Python bytes type. For example:
data = b"Ats\\Quote\\Model\\Quote"
collection.update_many({}, {"$set":{"__class": data }})

This will result in value BinData(0, "QXRzXFF1b3RlXE1vZGVsXFF1b3Rl") in the MongoDB collection.
If you're using Python2, the data must be wrapped as an instance of bson.binary.Binary from the bson module.

BinData(128, "QXRzXFF1b3RlXE1vZGVsXFF1b3Rl")

Also, worth mentioning that the way you construct BinData is not common BSON (although you may have a special reason).
BinData takes parameters in the form of BinData(subtype, base64str). The subtype is utilised to indicate what kind of data is in the byte array. According to the BSON specifications generic binary subtype is 0. This is the most commonly used binary subtype and should be the 'default' for MongoDB drivers (i.e. PyMongo) and tools.
While subtypes from zero to 127 are predefined or reserved, subtypes from 128-255 are user-defined. Unless you're purposely specifying 128 to define your own type, I would suggest to use 0.


Postgresql: create index issue"Index row requires 23653 maximum size 8191" error 54000

Question: I am trying to create an index with include columns.
One of the include column "memo" is type byteA and has huge amount of data.
<code>CREATE INDEX IDX_memo ON dbo.tbl_memo
(crtdate ASC,Inov ASC)
INCLUDE(memo,type)
</code>
This is not working with error max size 8191.
I tried to create extension btree_gist and postgis based on docs.
Still I am getting same error
Any help is appreciated
Answer: The answer is simple: you cannot do that. I guess you are trying to get an index-only scan that way. Try to avoid fetching these big attributes all the time.
Comment: Thanks. The column which I am trying to include  is of byteA type. So how do I create index on that column.
Comment: You cannot do that.


Probability of drawing three cards, with the third being a King

Question: CONTEXT: First year university statistics course exercise
If $C$ is the number of cards drawn from a deck of 52 cards until a King
is drawn, find $\mathbb P(C = 3)$. I'm not 100% sure how to do this question.
This would mean the first and second cards are not Kings but the third is.
Let $A$ be the event that you draw two non-Kings and then a King.
$|A| = {48 \choose 1}{47 \choose 1}{4 \choose 1}$.
The sample space $\Omega$ would be any three card selections. $|\Omega|={52 \choose 1}{51 \choose 1}{50 \choose 1}$
By the equilikely principle, this means $\mathbb P(C = 3)=\frac{{48 \choose 1}{47 \choose 1}{4 \choose 1}}{{52 \choose 1}{51 \choose 1}{50 \choose 1}}$?
Any help would be greatly appreciated (I'm finding it difficult to check my counting answers!)
Answer: $\color{olive}\checkmark$ Yes, that is okay.
You want the probability for obtaining two from forty-eight non-kings and then one from four kings, when selecting two from fifty-two cards and then one from fifty remaining cards.
$$\dfrac{\dbinom{48}2\dbinom 41}{\dbinom{52}2\dbinom {50}1} =\dfrac{48\cdot 47\cdot 4~~}{52\cdot 51\cdot 50}$$
Answer: I think your answer and reasoning is correct, but sometimes it's easier to think about the events separately; you have three independent events, P(not King 1st draw), P(not King 2nd draw | no King on 1st) and then P(King | no King on 1st or 2nd draws) and the final probability is just these multiplied together.
$$\frac{48\choose{1}}{52\choose{1}}\times\frac{47\choose{1}}{51\choose{1}}\times\frac{4\choose{1}}{50\choose{1}}$$
I know it's equivalent but I find it helps even just thinking about it in a slightly different way.


A good source to learn the theory of chords in an accordion

Question: I have been learning to play accordion for a few months and I can play 15-20 songs with their chords now. I know the physics behind the musical notes (such as I can understand what one implies by saying A has 55, 110, 220 Hz., etc.) since I know signal processing but I don't know how the chords are created: major, minor, 7, and dim. That is, I know the physics part, but I lack musical background. I suppose that I have the fundamentals to learn them by reading but I don't know where to look since I've no experience with musical terms. Would you recommend me a good tutorial or a book on harmony (especially using accordion)?
In addition, I would be appreciated if there is any source discussing on how to create chords for a song? I bring a song to my teacher, he checks the notes and writes down the accompanying chords. There should be a reasonable way to do this myself I guess.
Answer: Most teachers regardless of whether they teach piano, guitar, voice, or tuba, should be teaching you the basics of music theory. This should include key signatures, time signatures, note durations, and how chords are made, inverted and arpeggiated. Since you mention major, minor, diminished I assume you are learning western music vs other world music. Because by in large many accordions have buttons that play chords perhaps your teacher is not so concerned about chord construction?
Traditionally in western music chords are built on scales. There are many types of chords but the most basic chord is the diad, or double stop, two notes that are sounded together.
Typically, diads are major or minor 3rds or 6ths, or 10ths, and often compliment each other.
However diads can be ambiguous as far as defining tonality. Since they are composed of only two notes it can be difficult at times to determine the exact scale one is playing unless there are enough of these to define a scale.
On the other hand, triads are three note chords that generally leave no doubt about their tonality and scale being performed. A major triad is played with the root, maj. 3rd, and perfect 5th.
In a major scale you will have the following chords from tonic to tonic: major chord (tonic), minor chord (supertonic), minor chord (mediant), major chord (subdominant), major chord (dominant), minor chord (submediant) and diminished (leading tone). All of these chords have a scale degree as the root note, then a 3rd and then a 5th (not always perfect).
More here but referenced to guitar:
http://www.zentao.com/guitar/theory/chord-scale.html
Chords can have more than 3 notes, there are dominant 7ths and 9th chords and even 11ths thrown in as you build your repertoire to include music from the classics to jazz. Also chords do not have to have all the members played, you can easily have a root, a 5th, a 9th in one chord.
Chords can be implied by arpeggios so the notes do not all have to sound together, but can imply the same by being played as a string of notes.
Also you will learn that in the 20th century many western music composers abandon tonality for atonality.
In these works you will find no sense of a key center, and you may find the use of tone clusters which are chords made of several notes in an unusual order. Or mega chords that might expand the entire range of the piano.
Things you can do without buying another text book. Google and search Youtube to hear and see how the following key words will help you learn about music theory:
Chord construction
Scales
Modes
Arpeggios
...and get specific with adding 'accordion' to your search as well.
Answer: Stradella chord diagrams are a dime a dozen, and if your teacher can write down chords for you, you presumably know (or can look up) the relation between a chord name and the button.
So I'll focus on the specific relation of chord buttons to individual notes on an accordion, in order to answer the accordion-specific part of the question not easily found elsewhere.
Accordion bass/chord buttons have a lackadaisical relation with octaves and chord voicings: essentially they are being ignored.
The accordion mechanics map the Stradella chord buttons to 24 separate "notes", 12 bass notes and 12 chord notes.  Almost all accordions automatically play the corresponding "chord note" along with whatever "bass note" is being played in order to have more full-bodied bass notes.
Almost all accordions play exactly 3 chord notes on each chord button.  With 4 chord rows, the 4 chords in the C row are then spelled c=, cm=<c e♭ g>, c7=<c e b♭>, cdim=<c e♭ a>.  If there are only 3 chord rows (because there are only 5 button rows all-in-all or because 3 rows are bass rows), they are spelled c=, cm=<c e♭ g>, c7=<e g b♭>.  This means that with only 3 chord rows, the chord that is labelled c7 actually plays the notes that the system with 4 chord rows labels gdim.
Note that all this reckoning of notes completely ignores the octave relation of the notes in the chords and rely on equal-tempered tuning.  So what octave do they actually come from?  The answer is "it depends on the registration".  An accordion has "reed banks" that have a range of 1 octave in the bass, and there are usually several reed banks.  Common large accordions have 5 reed banks on the bass side, 2 for the chord notes, and 3 for the chord notes.  Which of them are active, depends on the registration.  Large Hohner instruments (though not their "Gola" top model line) tend to have bass octaves start from E1, E2, and chord octaves start from E3, E4, E5.  Italian instruments are much more diverse, I have one with octaves starting at A1, A2, F♯3, C4, C5.  When fully registering an instrument with such staggered reed banks, its bass notes utilising all 5 reed banks "wrap octaves" in different reed banks on different notes, giving the bass notes a comparatively "unordered" character where declaring one to be of higher pitch than another makes little sense and only the "functional" character of a particular note remains.
Typically, this "functional" treatment of chords and bass notes works best with full registrations that, for reasons of tonal balance with the treble side of the accordion, require playing bass and chord notes in a semi-staccato manner.  When using registers with fewer reedbanks, the octave breaks become more obtrusive in bass runs and in the chord's voice leading.  For example, the sequence b7-e on an instrument using only one reed bank starting at E3 may end up using notes A3-B3-D♯4 and E3-G3-B3 which has awful voice leading.
With regard to the actual chord buttons to be played, all those are "implementation details": that the chords have no dependable inversion tends to be comparatively unimportant musically when an accompaniment pattern of alternating bass and chord notes is chosen where the bass notes are of unspecific but lower octave than the corresponding chords: that tends to "ground" the chords properly.
Pressing chord buttons not matching the preceding bass button or pressing multiple chord buttons (possibly along with bass buttons) can produce more complex chords: those are quite useful for chords typically used in Jazz.  However, that's a more advanced topic.
Answer: Almost all accordions (button or piano) have a Stradella Bass arrangement. Chords are layed out in a 6x20 or similar pattern. The "short" direction has several chords with the same root and the roots are traversed in the "long" direction. One direction (top of the accordion, closest to your face when playing) is row 6 and the bottom (near your feet) is row 1 (there may be extra rows or fewer but these are the main ones. (Or the other way around if I remember badly.)
Row 2 is the "root" row. Each button plays a single note (perhaps doubled at the octave depending on how many reeds the accordion has.) There is usually an indentation in the C button (to make it easy to find by feel.)
Just above row 2 is row 1 called the counter-bass row. It plays single notes a major third above row 2. Thus one can play walking or boom-chick bass lines or even a counter-melody on the first two rows. (A few accordions have an extra row (row 0, I guess) above this but I don't know what notes are used.)
Row 3, below row 2, plays the major triad with the row 2 note as the root. Its a three-note chord (perhaps doubled) using scale steps 1, 3, and 5. (C-E-G for a C bass.)
Row 4, plays the minor triad for the same root, steps 1, b3, and 5.(C-Eb-G)
Row 5, plays the "dominant seventh" chord with the fifth omitted. This is notes 1, 3, b7. The fifth is omitted to keep the chord density the same across types. Some accordion makers do just use different densities by keeping scale step 5. (C-E-Bb)
Row 6, plays the "diminished seventh" with the fifth omitted. The notes are scale steps 1, b3, and b6. (C-Eb-Ab) This also the Italian Sixth on C (used mostly in the key of E); adding (right hand, which I do, or counter-bass line on row 1) F# or F gives either the German or French Sixth which can be useful.
I have usually played the bass row with my 3rd (ring) finger and chords with the second (pointer) finger. Newer texts recommend using the 4th and 3rd fingers instead. There should be tutorials on the internet.


How to create mysql triggers using migrations in Rails?

Question: Is there a way to create mysql triggers using Activerecord migrations  ?  Has anybody worked on it share your experience . Thanks
Answer: There's no magic method allowing you to create a trigger without writing any SQL.
But you can execute raw sql inside any migration.
def self.up
    execute <<-SQL
        CREATE TRIGGER my_trigger ...
    SQL
end

Then you just need to appropriately write your trigger or update it depending of the migration.
Edit : I've just found rails_on_pg, which provides some helpers to migrations.
It doesn't work with any other database server than PgSQL. But it can be a good lead if you're up to writing some MySQL triggering helper.
Comment: Thanks , for your resource , i wasn't knowing that it did exists :)
Comment: Best remove the reference to `rails_on_pg` now :) it was last updates 6 years ago :)
Comment: The advantage a gem like `hairtrigger` is that it will write your triggers to shcema.rb ensuring your database has them on recreation or in testing.
Answer: there's a gem called hairtrigger that makes this a little easier and more portable (mysql/sqlite/postgres). it lets you create triggers in your migrations in a db-agnostic way, or even better you can declare them in your models and then run rake db:generate_trigger_migration to do it for you.
Comment: the gem has been updated to support the latest versions of rails
Comment: This gem is outdated - supports Rails 2.3 - Rails 3.0.x. But idea is great.
Comment: Jon your gem is fantastic. Do you know any to generate pg indexes?
Answer: Thought it might help someone...
If we put custom SQL it may not work on development environment, if we are using SQLite3 and our migrate command would fail on sqlite:
rake db:migrate

I found it more useful to create trigger sql in a separate file under db/scripts and execute them in mysql cli. That way I could re-run them as per the need when the trigger changes.


What controls the placement of links relative to the body?

Question: I am struggling with getting the "Read more" and "Add new comment" links placed below the body on a custom node content type called "Wikitext" that has been created using the GUI on a Drupal 8.9.17 website.
The site is running the default theme (Bartik) and I have not edited any templates. The built-in content type "Article" shows these links below the body.  "Wikitext" is supposed to be identical to "Article", but displays them above the body.
I've unticked "Show reply form on the same page as comments" on the comment settings form for both content types.
Below the acreenshot is a copy of the "Manage display" form. It is identical for both content types, and has "Links" and "Comments" as the last two fields to display.
I have looked very carefully, but cannot locate anywhere in the GUI where I can control the placements of these links.  Does anybody know where to look?
Answer: It's the Links field that appears also the question's screenshot, but for the Teaser view mode, whose settings are on /admin/structure/types/manage/wikitext/display/teaser, for the Wikitext content type. (I assume wikitext is the machine name for that content type.)
I changed the Teaser view mode for the Article content type and re-ordered the fields as follows.

This is how an article appears now in the front page, once it's promoted on front page.


Stream Position in flutter with Geolocator

Question: I have a HERE map with various functionality that is operating fine
I have a location indicator that currently operates Geolocator.getCurrentPosition(); which works fine, taking the current lat,long and heading to place indicator.
I want it to update regularly with users location from device as a stream.
I need to use Geolocator.getPositionStream to achieve this but after trying the implementation example online I'm stuck as it has different requirements to Current Position and the code won't work
Here is the LocationIndicator method, set to getRandom
void _addLocationIndicator(GeoCoordinates geoCoordinates, LocationIndicatorIndicatorStyle indicatorStyle) {
  LocationIndicator locationIndicator = LocationIndicator();
  locationIndicator.locationIndicatorStyle = indicatorStyle;

  Location location = Location.withCoordinates(geoCoordinates);
  location.time = DateTime.now();
  location.bearingInDegrees = _getRandom(0, 360);

  locationIndicator.updateLocation(location);

  _hereMapController.addLifecycleListener(locationIndicator);
}

This is the given code for Stream
final LocationSettings locationSettings = LocationSettings(
  accuracy: LocationAccuracy.high,
  distanceFilter: 100,
);
StreamSubscription<Position> positionStream = Geolocator.getPositionStream(locationSettings: locationSettings).listen(
    (Position position) {
        print(position == null ? 'Unknown' : position.latitude.toString() + ', ' + position.longitude.toString());
    });

This is the Current Location example which I have used and it works fine for current location
import 'package:geolocator/geolocator.dart';

/// Determine the current position of the device.
///
/// When the location services are not enabled or permissions
/// are denied the `Future` will return an error.
Future<Position> _determinePosition() async {
  bool serviceEnabled;
  LocationPermission permission;

  // Test if location services are enabled.
  serviceEnabled = await Geolocator.isLocationServiceEnabled();
  if (!serviceEnabled) {
    // Location services are not enabled don't continue
    // accessing the position and request users of the
    // App to enable the location services.
    return Future.error('Location services are disabled.');
  }

  permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.denied) {
      // Permissions are denied, next time you could try
      // requesting permissions again (this is also where
      // Android's shouldShowRequestPermissionRationale
      // returned true. According to Android guidelines
      // your App should show an explanatory UI now.
      return Future.error('Location permissions are denied');
    }
  }

  if (permission == LocationPermission.deniedForever) {
    // Permissions are denied forever, handle appropriately.
    return Future.error(
      'Location permissions are permanently denied, we cannot request permissions.');
  }

  // When we reach here, permissions are granted and we can
  // continue accessing the position of the device.
  return await Geolocator.getCurrentPosition();
}

Thanks
Comment: could you tell us what's the specific issue?
Answer:  final LocationSettings locationSettings = LocationSettings(
    accuracy: LocationAccuracy.high,
    distanceFilter: 100,
  );
  @override
  void initState() {
    super.initState();
    StreamSubscription<Position> positionStream =
        Geolocator.getPositionStream(locationSettings: locationSettings)
            .listen((Position? position) {
            // do what you want to do with the position here
    });
  }

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Negative binomial distribution interpreted as a waiting time

Question: I'm reading Achim Klenke's text on probability theory, and a few different distributions (with applications) have been introduced. I'm confused by the explanation given of the negative binomial distribution:
$$
b_{r,p}^- := \sum_{k=0}^\infty \binom{-r}{k}(-1)^k p^r(1-p)^k \delta_k
$$
where $\delta_k : 2^\mathbb R \to \{0,1\}$ is the point measure. Klenke says that "If $r \in \mathbb N$, then one can show ... that $b_{r,p}^-$ is the distribution of the waiting time for the $r$th success in a series of random experiments". I think I'm interpreting this explanation incorrectly, because as I understand it, something doesn't make sense.
Suppose that $X_r : \Omega \to \mathbb R$ is this random variable, and $(\Omega, \mathcal A, \mathbb P)$ is our probability space. In particular, $\mathbb P_{X_r} = \mathbb P \circ X_r^{-1} = b_{r,p}^-$. In this setting, $\mathbb P(X_r=k) = b_{r,p}^-(\{k\}) = \binom{-r}k (-1)^k p^r(1-p)^k$ is the probability that the $r$th success will come at time $k$. The reason I'm confused is, practically speaking, if $r > k$, shouldn't this probability be $0$? For example, if our experiments are coin tosses with $p=1/2$, and we consider "heads" to be success, if $r=3$, the probability of getting $3$ heads on the $2$nd experiment ($k=2$) is obviously $0$, but according to this formula, the probability is $$\mathbb P(X_3 = 2) = \binom{-3}{2}(-1)^2\left(\frac 1 2 \right)^3 \left(\frac 1 2 \right)^2 = \frac 1{32} \times \frac{(-3)(-4)}{2} = \frac 3{16}$$ which seems absurd to me. Can anyone shed some light on this interpretation?
Answer: For the negative binomial defined by $$\Pr[\mathbf X = k] = (-1)^k\binom{-r}{k} p^r (1-p)^k$$ the precise "waiting time" characterization is that $\mathbf X$ counts the number of failures seen before the $r^{\text{th}}$ success. Thus, $\mathbf X=0$ corresponds to the outcome in which there are no failures at all: the first $r$ outcomes are successes. The formula above correctly says that this has probability $p^r$.
That being said, some people do define the negative binomial to be the total number of trials before the $r^{\text{th}}$ success. Since the total number of trials is just $r$ more than the number of failures, this shifts everything over by $r$ and then the $\Pr[\mathbf X = k] $ is indeed equal to $0$ for $k < r$. In this version, the formula is $$\Pr[\mathbf X = k] = \binom{k-1}{r-1} p^r (1-p)^{k-r}.$$
Comment: I see, so whereas I was interpreting $k$ as the number of *experiments*, I should have been interpreting it as the number of *failures*. Thank you for the clarification!