How to configure dual homed server in order for both network segments to communicate?

Question: We want to add an additionnal network segment (LAN2) and need some machines on LAN1 to access ressources on LAN2. Some machines on LAN2 also need to access ressources on LAN1 and the WAN segment. Gateway between LAN1 and LAN2 is called "SRV-01", a dual homed Linux server.
I can't access LAN2 from LAN1 or LAN1 from LAN2 neither WAN from LAN2. I wonder how to make LAN1 hosts and LAN2 talk together and also how to allow access to the WAN from LAN2 machines.
Troubleshooting
I get the following replies using ping:

IP             (source)         ---> IP           (destination)    : Ping reply
---------------------------------------------------------------------------
192.168.5.33   (client on LAN1) ---> 192.168.5.8  (SRV-01:eth0)    : OK
192.168.5.33   (client on LAN1) ---> 10.0.2.1     (SRV-01:eth1)    : NO
192.168.5.33   (client on LAN1) ---> 10.0.2.2     (SRV-02:eth0)    : NO
*.*.*.*.*      (SRV-01)         ---> 192.168.5.33 (client on LAN1) : OK
*.*.*.*.*      (SRV-01)         ---> 10.0.2.2     (SRV-02:eth0)    : OK
10.0.2.2       (SRV-02)         ---> 10.0.2.1     (SRV-01:eth1)    : OK
10.0.2.2       (SRV-02)         ---> 192.168.5.8  (SRV-01:eth0)    : OK
10.0.2.2       (SRV-02)         ---> 192.168.5.33 (client on LAN1) : NO

Network topology

WAN --- (ISP Router) --- LAN1 --- (SRV-01) --- LAN2 --- (SRV-02)

ISP Router
Internet service provider (ISP) router provides NAT (two network adapters) and act as a DHCP server for LAN1. We have no shell/admin access to this equipment.

xxx.xx.xx.xx/xx (eth0, WAN)
192.168.5.4/24  (eth1, LAN1)

SRV-01 server
SRV-01 is a dual homed Ubuntu Server 14.04 (two network adapters) which would act as a gateway between LAN1 subnet and LAN2 subnet.

192.168.5.8/24 (eth0, LAN1)
10.0.2.1/24    (eth1, LAN2)

/etc/network/interfaces
# Loopback
auto lo
iface lo inet loopback
# LAN1
auto eth0
iface eth0 inet static
    address 192.168.5.8
    netmask 255.255.255.0
    network 192.168.5.0
    broadcast 192.168.5.255
    gateway 192.168.5.4
    dns-nameservers xxx.xxx.xxx.xxx
# LAN2
auto eth1
iface eth1 inet static
    address 10.0.2.1
    netmask 255.255.255.0
    network 10.0.2.0
    broadcast 10.0.2.255
    dns-nameservers xxx.xxx.xxx.xxx

Routing

~$ netstat -r
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
default         192.168.5.4     0.0.0.0         UG        0 0          0 eth0
10.0.2.0        *               255.255.255.0   U         0 0          0 eth1
localnet        *               255.255.255.0   U         0 0          0 eth0

~$ ip route show
default via 192.168.5.4 dev eth0
10.0.2.0/24 dev eth1  proto kernel  scope link  src 10.0.2.1
192.168.5.0/24  dev eth0  proto kernel  scope link  src 192.168.5.8

IP forwarding

~$ sudo sysctl -a | grep net.ipv4.ip_forward
net.ipv4.ip_forward = 1
net.ipv4.ip_forward_use_pmtu = 0

Firewall
Ubuntu "Uncomplicated FireWall" (UFW) is disabled on server "SRV-01" and all iptables chains have a default policy set to ACCEPT target. Note that no single packet made his way to the FORWARD table yet...

~$ sudo ufw status
Status: inactive

~$ sudo iptables -L -v | grep policy
Chain INPUT     (policy ACCEPT 369 packets, 28278 bytes)
Chain FORWARD   (policy ACCEPT 0 packets, 0 bytes)
Chain OUTPUT    (policy ACCEPT 187 packets, 19740 bytes)

SRV-02 server
SRV-02 is an Ubuntu Server 14.04 with one network adapter.

10.0.2.2/24    (eth0, LAN2)

/etc/network/interfaces

# Loopback
auto lo
iface lo inet loopback
# LAN2
iface eth0 inet static
    address 10.0.2.2
    netmask 255.255.255.0
    network 10.0.2.0
    broadcast 10.0.2.255
    dns-nameservers xxx.xxx.xxx.xxx

Routing

~$ netstat -r:
Kernel IP routing table
Destination     Gateway     Genmask         Flags   MSS Window  irtt Iface
default         10.0.2.1    0.0.0.0         UG        0 0          0 eth0
10.0.2.0        *           255.255.255.0   U         0 0          0 eth0

~$ ip route show
default via 10.0.2.1 dev eth0
10.0.2.0/24 dev eth0  proto kernel  scope link  src 10.0.2.2

Firewall
Ubuntu "Uncomplicated FireWall" (UFW) is disabled on server "SRV-02" and all iptables chains have a default policy set to ACCEPT target.

~$ sudo ufw status
Status: inactive

~$ sudo iptables -L -v | grep policy
Chain INPUT     (policy ACCEPT 0 packets, 0 bytes)
Chain FORWARD   (policy ACCEPT 0 packets, 0 bytes)
Chain OUTPUT    (policy ACCEPT 0 packets, 0 bytes)

What am I missing here? I wonder what static route should be added to SRV-01 and also if default gateways are properly configured...
Answer: There are two problems with this setup:

The hosts on LAN1 know nothing about the LAN2 segment. When you ping a host on LAN1 (let's call it host1) from SRV-02, the packet will be routed through SRV-01 and will reach host1. However, host1 will send the reply to it's default gateway (ISP router) as it doesn't have a specific route to LAN2. (The ISP router will either a) also send it to it's default gateway as it also doesn't know about LAN2, or b) drop the packet as it comes from an unknown source not it's local LAN.)
When trying to reach WAN from LAN2, the packets will be routed through SRV-02 to ISP router where two situations are possible:

The router will not NAT translate the packet as the source of the packet (LAN2) is not it's local LAN (this is the more probable situation), or
The router will NAT translate the packet and send it to the Internet. However, when the reply comes and the destination is translated back to the LAN2 address, the packet will not be delivered as the ISP router doesn't have a route for that network. The packet will be sent incorrectly to the default gateway (ISP).

These issues could be fixed by adding a static route to LAN2 to ISP router and adding a source NAT configuration for LAN2 on SRV-01. However, that is not possible due to no admin access to the ISP router.
There are two solutions that get around it:
A. Make SRV-01 a full router for LAN1 and LAN2 hosts

Add another network adapter to SRV-01 (making it 3 in total)
Change the topology as follows:

.
WAN -> ISP router -> LAN1 -> SRV-01 +-> LAN3 (for hosts originally in LAN1)
                                    +-> LAN2 -> SRV-02

Basically, we're making SRV-01 a router for both LAN segments.

This will require moving hosts originally in LAN1 to a new subnet LAN3 - let's say we use 10.0.1.0/24
The network configuration of SRV-01 will need to be changed as follows:

/etc/network/interfaces:
# LAN1 - to ISP router
auto eth0
iface eth0 inet dhcp
# we can even use dhcp as the IP address is not really important
# - there are no more hosts on LAN1 apart from ISP router and SRV-01

# LAN3 - for hosts originally in LAN1
iface eth1
    address 10.0.1.1
    netmask 255.255.255.0

# LAN2
iface eth2
    address 10.0.2.1
    netmask 255.255.255.0

iptables rules to make WAN access work:
iptables -t nat -A POSTROUTING -o eth0 -s 10.0.1.0/24 -j MASQUERADE
iptables -t nat -A POSTROUTING -o eth0 -s 10.0.2.0/24 -j MASQUERADE

Alternatively, if you choose to keep the static IP address on SRV-01 on eth0 the rules could be changed (although MASQUERADE would still work):
iptables -t nat -A POSTROUTING -o eth0 -s 10.0.1.0/24 -j SNAT --to-source 192.168.5.8
iptables -t nat -A POSTROUTING -o eth0 -s 10.0.2.0/24 -j SNAT --to-source 192.168.5.8

DHCP will need to be configured on SRV-01 on eth1 (LAN3, for hosts originally on LAN1), and possibly on eth2 (LAN2) as well if required. (In both cases the gateway will be the local address of eth1 or eth2 respectively, but that goes without saying :)

This will make communication possible between LAN3 and LAN2 (via SRV-01 which is the default gateway for both). WAN access will also work from both LAN3 and LAN2 thanks to the double source NAT.
B. Make SRV-01 a DHCP server for LAN1
This approach is not as clean as above but is slightly simpler. It assumes you are able to disable DHCP on ISP router

Disable DHCP on ISP router
Set up DHCP for LAN1 on SRV-01 and make SRV-01 (192.168.5.8) the default gateway for LAN1
Set up source NAT translation for LAN2 on SRV-01 so that the WAN access works from LAN2:

.
iptables -t nat -A POSTROUTING -o eth0 -s 10.0.2.0/24 -d 192.168.5.4 -j SNAT --to-source 192.168.5.8
iptables -t nat -A POSTROUTING -o eth0 -s 10.0.2.0/24 ! -d 192.168.5.0/24 -j SNAT --to-source 192.168.5.8

The first line enables SNAT so that LAN2 hosts can access the ISP router itself and the second line disables SNAT for LAN2-LAN1 access.
Again, this approach is not as clean as the one above as there are two routers in the same subnet (SRV-01, ISP router). When I used this approach myself I noticed my second router (SRV-01 in this scenario) would send ICMP redirects to the ISP router as it would see that the client (host on LAN1) and the upstream router (ISP router) are on the same LAN. This might not be desired as network policies implemented on SRV-01 could be circumvented.
Hope that helps.
Comment: Thanks for the detailed & educational answer. What if it would be possible with our current topology to:
**( a )** Desactivate DHCP on ISP router **( b )** Set SRV-01 to provide DHCP for LAN1 (192.168.5.0/24) & LAN2 (10.0.2.0/24) plus default gateway to 192.168.5.4 (ISP router eth1 - LAN1) **( c )** Set hosts on LAN1 default gateway to 192.168.5.8 (SRV1 eth0) **( d )** Set hots on LAN2 default gateway to 10.0.2.1 (SRV1 eth1) or 192.168.5.8 (SRV1 eth0).
Are there routing tweaks missing here, what would be the impact on security & performances?
Comment: My pleasure. This approach would work as well - in fact I used it myself with my stupid cable modem that didn't have a static route option. I edited my answer and added this simpler approach - note the SNAT config required for LAN2. If at all possible I would use the cleaner first option though. PS: if my answer was helpful could you perhaps upvote it/mark it as accepted? :) Thanks!
Comment: I'm note sure why use MASQUERADE if keeping DHCP enabled for LAN1 as proposed within solution A (first solution), could you elaborate?


getting 500 error on wp-admin page

Question: i am having weird situation last week i open my site and then i open my wp-admin page it should work like my front but i am having 500 error.
i tried almost every thing on google to find this situation but nothing helped me.
as i remember last time i work in theme function file and WordPress config file i checked .htaccess file eveything is fine.
also i did replace content with old content and create new file for config but nothing works. i disabled all plugins enabled debug mode but nothing helped me
what should i do ? i dont want to lose anything
Comment: Possible duplicate of [500 Internal Server Error - Wordpress](https://stackoverflow.com/questions/11769262/500-internal-server-error-wordpress)
Comment: Did you try to change wp_debug to true and see if this shows any errors?
Comment: @NeilKennedy yeh i did wp_debug to true all i see is deprecated warnings and some plugins notices so i disabled plugins that causes of notices but remains all plenty of warnings something deprecated etc etc. i am not WordPress developer. all i get is that all warning is not my problem and i thought my problem is something else but i didn't know.
Comment: So when you set wp_debug to true and tried to load the wp-admin, the 500 error didn't show, just the warnings and error messages showed?  In my experience when this happens, it is one of these errors that is causing the issue with the 500 error.  Are any of the errors 'fatal'?
Answer: Glad you sorted your error with incompatible PHP versions.
In order to properly debug an HTTP 500 error, you should do the following.

In your php.ini, set error_reporting to -1
Turn display_errors off
Set a custom error_log path.

Then in your terminal, type tail -f /path/to/error_log.
Now as you work on your project, you can go into your terminal and you will see all notices, warnings, deprecation messages, and fatal error messages, scrolling past in real time.
Then you can tighten the screws. An empty log means well written code!

getting 500 error on wp-admin page


Given a prediction problem, what principles drive the design of a neural network for that problem?

Question: Research work that have solved problems using neural networks, simply state the structure of their networks in their research papers. No explanation is generally given about what led them to that structure (for example, AlphaGo's neural networks).
It can't be trial and error, since with huge networks the search space is huge; one can't simply try a lot of options and get to the correct structure.
And, it can't be fully deterministic either; some trial and error is involved, but not much. I've been taught in college that experts on neural networks make educated guesses of what to try.
I want to know what those educated guesses are and how is it driven. There must be some base principle/intuition or some data analysis on the given dataset, that can help us make educated guesses of our desired structure.
Please answer with small examples if possible. An example could be on a small enough dataset to make your point, or some problem that you solved using neural network (and knew how to design the network), or some research material where the actual process is explained. If these principles can be explained using XOR (classification) data, then please do so on that example..
One general idea is that instead of random weights, initialize the network weights using some domain knowledge about the problem. How is this done specifically?
Any more such ideas?
Comment: This is a good question, but it is awfully broad. It isn't clear how well someone will be able to give you a comprehensive answer. You might consider editing this to make it more focused & concrete. Seeing how this might be done in a particular situation may help you understand how the process could be applied even in a different situation.
Comment: @gung Yeah, its a pretty broad question. I think the intuition (for experts), comes from their personal experience of having worked on neural nets a lot. The best way to answer this question would be to quote examples, with a dataset. Maybe this question can be answered with something as simple as the XOR data, but I can't be sure if that is too narrow. Hence leaving it open for people to cite examples..
Comment: If people think it's too broad, this will likely be closed. You may want to narrow this & make it more concrete. You can also ask several related questions, each pertaining to a different situation, & link between them for context.
Comment: I've incorporated a sub-question on weights initialization in the question now..
Answer: This is often referred to as hyperparameter tuning. How to initialize the weights, or what learning rate to use in order to produce the lowest error, are a couple of examples of hyperparameters: basically everything that doesn't involve the weights of the net itself.
Tuning of hyperparameters is usually done by grid search, or randomized search. Sure, domain knowledge is useful, but at the same time can induce bias.
If you need some insights, you can read this paper, which presents randomized hyperparameter search but also explains how hyperparameters are tuned with carefully crafted grid search:
http://www.jmlr.org/papers/volume13/bergstra12a/bergstra12a.pdf


Monitor if Perfmon counter sets are running

Question: We have an issue where occasionally over time, a Perfmon counter set will stop.  We are looking for a way to monitor if a particular counter set is running, does anyone know of a way to do this?  We use Nagios for basic alerting but we have another monitoring tool that can run executable vbscrips, batch files, wmi queries, ect.
Does anyone have a way to verify if a perfmon set is running or stopped?  We'd rather not have to audit 120 servers manually.
Answer: If you're just looking for a way to check if a PerfMon Counter is running, have you checked into Logman? A simple logman query will show you the status of all of the counters on a system.
However, if you want to take the next step and automatically restart stopped counters, you might find this handy:
@echo off
set COUNTER_LIST=("LogA" "LogB" "SoForth")
for %%i in %COUNTER_LIST% do logman start %%i

That's a simple .bat script which will automatically restart all PerfMon Counters named in COUNTER_LIST. If a counter is already running, logman start delightfully does nothing.


É recomendável usar o Linq em vez de SQL?

Question: Para evitar abuso de string e evitar problemas de injeção de código pode ser uma boa pratica o uso do Linq.
Também posso imaginar que por exemplo, que seja mais devagar.
Quem já usou o Linq para comunicar com banco de dados, o recomendaria?
Comment: Em que **contexto**?
Comment: **Sim!** É importantíssimo um contexto para que sua pergunta seja respondida. Postei uma resposta, mas no final das contas note que não respondi diretamente sua pergunta, apenas discorri sobre o assunto. Já com um contexto seria possível afirmar *"isto é/não é recomendável"*.
Comment: Eu estou no processo de ser aceito ou não num novo emprego, onde usam o C# e ligam com banco de dados (no caso por GUI local, não por web). Eu não tenho experiência extensa com o C# e daí fico curioso se a prática comum seria usar Linq ou usar SQL por string, e se isso é uma boa ou má prática... Vendo a sua pergunta posso entender que isso depende do contexto?
Comment: Mesmo assim, a sua resposta na verdade é mesmo o que precisei ouvir! Obrigado!
Answer: LINQ em si é uma parte do .NET que adiciona ao framework funcionalidades de consulta. Linq não é atrelado a nenhuma tecnologia, ele trabalha sobre uma interface (IQueryable). A implementação da consulta final (que acessa o provedor de dados) fica a cargo de quem implementa a interface.
Se você está utilizando linq para acessar um banco de dados SQL é porque está usando alguma implementação específica para isso (como Entity Framework, LINQ to SQL ou NHibernate).
Em termos de segurança de código não dá para afirmar... nada. Isso fica dependente da implementação do provider que você estiver utilizando.
O que é possível afirmar é que uma das vantagens de se utilizar linq é que suas queries serão compiladas, isto é, dependendo do que for erroneamente alterado o compilador poderá te gerar um erro.
Por exemplo, vamos supor que é removida uma coluna do banco de dados. Analogamente a remoção da coluna você altera também o código do sistema para sua classe e suas queries não referenciarem a coluna. Se por ventura o programador esquece de substituir em uma consulta que utiliza linq o compilador irá gerar um erro de compilação, pois as queries envolverão uma propriedade que não existe mais. Já com queries sql como texto isso não acontece, irá ocorrer somente o erro em execução.
Uma possível vantagem de se utilizar queries sql diretamente é performance. Geralmente, por oferecerem um nível maior de abstração, as consultas feitas indiretamente com linq tendem a não ser tão performáticas quanto executar uma consulta sql diretamente. Existem alguns casos que essa pequena diferença de performance é relevante. É comum encontrar sistemas que fazem apenas as operações mais pesadas dessa forma.
Comment: Obrigado, deixa bem claro que algumas supostas vantagens não necessariamente estão aí. Daí sei em quê preciso prestar atenção.
Comment: E é sempre bom lembrar: pelo menos em relação a bancos relacionais, e pelo menos quanto ao LINQ utilizado com Entity Framework, LINQ to SQL e NHibernate, a consulta LINQ *será automaticamente transformada*, no final das contas, em uma consulta SQL.
Answer: Embora seu questionamento já esteja respondido, o título de sua pergunta me atraiu a compartilhar alguns outros benefícios que temos sentido em nossa empresa no uso do Linq, caso alguém esteja passando pelo mesmo processo de decisão. Então lá vai:

O Linq troca o uso de Strings Mágicas por instruções compiladas: Na prática, você traz às suas query's os benefícios de uma linguagem fortemente tipada e de refatoração;
O Linq nos trouxe de quebra uma auto-documentação, pois ao criar as classes tivemos que rever o mapeamento entre as tabelas (como possuímos uma base legada, não utilizávamos contraints de chave estrangeira). Deu trabalho, mas hoje novos programadores conseguem facilmente navegar de uma tabela a outra sem se preocupar com joins. Ainda, a mão na roda do Intellisense do Visual Studio torna a escrita de query's muito rápida;
O Linq padroniza todas as query's criadas no mundo .NET. No caso de Linq para SQL, isso significa que você adotará um mesmo padrão podendo este ser renderizado em vários dialetos* de bancos de dados distintos. Vale lembrar que ainda que o SQL seja uma linguagem ANSI, é difícil se restringir ao padrão (tome as funções SQL substring e top N como exemplo);
E se você ainda precisar de uso de String's para formar sua query dinamicamente sem muita complicação, você pode recorrer ao Dynamic Linq.

E sim, volta e meia temos problemas de performance por query's mal formadas, mas dá-se um jeito. Em resumo, digo que vale (muito) à pena.
[*] Em nosso caso, estamos utilizando o Linq para SQL implementado pelo excelente NHibernate que já traz suporte aos bancos de dados mais comuns do mercado.
Answer: Sim, o uso do LINQ força o programador a proteger seu código contra injeção de SQL.
Sim, o LINQ algumas vezes é mais lento. Mas há mais de uma maneira de detectar e resolver estes problemas.
Sim, já usei o LINQ extensivamente para comunicar com banco de dados e recomendo. Principalmente na versão para Entity Framework, já que o Linq-to-SQL não é mais atualizado.
Answer: Nas minhas experiências, o LINQ tem várias qualidades, sim, mas tem suas limitações também. Já passei, por exemplo, de um Dataset tão grande que o LINQ quebrou todo o programa. Usando um for { ... }, consegue fazer a mesma coisa mas extremamente mais rápido.
Creio que essa lentidão vem do extremo 'overhead' que usando o LINQ traz, sendo que no fundo, o .NET faz um for { ... } do mesmo jeito.
(Desculpe o português aí :P)
Comment: Você vai dizer que não viveu no Brasil quase sua vida toda? :D
Comment: Vivi alguns anos no Brasil só :)
Answer: O que posso dizer do LINQ, no meu ponto de vista só vale a pena para fazer cadastros, simples. Mesmo assim não vejo vantagem. Veja bem, o Delphi sempre foi uma linguagem de desenvolvimento muito rápido, e faz exatamente  o que o link faz, estranho eu estar falando isso mais veja bem, quando você usa os componente do Delphi como o ClientDataSet, ele vai fazer um mapeamento da sua tabela e ali ele adiciona todas as funcionalidades básicas de um cadastro, o problema é que ele faz um mapeamento da tabela de acordo com o banco de dados que você está utilizando e desta forma ele te amarra no banco, se você precisar mudar de banco você teria problemas, vários. No Linq acontece este mesmo mapeamento da tabela, ele acaba criando as classes mais também vai amarra o banco que você esta utilizando, sendo que quando você usa SQL, você faz a criação de cada classe separadamente, usando os tipos de campos primitivos que vai servir para qualquer banco de dados, basicamente você tem a conexão ao banco e as classes que representa as suas tabelas, não tem um vinculo direto, então no final, vai ser SQL puro fora que não vai precisar aprender uma nova sintaxe do LINQ. Então para mim no meu ponto de vista não compensa, eu desenvolvo usando um projeto para o Repositorio, Dominio, Aplicação e um projeto para a apresentação, acho que vale a pena você fazer um pequeno projeto, para testar mais para mim  o LINQ, só é bom para fazer cadastro simples.  Sobre a Injeção de SQL, basta usar o @Html.AntiForgeryToken()  no HTML e na controller [ValidateAntiForgeryToken].


Can L-smooth (L>0) convex function to be non-differentiable?

Question: As we know, a function $f:\mathbb{R}^n\to \mathbb{R}$ is called L-smooth (with a finite $L>0$), if $x\mapsto \frac{L}{2}\|x\|^2 - f(x)$ is convex. This definition does not restrict $f$ to be differentiable. I would like to know: "is there any $\textbf{convex}$ L-smooth function which is not differentiable?" Otherwise, how to prove that any L-smooth convex function is differentiable?
Many thanks for any comment.
Answer: I think the answer is: any convex L-smooth function $f$ is differentiable.
A possible proof is as follows: we try to show that the subdifferential $\partial f(x)$ is always a singleton at any point $x\in \mathbb{R}^n$.
First, the non-emptyness of $\partial f(x)$ is known.
Second, by contradiction, suppose that there exists $x\in \mathbb{R}^n$ such that $\partial f(x)$ contains two different subgradients $v_1$ and $v_2$. Then by the convexity of $f$, we have
$$\forall h\in \mathbb{R}^n,\quad f(x+h)\geq f(x) + \langle v_1, h \rangle.\qquad (1)$$
And by the convexity of $g(x)=\frac{L}{2}\|x\|^2 - f(x)$, we have
$$\forall h\in \mathbb{R}^n,\quad g(x+h)\geq g(x) + \langle z, h \rangle.\qquad (2)$$
where $z\in \partial g(x)$.
Using the fact
$$\partial g(x) = Lx - \partial f(x).$$
Then we take $z = Lx - v_2$ and get from $(2)$ that
$$\forall h\in \mathbb{R}^n,\quad g(x+h)\geq g(x) + \langle Lx-v_2, h \rangle.$$
That is (by replacing the expression of $g$):
$$\forall h\in \mathbb{R}^n,\quad \frac{L}{2}\|x+h\|^2 - f(x+h)\geq \frac{L}{2}\|x\|^2 - f(x) + \langle Lx-v_2, h \rangle.\qquad (3)$$
Summing $(1)$ and $(3)$. Then
$$\forall h\in \mathbb{R}^n,\quad \langle v_1-v_2, h \rangle \leq \frac{L}{2}\|x+h\|^2 - \frac{L}{2}\|x\|^2 -\langle Lx, h \rangle = \frac{L}{2}\|h\|^2.$$
Taking $h=t(v_1-v_2)$ with $t\geq 0$. Then
$$t \|v_1-v_2\|^2 \leq \frac{L}{2}t^2\|v_1-v_2\|^2.$$
That is $$\forall t\geq 0,\quad (\frac{L}{2}t^2-t)\|v_1-v_2\|^2\geq 0.$$
Consider the case where $0<t<\frac{2}{L}$, then $\frac{L}{2}t^2-t<0$ and we get
$$\|v_1-v_2\|^2\leq 0.$$
This implies (by the definiteness of the norm) that
$$v_1=v_2,$$
which contradicts the assumption $v_1\neq v_2$.
Therefore, the subdifferential $\partial f(x)$ is a singleton at any point $x\in \mathbb{R}^n$, implying that $f$ is differentiable over $\mathbb{R}^n$.


Spring store data in jdbcTemlate(h2 db) permanently

Question: I am starting to learn Spring and faced with some issues regarding spring-jdbc.
First, I tried run the example from this: https://spring.io/guides/gs/relational-data-access/ and it worked. Then, I commented lines with droping and creating new tables(http://pastebin.com/zcJHsL1P), in order to not override data, but just get it from db and show it. However, spring showed me error:

Table "CUSTOMERS" not found; SQL statement: ...

So, my question is: What should I do to store my database permanently? I don't want to recreate all time new database, I want create it once and update it.
P.S. I used H2 database. Maybe problem exists in tis db?
Answer: That piece of code looks like you are "prototyping" something; so it's easier to automatically create a new database (schema, tables, data) on the fly, execute and/or test whatever you want to...and finish the execution.
If you want to persist your data and only modify/update it, either use H2 with the "file layout" or use MySQL, PostreSQL, etcetera.
By the way, the reason you are getting Table "CUSTOMERS" not found; SQL statement: ... is because you are using H2 as an in-memory database and every time you start your application you need to re-create the tables and populate them with data.


Where is source location?

Question: <audio controls>
<source src="vincent.mp3" type="audio/mp3"/>
<source src="vincent.ogg" type="audio/ogg"/>
</audio>

Where is my source location? On GoDaddy? On my computer?
Comment: If you only see the filenames, then your HTML expects those files to be right next to it - in the same directory.
Answer: The Source file must be in the same directory of the file that you put this code illustrative img if you use a server to host your site the same logic applies, you can also use a subdirectory like a folder "myfolder" and add this the location in the source like that
<audio controls>
<source src="myfolder/vincent.mp3" type="audio/mp3"/>
</audio>

There is another ways to access a file that is out of the folder using for example ../ to step back or using ./ to make the path start in the root folder
 <audio controls>
 <source src="../myfolder/vincent.mp3" type="audio/mp3"/>
 </audio>

[UPDATE] Try this in your index.html in the Server after that try to access your domain "http://stevegilman.net/index.html" if still dosen't work keep the files like that that I'll will check, but try others browsers like Firefox or Opera to test
<!DOCTYPE html>

<title>Audio Test</title>

<audio controls>
<source src="http://stevegilman.net/thinking_of_you_test.mp3" type="audio/mp3"/>

</audio>

[UPDATE 2] the first source code is my with only one type of Double Quotes your is below with two types of Quotes, Curly and Stright Quotes
Comment: See my problem here:  http://stevegilman.net/
Comment: In your first code you have the source with this path "stevegilman.net/ Thinking of you cd 4. mp3" just remove "stevegilman.net"  or add a folder with this name,  after that rename your file without spaces  like that "thinking_of_you_cd4.mp3 " notice that I add underscore instead of space  and remove the capital letters e don't forget to put the same name in the your mp3 file  "thinking_of_you_cd4.mp3" your second code have the same problem you put alot of name in the path  /home/stevegilman/public... each name with the slash will be treated like a folder remove them all
Comment: I made the suggested changes. See the update at:  http://stevegilman.net/  Still doesn't work. Explorer still says invalid source.
Comment: I tested the code and works fine, including with your own file music "stevegilman.net/thinking_of_you_test.mp3" so try again with the code that I updated in the answer and try to test others browsers too – Kleber Germano 1 hour ago    Delete
Comment: Well I uploaded your code and it worked like a champ in all browsers! I am just learning HTML5 and this will be a lot of information for me to think about and try to understand. I really appreciate you taking the time to help me!! Thank you very, very much!
Comment: This is the line that was corrupt somehow:   . When I put them in a document comparer they show as different but I can't see how. When I replaced that single line of my code with that single line of your code my code then works. But I still can't see how they differ.
Comment: You welcome, so about the difference between the two codes is that in your code you put two types of quotes one is Curly and the other is Straight, probably you copyed the code from web where the Curly Double Quotes are sometimes used, so you must have edited just one parte of the code in Text Editor or IDE where the stright quote is more often used, and as the Quotes dosen't match the code don't work I'll update the answer with a image of the difference
Comment: By the way, If the question was solve pls don't forget to mark the answer as the right one in the check symbol :)
Comment: Did I close this out correctly so you get your points? I am watching Youtubes to see how stackoverflow works.
Comment: Yes, when you checked the question as answered anyone that has the same problem will see that this question has the solution, this is why is important mark as "answered" besides that, some points for who asnwered the question isn't a bad thing, hehe
Comment: tks for your concern to close the question right, some fellas just get off with the answer without a feedback, good luck in your studies and any issue just come back

Where is source location?


Firewall config for Amazon Lightsail with CDN distribution

Question: I set up an Amazon Lightsail (Wordpress) server and I'm using CDN distributions with a custom domain and SSL certificate as described in this official article. All works well, and I'm able to access the site from the cloudfront distribution's HTTPS terminated endpoint (with the custom domain).
The problem is that I can still access the site directly via http and https on the server's static public IP address (which is the origin that cloudfront connects to). I went into Networking->IPv4 Firewall and disabled HTTPS because I read that cloudfront will only use http to connect to the origin. However I'm not sure if it will work if I disable http also, and I'm a bit puzzled by why Amazon never mentions this in the documentation. Are we supposed to leave the HTTP/HTTPS ports open in the firewall when serving lightsail through cloudfront, or should we limit it to cloudfront's proxy client's IP range? I know that in general leaving the proxied server open to public can cause (security) issues with certain code (or wp plugins) that expect always being called from behind a reverse proxy, as well as performance issues and possibly other issues if people, bots or hackers connect directly to the server instead of going through the CDN.
Answer: This article might be what you are looking for: Access An Application Using Only A Single Domain With Apache.
My self I followed the instructions on the last paragraph:
"Redirect All Domains To Your Own Domain And Force HTTPS"
To redirect all domains to your own domain and force HTTPS, add the following configuration into the /opt/bitnami/apache2/conf/bitnami/bitnami.conf file.
Remember to replace example.com with your own domain.
    <VirtualHost _default_:80>
RewriteEngine On
RewriteCond %{HTTP_HOST} !^(localhost|127.0.0.1)
RewriteRule ^(.*)$ https://example.com$1 [R=permanent,L]
...

<VirtualHost _default_:443>
RewriteEngine On
RewriteCond %{HTTP_HOST} !^example.com$
RewriteCond %{HTTP_HOST} !^(localhost|127.0.0.1)
RewriteRule ^(.*)$ https://example.com$1 [R=permanent,L]
...

By adding the above configuration to your bitnami.conf file it will force HTTPS protocol for your website and it will redirect all the traffic from your static IP address to your domain name. To change the communication protocol between your distribution and origin to https you'll need to have installed an SSL certificate on the Cloudfront distribution of your Lightsail Instance and an SSL certificate on the origin IP address.
To access the file /opt/bitnami/apache2/conf/bitnami/bitnami.conf you must connect to your static IP using FTP or SSH. You can do this easily using a program like Filezilla.
Comment: I'm not sure what this has to do with AWS Lightsail
Comment: Is not your Wordpress installation offrered by Bitnami? Bitnami offers the Wordpress package for AWS Lightsail users. If you access your static IP via FTP you should be able to see the Bitnami directory.
Comment: Gotcha, my bad - the bitnami stuff is all abstracted away so I never touched it. So, the Cloudfront Distribution will connect to the Origin only on localhost/127.0.0.1? Is Cloudfront runinng on the same server as bitnami then? Another thing I struggle with, is that if I enable HTTPS communication to the Origin, then how will that work? Then I would need to create and maintain an SSL certificate for the origin's Apache sever separately, no?
Comment: Yes, correct. If you want the communication between the origin and the distribution to be over HTTPS you need to have installed an SSL certificate on the origin, as well as on the distributution. Now for the first question, I don't quite know what the localhost/127.0.0.1 actually means, but it should remain as it is. I can verify that I'm using this configuration and is working. Only thing you need to modify is to write your domain name.
Comment: Ok, so you're using this configuration with AWS Lightsail and Cloudfront Distribution and can confirm it's working? I still find it a bit odd that it requires so much extra work (and maintaining/renewing an extra SSL certificate) for something that I would think should just work out of the box (like Amazon advertises it)
Comment: Out of the box it works with an http:// communication. The rest needs adjustment. My answer above is simply to make your IP address of your Lightsail instance unaccessible to users by redirecting the traffic to your main domain while forcing https:// on your domain for all the contents.


Unable to start Active Directory Certificate Services afer migrating from 2003 to 2012 R2

Question: I was in the process migrating our CA from a 2003 server to a 2012 R2 using this guide
After a server restart the CA service will no longer start. I receive error 21: The device is not ready.
Is it worth fixing or would it be better, possibly my only solution, to start over? We don't use our CA for much. We have maybe 3 certificates pushed out from the CA. Something I'd like to work on as well...
update
I found the issue for my original problem. The original CA had the database installed on a separate volume opposed to the default location. I made the changes necessary in the registry to get the service started. My new problem is that when I click on Certificate Templates I'm greeted with the error: Template information could not be loaded. Element not found. :/
Comment: unfortunately, you chose the bad guide. Although, MS blogs are helpful, but not always. You should use official migration guide: https://technet.microsoft.com/en-us/library/ee126170(v=ws.10).aspx
Comment: It seemed helpful till I restarted the server. :( After that the service fails to start. I did go through the official guide trying to find a solution... I changed the permissions on AIA and CDP containers, etc... Didn't help. Looks like I'll be starting over.
Comment: Unfortunately, the StackExchange board format doesn't allow deep problem investigation, so I would suggest to post the question on TechNet forums (Windows Server Security forum directory) where we can delve into details. Hope this suggestion doesn't violate SE rules.
Comment: you might like to read the question posted by the OP - its not 2008 it's 2003 and it's not a migration its an upgrade - from the guide you linked to:  "In-place upgrades from Windows Server 2003 with Service Pack 2 or Windows Server 2003 R2 to Windows Server 2012 are not supported."
Comment: I think found the problem. The OLD CA didn't use the default locations for the install. The previous admin decided to create shares and put them there instead. Now I have to go through the registry and make the needed changes to see if I can get it to work.
Answer: Speaking personally, I would never upgrade a Windows system to a new release not even a desktop, migrating apps and data with the old configuration and a clean install of Windows is far more attractive in the long run, moreover there are almost 10 years between the Two systems and you will end up with a technical dept by upgrading - to put it in perspective this would be like upgrading Ubuntu 4.04 to 12.04 - if you have only signed 3 certificates then I would certainly do a clean install and take to opportunity to learn about root certificate authorities.
Comment: I definitely need to learn more about CA's. I guess now is the time.
Comment: The OP did not do an in-place upgrade of the OS, but rather a migration of the certificate services database and configuration. Did you even look at the process that he linked to?


Finding the minimal $n$ such that $C_{12}$ is a subgroup of $S_{n}$

Question: I guess that there is no general solution for $C_{k}$ and unfortunately, I couldn't find a specific one for $C_{12}$.
Cayley's theorem claims that such $n$ exists, and Lagrange's theorem claims that $n \geq 4$; Don't know what to do next; If I'm not mistaken, $C_{12}$ is isomorphic to $\mathbb{Z_{12}}$ but I don't know how it may help.
Comment: You need an element of order $12$ in your $S_n$. There are different ways of achieving that. For instance, $S_{12}$ has a cycle of length (and therefore order) 12. Can you do better?
Comment: See http://oeis.org/A008475
Comment: Oh, well... Then $S_{7}$ may be represented as 4+3, so element order is 12 and the answer is $S_{7}$, right?
Comment: You need to show that $S_6$ is impossible. But other than that, yeah.
Comment: Thanks a lot! it really helped
Comment: See also [here](https://math.stackexchange.com/questions/3362305/how-we-can-find-the-symmetric-group-with-least-n-whose-subgroup-of-it-is-isomo?rq=1).
Answer: The minimal permutation degree $d(G)$ of a finite group $G$ is the least integer $d$ such that $G$ can be embedded into $S_d$.
Let $G\cong C_{p_1^{e_1}}\times \cdots \times C_{p_r^{e_r}}$. Then we have
$$
d(G)=\sum_{i=1}^r p_i^{e_i}.
$$
For a proof see for example here. Since $12=2^2\cdot 3$, we have $$
d(C_{12})=2^2+3=7.
$$


Text auto refreshing in google chrome (rendering issue)

Question: Look carefully below two images, the Q letter(g and y also has this issue), some period of time (5 or 6 seconds) in Google chrome render the text something like to image 01 even though original text is image 02 other web browsers are render the correct form of text which is image 02, but chrome some period of time suddenly shows the image 01 and change back to image 02, I just put this text in  tag, I would like to know how to fix this.
image 01

image02
Answer: Without seeing your code it is hard to diagnose the problem, but it looks as if the characters might be getting chopped off at a horizontal line - Q, g and y are all characters that extend further down than most. The last time I had this type of issue I had a fixed height for my div in CSS, and the content was too big to fit inside it. Changing the height of my div so that it was bigger than the content meant that Chrome wasn't rearranging my document to make everything display properly.


Unable to add WHERE conditions as OR to query object

Question: I'm attempting to override the query method for a node migration in the migrate_d2d module by adding two where conditions with "OR", and the first one is being added as AND instead of OR for some reason.  In this case, there is already one WHERE condition of node type, so I am adding two more, which means I'm trying to change
SELECT blah from {node} WHERE type = 'type1';

to
SELECT blah FROM {node} WHERE type IN ('type1', 'type2', 'type3');

It doesn't look like it is possible to override an existing WHERE condition without completely overriding the entire query method, so it seems that my next best bet is to add the WHERE conditions with OR so that the resulting query is
SELECT blah FROM {node} WHERE (type = 'type1') OR (type = 'type2') OR (type = 'type3');

To accomplish this, based on what I've found searching around (such as here), I used db_or():
$db_or = db_or();
$db_or->condition('type', 'type2')
  ->condition('type', 'type3');
$query->condition($db_or);

However, when I print out the resulting query what I actually get is
SELECT blah FROM {node} WHERE (type = 'type1') AND (type = 'type2') OR (type = 'type3');

and this is verified by the migration results, since the migration doesn't bring across any nodes (which makes sense, since one node can't be of two types).
I also tried it with separate additions to $db_or:
$db_or->condition('type', 'type2')
$db_or->condition('type', 'type3');

and even tried adding as one condition:
$db_or->condition('type', array('type2', 'type3'), 'IN');

but the result is still the same.
What it looks like to me is that no matter how you add a WHERE condition when there already is one, it automatically adds the next one as AND, even if you specify that it should be OR.
So my questions are:

Am I adding these conditions to the query object correctly (assuming I want them as OR)?
Is there a way to remove the initial condition so that I could just add my own WHERE condition from scratch?
Is there a better way to do this?

Thanks.
Answer:
Am I adding these conditions to the query object correctly (assuming I want them as OR)?

Not quite; all components of the the OR need to be added to the condition object, so you need to do something like this:
$query = db_select('node')->fields('node', array('nid'));

$db_or = db_or();
$db_or->condition('type', 'type1')
  ->condition('type', 'type2')
  ->condition('type', 'type3');

$query->condition($db_or);

That'll give you this query string:
SELECT  node.nid AS nid
FROM
{node} node
WHERE ( (type = :db_condition_placeholder_0) OR (type = :db_condition_placeholder_1) OR (type = :db_condition_placeholder_2) )

Is there a way to remove the initial condition so that I could just add my own WHERE condition from scratch?

Yes you can use SelectQuery::where(), but there's really no need. You can use the above, or preferably...

Is there a better way to do this?

Yes, by using IN as you originally planned:
$query = db_select('node')
  ->fields('node', array('nid'))
  ->condition('type', array('type1', 'type2', 'type3'), 'IN');

That gives:
SELECT  node.nid AS nid
FROM
{node} node
WHERE  (type IN  (:db_condition_placeholder_0, :db_condition_placeholder_1, :db_condition_placeholder_2))

Note that the third parameter of "IN" to condition() isn't strictly necessary, as the DB class automatically assumes "IN" if an array is passed.
Comment: Are you sure this should work with an existing query object that already has a WHERE condition  - `type = 'type1'` - by the time I get it? I tried the first and last options you suggested, and it just added the three conditions - with the first one being AND, just like before - to the existing one, not replacing it.
Comment: Oh, my bad I didn't pick up on that. Yeah that's a load of fun, [here's one I made earlier](http://drupal.stackexchange.com/questions/23131). The edit to that answer is probably the most interesting bit for your case (looping through the conditions). Is the information in this answer of any use at all? If not I'll get rid of it
Comment: Speaking for myself, I already understood what you posted above. In regards to the other answer, I see what you're doing by rebuilding the conditions, but I don't see a step to remove the existing condition from the $query object. I can't access $query->where directly since it's protected, and I don't see a method to alter $query->where->conditions in DatabaseCondition.


query string of tid not working on page

Question: I need my view to default the exposed filter depending on the ?tid= variable that i put in the url .  It was working before, but now it no longer does.  Is there a setting in the view that makes that tid variable work?
Comment: Are you using contextual filters. ?
Answer: In the view you need an exposed filter on the term field. In the settings for this field, expand on the "More" section near the bottom and you'll see a field called "filter identifier" - enter tid in this field (in this screenshot, you can see I used "category" it can be whatever label you want to give it). Click Apply this display. Save the view.

query string of tid not working on page


Update data base table columna

Question: I want to update a database column table with new data using the following query :
update visit set day = px
from (values (1, 'Thursday'), (2, 'Friday'), (3, 'Friday'), (4, 'Friday'),(5,'Friday'),(6,'Friday'),(7,'Saturday'),(8,'Saturday'),
(9,'Saturday'),(10,'Saturday'),(11,'Saturday'),(12,'Saturday'),(13,'Saturday'),(14,'Saturday'),(15,'Saturday'),
    (16,'Saturday'),(17,'Saturday'),(18,'Saturday'),(19,'Saturday'),(20,'Saturday'),(21,'Saturday'),(22,'Saturday'),(23,'Saturday'),(24,'Saturday'),
    (25,'Saturday'),(26,'Saturday'),(27,'Saturday'),(28,'Saturday'),(29,'Saturday'),(30,'Saturday')
    (31,'Saturday'),(32,'Saturday'),(33,'Saturday'),(34,'Saturday'),(35,'Saturday'),(36,'Saturday'),(37,'Saturday'),(38,'Saturday'),(39,'Saturday'),(40,'Saturday')
    ,(41,'Saturday'),(42,'Saturday'),(43,'Saturday'),(44,'Saturday'),(45,'Saturday')
    ,(46,'Saturday'),(47,'Saturday'),(48,'Saturday'),(49,'Saturday'),(50,'Saturday'),
    (51, 'Saturday'), (52, 'Saturday'), (53, 'Saturday'), (54, 'Saturday'),(55,'Saturday'),(56,'Saturday'),(57,'Saturday'),(58,'Saturday'),(59,'Saturday'),
    (60,'Saturday'),(61,'Saturday'),(62,'Saturday'),(63,'Saturday'),(64,'Saturday'),(65,'Saturday'),
    (66,'Saturday'),(67,'Saturday'),(68,'Saturday'),(69,'Saturday'),(70,'Saturday'),(71,'Saturday'),(72,'Saturday'),(73,'Saturday'),(74,'Saturday'),(75,'Saturday'),
    (76,'Saturday'),(77,'Saturday'),(78,'Saturday'),(79,'Saturday'),(80,'Saturday')
    (81,'Saturday'),(82,'Saturday'),(83,'Saturday'),(84,'Saturday'),(85,'Saturday'),(86,'Saturday'),(87,'Saturday'),(88,'Saturday'),(89,'Saturday'),(90,'Saturday'),(91,'Saturday'),(92,'Saturday'),(93,'Saturday'),(94,'Saturday'),(95,'Saturday')
    ,(96,'Saturday'),(97,'Saturday'),(98,'Saturday'),(99,'Saturday'),(100,'Saturday'),
    (101, 'SaturdaySaturdaySaturdaySaturday'), (102, 'Saturday'), (103, 'Saturday'), (104, 'Saturday'),(105,'SaturdaySaturday'),(106,'Saturday'),(107,'Saturday'),(108,'Saturday'),(109,'Saturday'),(110,'Saturday'),(111,'Saturday'),(112,'Saturday'),(113,'Saturday'),(114,'Saturday'),(115,'Saturday'),
    (116,'Saturday'),(117,'Saturday'),(118,'Monday'),(119,'Monday'),(120,'Tuesday'),(121,'Tuesday'),(122,'Wednesday'),(123,'Thursday'),(124,'Thursday'),(125,'Tuesday'),(126,'Thursday'),(127,'Thursday'),(128,'Thursday'),(129,'Thursday'),(130,'Thursday')
    (131,'Thursday'),(132,'Thursday'),(133,'Tuesday'),(134,'Friday'),(135,'Friday'),(136,'Friday'),(137,'Tuesday'),(138,'Wednesday'),(139,'Wednesday'),(140,'Friday'),(141,'Friday'),(142,'Monday'),(143,'Wednesday'),(144,'Wednesday')
    ,(145,'Tuesday'),(146,'Wednesday'),(147,'Tuesday''),(148,'Wednesday'),(149,'Thursday'),(150,'Friday'),(151,'Friday'),(152,'Monday'),(153,'Tuesday'),(154,'Friday'),(155,'Thursday'),(156,'Thursday'),(157,'Tuesday')
    ) p(i, px)where i = id;

When I run the query, I get the following error :
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from (values (1, 'Thursday'), (2, 'Friday'), (3, 'Friday'), (4, 'Friday'),(5,'Fr' at line 2

I have been unable to figure it out, how can I solve this out?
Comment: what are you actually trying to do?
Comment: I am trying to insert new data to  a new column I have in a table which  has  data.But the above query gives me a sql syntax
Answer: To test the update script create this table:
create table visit(day varchar(20), id int);
insert visit(day, id)
select 'Monday', 1;

Update:
update visit
inner join
(
select 1 i, 'Thursday' px
union all
select 2, 'Friday'
union all
select 3, 'Friday'
union all
select 4, 'Friday'
union all
select 5,'Friday'
-- fill in the rest
) p
on p.i = visit.id
set day = p.px

Confirm value of Day has changed:
select * from visit

Result:
DAY       ID
Thursday  1

Fiddle
Comment: @Strawberry more important, why did you downvote it ? Syntax was correct except for some missing commas from cut and pasting from the question. I assumed i was not suppose to validate data
Comment: I downvoted it because you replaced one query that didn't work with another query that didn't work. Is that helpful?
Comment: Prove it in a sqlfiddle, and I'll give you your point back ;-)
Comment: @Strawberry you were totally right, I had written the syntax in mssql. It was not compatible with mysql. After reading up on MySql which I never used. I learned the difference and attempted to write the syntax so it works. Included Fiddle in my answer

Update data base table columna


How do I get information from other nested elements?

Question: I am struggling with using LINQ to SQL XML. I'm following examples and getting some good results.  However I ran into a problem and hope that someone can help me.
<root>
<MyItem  Host="00155DFF045C" LastName="HOUSTON" FirstName="WHITNEY" >
    <TimeStamp ComputerTime="02/07/2011 - 21:41:53.715">
        <Group Name="Group1">
            <Variable ID="1001" Value="Happy" >
            </Variable>
        </Group>
        <Group Name="Group2">
            <Variable ID="2000" Value="Monday" >
            </Variable>
            <Variable ID="2001" Value="Tuesday" >
            </Variable>
        </Group>
        <Group Name="Group3">
            <Variable ID="3000" Value="January" >
            </Variable>
            <Variable ID="3001" Value="February" >
            </Variable>
        </Group>
        <Group Name="Groupe4">
            <Variable ID="4001" Value="108.000000" >
            </Variable>
            <Variable ID="4002" Value="800" >
            </Variable>
        </Group>
        <Group Name="CustomGroup">
            <Variable ID="1001000" Value="1.000000" >
            </Variable>
        </Group>
    </TimeStamp>
</MyItem>
<MyItem>
...
...
</MyItem>
</root>

I correctly get info like {Host="00155DFF045C" LastName="HOUSTON" FirstName="WHITNEY} thanks to the tutorial.
But I need to get some more information.  How can I retrieve Value of the Variable element with ID="4001" which belongs to Groupe4?
My current code is:
XElement xmlTweets = XElement.Parse(e.Result);
var toto = from tweet in xmlTweets.Descendants("MyItem").Take(10)
           orderby tweet.Element("TimeStamp").Attribute("ComputerTime").Value descending
           select new History {
               DisplayName = tweet.Attribute("PatientFirstName").Value + " " +
                             tweet.Attribute("PatientLastName").Value
           };

With this code, I can correctly get value for DisplayName.  I would like to get value of variable 4001, i.e., value 108.0000.
Comment: Do you have any code written down so far?  It would make helping you know how to do it, easier to do.
Comment: Hi Jeff, I just updat my initial poste with my current code. Hope you can help me :)
Comment: If you have some source code you'd like to format, just paste it in and indent it with four spaces. It will be displayed nicely for you.  Just be sure to adjust it afterwords so it is readable.  :)
Comment: Thx so much, it simply works with you gave me !
Answer: If you have a reference to a particular element, you can get values from any of its nested elements using the Element() or Attribute() methods.  You can get a list of these using Elements() or Attributes() to perform LINQ queries on them.  Assuming we have a reference to the root element, you can get the following information:
XElement root = ...;
XElement myItem = root.Element("MyItem");               // get the first "MyItem" element
string Host = myItem.Attribute("Host").Value;           // get value of "Host" attribute
string LastName = myItem.Attribute("LastName").Value;   // get value of "LastName" attribute
string FirstName = myItem.Attribute("FirstName").Value; // get value of "FirstName" attribute

// find "Groupe4"
XElement Groupe4 = (from g in myItem.Element("TimeStamp")
                                    .Elements("Group")
                    where g.Attribute("Name").Value == "Groupe4"
                    select g)   // only one element should be found
                   .Single();   // assign that element to variable Groupe4

// Get Value of Variable with ID = 4001
double Value4001 = (from v in Groupe4.Elements("Variable") // of all Variable elements
                    where (int)v.Attribute("ID") == 4001   // choose elements where ID = 4001
                    select (double)v.Attribute("Value"))   // select the Value
                   .Single();                              // assign that value to variable Value 4001

So to apply that to your query, you can do something like this:
XElement xmlTweets = XElement.Parse(e.Result);
var id = 4001;   // the ID to find
var toto = from tweet in xmlTweets.Descendants("MyItem")
                                  .Take(10)
           orderby (DateTime)tweet.Element("TimeStamp")
                                  .Attribute("ComputerTime") descending
           select new History {
               DisplayName = String.Format("{0} {1}",
                   tweet.Attribute("PatientFirstName").Value,
                   tweet.Attribute("PatientLastName").Value),

               // find the Variable with matching ID and get its Value as a double
               Value = (from v in tweet.Descendants("Variable")
                        where (int)v.Attribute("ID") == id
                        select (double)v.Attribute("Value"))
                       .Single()
           };

Answer: Once you have and XElement variable named myItemElement,
     myItemElement
            .Element("TimeStamp")
            .Elements("Group")
            .FirstOrDefault(x => x.Attribute("Name") != null && x.Attribute("Name").Value == "Groupe4")
            .Elements("Variable")
            .FirstOrDefault(x => x.Attribute("ID") != null && x.Attribute("ID").Value == "4001")
            .Attribute("Value").Value;

Comment: Hi Smartcaveman, you solution also works great ! Many thx to both of you.


Using Django generic CreateView with field editable=False

Question: I'm using a url scheme similar to /foo/1/bar/create where I'm creating a Bar object that has a foreign key to an existing Foo object with an id of 1.  I've made the foreign key field back to Foo within Bar with editable=False.
The Django docs give some general advise on dealing with fields editable=False, or fields you've excluded from the form but that are required on the save(), but not any advice specific to using the generic CreateView.
My CreateBarView already gets the Foo id via the url and hence it is already in the view's self.kwargs.  I'm trying to embrace the generic views to keep things DRY.
Is there a straight forward way of doing this in Django's Generic Views?  Particularly without having to subclass the form?
Note: overriding get_initial() doesn't work, and I believe the docs support that.
edit: Django 1.9
Answer: Reading over the Django Generic Views, it looks like overriding get_form() via get_form_kwargs might be the most straightforward if I follow the general docs, e.g.,
class FormMixin(...): # from django.views.generic.edit

    def get_form(self, form_class=None):
        """
        Returns an instance of the form to be used in this view.
        """
        if form_class is None:
            form_class = self.get_form_class()
        return form_class(**self.get_form_kwargs())

So,
class CreateBarView(...):

   def get_form_kwargs(self):
      kwargs = super(CreateBarView, self).get_form_kwargs()
      kwargs['instance'] = Bar(foo_id=self.kwargs['foo_id'])
      return kwargs


Set height to same as sibling div floating next to it?

Question: So I have 2 divs
currently
div#1 is {float:left; width:48%} and contains some gallery doodad
div#2 is {float:right; width:48%} and contains a stack of buttons
after that, within the same container a bunch of other divs and plaintext follows.
So what I would like to do is have div#1 keep doing its automatic height thing but I want div#2 height to equal div#1 so I could vertically stretch out the buttons inside.
I have no access to the structure (buried somewhere deep in the php framework) and all I got is CSS. Is this possible within my current constraints?
Answer: Apply
display: flex;

to the surrounding container, then
float: none;

to div#1and div#2.
Note: This is only a viable solution if there is a parent container that does only contain these two div.
Learn more about flex.
Comment: hooray, I done it with {display:flex; flex-wrap:wrap;} since I had more stuff in there. They seem to follow their available dimension specs when in wrap mode so 100% for 1 in row, <50% for 2 in row etc.
Comment: Remember to click the checkmark left of the answer that best helped you solve the problem.
Answer: Without seeing it's hard to say for sure, but I would think that if div#1 and div#2 both had height:100%, then when div#1 "grows" from content, so will the parent div, and because both child divs (1 & 2) are 100% height of the parent, both should grow equally.
Answer: For browsers that support CSS3.
Set a parent DIV:

Then in CSS set #parent_DIV to display as table (display:table). Each child DIV set to display:table-cell.
In this case the higher div will set the rule.
Add borders to each (including parent) for trial and test it out.
I have pulled this from the head but generally that will work, including newer IE browsers.
Here it's in more details:
http://www.brenkoweb.com/tutorials/css/css-visual-formatting-model/display-property.php
And soon hopefully more examples will folow.


How to show that $\frac {1}{2^n} \lt \frac {1}{n}$ for all $n \in \mathbb N$?

Question: How to show that $\frac {1}{2^n} \lt \frac {1}{n}$ for all $n \in \mathbb N$? I tried using mathematical induction. The base case is evidently true since $$\frac {1}{2} \lt 1$$ Assuming that the proposition holds for some $k \ge 1$ such that $k \in \mathbb N$, then we need to show that $$\frac {1}{2^{k+1}} \lt \frac {1}{k+1}$$ This is where I don't know how to proceed. All I could achieve was $$\frac {1}{2^{k+1}} \lt \frac {1}{2} \cdot \frac {1}{2^{k}} \lt \frac {1}{2^{k}} \lt \frac {1}{k}$$
Comment: You can also just prove that $2^n>n$ for all $n\in\mathbb{N}$.
Comment: use $2^n\geq 2n>n$
Comment: If you don't forget the factor $\frac12$ and write $$\frac{1}{2}\cdot\frac{1}{2^k} < \frac{1}{2}\cdot\frac{1}{k},$$ you will probably get to the end.
Answer: $\frac {1}{2^{k+1}} = \frac {1}{2*2^{k}} \lt \frac {1}{2k} \leq \frac {1}{k+1}$
Comment: The leftmost strict inequality does not hold. It's an equality.
Comment: Yea but again the right-most has an issue. Take $k=1$, we have an equality. See my hint above.
Answer: $\dfrac{1}{2^n}\leq \dfrac{1}{2n}<\dfrac{1}{n}$
Answer: We shall show that for all $n\in \mathbb{N}\backslash\{0\}$, $n<2^n$. Let $n=1$, then the result is trivial. Now suppose we have already proven that $n<2^n$ for $n\ge1$. Then we have
$$2^{n+1}=2\cdot2^{n}>2\cdot n \ge n+1$$
Since $n\ge1$, so we have $1/2^n<1/n$ as desired.


Can I prevent calc() from simplifying when setting the style in Javascript?

Question: I created a function in JavaScript to apply a style.right to an element. Depending on the media width, I am applying one of the following three styles to it
listElements[i].style.right = "calc(425 * " + portfolioScrollPosition + "px)";

or
listElements[i].style.right = "calc(33.333 * " + portfolioScrollPosition + "vw)";

or
listElements[i].style.right = "calc(50 * " + portfolioScrollPosition + "vw)";

I need it to be written into html embedded styles EXACTLY like this. However, the calc() is simplifying, and is just writing something like calc(425px). Is there any way to prevent JS from making this simplification?
Comment: each value must have a unit, it's not a simple calculator as you think it is...so it would be `425px` and `33.333vw`
Comment: With multiplication only one argument needs a unit, so this should be working though since it's applying the unit it looks like `portfolioScrollPosition` is 1.
Comment: It depends on what you want the calculation to do. If you simply want it to multiply, why can't it "simplify" that by multiplying the two numbers when you set the numbers? There is no difference between `calc(50 * 2vw)` and `calc(100vw)`
Comment: it's because it doesn't know that your 425 number is. You must supply unit type with it, i.e. `425px`
Comment: @vanowm: there is a unit, both `px` and `vw` in the various assignments?
Comment: @vanowm: [nope](https://jsfiddle.net/davidThomas/b3fo8k6y/).
Comment: oh, interesting, it does simplify when one number is 1
Comment: You might consider instead of setting up values like this, set [CSS variables](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties) instead and have CSS that would use these variables in the `calc()`
Comment: Please provide enough code so others can better understand or reproduce the problem.
Comment: @vanowm, in `calc(..)` the end result must have a unit that is accepted by the attribute the result is assigned to. And using unitless values in `calc(..)` is perfectly legal with mult and div (*/): `calc(100vw / 5)` or `calc(425 * 5px)` both result in a legal value.
Comment: @vanowm here's some code I use daily: `:root { --a11y-scale: 1; --doc-lh: clamp(1.25, calc(-0.125 * var(--a11y-scale) + 1.625), 1.5); --doc-unit: 0.0625rem; --doc-base: calc((0.625vmin + 12 * var(--doc-unit)) * var(--a11y-scale)); }` to calculate a responsive `line-height` and `font-size` based on some a11y scale value including *px* to *rem* conversion (`--doc-unit`). Usage: `body { font-size: var(--doc-base); line-height: var(--doc-lh) }` and enable changing `--a11y-scale` with a range slider. Just showing the power of linear math in `calc(..)`.
Comment: Why do you need this be EXACTLY in this format?
Answer: Getting it into the rendered style sheet is tricky but adding it to an elements in-line style that reads as you want it when examined in developer tools can be done by using template literals (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)
Elemement.setAttribute("style", `right:calc(425 * ${portfolioScrollPosition}px;`);

If you really need it in the style sheet, you would have to change the inner text of the entire style element.
 is like any other element, you can make a reference to it and change it's inner text using element.textContent = "" or element.innerText. It will be messy with a big style sheet.
Edit I've made a working example to illustrate the approach of re-writing the style element's innerText here: https://jsfiddle.net/DaveCP/8czrnhwe/1/
(the SO snippet tool has trouble with new line characters in a string).
In the example, the style rule aspect-ratio: calc(2 / 1); is re-written to aspect-ratio: calc(4 / 1)


Find $p,q,r\in \mathbb Q$ such that $r^2-5=p^2$ and $r^2+5=q^2$

Question: Find $p,q,r\in \mathbb Q$ such that
$$r^2-5=p^2$$
$$r^2+5=q^2$$
I added and subtracted those two that gave me no luck.
Comment: Then the answer can be given in terms of $p$ and $q$? If you add, you get $2r^2=p^2+q^2$. You just want to move the factor of $2$ to the right, and get rid of the square, which should be direct.
Comment: @KevinLong The question is to find such $r$,$p$, and $q$. I'll revise to clarify this,
Comment: The following might be helpful but won't give a solution. Start from $2r^2=p^2+q^2$ and denote $x=p/r, y=q/r$. Then the equation becomes $x^2+y^2=2$. This equation has a solution $(1,1)$ and all of its rational solutions can be parametrized by lines which passes $(1,1)$ and has rational slope except (1,-1). Then you can find all possible solutions of $x=p/r$. To proceed you need to consider $1-5/r^2=x^2$, or $1/(1-x^2)$ need to be a rational. I don't know how to do this part.
Comment: Decision in what numbers am I looking for? In integer or rational?
Comment: @individ Rational. Thanks.
Answer: Here is an extension of my comments.
Start from $p^2+q^2=2r^2$. Denote $x=p/r,y=q/r$. Then the equation become $x^2+y^2=2$. We solve all possible rational solutions of the equation $x^2+y^2=2$. It has one solution $P=(1,1)$. Let $Q\ne (1,-1)$ be any other rational point on this circle, then the slope $k$ of $PQ$ is rational. The line equation of $PQ$ can be expressed as $y=k(x-1)+1$. From the line and circle equation one get the $x$-coordinate of $Q$ is
$$(1)\quad x_Q=\frac{k^2-2k-1}{k^2+1}.$$
We need to consider another equation $r^2-5=q^2$, which can be rewritten as $$1-\frac{5}{r^2}=x^2.$$
From equation (1), one obtains
$$\frac{5}{r^2}=1-x^2=\frac{4k(k-1)(k+1)}{(k^2+1)^2}.$$
Let $Y=(k^2+1)/(2r)$ and $X=k$, the above equation becomes
$$5Y^2=X^3-X, X\ne 0, \pm 1.$$
This equation is equivalent to
$$(2)\quad Y^2=X^3-25 X. X\ne 0, \pm 5.$$
The above elliptic curve has no torsion points other than $X=0,\pm 5$. Since $5$ is a congruent number, the elliptic curve (2) has infinite number solutions. The reference is N.Koblitz' book "Introduction to Elliptic curves and modular forms".
Here is one solution $p=113279/1494696$, $q=4728001/1494696$, $r=3344161/1494696$ with $k=41^2/(5\cdot 12^2)$.
Here are further details on how to find solutions of your problem. This is essentially proposition 1.1 of Koblitz' book. We call an integer $n$ a congruent number if it is area of a right triangle whose sides are rational numbers, i.e., if there exists $X,Y,Z\in \textbf{Q}$ such that $Z^2=X^2+Y^2$ and $n=\frac{1}{2}XY$. We call $(X,Y,Z)$ a solution of the congruent problem for $n$.
We next consider your problem: (Problem (*)) given a positive integer $n$, is it possible to find rational $p,q,r$ such that $r^2-p^2=n, r^2-q^2=-n$.
Proposition 1.1 of Koblitz' book says that the above two problems are equivalent in the following way.
Given a solution $(p,q,r)$ of Problem (*), let $X=q+p,Y=q-p,Z=2r$. Then $(X,Y,Z)$ is a solution of the congruent problem for $n$.
Conversely, given a solution of the $X,Y,Z$ of the congruent problem, one can find a solution of the congruent problem by $r=Z/2,q=(X+Y)/2,p=(X-Y)/2$.
Now your question becomes how to find a congruent problem for 5. Here is one classical solution $(X=20/3,Y=3/2,Z=41/6)$. Using the above correspondence and this classical solution, one can get an easier solution of your problem $$p=31/12,q=49/12,r=41/12.$$
My previous solution is too complicated, and it also comes from Koblitz' book. The elliptic curve method has at least one advantage: from one solution, one can get infinite number solutions by addition law from the elliptic curve.
In general, the congruent number problem is very hard and probably not solved in its most general form. This is an active area of research.
Comment: Thanks. Could you give me a little bit more of information on how to find rational solutions for the equation (2)? [some link or etc. as I don't have the book you mentioned. Thanks.]
Comment: @KayK. I edited my post and gave a much easier solution. But the easier solution comes from the book I mentioned. Probably I should delete my original solution.
Comment: Thanks. I really appreciate.
Answer: multiplying $$r^2-5=p^2$$ by $-1$ and adding to the second one we obtain
$$10=p^2-q^2$$ wrting this equation in the form $$10=(q-p)(q+p)$$ can you finish now?
Comment: It's not so simple: you have to pick $p$ so that $p^2+5$ is a square of a rational number.
Comment: @TonyK I think the Dr. saw my question before I clarified. He probably thought as if $p$ and $q$ were given. I'll +1 to cancel the downvote.
Comment: I think it may also not have been immediately obvious that the variables involved were over the rationals; factoring approaches make a lot of sense over the integers (and provide the clearly-unique solution there).


No intercept model with more than one factor

Question: I am using SAS for linear regression with two independent categorical variables.  When I run models with each categorical variable separately, I get estimates for every level of both variables. This makes sense since I have no intercept to act as the reference. However, when I put both categorical variables in the same model, I am not getting an estimate for one level of one of the categorical variables. I believe I should get estimates for every level of both categorical variables since there is no intercept to act as a reference. Do categorical variables need to be parameterized differently in a no intercept model with multiple categorical variables?
Comment: Note that the issue here really doesn't relate to SAS; it's a mathematical issue. I will change your title to be more general
Answer: The "omit the intercept to get estimates for each level" thing only works with one factor.
By having all the levels of the first factor you have (in effect) an intercept in there (the sum of the 0-1 dummies for that first factor is all ones), which means you must leave out one df from any further factors in the model just as if you had an explicit intercept.
As soon as you have all levels of two factors, you will have perfect multicollinearity (the sum of the dummies for the first factor is identical to the sum of the dummies on the second factor).
e.g. consider two factors, $g$ (3 levels) and $t$ (2 levels). The 6 possible factor combinations are:
<code>  t1   t2       g1  g2  g3
  1    0        1   0   0
  1    0        0   1   0
  1    0        0   0   1
  0    1        1   0   0
  0    1        0   1   0
  0    1        0   0   1
</code>
Now to see there's perfect multicollinearity there, we just compute the sum for each factor: T = t1+t2 and G= g1+g2+g3
<code>  t1   t2  T     g1  g2  g3  G
  1    0   1     1   0   0   1
  1    0   1     0   1   0   1
  1    0   1     0   0   1   1
  0    1   1     1   0   0   1
  0    1   1     0   1   0   1
  0    1   1     0   0   1   1
</code>
... and we see that T=G, which shows that we have perfect multicollinearity.


Migration from Xen to KVM

Question: I have Xen domU virtual machines running Windows. Each of them are installed in their own LVM logical volumes. I want to migrate them to another server with KVM on lvm to.
How can I do this faster and better with low downtime.
Answer: look at http://fedoraproject.org/wiki/Features/Xen_to_KVM_migration
virt-v2v description: http://rwmj.wordpress.com/tag/virt-v2v/
Answer: A lot depends on how the LVM logical volumes are constructed and accessed.
If they are on a shared storage, it should just be a simple matter of creating new KVM machine configurations and pointing them towards the shared storage. You will need to ensure that the Xen configurations and KVM configurations match as closely as possible.
Then, you will need to shutdown the machines on the Xen and start them on the KVM. The Windows machines will probably complain that they have been moved and may need to be re-activated.
If they are not on a shared storage, then there is no easy way. You will need to replicate the LVM volumes. Since this will take an awful lot of time over the network, you may just want to re-create the machines on the new server.

Migration from Xen to KVM


How to develop Nth level of nested tabular output by using angular js ng-repeat

Question: out of curiosity i like to know can we develop Nth level of nested tabular output by using angular js ng-repeat.
here is one screen shot attached because other people can understand what kind of output i am after. basically i have to show manager and employee relation info in nested format. a manager can have many employee and each employee can again manager of other employee. in this scenario it is not know how many nesting could be show by ng-repeat. so give me honest feedback that this kind of nth level nested output can be achieve by ng-repeat or do i need to look for any angular free grid. thanks
Answer: You can use this type of a pattern with ng-repeat and ng-include to create a nested grid with an unknown number of nestings.
ng-repeat unknown number of nested elements
Comment: thanks but how can i load detail row dynamically when user click on parent. any idea.


Adding Divs in Blocks

Question: I've created a custom block with Div and P tags in which some have id and class attributes. I've tried use FULL & Filtered html formats for the block body however the id and classes don't show up once I've added the block.
Comment: As you've noticed, The FULL and Filtered HTML filters strip out CSS styles, id's, classes, etc. from the full or filtered tags.  No way around it except to either create a verbatim filter to to create the block in a module.
Comment: how would i create a verabtim filter? would this be done in views?
Answer: In admin/structure/types/manage/your_content_type/display  (drupal 7 path) make sure field Body has format "Default" selected. If you have any other format those will remove the div ids and classes from the body.
Answer: Please try change to PHP code which this option appear when you enable php filter in Modules page.
Comment: umm, do this only at great peril
Comment: Oh, I just know this way is peril. Thanks Jimajamma
Comment: Enabled php filter on production site can cause big problems if editor of the site is not careful.

Adding Divs in Blocks


Deriving sum of powers formula using generating functions

Question: Just for fun I wanted to try to derive a formula for the sum of $p$-powers using generating functions, but without using any literature or websites for help. However I do need a small push or hint.
Let $p$ be some positive integer constant.
Define $f(n) = \sum_{k=0}^{n} k^p = 0^p + 1^p + 2^p + 3^p + \cdots + n^p$
I can also state it as a recurrence: $f(n) = f(n-1) + n^p$ where $f(0) = 0$.
Define $G(x) = \sum_{n=0}^{\infty} f(n) x^n$
Then
$$
\begin{aligned}
G(x) &= f(0)x^0 + \sum_{n=1}^{\infty} f(n) x^n\\
G(x) &= 0 + \sum_{n=1}^{\infty} f(n-1) x^n + \sum_{n=1}^{\infty} n^p x^n\\
G\left( x \right) &=x\sum_{n=1}^{\infty}{f}\left( n-1 \right) x^{n-1}+\left( -0^px^0+\sum_{n=0}^{\infty}{n}^px^n \right)
\\
G(x) &= x\sum_{n=0}^{\infty} f(n) x^{n} + \sum_{n=0}^{\infty} n^p x^n\\
G(x) &= xG(x) + \sum_{n=0}^{\infty} n^p x^n\\
G(x) - xG(x) &= \sum_{n=0}^{\infty} n^p x^n\\
G(x) &= \frac{\sum_{n=0}^{\infty} n^p x^n}{1-x}
\end{aligned}$$
So now it is all about finding the generating function for $H(x,p) = \sum_{n=0}^{\infty} n^p x^n$
I need some way to get from $H(x,p-1) = \sum_{n=0}^{\infty} n^{p-1} x^n$ to $H(x,p) = \sum_{n=0}^{\infty} n^p x^n$ because the base case is $H(x,0) = \sum_{n=0}^{\infty} n^0 x^n = \sum_{n=0}^{\infty} x^n = \frac{1}{1-x}$
At this point I feel a little stuck and could use a push in the right direction. Am I onto a solution here or am I just spinning my wheels? Where can I go from here? I know one usual approach is to keep taking the derivative of both sides but I'd prefer to avoid that method (no real reason, just want to see if it can be done without noticing that trick).
How can I relate $H(x,p-1)$ to $H(x,p)$?
Comment: Good progress so far! Hint: what is $x\cdot \frac d{dx} H(x,p-1)$?
Comment: You might try $$x \dfrac{\partial}{\partial x} H(x,p) = H(x,p+1)$$
Comment: I'm not really familiar with how generating functions work, but I got $$H(x,p)=xH(x,p-1)-\int H(x,p-1) dx $$
Comment: @RobertIsrael Yes, but I have no clue what to do with that in terms of finding a closed-form for the generating function. What do you recommend for a next step?
Answer: It's convenient to use the  differential    operator $D_x:=\frac{d}{dx}$    and   the coefficient of operator $[x^n]$     to     denote     the coefficient  of  $x^n$  of a  series $A(x)=\sum_{k=0}^\infty a_kx^k$.

Hint: Study the operator
  \begin{align*}
[x^n]\frac{1}{1-x}(xD_x)^p
\end{align*}
  applied on $\frac{1}{1-x}$.

A detailed answer can be found here.
Answer: This answer may not follow the same line of reasoning but you might want to try out using derivatives and integrals of the generating function of $x^n$. the derivative of $1+x+x^2...+x^s$ is $1+2x+3x^2...sx^{s-1}$. On the rhs, we can differentiate the generating functions of the corresponding series. The derivative of $\frac{1-x^{s+1}}{1-x} = \frac{1-(1+s)x^s + s x^{1+s}}{(1-x)^2}$. Then apply l'Hopital's rule as $lim_{x \to\ 1}$. That will give you a function for the sum up to $s$. It is easy to see that in order to find the sum of $p$ powers, one must multiply the result by $x$ and differentiate the rhs, $p$ times.
Further, if we want to find the sum of inverse powers using generating functions, we must integrate the geometric series generating function and divide by $x$, $p$ times. This will not however give us a 'closed form' solution of formula in the case of inverse powers unless you consider the formula for the infinite sum of harmonic numbers, which is $-ln(x-1)$, this is technically true since the harmonic series ends up growing like the natural logarithm function. Also, this formula is useful because if you work it out for $x=-1$ you get the infinite sum of the alternating harmonic numbers - ln(2) - which is correct although the series is only conditionally convergent.
The method is pretty cumbersome since differentiating the fractions becomes increasingly complicated and you will have to apply l'hopital's rule $p+1$ times on the resulting fraction. So generating functions, (at least the method I used) would not really be practical to carry out unless you use software. A better method is described here...
https://en.wikipedia.org/wiki/Faulhaber%27s_formula
Answer: If I may, I will use the derivative but only very briefly.
Consider:
$$\frac {d^p}{dx^p}e^{kx}=k^pe^{kx}$$
Now sum over $k$:
$$\sum_{k=0}^n \frac {d^p}{dx^p}e^{kx} =\frac {d^p}{dx^p}\sum_{k=0}^n e^{kx}$$
You will recognize the geometric series on the right. This yields:
$$G(x)=\frac {e^{(n+1)x}-1}{e^x-1}$$


External Hosted React JS with plain Javascript and HTML page

Question: We have a common widget in each of our pages across multiple services, and we want to write a common client-side rendition code in ReactJS for this widget as an external hosted js, such that each of the pages can include this externally hosted JS in their pages to render the widget. But many of these pages are written in different JS frameworks (angular/inferno/typescript/etc) or even in plain vanilla JS. Now pardon me if this is an ignorant question, but I think that ReactJS code can be compiled into javascript using babel, and the bundled js file can then be directly included in any page using any framework(angular/typescript/etc). Is my assumption correct, or will such an approach lead to problems. Any other inputs?
PS: I am very new to any of these JS frameworks, and have only worked on small projects involving plain vanilla JS.
Answer: You can mount your react root node (typically <App/> ) in any html DOM node. This is what react-dom does by
render( <App />, document.getElementById("root"));

which would be a familiar line for you.
Now, coming to how to actually do this. I assume you are using create-react-app.

Run npm run build inside your project folder.
When it finishes, you will find a bunch of files inside your-project-folder/build, including

build/index.html
build/static/js, build/static/css, etc

Open the build/index.html file in a text editor and study it. I think you will be able to figure out the rest.
Comment: thanks @anand, but can including my JS file on the page conflict with common js libraries and versions used in both places. So lets say my widget JS is written in one version of reactJS and some other js libraries, while the page which includes the externally hosted compiled js for the widget, is written in another version of reactJS and imports different versions of same libraries, I think it can break the overall rendition of the page. Is there a way to go around such an issue.
Comment: My understanding is that it will typically not pollute the global namespace, as all the modules are supposed to be enclosed in closures when compiled to JS. But I am not sure if there is any way to be SURE of this.
Comment: However, if it is any comfort, note that adding react widgets into existing pages is a recommended way to use react https://reactjs.org/docs/installation.html#adding-react-to-an-existing-application
Comment: From the official docs: https://reactjs.org/docs/integrating-with-other-libraries.html


How can I have Behat create content with an address field properly filled?

Question: I'm writting a Behat test, where I'm triying to create a content that uses a field address, generated by Address Module. I'm using Drupal 9.0.7, Address Module 1.9.0 and behat 3.8.1. My goal is to create this type of content in my scenario; I'm using a behat table for this, and a Given statement like the following.
Given place content:

  | title   | field_address:country_code |field_address:address_line1 | status |
  |<<title>>| es                         | Behat test street          | 1      |

field_address:country_code and field address:address_line1 are sub-fields of the address field.
This way of naming the sub-fields doesn't seeem to work.
How should I have to name the table headers, in order to make Behat create content with a field address properly filled?
Comment: Have you already tried it in a format like at the bottom of the opening post there: https://github.com/ymcatwincities/openy/pull/237#issue-111160763
Comment: `| title | field_address:country_code | :address_line1 | status |` maybe?
Comment: Yes, and it doesn't work. It gives me "Notice: Undefined offset: 0 in vendor/drupal/drupal-driver/src/Drupal/Driver/Fields/Drupal8/AddressHandler.php line 54".
Comment: Is it maybe important, that there's a space between the pipe character and the field name? Because there the space is missing: `|field_address:address_line1` and here as well: `|<>|`. Is `<>` some kind of placeholder or wildcard? And is this address field a multi-value field?
Comment: I don't think the space is important but I will try it to assure that that's not the case. And no, <> it's not a wildcard. It doesn't matter here because title works properly,and when I post the question, I didn't pay attention to it, and place it as a wildcard to expess that it's not important. Sorry if Iconfuse you. I will try to put the spaces to see if it works. Thanks for your help!!
Answer: I'm a bit late to the party but here is the proper way of doing it.
And "CONTENT_TYPE" content:
  | title          | field_address                    |
  | Bert and Ernie | address_line1: Sesame Street 123 |

The supported options are:
$addressFields = [
  'given_name',
  'additional_name',
  'family_name',
  'organization',
  'address_line1',
  'address_line2',
  'postal_code',
  'sorting_code',
  'locality',
  'administrative_area',
  'country_code',
];

Which can be found in \Drupal\Driver\Fields\Drupal8\AddressHandler::expand
Currently there is a bug in drupal/drupal-driver so if you are using composer (which you should) you can apply the following patch. Otherwise you will get an error like "Notice: Undefined offset: 0"
"drupal/drupal-driver" : {
    "Issue #206: Address field in Drupal 8 (PR: 236/240)": "https://patch-diff.githubusercontent.com/raw/jhedstrom/DrupalDriver/pull/240.diff"
}


Implementing challenge/response scheme with python-requests

Question: I'm starting to learn how to use the python requests module. For practicing I tried to manage a challenge/response problem: I want to access the data on http://lema.rae.es/drae/srv/search?val=hacer
With the "Tamper Data" plugin for Firefox I inspected the necessary HTTP requests:
GET http://lema.rae.es/drae/srv/search?val=hacer
POST http://lema.rae.es/drae/srv/search?val=hacer

I copied the exact headers that are sent by Firefox in the two HTTP requests and implemented the JavaScript "challenge" function in Python. Then I'm doing the following:
url = "http://lema.rae.es/drae/srv/search?val=hacer"
headers = { ... }
r1 = requests.get(url=url, headers=headers)
html = r1.content.decode("utf-8")
formdata = challenge(html)
headers = { ... }
r2 = requests.post(url=url, data=formdata, headers=headers)

Unfortunately, the server will not answer in the expected way. I checked all the headers I'm sending via "r.request.headers" and they agree perfectly with the headers that firefox sends (according to Tamper Data)
What am I doing wrong?
You can inspect my full code here: http://pastebin.com/7JAZ9B4s
This is the response header I should be getting:
Date[Tue, 10 Feb 2015 17:13:53 GMT]
Vary[Accept-Encoding]
Content-Encoding[gzip]
Cache-Control[max-age=0, no-cache]
Keep-Alive[timeout=5, max=100]
Connection[Keep-Alive]
Content-Type[text/html; charset=UTF-8]
Set-Cookie[TS014dfc77=017ccc203c29467c4d9b347fb56ea0e89a7182e52b9d7b4a1174efbf134768569a005c7c85; Path=/]
Transfer-Encoding[chunked]

And this is the response header I really get:
Content-Length[5798]
Content-Type[text/html]
Pragma[no-cache]
Cache-Control[no-cache]

Comment: Found this via google. This does NOT work: https://github.com/vibragiel/glotologia/blob/master/enmiendas_drae/enmiendas-drae.py The following on the other hand suggests that we need to set a cookie: http://stackoverflow.com/questions/26952643/how-to-obtain-a-cookie-from-a-remote-domain-using-greasemonkey But for me the page also works when disabling cookies in the browser!
Comment: This works (!): https://github.com/javierhonduco/nebrija I still have to find out how it works though...
Comment: ... it always sends the same challenge string and it doesn't set any cookies or anything?!
Answer: I found the reason why my code doesn't work:
The server expects the POSTDATA in exactly the same order in which the entries appear as input-elements of the form. In my code the values of the input-elements were stored in a python dict. But this data type does not preserve the order in which values have been declared!
The ruby script (referred to in the comments) however does work because the ruby dict data type seems to preserve the order of declaration!
Furthermore, reimplementing the javascript challenge() function in python was not necessary at all, because the server will be happy to accept any response string (that worked in the past) over and over again!
Comment: One solution, i.e. one way to send the header in a predefined order, is by using urllib2.urlopen which expects a `params` parameter that contains the POSTDATA as a string (that is necessarily ordered, of course).


Excluding specific user role from query

Question: I have this query, which fetches all users with the role #7.
<code>$query = 'SELECT DISTINCT(ur.uid)
  FROM {users_roles} AS ur
  WHERE ur.rid IN (:rids)';

$result = db_query($query, array(':rids' => array(7)));
</code>
Some users currently have both roles #7 and #8. I beleive they are all fetched by this query. I would like to exclude users with the role #8.
Can someone help me?
Comment: this query is working fine for me.
Answer: Try
<code>$query = 'SELECT DISTINCT(ur.uid)
  FROM {users_roles} AS ur
  WHERE ur.rid IN (:rids) AND ur.rid NOT IN (:rids2)';

$result = db_query($query, array(':rids' => array(7), ':rids2' => array(8)));
</code>
Or if you wanted just the more specific version
<code>$query = 'SELECT DISTINCT(ur.uid)
  FROM {users_roles} AS ur
  WHERE ur.rid = (:rids) AND ur.rid != (:rids2)';

$result = db_query($query, array(':rids' => 7, ':rids2' => 8));
</code>
Comment: this looks logical to me, however I still get users tagged in both roles :(
Answer: I found it.
<code>$query = 'SELECT DISTINCT(ur.uid) FROM `users_roles` AS ur
WHERE ur.rid = (:rids) AND ur.uid
NOT IN (SELECT uid FROM `users_roles` WHERE rid = (:rids2))';

$result = db_query($query, array(':rids' => 7, ':rids2' => 8));
</code>

Excluding specific user role from query


Why is there space at the right of my website? (Wordpress)

Question: I have a wordpress site.
I don't know how this happened, but now it obviously has got a lot of spae to the right!
Can some of you see through the souce and see if you find anything suspicious?
It would be really appreciated! Thanks :)
Site: gone! :)
Comment: Seems fine. What browser are you having problems with?
Answer: It's because of your translation bar image in line 1031.

I'ts 960 Pixels wide and forces the body to stretch to the right.
Best clip it, or give one of the surrounding containers overflow: hidden.
The Web Developer Toolbar for Firefox is a great extension that helps find out such things using its "highlighter" function. I use it alongside Firebug to debug HTML.
Comment: Thank you!
I can fix it, now that I know where the problem is :)
Answer: It is because of the code that you have put for the flags, when i removed this code using firebug:

There was no more space :)


Problem with a basic lemma in Lambda Calculus

Question: I have some serious problems with Lambda Calculus. In an introduction by Barendregt and Barendsen at page 11 there is the following lemma, whose proof I do not completely get.

$\mathbf{\lambda} \vdash ( \lambda x_1 \dots x_n . M) X_1\dots X_n = M [ x_1 := X_1] \dots [x_n := X_n]$.

Even if I find the result intuitive, the proof, which should be obvious by induction and $\beta$-reduction, is not clear. In particular, I really don't get why the order is preserved in the manipulation, that is, from LHS we get on the RHS that  $x_1 := X_1$,
$x_2 := X_2$, etc (and I think here the order has to be important). I have the feeling that this is the symptom of a deep misunderstanding of how lambda calculus works in general.
Any feedback is greatly appreciated.
Answer: There is an implicit but fundamental hypothesis in the lemma you cited: the variables $x_1, \dots, x_n$ are not free in $X_1, \dots, X_n$. This is the reason why the order of the substitutions in $M[x_1:=X_1]\dots[x_n :=X_n]$ actually does not matter.
This hypothesis is implicit in the definition of $\beta$-conversion, because you always assume the variable convention 2.6 (p. 10):

If $M_1, \dots, M_n$ occur in a certain mathematical context (e.g.
  definition, proof), then in these terms all bound variables
  are chosen to be different from the free  variables.

Note that this variable convention is also crucial in the definition of substitution for abstractions (p. 10). Indeed, setting
$$(\lambda y.M)[x := N] \equiv \lambda y. M[x := N]$$
is correct only in the case $y$ is not a free variable in $N$; this condition can always be fulfilled by renaming bound variables ($\lambda$-terms are considered up to $\alpha$-conversion, i.e. up to renaming of bound variables).
If the variable convention were not fulfilled you would have for instance
$$(\lambda y. x)[x := y] \equiv \lambda y.y\,,$$
which is clearly wrong, instead of the correct
$$(\lambda y. x)[x := y] \equiv \lambda z.y\,.$$
Comment: Thanks a lot for your answer. I think I need some time to digest it, since it is slightly more abstract that what I was looking for. But still, thanks a lot!
Comment: Concerning your comment below Patrick Stevens' answer, I see what you mean (I think that Patrick Stevens was assuming it as well as I was).
Comment: Not sure you could see it, but I just wrote now below Patrick Stevens' answer a comment where I try to express how helpful your answer is (I am literally understanding, maybe the obvious, but still something I did not understand before).
Answer: Note that $(\lambda x_1 x_2. M)X_1 X_2$ is actually shorthand for the following:
$$((\lambda x_1 . (\lambda x_2 . M)) X_1 ) X_2$$
Considering the second $\lambda$-term as being opaque - say it's $Q$ - that is $((\lambda x_1 . Q) X_1 ) X_2$, which is just $(Q[x_1 := X_1])X_2$ by $\beta$-reduction.
Now substitute back $Q = \lambda x_2 . M$, so we have $$((\lambda x_2 . M)[x_1 := X_1]) X_2$$
Since $x_1$ does not appear in the phrase "$\lambda x_2$", we can move the substitution inside the $\lambda$-term: $$(\lambda x_2 . M[x_1 := X_1]) X_2$$
And now we are in a position to use induction: we've shown that $$(\lambda x_1 x_2 .M)X_1 X_2 = (\lambda x_2 . M[x_1 := X_2])X_2$$
and we can just keep going in the same way.
Comment: Pay attention that $(\lambda x_2.M)[x_1 := X_1] \equiv \lambda x_2.M[x_1 := X_1]$ holds not only because $x_1$ does not appear in the phrase "$\lambda x_2$", but also (and most importantly) because $x_2$ is not a free variable in $X_1$ according to the variable convention (see my answer).
Comment: Indeed, I was rather hoping that the OP would accept your answer and not mine :)
Comment: I don't care about points. The important thing is to understand the reason why something works. :-)
Comment: Exactly what I was looking for. Thanks a lot!
Comment: LOL. Btw, I wanted to write to Taroccoesbrocco that the more I think about his answer the more I appreciate it, but still I really needed the actual manipulation. Thus, for example, his emphasis on the variable being free suddenly made me literally see what's going on that I never got about this mysterious $lambda$-calculus, e.g.,for something like $\lambda x. (\lambda x. x)2$, since in $M := \lambda x. x$ the variable $x$ is not free, and the expression stays the same (*I truly hope now I did not write something completely wrong!*). Thus, really thanks a lot to both of you!
Comment: @PatrickStevens: I just came back to your answer and I was wondering about your statement that the original expression is a shorthand for $(\lambda x_1 . (\lambda x_2 . M)) X_1 X_2$. Just to be sure I see how it works step by step, shouldn't it actually be a shorthand of the even more cumbersome $((\lambda x_1 . (\lambda x_2 . M)) X_1 ) X_2 )$?
Comment: @Kolmin Yep, I did indeed miss out those brackets.
Comment: @PatrickStevens: Ok, great! Maybe you could edit the answer for the learners that will come (if it is a problem, I will do it for you).


How to use query params to filter objects in DRF?

Question: I try to query a Course by its own field "name" instead of pk.
And what should be the path when querying this?
All basic Cruds and query by pk works fine with this code.
Here I have all related files attached:
models.py
from django.db import models

# Teacher = opettaja in Finnish
class Opettaja(models.Model):
    nimi = models.CharField(max_length=100, default='')
    puhelin = models.CharField(max_length=20, default='')

    class Meta:
        ordering = ['nimi']

# Course = kurssi in Finnish
class Kurssi(models.Model):
    nimi = models.CharField(max_length=100, default='')
    laajuus = models.IntegerField()
    opettaja = models.ForeignKey(Opettaja, on_delete=models.CASCADE)

    class Meta:
        ordering = ['nimi']

serializers.py
from rest_framework import serializers
from .models import Opettaja, Kurssi

class OpettajaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Opettaja
        fields = ['id', 'nimi', 'puhelin']

class KurssiSerializer(serializers.ModelSerializer):
    class Meta:
        model = Kurssi
        fields = ['id', 'nimi', 'laajuus', 'opettaja']

urls.py
from django.urls import include,path
from rest_framework import routers
from . import views

router = routers.DefaultRouter()
router.register(r"opettaja", views.OpettajaViewSet)
router.register(r"kurssi", views.KurssiViewSet, "nimi")

# My app is simply named as app in this project
urlpatterns = [
    path("api/", include((router.urls, "app"))),
]

views.py
from rest_framework import viewsets from .models import Opettaja, Kurssi from .serializers import OpettajaSerializer, KurssiSerializer

class OpettajaViewSet(viewsets.ModelViewSet):
    queryset = Opettaja.objects.all()
    serializer_class = OpettajaSerializer

class KurssiViewSet(viewsets.ModelViewSet):
    queryset = Kurssi.objects.all()
    serializer_class = KurssiSerializer
    def get_queryset(self):
        queryset = Kurssi.objects.all()
        nimi = self.request.query_params.get("nimi")
        if nimi is not None:
            nimi = nimi
        return queryset

I try to query a Course by its own field "name" instead of pk.
And what should be the path when querying this?
Answer: Give this a try
def get_queryset(self):
    queryset = Kurssi.objects.all()
    nimi = self.request.query_params.get("nimi")
    if nimi is not None:
        queryset = queryset.filter(nimi=nimi)
    return queryset

You don't have to change the URLs path for this, the URL should be something like

api/kurssi?nimi=some_name


calculate $\lim_{n\rightarrow\infty} n\left ( \ln(n^2 +1) -2\ln(n)\sqrt[n]{\ln(n)}\right )$

Question: As above, I have to calculate $$\lim_{n\rightarrow\infty} n\left  (  \ln(n^2 +1) -2\ln(n) \sqrt[n]{\ln(n)} \right )$$I tried to multiply it by $$ \frac{\left  (  \ln(n^2 +1) +2\ln(n)\sqrt[n]{\ln(n)}\right )}{\left  (  \ln(n^2 +1) +2\ln(n)\sqrt[n]{\ln(n)}\right )}$$ so that it is $$\lim_{n\rightarrow\infty} n \frac{\left  (  \ln^2(n^2 +1) -2\ln^2 (n) \sqrt[\frac{1}{2}n]{\ln(n)} \right )}{\left  (  \ln(n^2 +1) +2\ln(n)\sqrt[n]{\ln(n)}\right )},$$but it is not so easy to play with (first glance says that it goes to infinity), nevertheless, can somebody take a closer look at this and suggest something, please? I would be very grateful.
Answer: The following expansions yield readily an equivalent, hence the limit:

$\ln(n^2+1)=2\log(n)+\log\left(1+\frac1{n^2}\right)=2\log(n)+o\left(\frac1n\right)$.
$\sqrt[n]{\log n}=\exp\left(\frac1n\log\log n\right)=1+\frac1n\log(\log n)+o\left(\frac1n\right)$.