Como fazer relacionamento entre 5 tabelas?

Question: Tenho as seguintes tabelas: conteúdo, aulas, curso, turma, grupo_User aonde a lógica será a seguinte:

Um conteúdo pode pertencer a diversas aulas, como uma aula pode ter  diversos conteúdos
Uma aula pode pertencer a diversos cursos, assim como um curso pode ter diversas aulas.
Um curso pode pertencer a várias turmas, assim como uma turma pode ter diversos cursos para se matricular.
Um grupo de usuários pode estar vinculado a diversas turmas, assim como uma turma pode receber diversos grupos de usuários diferente.

Se eu estiver certo, esses relacionamentos são todos N:N, sei também que é necessário uma tabela a mais para realizar a ligação entre as tabelas.
Abaixo deixarei a estrutura das tabelas:
Conteudo:
CREATE TABLE conteudo (
    id INT(12) PRIMARY KEY,
    autor VARCHAR(50),
    conteudo MEDIUMTEXT,
    data_criacao DATETIME,
    ultima_edicao VARCHAR(50),
    data_edicao DATETIME
);

Aulas:
CREATE TABLE aulas (
    id INT(12) PRIMARY KEY,
    autor VARCHAR(50),
    nome VARCHAR(50),
    data_criacao DATETIME,
    ultima_edicao VARCHAR(50),
    data_edicao DATETIME
);

Curso:
CREATE TABLE curso (
    id INT(12) PRIMARY KEY,
    autor VARCHAR(50),
    nome VARCHAR(50),
    data_criacao DATETIME,
    ultima_edicao VARCHAR(50),
    data_edicao DATETIME
)

Turmas:
CREATE TABLE turmas(
    id INT(12) PRIMARY KEY,
    autor VARCHAR(50),
    nome VARCHAR(50),
    data_criacao DATETIME,
    ultima_edicao VARCHAR(50),
    data_edicao DATETIME
)

Grupo_User:
CREATE TABLE grupo_User(
    id INT(12) PRIMARY KEY,
    nome_Grupo VARCHAR(50),
    id_Users INT(20)
)

Até consegui ligar o conteúdo às aulas usando a seguinte tabela:
CREATE TABLE aula_has_conteudo (
    idAula INT(12),
    idConteudo INT(12),
    CONSTRAINT PK_aulas_has_conteudo PRIMARY KEY (idAula, idConteudo),
    CONSTRAINT FK_aulas_has_conteudo_aula FOREIGN KEY (idAula) REFERENCES aulas (id),
    CONSTRAINT FK_aulas_has_conteudo_conteudo FOREIGN KEY (idConteudo) REFERENCES conteudo (id)
);

Usando o seguinte SELECT consigo trazer os dados pretendidos:
SELECT  a.autor as autorAula, c.conteudo as conteudo FROM aulas a INNER JOIN aula_has_conteudo h ON a.id = h.idAula
INNER JOIN conteudo c ON c.id = h.idConteudo

E consegui ligar as aulas com os cursos usando a seguinte tabela:
CREATE TABLE curso_has_aula (
    idCurso INT(12),
    idAula INT(12),
    CONSTRAINT PK_curso_has_aula PRIMARY KEY (idCurso, idAula),
    CONSTRAINT FK_curso_has_aula_Curso FOREIGN KEY (idCurso) REFERENCES curso (id),
    CONSTRAINT FK_curso_has_aula_Aula FOREIGN KEY (idAula) REFERENCES aulas (id)
)

Mas não consigo realizar a ligação entre as outras tabelas.
Como posso relacionar todas essas tabelas sabendo os requisitos citados acima?
Após relacionadas, como posso fazer um select para obter dados das cinco tabelas?
Comment: quais as outras tabelas de ligação? do tipo "aula_has_curso" por exemplo?
Comment: editei a pergunta @RicardoPontual
Answer: Basta você seguir fazendo os joins com as demais tabelas, vai ficar grande mas é só ir adicionando as demais tabelas:
SELECT a.autor as autorAula, c.conteudo as conteudo
  FROM aulas a
 INNER JOIN aula_has_conteudo h ON a.id = h.idAula
 INNER JOIN conteudo c ON c.id = h.idConteudo
 INNER JOIN curso_has_aula cha on a.id = cha.idAula
 INNER JOIN curso cr on cr.id = cha.idCurso
 -- e assim por diante

Comment: Ricardo, então está certo eu ir realizando os relacionamentos com uma tabela a mais? Por exemplo, relacionar o `curso` com a `turma` eu criaria a tabela `turma_has_curso` e seguiria o mesmo raciocínio no select?
Comment: Sim, se a relação for `n: n`, se for `1: n`, a tabela "n" pode receber uma chave estrangeira e não precisaria criar outra tabela
Comment: Muito bom, então eu estava seguindo o raciocínio correto, só queria ter certeza de que estava certo. Em relação ao `select`, obrigado pela orientação.
Comment: Trnaquilo, disponha :)


Split an array or list when founds a "#"

Question: I want to split an array when that for loops founds a "#", i'm trying to make a simulation in console and this is how the user will see.
But I can't found in no where a way to make this work.
 def grid(self):
        while True:
            size = input("Size of Map (N x N): ")
            if size.isnumeric() and int(size) >= 2:
                intSize = int(size) * int(size)
                mapH = list()
                map = list()
                for elementos in range(1, intSize + 1):
                    if elementos%10 == 5 or elementos%10 == 0:
                        mapH.append(elementos)
                        mapH.append("#")
                    else:
                        mapH.append(elementos)
                for el in mapH:
                   # I don't know what to make here
                return map
            else:
              continue

Comment: Are you trying to build rows and columns here?  And by the way, saying `if elementos%10 == 5 or elementos%10 == 0:` is exactly the same as `if elementos%5 == 0:`.
Comment: Yep, i want to build columns, but i failed lol
Answer: Assuming there is one # in the array.
i = 0
splitArray = []
for element in inputArray:
    if element == "#":
        splitArray = inputArray[:i]
    i += 1

Comment: I agree with this, but it would be much smarter just to create it as rows and columns in the first place.  It's silly to build a 1D list and then change it to 2D afterward.
Comment: @TimRoberts definitely agree with you, their implementation in general is a bit of a nightmare.
Answer: Why on earth do you ask the user for a size, if you hardcode the rows to 5?
def grid(self):
    while True:
        size = input("Size of Map: ")
        if size.isnumeric() and int(size) >= 2:
            size = int(size)
            intSize = size * size
            mapH = list()
            map = list()
            for elementos in range(1, intSize + 1):
                if len(mapH) == size:
                    map.append(mapH)
                    mapH = []
                else:
                    mapH.append(elementos)
            return map


Bending invariants in higher dimensions

Question: The determinant of the Gauss map of an embedded surface in 3 space is a bending invariant of the surface.
What about the determinant of the Gauss map for hypersurfaces of n space?
How does one obtain all of the bending invariants of the hypersurface from the Gauss map?
Comment: What do you mean by determinant of the Gauss map?  The derivative has a determinant, but this is just the curvature.
Comment: Yes, the determinant of the differential of the Gauss map. I know it's the Gauss curvature for a surface. I am asking about the same questions for hypersurfaces in higher dimensional Euclidean space e.g. 5 manifolds in 6 space.
Answer: I assume what you are interested in is the product of the principal curvatures for hypersurfaces in Euclidean $n$-space for $n\geq 4$.  This quantity is not a Riemannian invariant, i.e. it is not preserved by isometries.  When you say that you want to obtain all the bending invariants from the Gauss map, do you mean sectional curvature?  If so, in each two-dimensional direction determined by a pair of principal directions, the sectional curvature will be the product of the two principal curvatures, just as for Gaussian curvature.

Bending invariants in higher dimensions


Win32API: how to create a shortcut (.lnk file)

Question: I'm a Java developer, so please excuse my ignorance.
I want to create a shortcut to an executable, e.g., in the user's autostart or send-to folder (I don't want an installer to do that, because the installer usually is run by an administrator). What API (C preferred) I could use for that task (maybe using JNA)? Thanks in advance.
Comment: Why not let the installer do it for you?
Comment: You could do it using [JScript or VBScript](http://msdn.microsoft.com/en-us/library/fywyxt64%28VS.85%29.aspx) using the Windows Scripting Host.  Though I don't know how you'd do it using or integrating JNA.
Answer: It requires using COM, ShellLinkObject from shell32.dll.  No idea what that takes in Java, but you'll find C# code in my answer in this thread.
Answer: As @Hans indicated, it requires COM (via ShellLinkObject or WScript.Shell). In Java you can call COM objects using a Java to COM bridge. There are a few available, ranging from free to commercial. A couple that I know of are:

Java2COM
JACOB
JCOM


Como printar elementos de uma pilha?

Question: Estou com problema de formatação de saída desse programa. Abaixo segue o trecho do código que faz a impressão da pilha, em seguida segue a img do problema
def __repr__(self):
    r = ""
    pointer = self.top
    while(pointer):
        r = r + str(pointer.data) + " "
        pointer = pointer.next
    return r

Comment: Só por curiosidade o que seria esse `self.top`?
Comment: acredito que o topo da pilha
Comment: Beleza é topo da pilha, mas esse topo da pilha é instancia de que classe?
Comment: `class Stack:
    def __init__(self):
        self.top = None
        self._size = 0`               tá falando da classe da pilha?
Comment: kkkk desculpa, não manjo muito estou pagando ed pela 1ª vez
Answer: Você precisar adicionar o método strip(). Para remover espaços em branco no inicio e final das strings geradas.
Uma possível solução, utilizando o seu código, seria:
def __repr__(self):
    r = ""
    pointer = self.top
    while(pointer):
        r = r + str(pointer.data) + " "
        pointer = pointer.next
    return r.strip()

Desta forma a saída esperada será igual a resposta obtidas do seu programa.
Comment: grato pela resposta

Como printar elementos de uma pilha?


Finding Complex root of z^{3/4} types

Question: Can't get more than one solution whilst going over this textbook question:

$$\ z^{3/4}= \sqrt{6}\ +\sqrt{2}i $$
  $$\text{Answers in the form } re^{i\theta}; r>0,\text{ and } -\pi < \theta \leqslant \pi$$

Converted the RHS ($\ z^\frac{3}{4}=\sqrt{8}e^{\frac{\pi}{6}i}$), then applied de Moivre's Theorem and introduced $2k\pi$. $(z=[\sqrt{8}e^{(\frac{\pi}{6} + 2k\pi)i}]^\frac{4}{3}$), $k\in \mathbb{z}$. So we get $$\\z=4e^{\frac{4}{3}i(\frac{\pi}{6} + 2k\pi)}$$ $$ z=4e^{i(\frac{2\pi}{9} + \frac{24k\pi}{9})}$$ On inspecting this, I see the only possible value of k is $0$ as others give $\theta$ values outside the range. My answer being$\ z=4e^{\frac{2\pi}{9}i}$.Where have I gone wrong? I'm sure there's more than one solution, the textbook indicates so.
PostScript:$\ $
So, in the solution that's provided in the text book, de Moivre's Theorem is applied twice: first using $[\sqrt{8}e^{i(\frac{\pi}{6})}]^4=64e^{i(\frac{2\pi}{3})}$ and then $[64e^{i(\frac{2\pi}{3}+2k\pi)}]^\frac{1}{3}=4e^{i(\frac{2\pi + 6k\pi}{9})}$ It's on the second application that they introduced the $2k\pi$. Using their method, we reach 3 solutions, one of which is the one I got.
Why can't de Moivre's theorem be applied in one step with the whole fraction?
Answer: It can, and your solution is correct... up to the point where you concluded that the "others give $\theta$ values outside the range". The range doesn't matter: the solutions are actually correct for every $k\in\mathbb Z$, except that it turns out that some of them are identical, so we try to remove the duplicates and keep just the non-identical ones.
To demonstrate: in the book, the solutions are $4e^{i\frac{2\pi}{9}}$, $4e^{i\frac{8\pi}{9}}$ and $4e^{i\frac{14\pi}{9}}$. Let's try to see that you got the same three solutions using your formula, by varying $k$:

$k=0$: $4e^{i\frac{2\pi}{9}}$
$k=1$: $4e^{i\frac{26\pi}{9}}=4e^{i\left[\frac{18\pi}{9}+\frac{8\pi}{9}\right]}=4e^{i\left[2\pi+\frac{8\pi}{9}\right]}=4e^{i\frac{8\pi}{9}}$
$k=2$: $4e^{i\frac{50\pi}{9}}=4e^{i\left[\frac{36\pi}{9}+\frac{14\pi}{9}\right]}=4e^{i\left[4\pi+\frac{14\pi}{9}\right]}=4e^{i\frac{14\pi}{9}}$

... the same as the book solution.
Then, $k=3$ would give you $4e^{i\frac{74\pi}{9}}=4e^{i\left[\frac{72\pi}{9}+\frac{2\pi}{9}\right]}=4e^{i\left[8\pi+\frac{2\pi}{9}\right]}=4e^{i\frac{2\pi}{9}}$, i.e. the same solution as for $k=0$, and similarly, the other solutions will appear again when $k$ takes subsequent values ($4,5,6$ etc.)
Comment: You're absolutely right! Thank you. I appreciate you offering your time!^ :)
Answer: In my opinion, it's simpler to solve congruences:
$$\bigl(\mathrm e^{i\theta}\bigr)^{\tfrac 34 }=\mathrm e^{\tfrac{i\pi}6}\iff \frac{3\theta}4\equiv \frac\pi6\mod 2\pi\iff9\theta\equiv 2\pi\mod 24\pi\iff\theta\equiv \frac{2\pi}9\mod \frac {8\pi}3,$$
so that $$\theta\in\Bigl\{\frac{2\pi}9,~ \frac{26\pi}9,\frac{50\pi}9\Bigr\}. $$

Finding Complex root of z^{3/4} types


While loop with two true conditions but it only validate one

Question: I need the code to run until both conditions at the while are true, I am using logical AND (&&):
while ((A.i != B.i) && (A.j != B.j))
{
    // do something
}

at the run, the loop stops if
A.i=B.i

without checking the second condition, what am I doing wrong?
Comment: You seem to not understand either what `&&` means or what `while` means. Can you describe what you believe them to mean, and we can tell you where you are wrong?
Comment: It is doing exactly what you've told it to do.  What behavior do you expect?
Comment: If `A.i=B.i` then both conditions are not true.
Comment: @DourHighArch how so?
Comment: Because `A.i != B.i` is false, so at least one condition is not true. If one condition is not true, then both conditions cannot be true.
Comment: What are the both conditions that need to be true?
Comment: What I want to achieve is:
if A.i = B.i AND A.j=B.j then break the loop
Comment: @HishamSiam: Then start by writing exactly that:  `while(true) { if (a.i == b.i && a.j == b.j) break;  ... body of loop here ... }`
Answer: In a conditional statement where the && operator is used, the second condition is only evaluated if the first one is true. That is why when A.i==B.i you immediately break out of the check
"I need the code to run until both conditions at the while are true"
That confuses me, because if you want a while loop to run until certain conditions are true, then you would not want those conditions to be evaluated in the while() statement..
If you want your code to run UNTIL both of those conditions are true, then it really should be:
// Keep running while EITHER A.i is equal to B.i OR A.j is equal to B.j
while ((A.i == B.i) || (A.j == B.j))
{
    // do something
}

Comment: You flipped his != to == which breaks on the OR here
Comment: OP said he wants the loop to run until those conditions are both met, so hes basically saying he wants the loop to run until `A.i is not equal to B.i and A.j is not equal to B.j` which is what that loop checks.. if either `A.i == B.i` OR `A.j == B.j` the loop will continue
Answer: Switch your && to ||
Your loop says "while A.i is not equal to B.i AND A.J is not equal to B.j" loop. Once A.i equal B.i that statement is no longer true, so the loop exits (it doesn't actually care about the second equality at that point). By using an OR it will loop until both conditions are false.
Comment: I see your point..
Answer: Not clear but I suspect this is what you are looking for
while ( !(A.i == B.i && A.j == B.j) )

Which is the same as
while ( A.i != B.i || A.j != B.j) )

I think?
Answer: OP, your question isn't very clear, but I'm pretty sure you are up against one of two problems.

This is a very common logic error
while (a == b) || (c == d)

is the same as
until (a != b) && (c != d)

Meanwhile,
while (a != b) && (c != d)

is the same as
until (a == b) || (c == d)

Notice how when you switch from == to !=, you also need to switch && for ||.  A lot of devs miss this very obvious sort of logic flip (see De Morgan's Laws).  Anyway, you just need to think the logic through.  From your post, it is not clear what you are intending, but you might just need to switch && for ||.
Short circuit evaluation
Sounds like you wanted the second half of the logic to run, perhaps because the getter for j has some side effect that you want (which by the way isn't a great idea).
If you want the second half to always run, you should use | instead of ||.  The || operator doesn't bother with the right hand side if the left hand side is true.  Similarly, the && operator doesn't bother with the right hand side if the left hand side is false.  This is called Short-circuit evaluation.
Answer: Because A.i != B.i evaluates to false so no need to complete the condition


Como determinar a localização aproximada do usuário pelo IP?

Question: Quando utilizo motores de busca para certas pesquisas, principalmente relacionadas a mapas ou estabelecimentos comerciais, esses sistemas geralmente me servem resultados relevantes para a minha localização geográfica.
Quando estou no PC, os motores de busca podem até não conhecer minha posição geográfica com precisão de GPS, mas sabem ao menos em que cidade eu estou.
Acredito que isso seja determinado pelo endereço IP, dado que geralmente uma faixa de endereços específica é fornecida pelo provedor para regiões bem determinadas.
Mas a nível de implementação, como é feita essa determinação? Existe fórmula para determinar a cidade ou região do usuário a partir de seu endereço? Ou ao menos um provedor conhecido do qual possamos consumir um serviço para obter essa informação?
Comment: Lembrei na hora [desse XKCD](http://xkcd.com/195/)... Infelizmente não encontrei nenhuma informação seja no fórum, no blog post ou no slashdot sobre como esse mapa foi feito (não procurei a fundo, entretanto). E pelo que eu li [aqui](http://www.iplocation.net/), a maioria das bases de dados de geolocalização por IP é comercial (paga), e a qualidade das mesmas varia bastante.
Comment: Não responde a sua pergunta, mas pode ser um começo. Encontrei [aqui](http://www.macoratti.net/07/05/vb_ipurl.htm) uma relação país/faixa de IP.
Comment: Vale também lembrar que essa informação é orgânica (muda com frequência) e ad hoc (a distribuição dos ips é feita pelo ICANN e os banco de dados disponíveis por aí são construídos parte com essa base do ICANN e parte através de amostras estatísticas). Isso significa que o melhor serviço de geoip oferece não mais que 90 a 95% de segurança quanto ao país e não mais que 80-90% com relação a informação da cidade.
Answer: IP GEOLOCATION
Isso na verdade é muito simples e funciona da seguinte maneira:

As operadoras fornecem números IP's de acordo com uma faixa
O registro da faixa é feito por localidade
Dependendo da quantidade isso pode ser um prédio, rua, bairro ou cidade
Com o intuito de facilitar o rastreamento de crimes essa informação é atualizada  em um banco de dados
As operadoras fazem intercâmbio dessas informações com os seus reguladores
Uma vez por mês esse banco é atualizado para o público
Esse banco é o GeoLite Database.
Um arquivo em formato binário ou CSV, com todos os blocos IP's atuais:
GeoIP Legacy Downloadable Databases
Existem diversas formar para localizar um IP nesse banco.
Dentre as maneiras prontas estão:
GeoLite CSV Java - Exemplo simples
GeoIP2 Apache - Módulo para o Servidor Apache
GeoIP2 Databases Binários - Exemplos avançados em várias linguagens de programação
Answer: Da uma olhada aqui: http://php.net/manual/en/function.geoip-record-by-name.php
Usamos isso nosso site (www.ansb-brasil.org). Se vc escreve usando o formulário de contato, quando o site agradece você, ele indica o IP, o pais, e a cidade de você.
De verdade, isso não dá exatamente o nome da sua cidade, mas o nome do ponto de acesso internet de você.
Comment: O fato de isso ser uma função oficial do PHP me anima. Vou testar de casa mais tarde :)
Comment: Cuidado; antes de usar, faz um "PhpInfo()" para ver se o PHP que vc tem, tem esta possibilidade. Tambem, tem empresa de hospedagem que usam um sistema diferente. Sou em Brasilia mas nos usamos um hospedagem da Europa que oferece um sistema um pouco diferente do Geiop (temos $_SERVER[GEOIP] por exmplo)
Answer: Sem querer fazer um jabá, mas já fazendo, eu tenho uma biblioteca chamada WallaceMaxters\IPInfo, que pega a informação de um determinado IP.
Veja um exemplo de uso:
 IPInfo::get('22.214.171.124')->getCountry();

Ela usa internamente a API do ipinfo.io.
Se você quiser um exemplo, acesse a url a baixo para capturar as informações:
http://ipinfo.io/184.108.40.206/json
Como já foi dito nas respostas anteriores, você não consegue determinar a localização exata da pessoa. Talvez apenas aproximada ou até apenas dentro do país.


"firebase deploy --only hosting" suddenly failing with "Error: Failed to list functions for "

Question: My firebase hosting deployments have suddenly started failing both in my Github CI Workflows and from my local machine.
<code>$ firebase deploy --only hosting

=== Deploying to '<project>'...

i  deploying hosting

Error: Failed to list functions for <project>
</code>
The project in question does not have any functions, and only hosts a static site. Google searches for "Failed to list functions" turn up empty, it seems like not a common problem. The only leads I can find indicate some kind of network error.
I have updated my firebase-tools, logged out and in again to generate a new CI token, tried the process from my Github workflows and also manually from my machine, all to the same effect.
I can't find any information about this problem, except that the error seems to come from this part of the firebase-tools codebase:
https://github.com/firebase/firebase-tools/blob/c0f19a32845135108c75a1050024965cb1e3f52d/src/gcp/cloudfunctions.ts
Answer: My firebase tools version was 11.14.0. I changed that to 11.13.0. Installed this specific version through npm install -g firstname.lastname@example.com. After that I could successfully deploy.
Answer: I came across the issue. using firebase-tools version 10.5 or upgrading it to blaze plan fixed my issue


Findind Hamiltonian functions for flow

Question: Consider the symplectic space $(\mathbb{R}^2, \omega_{st}=dx \wedge dy$. I want to find a Hamiltonian function, such that its time-1-flow is of the form
$\varphi(x,y)= (2x, \dfrac{1}{2} y)$
My ansatz:
Consider $\varphi_t(x,y):=(2xt, \dfrac{1}{2} y t)$. Now
$\dfrac{d}{dt} \varphi_t(x,y)= (2x, \dfrac{1}{2} y)$
The corresponding vector field would be $X(x,y)= 2x \ dx + \dfrac{1}{2} y \ dy $.
Let $v= a \ dx + b \ dy$
Then $\omega_{st}(X,v)=2xb-\dfrac{1}{2} y a$
Is that correct so far or is it complete nonsense?
Comment: Note that your ansatz gives the trivial map for $t=0$, when it should equal the identity. There are a couple of other problems, but that's the most fundamental one.
Answer: Let's look for a flow of the form $$\varphi_t(x,y) = \left(2xf(t), \dfrac{y}{2f(t)}\right)$$ for some function $f(t)$. No matter what happens, this'll always be a symplectomorphism. Since $\varphi_0 = {\rm Id}_{\Bbb R^2}$, we need $f(0) = 1/2$ and $\varphi_1= \varphi$ gives $f(1) = 1$. Moreover, the group-property of the flow now implies that $f$ is affine. So we necessarily have $f(t) = (t+1)/2$. With this we have that $$X_{(x,y)} = \frac{{\rm d}}{{\rm d}t}\bigg|_{t=0} \varphi_t(x,y) = \frac{{\rm d}}{{\rm d}t}\bigg|_{t=0}  \left(x(t+1), \frac{y}{t+1}\right) = x\partial_x\big|_{(x,y)}-y\partial_y\big|_{(x,y)}.$$Now we have that $$\omega(X, \cdot)  = ({\rm d}x\wedge {\rm d}y)(x\partial_x-y\partial_y, \cdot) = \begin{vmatrix} x & {\rm d}x \\ -y & {\rm d}y\end{vmatrix} = x\,{\rm d}y + y\,{\rm d}x = {\rm d}(xy). $$Alright, so there you have it: $H(x,y) = xy$.

Findind Hamiltonian functions for flow


flask-admin and allow_inheritance for an embedded document in mongoengine

Question: For flask-admin the following only gives me CRUD access to Task and the TaskItem embedded document, but no access to ItemParameter or ItemTitle. Is this not supported in flask-admin or am I doing something wrong? Thx
<code>class TaskItem(db.EmbeddedDocument):
    type = db.StringField(max_length = 32)
    column = db.IntField()
    row = db.IntField()
    width = db.IntField()
    height = db.IntField()
    meta = {'allow_inheritance': True}

class ItemParameter(TaskItem):
    label = db.StringField(max_length = 32)
    formula = db.StringField(max_length = 256)
    parameter = db.ReferenceField(Parameter)

class ItemTitle(TaskItem):
    label = db.StringField(max_length = 32)
    document = db.ReferenceField(Document)

class Task(db.Document):
    items = db.ListField(db.EmbeddedDocumentField(TaskItem))

    def __unicode__(self):
        return unicode(self.name)

# Flask-Admin
class SecuredModelView(ModelView):
    def is_accessible(self):
        return current_user.has_role('admin')

admin.add_view(SecuredModelView(Task))
</code>
Answer: As stated by the flask-admin creator this feature is not yet supported.
https://github.com/flask-admin/flask-admin/issues/907


Flutter : Check GPS Location Mode

Question: I have project related using maps and tracking location user , for this i used Geolocator Package. I need to check current location of user , in my flow project first i check last position of user , if last position null then i check current position of user.
Code
  Position _currentPosition;
  Position get currentPosition => _currentPosition;

  Future<void> getCurrentPosition() async {
    try {
      Position lastPosition = await Geolocator().getLastKnownPosition();
      if (lastPosition != null) {
        print("Success Get Last Position...");
        _currentPosition = lastPosition;
      } else {
        final currentPosition = await Geolocator().getCurrentPosition();
        if (currentPosition != null) {
          print("Success Get Your Current Position...");
          _currentPosition = currentPosition;
        } else {
          throw "Can't Get Your Position";
        }
      }
    } catch (e) {
      throw e;
    }
    notifyListeners();
  }

Then i calling getCurrentPosition Function on my button OnPressed to get location user like this :
Button GetLocation
void goToMaps() async {
    final mapsProvider = context.read<MapsProvider>();
    try {

      print('Get Location User');
      await mapsProvider.getCurrentPosition();
      print('Success Get location User');

    } catch (e) {
      globalF.showToast(message: e.toString(), isError: true, isLongDuration: true);
    }
  }

First Problem is , When GPS Location Mode is Device Only I can't get LastPosition or Current Position it never print Success Get Location User and still print Get Location User.
Second Problem is , When Gps Location Mode is Battery Saving user location i got is very inaccurate, compared i used mode High Accuracy.
My question is , How can i check if gps location mode != High Accuracy , then i can show warning user to set the gps to High Accuracy.
Similiar Like this question
Thank's.
Answer: For the second problem, it happens because in High Accuracy mode android uses both GPS and network location, but in Battery Saving mode GPS module is turned off. If it was native Android, you could check provider of the location if you get location from LocationManager. But provider is not available in Flutter in Position class. You can instead use accuracy. If it is greater than a threshold and not suitable for your application, you can suggest the user to turn on High Accuracy mode.
Another options would be to use other package than Geolocator (however I'm not aware of any package that provides necessary interface) or to modify source code of Geolocatior so that it provides information about which mode is currently active.

Flutter : Check GPS Location Mode


Save base64 string as image using phonegap?

Question: I am getting a base64 string from the server for a png file and i would like to save this image on the file system. It looks like phonegap filewriter only supports binary. Does anyone know how i can convert this base64 string to use in phonegap. I was looking at window.atob and window.btoa but couldnt make sense of things.
Comment: If its a single file then you can store it in local storage
Comment: my requirement i to save it on the file system
Comment: You may want to check this [post](https://stackoverflow.com/questions/20419574/saving-dataurlbase64-to-file-on-phonegap-android), it saves dataUrl which is base64 to a png image on android file system
Answer: You can not use the PhoneGap FileWriter to write binary data. You'd need to write a plugin to send your base64 encoded data to the native side, encode it into binary then write it using native code.
Check out the plugins info at: HERE  also take a look at the phonegap source code to see how we do the file writer and you can add some code to do the base64 decode before writing.
Comment: I believe you can use the phonegap filewriter to write binary data in IOS and Android. http://docs.phonegap.com/en/3.0.0/cordova_file_file.md.html#FileWriter
Comment: You can refer this also - http://blog.danguer.com/2011/10/24/base64-binary-decoding-in-javascript/
Comment: Refer - http://stackoverflow.com/questions/11388018/phonegap-plugin-to-convert-base64-string-to-a-png-image-in-android
Comment: thanks. FYI writing binary files using filewriter was added in phonegap 2.9
Answer: As far as I know, phonegap don't provide a way to save an image to the filesystem. You need a phonegap plugin to do that.
Canvas2Image nearly do what you want. It take a canvas id, extract a base64 string from the canvas and save it as an image. You can slightly alter the javascript part of the plugins to accept a base64 string instead of a canvas id.
Answer: Just found a good plugin to save BASE64 into filesystem.
Phonegap Image Resizer
<code>window.imageResizer.storeImage(
  function(json) {
    console.log('Saved to ' + json.url)
  }, function (error) {
    console.log("Error : \r\n" + error);
  }, imageDataInBase64);
</code>
More detail see the comment imageresize.js


How do you use addResourcepath() in R Shiny?

Question: I'm struggling to understand how to use the addResourcePath() function from R shiny (https://shiny.rstudio.com/reference/shiny/latest/resourcePaths.html), even despite this apparent solution to someone with a similar question How do I porperly use addResourcePath?
I want to refer to a folder containing several javascript files to be used in my shiny app, but I don't understand what the 'prefix' is supposed to be, nor how to get the 'directory path'. How does one use addResourcePath to give R Shiny access to files in a particular folder?
Answer: Here is a basic explanation in simple words.
Assuming you want to add the file myScript.js located in c:/javascript_files. The simplest solution would be to copy myScript.js to a www subdirectory where your app is located. Anything located in www can be accessed by the UI of your app by using the prefix /.
For this example to add your script to the UI you can use
tags$head(tags$script(src="myScript.js")))
The HTML code generated by Shiny is going to be

Your browser is going to interpret it as http://your_site/myScript.js. Here the prefix is just /.
But in the case you want to keep your JS code in the original location (c:/javascript_files), you need to make it accessible to the UI (front-end) of your app. Since you can not use a URL like http://your_site/c:/javascript_files/myScript.js, you need to create a "virtual" subdirectory that is mapping your local directory to a URL directory, that is actually the prefix parameter in addResourcePath().
For this example, lets use as prefix jscode. The expression:
addResourcePath("jscode", "c:/javascript_files")
is going to create a "virtual" directory named jscode to be used in the URL of your app for the local directory c:/javascript_files.
The expression:
tags$head(tags$script(src="jscode/myScript.js")))
is going to be translated to HTML as

which is going to be interpreted by the browser as http://your_site/jscode/myScript.js.
If you had a subdirectory like c:/javascript_files/code_a, you don't need to add it, you can reference it in the same way like:

The Shiny code to add the myScript.js file will be:
library(shiny)

addResourcePath("jscode", "c:/javascript_files")

ui <- fluidPage(
  tags$head(tags$script(src = "jscode/myScript.js"))
)

server <- function(input, output, session) {
}

shinyApp(ui, server)

Comment: You can see the prefix as an alias to refer to your local directory.
Comment: Very helpful, you did a nice job of explaining the prefix. I flailed around for a long time using the package resource materials and they were useless. Thanks for taking the time to patiently explain to us newbies
Comment: Thanks for your very detailed response @Geovany. So prefix does not actually refer to anything specific, but is just a name you are providing that you will refer to later when you want to pull a file from the location?
Comment: I'm glad to know that the explanation is useful.


Fetching 3 tables at a time, retrieve only the table which matches the condition (SQL)

Question: I have 3 tables: WATER_TENDER,ENGINE and TRAILER.
All of them have the EQ_ID as primary key and some other attributes, different for each table.
for example, EQ _ ID='WT-123' points a row inside the WATER _TENDER table only, and nothing inside the other tables.
As I do not know the EQ _ID in advance so I do not know which table to look at, how can I write a single query which checks all the 3 tables based on EQ _ID and retrieve just the table which matches the EQ _ID specified??
Comment: I think "retrieve just the row which matches the EQ _ID specified??"

is more correct...
Comment: Your effort would be better spent on constructing proper tables and referencial integrity.
Answer: If you decide to tackle the model a bit, you could use:
SELECT  Type, a ,b ,c ,d ,e ,f ,g ,h
FROM    Equipment AS eq
        LEFT JOIN ENGINE AS en ON en.EQ_ID = eq.EQ_ID
        LEFT JOIN TRAILER AS tr ON tr.EQ_ID = eq.EQ_ID
        LEFT JOIN WATER_TENDERER AS wt ON wt.EQ_ID = eq.EQ_ID
WHERE   eq.EQ_ID = 'WT-123'

Answer: You can use UNION ALL to select rows from all tables and select all columns, providing NULL when that column doesn't exist:
SELECT a, b, c, d, e, f FROM (
    SELECT a, b, NULL AS c, NULL AS d, NULL AS e, NULL AS f FROM WATER_TENDER
    UNION ALL
    SELECT NULL AS a, NULL AS b, c, d, NULL AS e, NULL AS f FROM ENGINE
    UNION ALL
    SELECT NULL AS a, NULL AS b, NULL AS C, NULL AS D, e, f FROM TRAILER) AS T1
WHERE _ID = @id

It's a bit dirty though, IMHO. It feels like there's something wrong with your design if you have to do this.
Comment: This would work, but for large sets of data I imagine it would cause quite a performance penalty.
Comment: The WHERE clause can be introduced into the individual SELECTs if you are worried about performance. I would think most DBs will perform this optimization automatically for you.
Answer: I don't think you can do that in a normal select query.  If possible, I'd recommend either:

performing some logic so that you know which table you're supposed to look in (i.e., a 'WT-' means you should look in the WATER_TENDER table)
performing 3 separate queries, 1 for each table
redesigning your database (possibly have a master table that stores the relationships between an id and records the other tables)


Drupal 7 & Facebook Connect - Connect Button Problem! Help please?

Question: I installed the module Drupal For Facebook. So far it was working perfectly, I enabled Facebook Connect and put the Facebook Connect login block in a sidebar. It was great until I went into configure the Facebook Connect login block and changed text in the body. Now the CONNECT button no longer appears and only text appears saying the words "Connect." I've tried every mix of plain text, full html, and filtered html to include the suggested enter of: Connect to no avail. The only thing I see is the word Connect in plain text every time.
I need to reset this module to default or learn how to properly add the button back. But I am very new to Drupal and have no idea how to do it.
Comment: have you tried removing the changes you made?
Comment: I have removed everything I added, which leaves the field blank and thus renders the block null. I then added (in plain text view but utilizing full html) what the module suggests (Connect) which simply leaves the word Connect on the page with no link or button.
Comment: Basically what I did to begin with was this: I installed the module, enabled and placed the FB Connect block, went in to configure it and because I use a WYSIWYG CKEditor all I saw in the field was the word Connect, which I edited to say Login Using Facebook, when I did so the button disappeared and came back on the site as simply text. I messed something up but I am not sure how/what.
Comment: this might probably be an issue with the module. post it in the module's issues on drupal.org .
Comment: I have the same issue. ... Your issue is not in the format -  I looked in admin/configuration/fbconnect - in the 4th tab it says that I am not connected to the FB App.  .....   Checked the API Key and the API Secret they are correct. If you google it there are some suggestions that you should just create another app, ,,,   FB has another key - an auth key separate from the API and secret and I think that is where all this problem is coming from. I do not want to create new app because my FB app page is all setup.
Answer: I have the same issue, FB Connect will do this when your site tries to connect to an  FB App and cannot. Check your API and Secret keys first, other possible problems are the URL settings which should match in both FB and Drupal/FBConnect. Lastly in my case, everything was working until I reset an auth key in FB which I should not have done and it created issues for me.


Why using apache kafka in real-time processing

Question: Lately I've been looking into real-time data processing using storm, flink, etc...
All architectures I came through uses kafka as a layer between datasources and the stream processor,  why this layer should exist ?
Answer: I think there are three main reasons why to use Apache Kafka for real-time processing:

Distribution
Performance
Reliability

In real-time processing, there is a requirement for fast and reliable delivery of data from data-sources to stream processor. If u are not doing it well, it can easily become a bottleneck of your real-time processing system. Here is where Kafka can help.
Before,  traditional messaging ApacheMQ and RabbitMQ was not particularly good for handling huge amount of data in real-time. For that reason Linkedin engineers developed their own messaging system Apache Kafka to be able to cope with this issue.
Distribution: Kafka is natively distributed which fits to distribution nature of stream processing. Kafka divides incoming data to partition ordered by offset which are physically distributed over the cluster. Then these partition can feed the stream processor in distributed manner.
Performance:
Kafka was designed to be simple, sacrificing advance features for the sake of performance. Kafka outperform traditional messaging systems by big difference which can be seen also in this paper. The main reasons are mentioned below:

The Kafka producer does not wait for acknowledgments from the broker
  and send data as fast as broker can handle

Kafka has a more efficient storage format with less meta-data.

The Kafka broker is stateless, it does not need to take care about the state of consumers.

Kafka exploits the UNIX sendfile API to efficiently deliver data from
  a broker to a consumer by reducing the number of data copies and
  system calls.

Reliability: Kafka serves as a buffer between data sources and the stream processor to handle a big load of data. Kafka just simple store all the incoming data and consumers are responsible for the decision how much and how fast they want to process data. This ensure reliable load-balancing that the stream processor will be not overwhelmed by too many data.
Kafka retention policy also allows to easy recover from failures during processing (Kafka retain all the data for 7 days by default). Each consumers keep track on offset of last processed message. For this reason if some consumer fails, it is easy to rollback to the point right before failure and start processing again without loosing information or need to reprocess all stream from beginning.
Comment: I just want to highlight the point, that Kafka brokers allow you to decouple producer and consumer systems. (This is part of the "reliability" point above, but I wanted to highlight it as it's not explicitly mentioned.) -- Furthermore, I want to point out, that Kafka is more than a pub/sub or messaging system. It's a Streaming Platform, with message brokers, clients, connectors to other systems, and stream processing capabilities -- thus you might now even need a Stream processing framework if you has Kafka already.


Gerar números aleatórios em Java

Question: Como gerar só números maiores que 2?
Como gerar só números maiores que 2 e os números gerados têm que serem múltiplos de 3(eg. 3, 6, 9)?
Como gerar só números menores que 10?
Como gerar só números menores que 10 e os números gerados têm que serem múltiplos de 3(eg. 3, 6, 9)?
Comment: Você pode utilizar a classe Random?
Comment: pode utilizar a class random: Random.nextInt(max - min + 1) + min onde min seria 2, agora as próximas situações acredito que deva fazer verificações em uma função recursiva para retornar apenas os resultados desejados...
Comment: Sim. Posso ser com Random.
Answer: Instanciando a classe Random:
Random random = new Random();

Como gerar só números maiores que 2?

Entre 2 e 1000, podendo substituir o mil ou dois por qualquer valor, por exemplo:
numero = random.nextInt(1000) + 2;

Como gerar só números maiores que 2 e os números gerados têm que serem
  múltiplos de 3 (ex. 3, 6, 9)?

Entre 3 e 3003 todos múltiplos de 3.
numero = (random.nextInt(1000) + 1) * 3;

Como gerar só números menores que 10?

numero = random.nextInt(10);

Como gerar só números menores que 10 e os números gerados têm que
  serem múltiplos de 3(eg. 3, 6, 9)?

numero = (random.nextInt(2)+1) * 3;

Gerar números negativos, por exemplo de -5000 a 5000

numero = ((random.nextInt(2000)) * 5) - 5000;

Gerar números aleatórios em Java


Qual nome do plugin do sublime t 2/3 que indica erro de sintaxe na linguagem php?

Question: Preciso saber algum plugin do sublime text 3 que ele indica erro na sintaxe do código tipo debuger real-time igual o que tem no phpStorm... alguém sabe?
Comment: https://packagecontrol.io/packages/PHP%20Syntax%20Checker
Answer: O plugin mais popular é o XDebug
https://xdebug.org/
Veja também o uso pelo netbeans:
http://wiki.netbeans.org/HowToConfigureXDebug


Total SA/Engineer Management Software

Question: So, as we've seen all over server fault, and over the years I've built several of each system,

System / Network Monitoring (I use nagios)
System / Network Trending (I use Cacti)
Centralized Log Monitoring (syslog-NG)
Host-Based Intrusion Detection System (OSSEC)
Ticketing Systems (Request Tracker)
Internal Wiki Software (MediaWiki)
IP Tracking (in house NMAP-based software)

However at the end of the day, I sometimes feel like I've somewhat "cobbled together" what seems like it could be one or two softwares, at most.
I'm kinda looking for an "All-in-one solution thats easier to manage then having to deal with 7 different softwares.   Something that just works.
Anyone know of any?  I've seen tons of monitoring apps and all that, but they always are missing the wiki and ticketing portions.    That never made much sense to me, in my opinion if a alert goes off that should be a ticket for an engineer to address.  Same goes for the IDS going off, and maybe trending warnings for future notice.
Comment: It's probably a good thing to have small independant components instead of a software beast that tries to do everything. That said, what would be *really* useful is a common inventory system from which all these components could draw configuration information...
Comment: i would kill for such a system...   I dont mind individual pieces, i just hate having to configure 5 softwares to add a single server...
Answer: There's also Groundwork Open Source which performs this "cobbling" for you. I don't think it has a wiki or ticketing system though:
http://www.groundworkopensource.com/
I've used an earlier version a few years ago and it seemed very promising. In the end, my company decided to blow their budget on HP OpenView, so we never went past initial trials.
It's worth a look IMHO.
Answer: It won't replace all 7, shows ads, sits on Windows, and has device limits, but if you're a forgiving sort you might look at Spiceworks.   Version 5 is now in beta.
Answer: I have indeed felt the same about this motley set of software components. Both nagios and RT3 seem pretty venerable and in need of being dragged into 2010. (Zabbix was a contender for the nagios replacement, but it was more pain that it was worth and I reverted to nagios, (after taking a diversion via hyperic))
HOWEver I may have found an answer! ;-) well a solution to having to deal with these many different configurations problem, and its data centre automation in the form of Puppet Labs (http://www.puppetlabs.com/)
Once you come over to the puppet way of thinking, you start to think of writing puppet recipes rather than configuring servers directly, and a lot of pain and trial and error of disparate a tool-set goes away.
Puppet (or if you prefer cfengine) combine revision management for your config files and centralised management of many of those tools.
I would estimate that once you have your servers managed by a template engine like puppet, 50% of your administrative pain goes away.
Comment: I guess puppet does not address the problem of ticketing systems, and the mediawiki for storing documentation.
Also I think there is a lot of scope for someone to develop a dashboard front end that pulls together the data from nagios (horrible web interface), rt3, munin, cacti, rsyslog, syslog-ng into something rivalling a commercial admin tool.
Comment: Puppet is an amazing piece of software, however it doesn't really replace the need of any of the above softwares; It makes deployment night-and-day more efficient, however it doesn't remove the need to have it properly monitored and thoroughly documented.
Comment: I think given the UNIX philosophy of "Write programs that do one thing and do it well", fully integrated tools are only going to exist in the commercial software realm. ANd saying that, I've not even seen anything slick there, HP Openview was very clunky.
Splunk was good for log monitoring but appears to be very expensive to get alerts
Comment: If you're looking at deployment/config automation, an alternative to Puppet is Chef, from http://www.opscode.com/
Answer: I just had a thought which is that all these tools have to pull their configuration data from somewhere. ie
nagios needs a list of servers to monitor,
cacti some devices to poll,
syslog needs to know where the central syslog-ng server is.
Additionally rt3 and mediawiki need authentication backends, ie user lists and passwords
And no-one wants to be maintaining these lists in many places.
Really the way to simplify the management of all these apps is to use a common configuration directory and database.
And this makes MS Active Directory looks like a really good idea!
Answer: As far as commercial products goes, KACE software gets very good reviews. I'm not sure of the expense, but if you're planning to use all its features and have the "single pane of glass" that marketers love, it's not unreasonable at all.
It includes patch management, software management, help desk ticketing, remote assistance (something you don't currently have), host re-imaging, and several other features that you mentioned.
I have no relation to KACE, but have seen several successful installs. That said, if you do like your individual solutions for each problem, there's no huge reason to go with something like KACE.

Total SA/Engineer Management Software


How can I calculate $\mathrm{E}\!\left[\sum _{i=1}^X I_{\{Y_i\leq Y_{n+1}\}}\right]$?

Question: Suppose that $Y_1,\dots,Y_{n+1}$ is a random sample from a continuous distribution function $F$. Let$X\sim\mathrm{Uniform}\{1,\dots,n\}$ be independent of the $Y_i$'s. How can I compute $\mathrm{E}\!\left[\sum _{i=1}^X I_{\{Y_i\leq Y_{n+1}\}}\right]$?
Comment: What do those vertical bars mean in "$I\mid Y_i\le Y_{n+1}\mid$"?  This is not a conventional notation for an indicator function, which raises doubts concerning what this question is asking.
Comment: This looks like the conditional expectation of a random variable $I$, given that $Y_i \leq Y_{n+1}$. What is $I$? Or, were you trying to write an indicator function? Like $I \{ Y_i \leq Y_{n+1} \}$?
Comment: If $I$ is an indicator function just use linearity of expectation.
Comment: @Zen I believe you might have misunderstood: somebody's (your?) edits had fixed the notational problem, not created them!  With the rollback, the strange notation has returned.
Comment: Maybe the OP only meant to use the first vertical bar.  That could mean that it is intended to mean conditioning.
Comment: @whuber and Michael, in an earlier edit of the question, the OP specifically said it meant an indicator function.
Comment: @gammer That's nice to know.  It's a pity that useful information disappeared.  Thank you for confirming.
Comment: Hi, Bill, sorry for editing the question to make the notation more standard, with the side effect of making your comments less inteligigle. It wasn't my intention. I'll rollback it to the former version.
Comment: @whuber: Ok! Let's rollback the rollback! Cheers.
Comment: @hadi if any of us has satisfactorily answered your question, could you mark the corresponding answer as "answered"? Thanks.
Answer: Here is an alternative answer to @Lucas' using the law of iterated expectations:
$$ \begin{align}
E\left[\sum_{i=1}^X1_{(Y_i \leq Y_{n+1})}\right] & = E\left[E\left[\sum_{i=1}^X1_{(Y_i \leq Y_{n+1})}|X\right]\right]
\\
& = E\left[\sum_{i=1}^XE[1_{(Y_i \leq Y_{n+1})}|X]\right]
\\
& = E\left[\sum_{i=1}^XE[1_{(Y_i \leq Y_{n+1})}]\right]
\\
& = E\left[\sum_{i=1}^XE\left[E[1_{(Y_i \leq Y_{n+1})}|Y_{n+1}]\right]\right]
\\
& = E\left[\sum_{i=1}^XE[F(Y_{n+1})]\right]
\\[12pt]
& = E[X]E\left[F(Y_{n+1})\right]
\\[12pt]
& =\frac{n+1}{2}E[F(Y_{n+1})]
\end {align}$$
The third step follows from independence of $Y_i$ and $Y_{n+1}$ from $X$; the fourth step is again an application of the law of iterated expectations; the last step is simply an application of the formula for the expectation of a discrete uniform random variable.
By inverting the order of integration, we derive the remaining expectation:
$$ \begin{align}
E[F(Y_{n+1})] & = \int_{-\infty}^{\infty}F(y)dF(y)
\\
& = \int_{-\infty}^{\infty} \int_{-\infty}^y dF(x)dF(y)
\\
& = \int_{-\infty}^{\infty} \int_{x}^{\infty} dF(y)dF(x)
\\
& = \int_{-\infty}^{\infty} (1-F(x))dF(x)
\\[10pt]
& = 1-E[F(Y_{n+1})]
\end{align} $$
which implies $E[F(Y_{n+1})] = \frac{1}{2}$. Hence:
$$ E\left[\sum_{i=1}^X1_{(Y_i \leq Y_{n+1})}\right] = \frac{n+1}{4} $$
Answer: By distributional symmetry, $\Pr\{Y_i\leq Y_{n+1}\}=\Pr\{Y_{n+1}\leq Y_i\}$, for each $i=1,\dots,n$. Since $F$ is continuous, we have
$$
  \Pr\{Y_i\leq Y_{n+1}\} = 1-\Pr\{Y_{n+1}< Y_i\}=1-\Pr\{Y_{n+1}\leq Y_i\}.
$$
Therefore, $\mathrm{E}\left[I_{\{Y_i\leq Y_{n+1}\}}\right]=\Pr\{Y_i\leq Y_{n+1}\}=1/2$. Now, we have
$$
  \mathrm{E}\!\left[\sum_{i=1}^X I_{\{Y_i\leq Y_{n+1}\}}\;\Bigg\vert\; X=x\right] = \mathrm{E}\!\left[\sum_{i=1}^x I_{\{Y_i\leq Y_{n+1}\}}\;\Bigg\vert\; X=x\right]
= \sum_{i=1}^x\;\mathrm{E}\!\left[I_{\{Y_i\leq Y_{n+1}\}}\;\Bigg\vert\; X=x\right]
$$
$$
  = \sum_{i=1}^x\;\mathrm{E}\!\left[I_{\{Y_i\leq Y_{n+1}\}}\right] = \frac{x}{2},
$$
in which we used the linearity of the conditional expectation and the independence of $X$ and the $Y_i$'s. Hence,
$$
  \mathrm{E}\!\left[\sum_{i=1}^X I_{\{Y_i\leq Y_{n+1}\}}\right] = \mathrm{E}\!\left[\mathrm{E}\!\left[\sum_{i=1}^X I_{\{Y_i\leq Y_{n+1}\}}\;\Bigg\vert\; X\right]\right] = \mathrm{E}\left[\frac{X}{2}\right] = \frac{n+1}{4}.
$$
Answer: We have
\begin{align}
E\left[ \sum_{i = 1}^X I[Y_i \leq Y_{n + 1}] \right]
&= E\left[ \sum_{i = 1}^n I[i \leq X] I[Y_i \leq Y_{n + 1}] \right] \\
&= \sum_{i = 1}^n  E\left[ I[i \leq X] I[Y_i \leq Y_{n + 1}] \right] \\
&= \sum_{i = 1}^n  E\left[ I[i \leq X] \right] \cdot E\left[ I[Y_i \leq Y_{n + 1}] \right] \\
&= \sum_{i = 1}^n \frac{i}{n} \cdot E[I[Y_i \leq Y_{n + 1}]] \\
&= \sum_{i = 1}^n \frac{i}{n} \cdot E\left[ F(Y_{n + 1})] \right] \\
&= \sum_{i = 1}^n \frac{i}{n} \cdot \frac{1}{2} \\
&= \frac{n + 1}{4}
\end{align}
The second step follows from the linearity of expectations, the third step from the independence of $X$ and $Y_1, ..., Y_{n + 1}$, and the fifth step from the fact that
$$F(y) = P(Y \leq y) = E[I[Y \leq y]].$$
To prove the sixth step, you can use partial integration. For the final step, you use the formula for partial sums.
Comment: If you mean: $N=n$ I do agree with the answer.
Comment: Where does your $N$ come from? As long as $N>n-1$, that is always going to be true hence you can fix the final result at the value you want.


Show sql queries when load content

Question: I'm working with the data from a Drupal 7 site that I have and I need to extract the data from a table with a relation to another table. The problem is that one of the tables is Node table and the other is field_data_field... that has a target_id.
The queries I have tried are not connecting  the data correctly between this tables. I know this because  when I go to the content page (http://example.com/ca/content/aalto-erick) the data is not the same.
Is there a way to display the SQL queries that executes the server when displays this content page?
PD: I put the url to show that the info is displaying in a content page.
Comment: Also show us what you tried and the query you have written for this
Answer: Yes. The Devel module has a submodule called Web Profiler. Once the Web Profiler module is enabled, there will be toolbar in the footer. The toolbar contains a DB inspection button signified by a DB "stack" with the number of queries performed and the time to perform them. Click the button will show you a profile of the DB queries made in the last request.
Comment: Important to note that Web Profiler only comes with the Devel's  8.x version and not with 7.x nor 6.x
Answer: Yes. The Devel module has "Display query log" settings, You can this or have another way to get this through by  hook_query_alter or hook_query_TAG_alter hooks. You can use this reference link.
How To Print SQL String Using Devel Module

Show sql queries when load content


Calculos em SQL

Question: Bom dia a todos,
Tenho uma duvida, tenho o seguinte Select SQL em que mostra o total da quantidade do produto, o sql esta a funcionar, porem mostra me os lotes repetidos.
SELECT stock.lote, stock.descricao,
CASE WHEN stock.tipo = 'XXXX' or stock.tipo = 'YYYY' or stock.tipo = 'ZZZZ'
     THEN +quantidade
     ELSE -quantidade
     END as quant FROM stock
     INNER JOIN lotes
        ON lotes.descricao = stock.lote AND lotes.active=1
     WHERE stock.descricao = 'NORMAL' AND stock.lote!=''

Resultado do select:

lote
descrição
quant

lote1
prod1
5

lote2
prod1
5

lote2
prod1
-11

Resultado do select que eu pretendo: (ja tentei usar o GROUP BY e nao funcionou.)

lote
descrição
quant

lote1
prod1
5

lote2
prod1
-6

alguem pode ajudar? obrigado
Comment: tenta usar `+SUM(quantidade)` ou `-SUM(quantidade)` e dá um group by pela `stock.lote`
Comment: Tentou com left join no lugar do Inner Join? Ou a função SUM()?
Comment: O left join não altera nada, como uso o sum neste select?
Comment: @WallaceMagalhães acho que não vai funcionar, aplicando dessa forma retornaria ou o valor positivo ou o valor negativo e não a diferença entre eles. Talvez seja caso de usar uma temporária.
Comment: Perfeito, era mesmo isso que precisava, muito obrigado.
Answer: O que você precisa é fazer a soma dos valores retornados no seu CASE, usando apenas o group by seria mostrado apenas um dos valores, possivelmente o último, então acredito que se você usar o SUM() como abaixo vá funcionar. Caso não dê me fale que edito a resposta com uma nova sugestão.
SELECT stock.lote,
       stock.descricao,
       SUM(CASE
             WHEN stock.tipo = 'XXXX'
                   OR stock.tipo = 'YYYY'
                   OR stock.tipo = 'ZZZZ' THEN +quantidade
             ELSE -quantidade
           END) AS quant
FROM   stock
       INNER JOIN lotes
               ON lotes.descricao = stock.lote
                  AND lotes.active = 1
WHERE  stock.descricao = 'NORMAL'
       AND stock.lote != ''
GROUP  BY stock.lote

Answer: Você deve utilizar o GROUP BY com a cláusula SUM.  O GROUP BY é utilizado para agrupar os campos.
No seu caso todos os "lotes e descrição" que sejam iguais serão agrupados e seus valores somados.
SELECT  stock.lote, stock.descricao, sum(stock.tipo) as stock.tipo
  from  stock
        INNER JOIN lotes ON  lotes.descricao = stock.lote
                         AND lotes.active=1
  WHERE stock.descricao = 'NORMAL'
    AND stock.lote!=''
  group by stock.lote, stock.descricao

Calculos em SQL


C# join 3 tabelas utilizando Linq?

Question: Estou pegando para aprender C# e estou apanhando em alguns pontos.
Eu tenho 3 Tabelas.
Seguem as models
public class Tag
{
    [Key]
    public int ID_Tag { get; set; }

    [Required(ErrorMessage = "Preencha o Nome")]
    [MaxLength(100)]
    public string Nome_Tag { get; set; }
}

public class Local
{
    [Key]
    public int ID_Local { get; set; }

    [Required(ErrorMessage = "Preencha o Nome")]
    [MaxLength(100)]
    public string Nome_Local { get; set; }
    public string Tipo_Local { get; set; }
}

public class LocTag
{
    [Key]
    public int ID_LocTag { get; set; }

    [Required]
    [ForeignKey("Tags")]
    public int ID_Tags { get; set; }

    [Required]
    [ForeignKey("Locais")]
    public int ID_Local { get; set; }

    public virtual Tag Tags { get; set; }
    public virtual Local Locais { get; set; }
}

e gostaria de fazer o retorno do SQL me retornar do seguinte modo.
"result":[ {
         "Locais" :  {
                        ID_Local,
                        Nome_Local,
                        Tag: [{
                              ID_Tag,
                              Nome_Tag }]
                      }
           }]

Eu tentei de varios modos alguns ficaram bem proximos, porem não do jeito que eu pretendia.
var result = db.LocTag.Where(x => x.Locais.Tipo_Local == Nome).ToList();

me da o seguinte retorno:
"result": [
        {
            "Locais": {
                "ID_Local": 5,
                "Nome_Local": "NOME'
            },
            "Tags": {
                "ID_Tag": 1,
                "Nome_Tag": "NOME_TAG"
            },
            "ID_LocTag": 1,
            "ID_Tags": 1,
            "ID_Local": 5
        },....}]

Comment: Você não consegue porque a entidade Local não tem a chave de Tag, perceba que apenas LocTag que conhece Tag. Por favor compartilhe conosco as suas entidades para maior detalhe.
Comment: @GabrielColetta adicionei no edit ali.
Answer: Você precisa acrescentar um Select depois do Where criado a estrutura que você deseja, abaixo segue um exemplo com classe anônima:
var result = db.LocTag.Where(x => x.Locais.Tipo_Local == Nome)
    .Select(c =>  new {
                          ID_Local = c.Locais.ID_Local,
                          Nome_Local = c.Locais.Nome_Local,
                          Tag = c.Tags
                       }).ToList();

Aqui outro exemplo onde criei uma classe para representar a estrutura:
public class Locais
{
    public int ID_Local { get; set; }
    public string Nome_Local { get; set; }
    public Tag Tag { get; set; }
}

Novamente executo o mesmo comando mas neste caso preencho a classe acima:
 var result = db.LocTag.Where(x => x.Locais.Tipo_Local == Nome)
      .Select(c => new Locais {
                                  ID_Local = c.Locais.ID_Local,
                                  Nome_Local = c.Locais.Nome_Local,
                                  Tag = c.Tags
                              }).ToList();

Espero ter ajudo, qualquer dúvida estou à disposição.
Comment: Fiz como me indicou, porem ele esta vindo um pouco fora do que eu estou tentando conseguir.
Adicionei em o retorno do seu exemplo na sua resposta.
Comment: Crie dois exemplos abaixo, qual dos dois atende?
Comment: var result = db.LocTag.Where(x => x.Locais.Tipo_Local == Nome)
                .Select(c => new { Locais = new {
                    ID_Local = c.Locais.ID_Local,
                    Nome_Local = c.Locais.Nome_Local,
                    Tag = c.Tags
                } }).ToList();
Comment: var res = db.LocTag.Where(x => x.Locais.Tipo_Local == Nome)
                .Select(c => new {
                    ID_Local = c.Locais.ID_Local,
                    Nome_Local = c.Locais.Nome_Local,
                    Tag = c.Tags
                }).ToList();

            var result = new { Locais = res };
Comment: Me avisa assim vou alterar a resposta
Comment: Perdão pela demora na resposta, estava sem internet. Os retornos não atenderam o modelo que eu necessitava no retorno. Utilizei um for each para aninhar o retorno que você me deu com o modelo que necessitava como medida para dar continuidade nos meus estudos.
Comment: Beleza cara, qualquer dúvida estou à disposição

C# join 3 tabelas utilizando Linq?


Windows script to change from DHCP to Static IP addressing

Question: I need a (WSH) script that clients can execute on their machines themselves and with a minimum of hassle and without me requiring any special privileges. The script should take the existing IP address, subnet mask and default gateway of the ethernet adapter and set these as static parameters. I also need a script to be able to undo this. I have figured out how to set the parameters manually on the command line using the netsh command i.e.
netsh.exe interface ip set address {Interface} static {IP} {SUB} {DEF} 1

However I suspect that this could be done automatically with a WSH script. The clients are either XP/Vista/Windows 7. What would be the best way to accomplish this?
Comment: Does the script need to poll the workstation for the address information (i.e. make a WMI query), then use this to set the static value?  Are you trying to move from DHCP to static?  How are you handling the DHCP pool once the address is migrated?
Comment: The script needs to be executed by our home customers to whose machines we have no access to. We intend to distribute it via a downloads page on our website. Our application requires that the customer switches to static networking before running the app and then switching back afterward.
Answer: strComputer = "."
Set objWMIService = GetObject("winmgmts:\\"& strComputer & "\root\cimv2")
Set colAdapters = objWMIService.ExecQuery _
    ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")

n = 1

For Each objAdapter in colAdapters
If (objAdapter.DHCPEnabled) Then
    If Not IsNull(objAdapter.IPAddress) Then
   For i = 0 To UBound(objAdapter.IPAddress)
    IPAddress = objAdapter.IPAddress(i)
   Next
End If

If Not IsNull(objAdapter.IPSubnet) Then
   For i = 0 To UBound(objAdapter.IPSubnet)
    SubNet = objAdapter.IPSubnet(i)
   Next
End If

If Not IsNull(objAdapter.DefaultIPGateway) Then
   For i = 0 To UBound(objAdapter.DefaultIPGateway)
      GateWay = objAdapter.DefaultIPGateway(i)
   Next
End If

If Not IsNull(objAdapter.DNSServerSearchOrder) Then
   For i = 0 To UBound(objAdapter.DNSServerSearchOrder)

   Next
End If

If Not IsNull(objAdapter.DNSDomainSuffixSearchOrder) Then
   For i = 0 To UBound(objAdapter.DNSDomainSuffixSearchOrder)
      WScript.Echo "    DNS suffix search list: " & _
          objAdapter.DNSDomainSuffixSearchOrder(i)
   Next
End If

objAdapter.DHCPEnabled = false
  If Not IsNull(objAdapter.DHCPLeaseObtained) Then
     utcLeaseObtained = objAdapter.DHCPLeaseObtained
  Else
     strLeaseObtained = ""
  End If

  If Not IsNull(objAdapter.DHCPLeaseExpires) Then
     utcLeaseExpires = objAdapter.DHCPLeaseExpires

  Else
     strLeaseExpires = ""
  End If
  WScript.Echo "    DHCP lease expires:  " & strLeaseExpires

n = n + 1

'netsh interface ip set address "Local Area Connection" static objAdapter.IPAddress(i) objAdapter.IPSubnet(i) objAdapter.DefaultIPGateway(i) 1

Dim WshShell, oExec, A
Set WshShell = CreateObject("WScript.Shell")

WScript.Echo "  IP address:             " & IPAddress
WScript.Echo "  Subnet:                 " & Subnet
WScript.Echo "  Default gateway:        " & Gateway

A = "netsh interface ip set address " & Chr(34) & "Local Area Connection" & Chr(34) & " static " & IPAddress & " " & Subnet & " " & Gateway & " 1"
wscript.echo A
Set oExec = WshShell.Exec(A)

  WScript.Echo "before runnig this script on the network take out all wscripts enjoy LCpl Worsnop"
End If
next

Comment: This script doesn't work. It only detects an ipv6 address since it just records the last ip in the objAdapter.IPAddress array. Also why does it need to know the DNS search order, DNS suffix search order, DHCP lease times?


How can I get my messages to show up properly?

Question: I have two buttons - one that sends two messages with a one-second interval, and the other only sends one message, with the second left as undefined (this will be clearer once you see the code). How do I stop undefined from showing up?

var credits = 0;
var currency = 'Skatter';

function addLog(logBefore, logAfter) {
  var par = document.createElement("p");
  var node1 = document.createTextNode(logBefore);
  var node2 = document.createTextNode(logAfter);
  par.appendChild(node1);

  var element = document.getElementById("logs");
  // Here you can also use element.childNodes.length
  const count = document.getElementById("logs").getElementsByTagName("p").length;
  if (count >= 18) {
    element.removeChild(element.childNodes[0]);
  }
  element.appendChild(par);

  if (node2 !== undefined) {
    setTimeout(function() {

      console.log(logBefore)
      console.log(logAfter)

      var par = document.createElement("p");
      var node2 = document.createTextNode(logAfter);
      par.appendChild(node2);

      var element = document.getElementById("logs");
      // Here you can also use element.childNodes.length
      const count = document.getElementById("logs").getElementsByTagName("p").length;
      if (count >= 8) {
        element.removeChild(element.childNodes[0]);
      }
      element.appendChild(par);
    }, 1000);
  }
};
<button onclick="addLog('Hunt begun', 'Hunt successful! You now have ' + credits + ' ' + currency)">HUNT</button>

<button onclick="addLog('Resources sold')">SELL</button>

Comment: Your getting the undefined message on the second calling of your `addLog` function, as the second parameter in the function on the second call expects two params, it is ***undefined***, non-existent...
Comment: but shouldnt it skip over the if statement if its blank?
Answer: On the second button you are passing just one argument to the addLog function.
Answer: The core problem with your code is that you are asking if node2 variable you have created is falsey (evaluates to false), but a text node will never evaluate to false because it is an object which holds values
// try this in your browser console
>>> if (document.createTextNode(undefined)) {
console.log("not null")
}
>>> "not null" //output

If you want to check if the program gave a value for the second parameter (logAfter), then you should, explicitly do this instead, like:
if (logAfter !== undefined) {
    // do stuff
}

Answer: You should change the conditional to check if the direct log logAfter is not undefined, not the textNode. This will fix you issue...

var credits = 0;
var currency = 'Skatter';

function addLog(logBefore, logAfter) {
  var par = document.createElement("p");
  var node1 = document.createTextNode(logBefore);
  var node2 = document.createTextNode(logAfter);
  par.appendChild(node1);

  var element = document.getElementById("logs");
  // Here you can also use element.childNodes.length
  const count = document.getElementById("logs").getElementsByTagName("p").length;
  if (count >= 18) {
    element.removeChild(element.childNodes[0]);
  }
  element.appendChild(par);

  if (logAfter !== undefined) {
    setTimeout(function() {

      var par = document.createElement("p");
      var node2 = document.createTextNode(logAfter);
      par.appendChild(node2);

      var element = document.getElementById("logs");
      // Here you can also use element.childNodes.length
      const count = document.getElementById("logs").getElementsByTagName("p").length;
      if (count >= 8) {
        element.removeChild(element.childNodes[0]);
      }
      element.appendChild(par);
    }, 1000);
  }
};
<button onclick="addLog('Hunt begun', 'Hunt successful! You now have ' + credits + ' ' + currency)">HUNT</button>

<button onclick="addLog('Resources sold')">SELL</button>


How can I rearrange a menu link programmatically?

Question: I created Menu Link Content entities and saved them in a menu.
$menu_link = MenuLinkContent::create([
  'title' => 'Menu item',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'internal:/']],
  'menu_name' => 'testing',
])->save();

$menu_link_2 = MenuLinkContent::create([
  'title' => 'Menu item',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'internal:/']],
  'menu_name' => 'testing',
])->save();

How can I rearrange $menu_link_2 to be a child of $menu_link?
Looking at menu_ui, they seem to update Menu Link Content in a given order, and then rebuild the menu tree; finally, the Menu entity is saved.
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_link_manager->updateDefinition($menu_link_2->getPluginId(), [
  'parent' => $menu_link->getPluginId(),
]);

How can I rebuild the menu tree and save the menu?
Why? I'm writing a Kernel test for a module that fires when the menu link content has been saved AND then when the Menu itself has been saved.
Answer: You can rearrange a custom menu link when you set the 'weight' of the menu. See below code.

$menu_link = MenuLinkContent::create([
  'title' => 'Menu item',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'internal:/']],
  'menu_name' => 'testing',
  'weight' => 0,
])->save();
$menu_link_2 = MenuLinkContent::create([
  'title' => 'Menu item',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'internal:/']],
  'menu_name' => 'testing',
  'weight' => 0,
])->save();
Comment: that's not what he's asking for, it's about nesting, not the weight
Comment: yes and no. In the title its about sorting. I came here for sorting an this is just what i wanted to know.
Answer: Some nice helpers for rearranging existing menus programmatically.
https://www.drupal.org/project/codit_menu_tools


How to show $\frac 1 e \sum\limits_{n=0}^{+\infty}\frac{n^x}{n!}$ is always an integer for $x \in \mathbb N$

Question: The series $$\frac 1 e \sum_{n=0}^{+\infty}\frac{n^x}{n!}$$ converges to an integer by some of my computations using wolfram alpha with $x \in \mathbb{N}$. I don't succed to show that this series is always integer by evaluating using the partial sum of it because the partial sum is complicated for every integer $x \geq 0$ .Then I have this question:
What is the partial sum of :$$\frac 1 e \sum_{n=0}^{+\infty}\frac{n^x}{n!}$$
for fixed integer $x$ such that $0\leq x < n$ and how I can prove it always integer ?
Comment: You wrote an infinite sum.  If you meant something else, you should edit.
Comment: @zeraoulia rafik:  I am confused.  If $x$ is an integer, then any finite sum of the form $\sum_{n=0}^N \frac{n^x}{n!}$ is a positive rational.  In particular $\frac{1}{e}$ times this sum is irrational, so not an integer.  What am I missing?
Comment: @lulu:  zeraoulia asks about the partial sums of the series.  That said, I agree that $x< n$ is meaningless.
Comment: I think you are confused.  The $x<n$ bit doesn't mean anything and you should remove it.  As to your sum, these are the [Bell Numbers](http://mathworld.wolfram.com/BellNumber.html) and the formula you want can be found on the page I linked to.
Comment: [here](https://oeis.org/search?q=1%2C2%2C5%2C15%2C52%2C203&language=english&go=Search) is the OEIS reference for the values.
Comment: $n$ is a dummy summation variable.  What does it mean to say $x<n$?
Comment: I meant the sum can't up to n^n/n!
Comment: @ for every fixed integer x we have  an integer sum
Comment: I have no idea what you are talking about.  You've written an infinite sum.  Maybe you have something else in mind, who knows?  Perhaps it would help if you wrote out an explicit example.  What happens if $x=2$, say?
Comment: @JasonDeVito, Try to fix x
Comment: $x$ is fixed in my comment (although my comment still applies if $x$ is allowed to vary, so long as it stays in integer). Could you do as @lulu asks and write out an explicit example?
Comment: @JasonDeVito see this : for x=2 ,https://www.wolframalpha.com/input/?i=(1%2Fe)sum(+n%5E2%2Fn!)),+n%3D0+to+infty
Comment: Maybe OP means: find a formula for the partial sums so that he/she can prove the infinite series converges to an integer, or maybe not, since $x<n$ thing still doesn't make sense.
Comment: @lulu, Thanks , and they are the same values i have got for every integer x
Comment: From you link, you don't mean partial sums at all - you mean the full infinite series.  I still don't understand what $x<n$ means in this context.
Answer: You are dealing with Touchard polynomials. We have
$$ \sum_{n\geq 0}\frac{e^{nz}}{n!} = \exp\left(e^z\right)$$
and by applying $\frac{d^m}{dz^m}$ to both sides we get
$$ \sum_{n\geq 0}\frac{n^m e^{nz}}{n!} = Q_m(e^z)\cdot\exp\left(e^z\right),\qquad Q_m(x)\in\mathbb{Z}[x] $$
so the evaluation at $z=0$ leads to
$$ \frac{1}{e}\sum_{n\geq 0}\frac{n^m}{n!} = Q_m(1)\in\mathbb{Z} $$
as wanted.
Answer: $\def\e{\mathrm{e}}$Denote$$
S_m = \frac{1}{\e} \sum_{k = 0}^\infty \frac{1}{k!} \prod_{j = 0}^{m - 1} (k - j),
$$
then$$
S_m = \frac{1}{\e} \sum_{k = m}^\infty \frac{1}{k!} \prod_{j = 0}^{m - 1} (k - j) = \frac{1}{\e} \sum_{k = m}^\infty \frac{1}{(k - m)!} = \frac{1}{\e} \sum_{k = 0}^\infty \frac{1}{k!} = 1 \in \mathbb{Z}.
$$
Now denote$$
T_m = \frac{1}{\e} \sum_{k = 0}^\infty \frac{k^m}{k!}.
$$
Note that for any $m \in \mathbb{N}$, $T_m$ is a linear combination of $T_0, \cdots, T_{m - 1}, S_m$ with combination coefficients being integers, by induction on $m$, $T_m \in \mathbb{Z}$.
Answer: For any integer $x \ge 0$, let:
$$T(x) = \sum_{ n \ge 0 } \frac{n^x}{n!}$$
Then you have $T(0) = \sum_\limits{ n \ge 0 } \frac{1}{n!} = e $, and for any integer $x\ge0$,
$$
T(x+1) = \sum_\limits{ n \ge 0 } \frac{n^{x+1}}{n!} = \sum_\limits{ n \ge 0 } \frac{ n \cdot n^x}{n!} = \sum_\limits{ n \ge 1 } \frac{n^x}{(n-1)!} = \sum_\limits{ n \ge 0 } \frac{(n+1)^x}{n!}
$$
Now you can expand the inner term using the binomial theorem to get a recurrence formula:
$$
T(x+1) =
\sum_\limits{ n \ge 0  }\sum_\limits{ 0 \le k \le x } \frac{C_k^x \cdot n^k}{n!} =\sum_\limits{ 0 \le k \le x }  C_k^x \sum_\limits{ n \ge 0  } \frac{ n^k}{n!}
= \sum_\limits{ 0 \le k \le x }  C_k^x \cdot  T(k)
$$
Therefore, you can easily show that $T(x)$ is an integer multiple of $T(0) = e$ for any $x \in \mathbb{N} $.


How to access iphone camera from server-side web page?

Question: How to access iphone camera from webapp(server-side web)? (ex asp,php,jsp)
Comment: I guess there is no way to access local resources of iPhone eg Camera, Files  using Web.So why Native App comes in picture to access local resources.
Answer: It's not possible for code running on a server to access an iPhone's camera.
It's not even possible for client-side web-app code (Javascript, HTML, CSS) to access the camera.
You'll need to write a full native app to be able to work with the camera. If you'd still like to be able to use web-technologies to do this, have a look at PhoneGap: http://phonegap.com/
PhoneGap makes it easier to write an app that loads a web page, but allows for access to device native APIs. Building the user interface will be more difficult though.
Comment: This answer is outdated and incorrect.
Answer: it is possible to  access camera in iOS
First, in HTML body use video tag as below
<video id="video" class="video" height="400" width="400" playsinline autoplay muted loop></video>

this will ask permission to access the camera
Then in JavaScript, by using video element, display the video on the video tag
var video = document.getElementById("video");

navigator.mediaDevices.getUserMedia({video: true, audio: false})
    .then(function(s) {
    stream = s;
    video.srcObject = s;
    video.play();
  })


Save java Bitset Object in mongoDB

Question: I am using mongoDB in java. I want to save java Bitset object in DB, but while performing table.insert(doc) I am getting IllegalArgumentException.
Error :

java.lang.IllegalArgumentException: can't serialize class java.util.BitSet
  org.bson.BasicBSONEncoder._putObjectField(BasicBSONEncoder.java:234)
Answer: See this question.
Basically, turn your BitSet into a long or byte array, and save that, converting back when you retrieve it.
Comment: Current I am doing the same i.e. using Byte array. But is there some way I can directly save Bitset Object and not converting it in any other form.
Comment: No. Which is obvious if you look at the BSON spec. Only BSON native types will be directly converted from their Java counterparts. All other types have to be converted to one of the BSON types at the application level.
Comment: We can use third party library for converting java objects to mongo type. In my case I used [morphia](http://code.google.com/p/morphia/)

Save java Bitset Object in mongoDB


In a linear program, how to add a conditional bound to x?

Question: I am working with a standard linear program:
$$\text{min}\:\:f'x$$
$$s.t.\:\:Ax = b$$
$$x ≥ 0$$
Goal: I want to enforce all nonzero solutions $x_i\in$ x to be greater than or equal to a certain threshold "k" if it's nonzero. In other words, I want to add a conditional bound to the LP: if any $x_i$ is > 0, enforce $x_i$ ≥ k.
Main issue: Is there a way to set up this problem as an LP? Any alternate approaches? Any input would be appreciated and I'm happy to provide any additional info as needed! Thanks!
Comment: This is not possible in linear programming. If you consider $k=1$ and add another linear constraint $x\le1$, the problem becomes $0$-$1$ integer linear programming, which is NP-hard.
Comment: Linear programs permit linear objectives and linear equations and inequality constraints---and that's it. Integer linear programs allow all of these, *plus* integrality constraints on the variables. It is a larger modeling space. And as you rightly point out, models with integer constraints cannot be solved with standard LP machinery (simplex or interior-point methods).
Comment: I just realized that... My understanding was that an LP had linear objective + linear constraints (which is correct).  However, adding the integer constraint is not linear.
Comment: A constraint like that is no longer linear, so it cannot be formulated as a linear program (of any kind).
Comment: @TravisJ no. An ILP is not an LP, but an LP is an ILP.
Comment: @MichaelGrant, would you mind explaining why?  Naively, I believed that the "LP" in "ILP" sort of implied that "ILP" was a subset of "LP" (granted the same methods to solve "real" LP's cannot be applied to "integer" LP's).
Answer: This cannot be solved with linear programming, but it can be solved with mixed-integer linear programming (MILP). What you are looking for is something called a semicontinuous variable in the MILP community. A semicontinuous variable $x$ is constrained to the disjoint set
$$x\in\{0\}\cup[\ell,u] \qquad\text{or}\qquad x\in\{0\}\cup[\ell,+\infty),$$
where $0<\ell<u$.
This kind of construct occurs commonly in practice. For example, consider a portfolio design problem in which a particular investment can only be purchased if you are willing to allocate a certain minimum amount to it---say, 10K USD. Any amount above that minimum is permissible: so 9.9K is not acceptable, but 10.1K and 100K are. This kind of constraint is naturally modeled with a semicontinuous variable.
Many MILP solvers such as CPLEX, Gurobi, and even lp_solve handle them explicitly. The method for specifying semicontinuity and the bounds $\ell,u$ depend on the specific solver, so you'll need to consult the documentation for the solver of your choice.
With solvers like, say, MOSEK that do not specifically handle semicontinuity, the case with the upper-bound is readily handled with the pair of inequalities
$$\ell z\leq x \leq u z$$
where $z\in\{0,1\}$ is an additional binary variable. If you don't have an upper bound, then you must take ChrKroer's approach and select an arbitrary one. Try not to make it any larger than necessary to preserve the solution set.
As you can see, the advantage to handling semicontinuity explicitly is that it can handle the $u=\infty$ case. Computationally both introduce a single branch into the problem, so I suspect there is no consistent performance benefit to one or the other, but I do not have the experience to say for sure.
Google searches for "semicontinuous variables" or "semi-continuous variables" turn up a wealth of useful results. There is also the notion of a semi-integer variable: as its name implies, it combines a semicontinuous constraint with an integrality constraint.
Answer: Like Rahul mentioned  in a comment to your question, this is not possible (incidentally, I do not agree with TravisJ's comment that an ILP is a special case of an LP. Rather, an LP is a special case of a mixed-integer linear program, of which integer-linear programming is also a special case. But I do not have enough points to comment yet). However, all is not necessarily lost.
If your goal is to solve some practical problem (rather than showing that this can be solved through linear programming), modeling your problem as a mixed-integer linear program and solving that instead might actually work. Solvers such as CPLEX and Gurobi are surprisingly fast.
If you have some a priori upper bound $M_i$ on each $x_i$, you could do the following: for each $x_i$, you can introduce a boolean variable $b_i$ and have the constraints:
$x_i\geq k\cdot b_i$, $x_i \leq M_i\cdot b_i$.
Comment: ... except that you need an a  priori bound $M$ for $x_i$.  If you don't have that, you could make $b_i$ an integer variable instead, and then have $x_i \le 2 k b_i$ instead of $x_i \le M b_i$.
Comment: Yes, that is true. I added that to my explanation. Your solution could lead to more branching, does it usually lead to worse practical performance in your experience?


How to Vertically and Horizontally align Modal in react native

Question: I am trying to write a signup form and its loading screen modal.
For some reason the modal is not vertically and horizontally align
<code><View style={{flex: 1,flexDirection: 'column',alignItems: 'center'}}>

      <View>
         <Text>Something</Text>
         <Text>Something</Text>
         <Text>Something</Text>
         <Text>Something</Text>
         <Text>Something</Text>

        <TouchableOpacity style={styles.button} onPress={() => alert('hello')}>
          <Text style={styles.button_text}>CREATE YOUR NEW ACCOUNT</Text>
        </TouchableOpacity>
      </View>

      <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
        <Modal
          animationType="slide"
          transparent={true}
          visible={modalVisible}
          onRequestClose={() => {
            Alert.alert('Modal has been closed.');
            setModalVisible(!modalVisible);
          }}>
          <View
            style={{width: 300, height: 300, backgroundColor: 'red'}}></View>
        </Modal>
      </View>
    </View>
</code>
Can someone help please, here is how current situation is,
I want the modal to horizontally and vertically align in the screen
Answer: Try this
<code>    <Modal
      animationType="slide"
      transparent={true}
      visible={modalVisible}
      onRequestClose={() => {
        Alert.alert('Modal has been closed.');
        setModalVisible(!modalVisible);
      }}>
      <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
         <View style={{width: 300, height: 300, backgroundColor: 'red'}}>
            ...other components you need
         </View>
      </View>
    </Modal>
</code>


Database of Latin Church Music

Question: Wondering if there is an online (and free or open source) database/collection of Latin Church music. By that I mean, Gregorian Chant type stuff like this, other monophonic chanting (stuff from 1000-1500CE), or even modern liturgical stuff like the latin songs you would hear in a large Church today (I'm not sure what these really sound like or if they are polyphonic or not). But basically some sort of melodies in the Latin churches. It sounds like it could be polyphonic as well.
Basically just looking for any available sheet music for stuff like that.
Comment: I'm voting to close this question as off-topic because requests for off-site resources are off-topic.
Answer: I can think of two resources, though neither are exclusively dedicated to Latin church music.

IMSLP, a very large online library of public domain scores, has a
category page for plainchant.
Hymnary.org's advanced search allows you to choose a language, so you can search for only Latin hymnals.
Comment: Oh this is great: https://imslp.org/wiki/Category:Scores :)
Comment: @LancePollard The [Choral Public Domain Library](https://www.cpdl.org/wiki/) might also be of interest.
Comment: https://gregobase.selapa.net/

Database of Latin Church Music


Setting the action text in JSP page in Struts2

Question: I have in my properties file:
viewType.periodText=Period Report
viewType.periodValue=periodreport

and in JSP I am doing this:
<s:radio theme="simple" name="webAcModel.reportView"
list="#{'%{getText('viewType.periodValue')}':
      '%{getText('viewType.periodText')}'}"></s:radio>

but it is giving me an error. But if I do this:
<s:radio theme="simple" name="webAcModel.reportView"
list="#{'periodreport':'Period Report'}"></s:radio>

it works fine.
Any idea how can I do this?
Answer: Too many symbols. There is no need for %{} inside #{} and since getText returns string '' are not needed too.
<s:radio theme="simple" name="webAcModel.reportView"
          list="#{getText('viewType.periodValue'):
                  getText('viewType.periodText')}" />

BTW using getText for the submitted value from radio button isn't the best approach IMO.
Comment: @Haider **One** of the solutions is to set some variable in your JSP that will hold the required value (like this: ``) and reference it then as needed (e.g. `Alias value: `)
Comment: @Haider: To make it consistent you should use some fixed key and not a property from the resources bundle. Don't forget to accept/upvote answers that helped you.
Comment: thanks, i didnt mentioned in the question that there is also a grid that will be shown/hide on basis of these and also queries will be runned according to the selected so to make it consistent i used this approach.
Comment: e.g if i declare these keys in class e.g class Constant { public String peridvalue = "periodreport"  } then how i i use it ?
Comment: @Haider: Declare it like `static final` and use it.
Comment: in my class i have public static final String periodreport = "periodreport"; now when i use this  the condition is not true??
Comment: {@com.packagename.models.UsernameModel$UsernameTypes@ALIAS is there a short way to write this eacuse i am using it many times


É possível contabilizar visitantes de busca orgânica?

Question: Gostaria de saber se há alguma ferramenta/api para saber a partir de que site o visitante veio, para contabilizar os visitantes vindos dos motores de busca. Obrigado à todos.
Answer: HTTP_REFERER

'HTTP_REFERER'
O endereço da página (se houver) através da qual o agente do usuário acessou a página atual. Essa diretiva é informada pelo agente do usuário. Nem todos os browsers geram esse header, e alguns ainda possuem a habilidade de modificar o conteúdo do HTTP_REFERER como recurso. Em poucas palavras, não é confiável.

Basta usar como abaixo, mas não confie nestes dados.
$origem = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : null;


Read CSV with Spark

Question: I am reading csv file through Spark using the following.
rdd=sc.textFile("emails.csv").map(lambda line: line.split(","))

I need to create a Spark DataFrame.
I have converted this rdd to spark df by using the following:
dataframe=rdd.toDF()

But I need to specify the schema of the df while converting the rdd to df. I tried doing this: (I just have 2 columns-file and message)
from pyspark import Row

email_schema=Row('file','message')

email_rdd=rdd.map(lambda r: email_schema(*r))

dataframe=sqlContext.createDataFrame(email_rdd)

However, I am getting the error:
java.lang.IllegalStateException: Input row doesn't have expected number of values required by the schema. 2 fields are required while 1 values are provided.
I also tried reading my csv file using this:
rdd=sc.textFile("emails.csv").map(lambda line: line.split(",")).map(lambda line: line(line[0],line[1]))

I get the error: TypeError: 'list' object is not callable
I tried using pandas to read my csv file into a pandas data frame and then converted it to spark DataFrame but my file is too huge for this.
I also added :
bin/pyspark --packages com.databricks:spark-csv_2.10:1.0.3

And read my file using the following:
df=sqlContext.read.format('com.databricks.spark.csv').options(header='true').load('emails.csv')

I am getting the error:
java.io.IOException: (startline 1) EOF reached before encapsulated token finished
I have gone through several other related threads and tried as above. Could anyone please explain where am I going wrong?
[Using Python 2.7, Spark 1.6.2 on MacOSX]
Edited:
1st 3 rows are as below. I need to extract just the contents of the email. How do I go about it?
1   allen-p/_sent_mail/1.   "Message-ID: <18782981.1075855378110.JavaMail.evans@thyme>
Date: Mon, 14 May 2001 16:39:00 -0700 (PDT)
From: email@example.com
To: firstname.lastname@example.com
Subject:
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
X-From: Phillip K Allen
X-To: Tim Belden
X-cc:
X-bcc:
X-Folder: \Phillip_Allen_Jan2002_1\Allen, Phillip K.\'Sent Mail
X-Origin: Allen-P
X-FileName: pallen (Non-Privileged).pst
Here is our forecast"
2   allen-p/_sent_mail/10.  "Message-ID: <15464986.1075855378456.JavaMail.evans@thyme>
Date: Fri, 4 May 2001 13:51:00 -0700 (PDT)
From: email@example.com
To: firstname.lastname@example.com
Subject: Re:
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
X-From: Phillip K Allen
X-To: John J Lavorato
X-cc:
X-bcc:
X-Folder: \Phillip_Allen_Jan2002_1\Allen, Phillip K.\'Sent Mail
X-Origin: Allen-P
X-FileName: pallen (Non-Privileged).pst
Traveling to have a business meeting takes the fun out of the trip.  Especially if you have to prepare a presentation.  I would suggest holding the business plan meetings here then take a trip without any formal business meetings.  I would even try and get some honest opinions on whether a trip is even desired or necessary.
As far as the business meetings, I think it would be more productive to try and stimulate discussions across the different groups about what is working and what is not.  Too often the presenter speaks and the others are quiet just waiting for their turn.   The meetings might be better if held in a round table discussion format.
My suggestion for where to go is Austin.  Play golf and rent a ski boat and jet ski's.  Flying somewhere takes too much time."
3   allen-p/_sent_mail/100. "Message-ID: <24216240.1075855687451.JavaMail.evans@thyme>
Date: Wed, 18 Oct 2000 03:00:00 -0700 (PDT)
From: email@example.com
To: firstname.lastname@example.com
Subject: Re: test
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
X-From: Phillip K Allen
X-To: Leah Van Arsdall
X-cc:
X-bcc:
X-Folder: \Phillip_Allen_Dec2000\Notes Folders\'sent mail
X-Origin: Allen-P
X-FileName: pallen.nsf
test successful.  way to go!!!"
Comment: could you print a sample of the first five rows from` emails.csv` (anonymyzing the data as required)?
Comment: `line(line[0],line[1])`.. That outside usage of `line()` means you are trying to call a list object, thus the error
Answer: If the RDD will fit in memory, then:
rdd.toPandas().to_csv('emails.csv')

If not, use spark-csv for your version of spark:
rdd.write.format('com.databricks.spark.csv').save('emails.csv')

In your example above:
rdd=....map(lambda line: line.split(",")).map(lambda line: line(line[0],line[1]))

don't you want:
rdd=....map(lambda line: line.split(",")).map(lambda line: (line[0], line[1]))

Comment: How do I attach the com.databricks.spark.csv library to spark? I have used the format specified in my post. Do you know where am I going wrong? And, I am trying to read the file.
Comment: Thanks @Alexander. I fixed it. But now while reading the file I get java.lang.IllegalStateException: Input row doesn't have expected number of values required by the schema. 2 fields are required while 1 values are provided. I have edited my post to show my 1st 3 rows. 1st column is file which is just 1, 2 ,3 in bold. And 2nd column is message which contains all message contents. Could you please tell me how can I correct this to incorporate the 2 columns as is?
Answer: If you have a huge file, why not use a pandas dataframe in chunks rather than loading all of it at once, something like :
import pandas as pd
df_pd = pd.read_csv('myfilename.csv',chunksize = 10000)

for i,chunk in enumerate(df1):
    if i==0:
        df_spark = sqlContext.createDataFrame(chunk)
    else:
        df_spark = df_spark.unionAll(sqlContext.createDataFrame(chunk))

df_spark would be your required spark dataframe. This is inefficient but it would work. For some other methods of implementing the same you can refer answers to this question
Another possible method is to use the inferSchema method of the rdd, but you need to have column names in your csv file for this to work, refer to this.
So you can do something like:
srdd = inferSchema(rdd)
email_rdd=rdd.map(lambda r: srdd(*r))

dataframe=sqlContext.createDataFrame(email_rdd)

Read CSV with Spark


Krull dimension of affine open subscheme of Noetherian scheme containing the generic points of all irreducible components

Question: Let $X$ be a reduced Noetherian scheme. It has finitely many irreducible components $\{X_j \}_{j=1}^n$. Let $x_j$ be the generic point of $X_j$. If $U$ is an affine open subset of $X$ containing every $x_j$, then is it true that $\dim U=\dim X$?
Somehow, I am not sure of this even when $X$ is affine.
Please help.
Answer: No, this is not true in general. Let $X=\operatorname{Spec} k[t]_{(t)}$. Then $D(t) = \operatorname{Spec} k(t)$ is an affine open subset containing the generic point (in fact, it's just the generic point) but of dimension zero, whereas $X$ is of dimension one.
This is true if $X$ is a scheme (locally) of finite type over a field, though. In this case, the dimension of an irreducible component is the transcendence degree over $k$ of the residue field at the generic point of that component, and this is clearly preserved when passing from $X$ to $U$.


Changing the visibility of sliders in JSXGraph

Question: I'm using JSXGraph to create a bunch of sliders, whose visibility is supposed to be changed by a checkbox. Unfortunately, setAttribute() does not really work. It only changes the visibility of the "head" of the slider, but not of its range. Here is an example of my code in javascript:
ctx.slider_A = ctx.box_left.create("slider", [[50, 50], [230, 50], [0, 0.4, 1]],
                {withLabel: false, snapWidth: 0.05, fillColor: ctx.textColor, visible: false});

function sliderVisibility(){
    var Checkbox = getElementById("check");
    if (Checkbox.checked == true) {
         ctx.slider_A.setAttribute({visible: true});
    }else{
         ctx.slider_A.setAttribute({visible: false});
    }
}

Does anyone know the problem? I'd be very thankful for any help.
Answer: I managed to solve it myself, even though the JSXGraph-documentation (https://jsxgraph.uni-bayreuth.de/docs/symbols/Slider.html) did not really help me. I made the mistake of assuming that a slider was treated as a single object, but it actually consists of four parts: the slider itself (the thing that I previously referred to as "head"), the baseline, the highline, and the ticks of the baseline. If you want to change the visibility of the whole thing, you need to change it for each component.
I don't know whether there is a more elegant way to do this (I'm pretty sure there is, but for me this solution is sufficient), but here's how I did it:
function sliderVisibility(){
    var Checkbox = getElementById("check");
    if (Checkbox.checked == true) {
         ctx.slider_A.setAttribute({visible: true});
         ctx.slider_A.baseline.setAttribute({visible:true});
         ctx.slider_A.highline.setAttribute({visible:true});
         ctx.slider_A.ticks.setAttribute({visible:true});
    }else{
         ctx.slider_A.setAttribute({visible: false});
         ctx.slider_A.baseline.setAttribute({visible:false});
         ctx.slider_A.highline.setAttribute({visible:false});
         ctx.slider_A.ticks.setAttribute({visible:false});
    }
}

Answer: Here is another solution (which works at least with v1.00+):
    var s1 = board.create('slider', [[-3,1], [2,1],[-10,1,10]], {
            name: 'A',
            visible: true,
            baseline: {visible: 'inherit'},
            highline: {visible: 'inherit'},
            label: {visible: 'inherit'}
        });

Then, toggling should be possible with
    s1.setAttribute({visible: false});


How do I run bat file inside cmd using tash scheduler

Question: How do I run bat file inside cmd using tash scheduler. I've tried this one
C:\windows\system32\cmd.exe C:\synchronization.bat
And doesn't working.
Comment: I found working method
`cmd /k mybatfile.bat`
Answer: You can use
cmd /c mybatfile.bat

to run a command and terminate the cmd shell or
cmd /k mybatfile.bat

to run a command and keep the cmd shell.