Multiple local sites in subdirectories using nginx

Question: I want to install both Drupal 9 and Drupal 10 on my localhost. I had based Nginx config on Nginx Drupal recipe and following is the part of Nginx config that I'm struggling with:
server {
    listen 80;
    root /var/www/drupal10;
    index index.php;

    location /drupal10 {
        try_files $uri /index.php?$query_string;
    }

    location @rewrite {
        rewrite ^ /drupal10/index.php;
    }
}
... and then the rest of configuration as per nginx drupal recipe

Similarly for nginx configuration of drupal9 subdirectory:
server {
    listen 80;
    root /var/www/drupal9;
    index index.php;

    location /drupal9 {
        try_files $uri /index.php?$query_string;
    }

    location @rewrite {
        rewrite ^ /drupal9/index.php;
    }
}
... and then the rest of configuration as per nginx drupal recipe

But I'm getting "404 Not Found". What could be the correct configuration?
Comment: There is a lot more configuration required for Drupal with nginx: https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/ You should base your configuration from the official one, then ask questions.
Comment: @cilefen that's true, I had based my configuration on nginx drupal recipes but I just put in the question only directives that I believe is impacting the setup to avoid long post. Do you think I should put the whole configuration for the question to be more clear?
Comment: You will save yourself much trouble by using DDEV for local Drupal development.
Answer: Resolved with following configuration:
server {
  listen 80 default_server;

  root /var/www;

  index index.php;

  location /drupal9 {
    alias /var/www/drupal9;
    try_files $uri /drupal9/index.php;
  }

  location /drupal10 {
    alias /var/www/drupal10;
    try_files $uri /drupal10/index.php;
  }

# Additional settings for PHP and Drupal from nginx drupal recipe[1]
# ...


Is there a way to add a Mapbox style to Drupal Leaflet?

Question: I have recently upgraded to the latest version of Drupal, and the module 'Leaflet Mapbox' (https://www.drupal.org/project/leaflet_mapbox) is no longer supported.  I was wondering how I would go about adding a Mapbox style to the Drupal Leaflet map?  I have tried following the Mapbox documentation, however, the leaflet map is already a container on drupal so this does not work.
Comment: Which version of Drupal, specifically? If you upgraded from 7 to 8, there is a dev version of the module here: https://www.drupal.org/project/contrib_tracker/issues/2756323  You can install that, but since it is a dev release it may have broken features and/or bugs.
Answer: The Leaflet Mapbox module has now been released for Drupal 8/9


Troubleshooting AWS S2S VPN connection with on-prem network

Question: I am trying to set up a VPN connection between our AWS servers and a 3rd party network. The VPN tunnel in itself is active, but network calls are timing out.
The setup:

EC2 instances in private subnets have their traffic go through a NAT gateway with an Elastic IP (setup already works to reach the internet)
Default VPC route table targets a transit gateway for the destination IP address e.g. 188.8.131.52
TGW uses static routing and has a route table has a route that forwards all traffic to the attached VPN connection
EC2 security groups allow incoming & outgoing traffic, there are no specific NACLs
3rd party network's firewall has whitelisted internal IP of the NAT gateway's EIP

ping and curl timeout, while trace route only shows stars. In the TGW flow logs, I see successful packet transmissions between the NAT gateway and the destination IP 126.96.36.199 across the VPN TGW attachment, yet nothing aside DPD logs in the VPN tunnel logs
At this point, I suspect that something prevents packets from reaching the VPN tunnel, as I suppose that I would see some VPN tunnel logs even if the 3rd party network's firewall did not whitelist the relevant IPs (correct me if I am wrong). How can I further troubleshoot ?
Comment: This kind of thing is really tricky to track down based on a description, as networking can be complex. There's all kinds of things to check, and the person doing the checking really just follows their nose based on experience and what they find. Your best bet is to get an experienced professional to log into your AWS account and diagnose the problem with / for you. AWS Support may also be able / willing to help, if you have business support or higher.
Answer: The issue was caused by the on-premise network's VPN not using the AWS VPN tunnel's inside IPv4 CIDR range in its interface, once the connection was set up with the tunnel's outside IP address and inside IPv4 CIDR range it worked like a charm
For anyone who runs through a similar issue where packets are dropped while the VPN tunnel is up, you can also use AWS' reachability analyzer to verify whether traffic from an instance reaches the VPN TGW attachment


Validar uma expressão com base que os parênteses deviam fechar

Question: Estou resolvendo um exercício em Python em que tinha que validar uma expressão com base que os parênteses deviam fechar direito:

Crie um programa onde o usuário digite uma expressão qualquer que use parênteses. Seu aplicativo deverá analisar se a expressão passada está com os parênteses abertos e fechados na ordem correta.

Ex:
((a+b)*c)(x+y(3+2/3)*z) #é uma expressão válida
))(( #não é válida
6+)+85( #não é válida

Mas meu código sempre valida a expressão:
n1 = str(input('Digite uma expressão: ')).split()
for n2 in range(0, len(n1)):
    if n1[n2] == '(':
        for n3 in range(n2 + 1, len(n1)):
            if n1[n3] == ')':
                del n1[n2]
                del n1[n3]
                break
print(n1)
if '(' in n1:
    print('Expressão inválida')
elif ')' in n1:
    print('Expressão inválida')
else:
    print('expressão válida')

Answer: Se a ideia é somente verificar os parênteses (sem levar em conta se o restante é uma expressão aritmética válida), você só precisa de um contador, e de apenas um loop percorrendo os caracteres da string e atualizando este contador.
Se encontrar um (, incremente o contador em 1. Se encontrar um ), decremente o contador em 1. Se em algum momento o contador estiver negativo, quer dizer que foi encontrado um ) que não tem o ( correspondente (e aí nem precisamos verificar o restante).
Ao final do loop, se o contador for zero, é porque cada ( tem o seu ) correspondente e a expressão é válida:
expressao = input('Digite uma expressão: ')
cont = 0
for c in expressao:
    if c == '(':
        cont += 1
    elif c == ')':
        cont -= 1
    # se o contador é negativo, foi encontrado um ")" sem "(" correspondente
    if cont < 0:
        break # sai do for

if cont == 0:
    print('Expressão válida')
else:
    print('expressão inválida')

No for eu percorro os caracteres da string (repare também que não precisa de split, basta percorrer a string toda de uma vez). E para cada caractere, vou atualizando o contador conforme a lógica já explicada acima.
Se no meio do loop o contador ficar negativo, eu já sei que a expressão é inválida (tem um ) sem o respectivo () e nem adianta verificar o resto, por isso eu interrompo o loop com break.
Outro detalhe é que input já retorna uma string, então fazer str(input()) é redundante e desnecessário.

As outras respostas estão complicando desnecessariamente o algoritmo (obs: uma delas foi apagada). Ambas usam dois loops aninhados (um for dentro do outro, percorrendo a mesma string várias vezes desde o início) e várias chamadas de replace, que criam uma nova string.
Ou seja, além de loops desnecessários, são criadas várias strings durante o processo, o que torna os algoritmos bem ineficientes. No meu exemplo acima, só é feito um loop e nenhuma outra string é criada desnecessariamente. Só porque o código das outras respostas "funcionou", não quer dizer que sejam as melhores opções.
Uma delas - a que foi apagada - consegue ser ainda mais ineficiente, porque além de replace, ainda usa várias vezes split (que cria uma lista) e join (que junta a lista em uma string), além de usar index (que percorre a string desde o início, para encontrar o índice do elemento - e usar isso em um loop seguidas vezes torna o algoritmo muito ineficiente).
É claro que para poucas strings pequenas, a diferença será imperceptível (frações de segundos), mas rode algumas milhares de vezes e a diferença se mostrará de forma mais clara. Podemos fazer um teste simples com o módulo timeit:
def loops_aninhados(n1):
    for n2 in range(0, len(n1)):
        if n1[n2] == '(':
            for n3 in range(n2 + 1, len(n1)):
                if n1[n3] == ')':
                    n1 = n1.replace('(', 'o',1)
                    n1 = n1.replace(')', 'o', 1)
                    break

    if '(' in n1:
        return False
    elif ')' in n1:
        return False
    else:
        return True

def loops_aninhados2(n1):
    for n2 in n1:
        if n2 == '(':
            for n3 in n1:
                if n1.index(n3) > n1.index(n2):
                    if n3 == ')':
                        n1 = ''.join(n1).replace(n2, '', 1).replace(n3, '', 1)
                        n1 = n1.replace('', ' ').strip().split(' ')
                        break
    if '(' in n1 or ')' in n1:
        return False
    else:
        return True

def loop_simples(n1):
    cont = 0
    for c in n1:
        if c == '(':
            cont += 1
        elif c == ')':
            cont -= 1
        # se o contador é negativo, foi encontrado um ")" sem "(" correspondente
        if cont < 0:
            return False

    return cont == 0

from timeit import timeit

# testando 100 mil vezes, com uma expressão válida e outra inválida
number = 100000
valida = '((a+b)*c)(x+y(3+2/3)*z)'
invalida = '6+)+85(x-y)+z(-13*2/23(r/4))'
print(timeit('loops_aninhados(valida)\nloops_aninhados(invalida)', number=number, globals=globals()))
print(timeit('loops_aninhados2(valida)\nloops_aninhados2(invalida)', number=number, globals=globals()))
print(timeit('loop_simples(valida)\nloop_simples(invalida)', number=number, globals=globals()))

timeit retorna o tempo de execução em segundos. O tempo exato varia conforme vários fatores (como o próprio hardware da máquina, se tinha outras coisas rodando ao mesmo tempo, etc), mas em geral, os loops aninhados são mais lentos (e o segundo, que usa split e join várias vezes, é mais lento ainda). Na minha máquina os tempos foram:
1.3530971
6.647586800000001
0.32360029999999895

Rodei algumas vezes e os tempos - e principalmente a proporção entre eles - foi similar: a primeira opção foi em média cerca de 3 a 4 vezes mais lenta (se comparada à minha solução), e a segunda foi cerca de 15 a 20 vezes mais lenta. No Repl.it os tempos foram diferentes, mas a diferença relativa entre eles foi similar.
Enfim, é como um dos nossos mais famosos usuários costuma dizer: "Funcionar é diferente de estar certo".

Por fim, vale dizer que usar for, split, join, replace e qualquer outro recurso da linguagem não é "errado" por si só. Mas é importante saber quando e como usá-los, e se tiver um algoritmo melhor, mais simples e eficiente, e que não precisa deles, não faz sentido continuar usando-os só porque "funcionou".
E lembrando mais uma vez que estas soluções só verificam os parênteses balanceados. Se a ideia fosse verificar se é uma expressão aritmética válida, aí precisaria de outra solução.
Answer: Olá, Presado!!
Quero ser sincero em dizer que a tua lógica está muito boa!
Eu fiz alguns ajustes no teu código para que funcione! Gostaria que preste atenção no código!!
n1 = str(input('Digite uma expressão: '))

for n2 in range(0, len(n1)):
    if n1[n2] == '(':
        for n3 in range(n2 + 1, len(n1)):
            if n1[n3] == ')':
                n1 = n1.replace('(', 'o',1)
                n1 = n1.replace(')', 'o', 1)
                break

if '(' in n1:
    print('Expressão inválida')
elif ')' in n1:
    print('Expressão inválida')
else:
    print('expressão válida')

Espero ter ajudado!!


What hooks does couchbase sync gateway provide for sync?

Question: Is it possible to use couchbase syny gateway in the following way:
1) Mobile client queries couchbase for data.
2) No data in couchbase present so this triggers a import of the needed data from for example a mysql database into couchbase.
3) The imported data is then transfered to the mobile client by couchbase synch gateway.
4) The mobile client  goes to sleep.
5) After 12 hours of inactivity the data is removed from couchbase.
6) Next day the mobile client still holds the data offline and syncs again which sync gateway
7) the data is again imported to couchbase server and the diffs are synced with the client
Does couchbase provide hooks to implement such an flexable usecase?
If yes could somebody point me to the important api calls?
Many Greetings
Answer: The preferred way to do this would run most things through Sync Gateway (the data imports from the external source in particular should go through Sync Gateway, not directly to Couchbase, and removing the data should go through SG also.)
Sync Gateway's sync function runs when SG receives documents.  In this sense, there's no way to trigger something based on nothing being there.
One way you might solve this is by having the mobile client push a special purpose document.  Your sync function could catch this and react in several ways (fire a webhook request, start a replication, or you could set up something to monitor a changes feed and trigger from that).
Next you have the issue of removing the data on the Server side. Here the question is a little unclear.  Typically applications write new revisions to SG, and these get synced to the client (and vice versa).  If you remove everything on the Server side, you'll actually end up with what are called tombstone revisions showing the document as deleted.  (This is a result of the flexible conflict resolution technique used by Couchbase Mobile.  It uses multiversion concurrency control.)
The question is a little unclear.  It sounds like you don't want to store the data long term on the Server side.  If that's right, I think you could do something like:

Delete the data (through SG)
Have the mobile client push data to SG
Trigger SG again with some special document
Update the data from the external source
Have the client pull updates from SG

That's a very rough outline.  This is too complicated to really work out in this format.  I suggest you post questions through the Couchbase developer forum to get more details.
So, the short answer, yes, this seems feasible, but a full answer needs more detail on what you're doing and what your constraints are.


OS X tools for testing & visualizing network performance between two points

Question: A client of mine has had intermittent network issues between their office and their server hosted on AWS.
A speedtest (at speedtest.net) shows their bandwidth is fine.
When I test their server, from a different location, the speed is fine – works on my machine.
Can you recommend any tools for OS X which will allow them to visualize connection performance between their location and the host?
Ease of use is important – they are not command line savvy.
Answer: Depending on your relationship with this client and the setup, I'd be tempted to get a small headless workstation with SSH access and connect it to their network with remote access for you. You can script connection tests and such from that system. Something small and out of the way, rather than relying on them to use their own systems and run a procedure that they probably don't want to know about or understand to get results they won't know what to do with.
Comment: Yeah, I was hoping for some magic.  But this is a good solution. Thanks.
Comment: There could probably be something rigged up, but from the client-interface side, and trying to communicate with you what is happening, you're better off handling it yourself and keeping the burden on you rather than shifting the burden on them. At least in my experience.


Jenkins Slack integration, but can't find post-build action

Question: I want to use the Slack plugin in Jenkins to ping notifications to a Slack channel.
Jenkins says success when I test the connection, and I saw that connect was successful.
And after that, I need to add to Jenkins job configurations and add a post-build action on each job that you wish to ping the slack channel.
But I can't find post-build action in Job's configure.
Jenkins has version 2.121.3.
Comment: You mean you don't see the post-build action section or you dont see "Slack notification" in post-build option list?
Comment: Yes, I mean that can't  see the post-build action section.
Answer: What kind of job configuration are you using ? Freestyle ? Multibranch ? Pipeline ? It's likely that the post-build actions will not appear for every kind of Jenkins job/project.
If you create a new job (New Item > Freestyle project), you should see the option at the end.
Comment: Good advice, but i using Pipeline!
Comment: Same problem, I'm on Jenkins version 2.204.5 using Pipeline with a Jenkinsfile.  Test of Slack Notification plugin in Jenkins returned success.  I had thought this would be specified in the Pipeline => Additional Behaviors list, but haven't found it there yet.


Debugging with jstl - how exactly?

Question: I've been trying to understand BalusC's answer with regard to debuggability, and I still cannot figure out exactly how jstl tags are more easily debugged than scriptlets.
When I think of debugging, I think of the ability to step through the code and determine at any given point what variables are loaded into memory, and see their contents.  With jstl, I cannot set up breakpoints of any kind, and if any part of it breaks, pieces of whatever form I'm working on go missing.  I'm not sure which is worse: a blank page, or a half-loaded page.  I've seen situations where when the jstl fails, OTHER parts of the form go missing rather than only the parts it affects.  In either case, it's impossible to really see what the problem is.
With scriptlets, I can place breakpoints, and see any point I'd like in an IDE.  Even if I'm not using such a feature, I can print to the console any part of the procedure I want to see and figure it out later.  If the page fails and shows me a blank page, annoying as that may be, I can at least step through and find out exactly which line it fails on.
With jstl, I'm completely in the dark.  Iterating through a collection really feels like a black box where you hope everything comes out ok rather than actually being able to step through and watch it happen.  It makes you feel powerless.
I admit, jstl is cleaner, and looks more intuitive, but that one glaring problem I have is the inability to really debug anything on the page.  Am I completely mistaken here?  Am I just missing the nice happy way to debug what's going on?  Or is my approach to debugging incorrect, and in need of rethinking?
I've googled the issue, but I can't really seem to come up with any direct answers... If anyone has any insight on this, it would be really helpful.  I want to use jstl in lieu of scriptlets, and this is the one glaring thing keeping me back...
Comment: Related: http://stackoverflow.com/q/6945820/1065197
Comment: From BalusC's answer in your link: *Debuggability: if scriptlet throws an exception halfway, all you get is a blank page*. This is the only part he mentions it and never talks about JSTL debugging.
Comment: Dumping all the domain objects can be useful, but seeing what's in them at the start and seeing what's in them while you iterate through them and do stuff to them are different stories :).  So besides a dump, is there really no better way?
Comment: I've done what you say and it could be hard or easy, depending on how you see the problem. A common technique is [Divide and conquer](http://en.wikipedia.org/wiki/Divide_and_conquer) lot of definitions but they point to the same idea: break the big problem into small pieces, solve each piece and will solve the big problem. So, go step by step adding the JSTL/EL you need, make some test and on and on. Note that you can use `` in order to print something on the page (like debug messages). Is it hard? Maybe, but if you understand the concepts as request attributes and all, it is not.
Answer: You can add jsp scriptlets and print the variables jstl uses. This gets printed in the console or in the container's out file
    <c:set var="myVar" value='${param.myUrlParam}' />

    <% System.out.println(pageContext.findAttribute("myVar") ); %>

This is the only best way I could find to debug a jstl page.
Answer: JSTL tags themselves doesn't need to be debugged if you use them conform the JSP/EL specification and JSTL documentation. In the answer which you found, the "debuggability" is merely meant in context of Java code for business logic which needs to be replaced by a Java class like a servlet, filter, entity or EJB, not Java code for presentation logic which needs to be replaced by JSTL tags like if/else blocks, for loops, HTML escaping, date/number formatting, string manipulation functions, etc.
However, if you face a problem for which you've tracked down the root cause to apparently the JSTL tags, then re-read the JSTL documentation if you used them properly. You can also just do a dump of EL variables of interest using the following template:

Request headers

    <c:forEach items="${headerValues}" var="entry">

<c:out value="${entry.key}" />

            <c:forEach items="${entry.value}" var="headerValue" varStatus="loop">
                <c:out value="${headerValue}" />${not loop.last ? ', ' : ''}
            </c:forEach>

    </c:forEach>

Request params

    <c:forEach items="${paramValues}" var="entry">

<c:out value="${entry.key}" />

            <c:forEach items="${entry.value}" var="paramValue" varStatus="loop">
                <c:out value="${paramValue}" />${not loop.last ? ', ' : ''}
            </c:forEach>

    </c:forEach>

Request scope

    <c:forEach items="${requestScope}" var="entry">

<c:out value="${entry.key}" />

<c:out value="${entry.value}" />

    </c:forEach>

Session scope

    <c:forEach items="${sessionScope}" var="entry">

<c:out value="${entry.key}" />

<c:out value="${entry.value}" />

    </c:forEach>

Application scope

    <c:forEach items="${applicationScope}" var="entry">

<c:out value="${entry.key}" />

<c:out value="${entry.value}" />

    </c:forEach>

You could if necessary wrap it in some popup panel which is opened via an access key and only rendered during development mode (the Java EE's MVC framework JSF has a much similar thing in flavor of <ui:debug>).
If in vain, naildown the problem into the smallest possible JSP file which reproduces the whole problem by just copy'n'paste'n'running (in such example, you can put the necessary business logic and e.g. request.setAttribute() lines in a scriptlet which is been placed in very top of the JSP file; prototyping like that is one of legitimate use cases for a scriptlet).
If you still can't figure it out based on that SSCCE, post it as a question on Stack Overflow. When properly put, you'll likely get an answer in less than a day. Don't be surprised if it more than often boils down to a simple typo or a syntax/logic error.

Debugging with jstl - how exactly?


What balancing method can I apply to an imbalanced data set?

Question: I'm trying to solve one classification problem from the UCI database repository. Unfortunately (or fortunately), I've noticed that my dataset is imbalanced. I've structured the data as 5 classes, according to the final mark reached by the pupil, like so:

If student gets a mark from 0 to 7 => class 1 [FAIL(E)]
If student gets a mark from 8 to 9 => class 2 [SUFFICIENT(D)]
If student gets a mark from 10 to 11 => class 3 [GOOD(C)]
If student gets a mark from 12 to 15 => class 4 [NOTABLE(B)]
If student gets a mark from 16 to 19 => class 5 [OUTSTANDING(A)]

My problem is that, as I said, data are imbalanced, so I want to balance it.
I've thought about applying some kind of undersampling method, but my dataset has only 649 instances so I think removing some of them is not the best idea. Then I thought about doing some oversampling, in order to replicate some of the minority class examples and then get classes balanced, but I'm still unsure if that could work.
I would be very grateful if you could give me a hand with this.
Its the first time I face a real problem with imbalanced data.
Comment: What is the percentage of each class?
Answer: Since you're using R, you could make use of some elaborated methods like ROSE and SMOTE. But I'm not enrirely certain if re-balancing your dataset is the right solution in your case.
An alternative could be a cost-sensitive algorithm like C5.0 that doesn't need balanced data. You could also think about applying Markov chains to your problem.
Answer: I think that in your dataset the main challenge is not being imbalanced.
The dataset is small and due to the few classes you don't have too many samples for any of them.
By using one-vs-all concepts ( A or not A, B or not B) you can get more samples for each concept.
You can take advantage of the fact the the classes are ordered (A > B > C > D > E) and use a concept the aggregates some of them (e.g., B and above, D and bellow).
Assuming there is no real difference in the reason to get D or E, not only you will get more samples, you also gain by diminishing the distinction between quite similar concepts.
As for changing the dataset in order to cope with the imbalance, go for it.
However, you should validate on the original distribution.
For details see:
https://datascience.stackexchange.com/questions/810/should-i-go-for-a-balanced-dataset-or-a-representative-dataset/8628#8628
Instead of just over/under sampling, you can use a better technique in order to cope with the imbalance.
For details see:
https://www.quora.com/In-classification-how-do-you-handle-an-unbalanced-training-set/answer/Dan-Levin-2
Answer: Learning from Imbalanced Data
If you choose to oversample, be sure to do it after you create your train-test splits. If you are using cross validation, you should oversample within each fold.


How do I find $ Pr\{X_1 < k \} $ and $ Pr\{X_1 > k \} $if $X_1 : G(p_1)$- geometric distribution

Question: I would think the song like $1-Pr\{X_1 < k \} $ but what is confusing to me is the fact that this is a discrete random variable, and these inequalities ussually apply to absolute continuous variables, so I just don;t know what to do?
I have to prove: Geometric random variables $X_1:G(p_1) X_2:G(p_2) X_3:G(p_3)$ are independent, prove the following :
$$Pr(X_1 < X_2 < X_3)= \frac{(1-p_1)(1-p_2)p_2p_3^2}{(1-p_2p_3)(1-p_1p_2p_3)}$$
I got started like:
$$\begin{align*} \Pr[X_1 < X_2 < X_3] &= \sum_{k=0}^\infty \Pr[X_1 < k < X_3]\Pr[X_2 = k] \\ &\overset{\text{ind}}{=} \sum_{k=0}^\infty \Pr[X_1 < k]\Pr[k < X_3]\Pr[X_2 = k]. \end{align*}$$
Comment: Why would going to the probability of the complementary event is appliable only in the continuous case?? Of course not: $\;P(\overline A)=1-P(A)\;$ in any case, and this is usually taught in every introductory course in Probability, usually with discrete variables.
Comment: Thats not what I meant. I can understand how it came off so. I meant in continuous variables finding $Pr(X < t)$ is much more common, so it seems easier to me.
Comment: http://math.stackexchange.com/questions/1304563/geometric-random-variables-x-1gp-1-x-2gp-2-x-3gp-3-are-independen
Comment: It didnt get an answer :)
Answer: A minor correction: as $\Pr[X_1<0]=0$ you must sum through $1\leq k<\infty$ .
$$\begin{align}
\Pr[X_1 < X_2 < X_3] \;
 &\overset{\text{ind}}{=}\; \sum_{k=\color{darkred}{1}}^\infty \Pr[X_1 < k]\,\Pr[X_2 = k]\,\Pr[X_3 > k]
\\[1ex]
 & = \; \sum_{k=\color{darkred}{1}}^\infty
\big(
 1-(1-p_1)^{k}
\big)\,\big(
 (1-p_2)^{k}p_2
\big)\,\big(
 (1-p_3)^{k+1}
\big)
\\[1ex]
 & = \; (1-q_2)\,q_3\Big(\sum_{k=\color{darkred}{1}}^\infty
q_2^{k} \, q_3^{k} -\sum_{k=\color{darkred}{1}}^\infty q_1^k\,q_2^k\,q_3^k\Big) & \text{where } q_n=1-p_n
\\[1ex]
 & = \; (1-q_2)\,q_3\left(\frac{q_2\,q_3}{1-q_2\,q_3} -\frac{q_1\,q_2\,q_3}{(1-q_1\,q_2\,q_3)}\right) & \text{as } \sum_{k=1}^\infty r^k = \frac{r}{1-r}
\\[1ex]
 & = \; (1-q_2)\,q_2\,q_3^2\left(\frac{(1-q_1\,q_2\,q_3)-q_1(1-q_2\,q_3)}{(1-q_1\,q_2\,q_3)}\right)
\\[1ex]
 & = \; \color{purple}{
 \frac{(1-q_1)\,(1-q_2)\,q_2\,q_3^2}{(1-q_2\,q_3)\,(1-q_1\,q_2\,q_3)}
}
\end{align}$$
The suspicion at this point is that you are meant to be using a different definition of geometric distribution than I am used to; one counting successes before the first failure rather than failures before the first success.
It is always important to specify exactly what you mean by a Geometric Distribution, as there are several definitions.


Threshold for apperance of quite short paths/cycles in random graphs

Question: We say that a graph $G$ is distributed with $\mathcal{G}_{n,p}$ if it is a graph on $n$ vertices, and for which each of the ${n\choose 2}$ possible edges is chosen independently of the other edges and with probability $p$.
A monotone property $P$ of a graph is a set of graphs (on $n$ vertices) that is closed from above (that is, if $G\in P$ and $G\subseteq H$ then $H\in P$.
A function $f(n)$ is said to be a threshold for a property $P$ if for any $p(n)=\omega(f(n))$, $G\sim\mathcal{G}_{n,p}$ has $P$ asymptotically almost surely (a.a.s.), and for any $p(n)=o(f(n))$, $G\sim\mathcal{G}_{n,p}$ does not have $P$ a.a.s.
For example, if $P$ is "has a triangle as a subgraph", then $P$ is clearly monotone, and $f(n)=n^{-1}$ is a threshold for $P$. $f(n)=\frac{\ln{n}+\ln\ln{n}}{n}$ is a threshold for the Hamiltonicity property (in a stronger sense).
My question is this: what are the thresholds for the properties of having "quite short" paths or cycles? By "quite short" I mean of length $\Theta(n^\varepsilon)$ for some $0<\varepsilon<1$, or of length $\Theta(\ln{n})$.
Answer: The threshold function is $f(n) = 1/n$ for each of your cases. In fact, Łuczak proved that if $v_1$ denotes the number of vertices of degree 1 in $G(n,p)$, then for $n p \to \infty$, w.h.p. $G(n,p)$ contains cycles of all lengths $r$, $3 \leq r \leq n - (1+\epsilon)v_1$. In particular, since $v_1$ is concentrated around its mean for this range of $p$, we have that: for any fixed $\delta \in (0,1)$, if $np \to \infty$, then $G(n,p)$ contains cycles of all lengths $r$, $3 \leq r \leq \delta n$.
Answer: For example you should be able to show that $f(n) = n^{-3/2}$ is the threshold for the property of having a path of length $2$, by a birthday paradox argument. This argument or something similar probably also holds for paths of any fixed finite length, but I'm not sure how to show it.


Void CheckError Oracle x IIS

Question: Bom, devido ao esgotamento das minhas tentativas de encontrar o erro, vou tentar buscar uma luz aqui com vocês. Desde já peço desculpas se o erro for genérico demais e não tiver as infos necessárias.
Mas ai vai uma parte do cenário e a situação:
SITUAÇÃO: A aplicação rodando no ISS em homologação ou produção, sendo usada por vários usuários, em um dado momento cai, em qualquer parte da aplicação. Isso ocorre ao acessar algum método ou mudar de página. É nessário reiniciar o IIS para a aplicação voltar a funcionar. Erro disparado:

Tenho impressão que essa informação é muito genérica. O método no qual se dá o erro é um metodo de obtenção de usuário. Método esse que é disparado em toda mudança de página. Pode acontecer em outros métodos de acesso ao banco também. Por isso não colocarei código a principio.
OBS: Rodando a aplicação na própria máquina no visual studio não acontece erro nenhum, em nenhum momento.
Tendo em vista que o erro só se da quando está rodando no IIS, eu gostaria de saber o que pode estar causando isso. Se é alguma configuração do IIS, ou se pode ser algum problema de gerenciamento das conexões com o oracle que reiniciando o IIS ele limpa e ai volta a funfar.
Estou aberto a fazer edições incluindo informações de acordo com as sugestões e qualquer dica de caminho a se investigar será bem vinda.
Answer: Pela breve descrição, o problema parece que está acontecendo por causa das configurações de reciclagem do pool de aplicação do seu site/aplicação no IIS.
Reveja as configurações de reciclagem, talvez o seu problema seja resolvido.
Um link para saber mais sobre reciclagem do pool no IIS.

Void CheckError Oracle x IIS


Select the radio buttons of "Create handouts in Microsoft Word" in Powerpoint 2007

Question: How can I write a macro in Powerpoint to select any option (Radio Button) that is displayed when you call "Create Handouts in Microsoft Word" (Office Button-> Publish -> Create Handouts in Microsoft)?
The macro to call "Create Handouts in Microsoft Word" is
Application.CommandBars.ExecuteMso ("CreateHandoutsInWord")

But I need to know how to write the macro to select the options (like "Notes Next to slide" , "Blank Lines next to line", "Notes below slides" etc...)  from the window that would be displayed when you call the above macro.
Answer: The solution for the above question is:
Application.CommandBars.ExecuteMso ("CreateHandoutsInWord")
SendKeys "{TAB}", True
SendKeys "{TAB}", True
SendKeys "{DOWN}", True      'Repeat as required...
SendKeys "{ENTER}", False here

See http://msdn.microsoft.com/en-us/library/aa202943(v=office.10).aspx for more details

Select the radio buttons of “Create handouts in Microsoft Word” in Powerpoint 2007


Como saber se o cliente me enviou algo?

Question: Fiz esse código aqui seguindo alguns tutoriais pela internet.
buttonAbrirConexão.Enabled = false;
TcpListener servidor = new TcpListener(6554);
servidor.Start();
while(true)
{
    Thread.Sleep(2500);
    if(servidor.Pending())
    {
    MessageBox.Show("Cliente conectado");
    Socket conexão = servidor.AcceptSocket();
    socketStream = new NetworkStream(conexão);
    escrever = new BinaryWriter(socketStream);
    ler = new BinaryReader(socketStream);
    escrever.Write("Alguma coisa");
    break;
    }
}

Antes de usar o ler.Read(), como vou saber se o cliente antes me mandou algo? Como saber também oque ele mandou? String? int?
Será que existir uma forma de disparar um evento assíncrono sempre que um cliente tentar conexão?
Comment: Você precisar dar uma lida nisso: http://pt.stackoverflow.com/q/101691/101
Answer: Sem entrar no mérito desse código estar adequado, até porque imagino que seja apenas uma tentativa inicial o problema é usar o Pending(). Se retirá-lo o "servidor" ficará esperando receber alguma coisa.
Agora se quer fazer assíncrono, a principal mudança seria pegar o método assíncrono AcceptSocketAsync(), algo assim:
buttonAbrirConexão.Enabled = false;
TcpListener servidor = new TcpListener(6554);
servidor.Start();
while(true) {
    MessageBox.Show("Cliente conectado");
    Socket conexão = await servidor.AcceptSocketAsync();
    socketStream = new NetworkStream(conexão);
    escrever = new BinaryWriter(socketStream);
    ler = new BinaryReader(socketStream);
    escrever.Write("Alguma coisa");
}

Coloquei no GitHub para referência futura.
Veja um exemplo.
Não tem como saber pleo código o que está vindo. Esse mecanismo transmite bytes, não dados específicos. Apenas um protocolo previamente combinado poderá determinar o que são os dados. O tipo do ser fixo, pode depender de posição, pode até ter metadados informando quais são os tipos dos dados.
Comment: Não entendi esse loop sem verificações que você colocou ai, seguindo isso ele vai ficar só colocando a mensagem "Cliente conectado" o tempo todo, não?
Comment: O exemplo é realmente espetacular, eu não sabia dessa instrução await
Comment: Vai toda vez que tiver uma conexão, antes o que ele fazia é pegar um dado e encerrar o servidor, normalmente não é o que deseja. Claro que precisa ter uma forma de sair, por isso falei que esse código está ruim e indiquei um exemplo melhor.
Comment: Consegui fazer o servidor rodar entre dois computadores, valeu!!! Agora já tenho outra dúvida e vou tirar no fórum

Como saber se o cliente me enviou algo?


clarification about C pointers

Question: In the following example:
int *i;
*i=1;

it produces a program to hang, because I know that I am putting a value directly to a memory position.
The question that I have is why the following:
int *i=1;

only produces a warning related to a casting of an integer and does not hang   the program?
and why this instruction does not produce not an error nor a warning?
char *s="acd";

if I am using something similar to the example before
Thanks
Answer: Let's talk about the 3 cases individually:
int *i;
*i=1;

The first line allocates memory for a pointer, but does not initialize it, leaving i with a random garbage value.  The second line tries to write to the memory address spelled out by the random garbage, causing undefined behaviour at runtime.
int *i=1;

This allocates memory for a pointer and assigns it the value 1 (i.e. the memory address 0x1).  Since this implicitly casts the integer value 1 to a pointer, you get a warning, since it's extremely rare to ever initialize a pointer to a non-null memory address.
As an aside, if you were to do:
int *i=1;
*i=1;

it would try to write the value 1 to the memory address 0x1, causing the same undefined behaviour as in your first case.
char *s="acd";

This creates a null-terminated string on the stack and makes s point to it.  String literals are the natural thing to assign to a char *, so no warning.
Comment: ***This creates a null-terminated string on the stack*** Are you sure it is in stack? I think the memory is allocated in the data segment.
Comment: @Krishnabhadra Data segment is a common choice, but it's [up to the compiler](http://stackoverflow.com/questions/2589949/c-string-literals-where-do-they-go) where to put them.  The spec only says you shouldn't write to them, they have static storage duration, and there's no guarantee that identical literals will have the same address.
Comment: No worries, just asked to confirm what I learned is correct.. String literal gets saved in read only part of data segment. We can't modify it later..
Answer: Your first case is the only one where you are trying to write to memory:
int *i; // i is a pointer but it's value is undefined
*i = 1; // Whoops, you just wrote to a random memory location.

int *i=1; // i is an invalid pointer (address 1), but you aren't writing to it

char *s="acd"; // s points to the string literal "acd" - again: no write.

Comment: To build a little bit on this answer: `int *i = 1;` is equivalent to `int *i; i = 1;`.
Answer: int *i = 1;

is equivalent to:
int *i;
i = 1;

By the same token:
char *s = "acd";

...is equivalent to:
char *s;
s = "acd";

The appearance of the asterisk in the type definition is notation for indicating that i and s are pointers.  This is distinct from when you see the asterisk used outside of a type definition, where it indicates a dereference.
So in these cases you are merely assigning the pointer value itself...not dereferencing it and writing to the memory it points to.  The memory for the pointer itself is allocated on the stack and thus accounted for.  Your danger comes when you dereference and try to write to it when it hasn't been initialized correctly.
Note that in the case of the string you can dereference into it.  Four characters of memory for acd\0 were set aside implicitly when the compiler saw the string literal...and then the literal evaluated to the address of that memory.  So your s pointer is good.  Your i pointer is an arbitrary value which is very likely to not be readable on most systems.
Answer: int *i;

declares a pointer. If done in a function this is an automatic variable and is not initialized. Then when you try to
*i = 1;

you access some memory given by the value that was in the memory location assigned to the name i. You probably don't have permission to access that memory, so your program crashes.
When you write
int *i = 1;

you declare the pointer and initializes it to point at memory location 1. Notice that you haven't tried to write anything into memory location 1, just pointed i at it. If you did try to write to it you would get a segfault again.
Your last case declares a character pointer to point at a string literal (because "string" evaluates to the address where that literal is stored) which is generally stored in a special part of memory that you have the right to read, but not to write.
Answer: For the first part, the declaration:
int *i=1;

is actually the same as doing:
int *i;
i=1;

Which is, the pointer i is declared to be at the memory location 1 (0x00000001 if you have a 32bit address space). The warning is merely because you're converting an integer into an address.
For the second part, it's the correct syntax for declaring strings. Which is why it doesn't trigger errors.
Answer: In your first example
int *i;
*i = 1;

you declare a pointer and let it be uninitialized. That is is uninitialized means that it basically have a random value, so the pointer points to a random memory location. Then you try to set the memory at that location to a value, which may crash your program. Using uninitialized pointers are undefined behaviour.
In the second example, you actually initialize the pointer. You do not assign a value at the location where i points, but you actually make i point to memory address 1.
The third example is just a variant of the second, where you tell the pointer s to point to the memory where the literal string "acd" is stored.
Answer: In the first example:
int *i;
*i=1;

You are assigning 1 to the location pointed to by i, which is uninitialized so it most likely writing to a location that is not valid.
In the second example:
int *i = 1;

You are assigning the value 1 to the pointer value i - that is your are saying i is pointed to memory address 1.  That is equivalent to:
int *i;
i = 1;

The warning occurs because i is of type int* and is of type int.
In the final example:
char *s="acd";

You are assigning s to point to a string literal.  The string literal is stored in static memory in the program so at run-time it is replaced with a valid address.  The type of a stirng literal is char*, which is the same type as s so there is no warning.
Answer: int *i;

declares the variable i to be a pointer to an int while
*i = 1;

tries to store the integer 1 at whatever address is stored at i.  As you execute this command before storing anything in i, this should be undefined behavior.  It's likely that i contains some random value and that you're therefore trying to store 1 at a random address.
int *i = 1;

declares the variable i to be a pointer to an int and attempts to initialize that pointer to 1.  Since 1 is an integer and not the address of an integer, you get a warning.
A string literal like "acd" is, by definition, a NULL-terminated char array containing the characters in the string.  On assignment, this array decays into a pointer to a char, and as you're assigning it to a char * there are no problems.  I don't think you're supposed to modify the elements of that array, though, so it would be better to assign it to a const char *, something which gcc will likely be happy to warn you about.

clarification about C pointers


Maven release downloading from lib-release instead of lib-snapshot

Question: I am trying to perform maven release from command line but I am getting below error. I also tried from jenkins job but the same error occurs. I even tried to delete the workspace before the build starts.
[INFO] [ERROR] The build could not read 1 project -> [Help 1]
[INFO] org.apache.maven.project.ProjectBuildingException: Some problems were encountered while processing the POMs:
[INFO] [FATAL] Non-resolvable parent POM: Could not find artifact com.example:pom:3.0.54 in central (http://artifactory.example.com/artifactory/libs-release) and 'parent.relativePath' points at wrong local POM @ line 5, column 10

Ideally maven should download 3.0.54 version from lib-snapshot location and upload it to lib-release but it is trying to download from lib-release where the artifact does not exists. I have mentioned proper details of artifactory in settings.xml
After incrementing the pom version to 3.0.55 I am now getting some different error. Earlier atleast snapshot build was working but now neither release nor snapshot build is working.
Parsing POMs
Failed to transfer Could not find metadata com.example.abc:3.0.55-SNAPSHOT/maven-metadata.xml in snapshots (http://artifactory.example.com/artifactory/libs-snapshot)
Failed to transfer Could not find artifact com.exampleabc.pom:3.0.55-SNAPSHOT in snapshots (http://artifactory.example.com/artifactory/libs-snapshot)

In all the poms I have same version as shown below
$ find . -type f -name "pom.xml" -exec sed -n '/3.0.54/p' {} \;

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>
                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>
                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

        <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

        <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

        <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

        <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

                <version>3.0.54-SNAPSHOT</version>

        <version>3.0.54-SNAPSHOT</version>

Comment: Version `3.0.54` is a release not a SNAPSHOT...and it's downloaded from the release repository instead of the SNAPSHOT repository...
Comment: Yes I understand. That is what my question is. I have mentioned 3.0.54-SNAPSHOT in my pom.xml. But it is still downloading 3.0.54 from lib-release. version 3.0.54 is not there in lib-release. It should be uploaded at the end of the build.
Comment: That's obviously not the case cause the output says something different. Furthermore a pom file here would help...
Comment: @khmarbaise, the pom file is pretty big and I will have to change a lot of thing. Do you need any specific settings?
Answer: Your error says
Could not find artifact com.example:pom:3.0.54

This means that at some point you referenced 3.0.54 instead of 3.0.54-SNAPSHOT. Maybe you are looking at a wrong branch or revision, maybe you mixed up projects.
Comment: After incrementing pom version i am getting different error. I have updated my question
Comment: Why do you increase the version? `3.0.55-SNAPSHOT` probably does not exist. You need to solve your original problem, namely: Somewhere you set the version to `3.0.54` instead `3.0.54-SNAPSHOT`. You need to find that point.
Comment: Like I shown in the question I fired find command to find all the pom.xml files and grepped the version but did not find anything without SNAPSHOT.
Comment: I understand 3.0.55-SNAPSHOT does not exists and that is why it is giving the error. But in my previous previous build I saw it normally finds the metadata file. Previously after incrementing the pom version I was to fix this type of issues
Comment: I cannot really follow you. Your error is that you reference `com.example:pom:3.0.54` but it is not there. So try to fix that.
Comment: Then you need to find the place where you reference `com.example:pom:3.0.54`. It may also be possible that your maven commands contain a call to a `versions` plugin.
Comment: I asked the developers to verify it from their side as well but they are saying all the poms are using SNAPSHOT and they are not using any version plugin.


Custom output filename from piped batch file

Question: when using > to pipe command output to a file, is there a way for the output filename to be dynamic?
simple example
c:\systeminformation > \servername\share\sysinfo.txt (output filename is sysinfo.txt, and can be overwrote, or appended by using >>)
Is there a command I can add that will give a unique output filename? if nothing else, maybe a DTS stamp.txt format? that way the output filename is unique.
Answer: Yes, fundamentally all you need is to put the filename into a variable.
set "var=\servername\share\sysinfo.txt"
whatevercommand >"%var%"

Beyond that, your question is too vague. There are special circumstances where this technique needs to be varied (but I'd guess you'd need \\servername\...)
Answer: you can attach the date and time to a file name dynamically if that serves your purpose.
Example:

set dynamicFname=sysinfo_%date:~4,2%_%date:~7,2%_%date:~10%_%time:~0,2%_%time:~3,2%.txt
c:\systeminformation > \servername\share\%dynamicFname%

the resulted file name will be something like this:
sysinfo_04_11_2014_16_44.txt
sysinfo_04_11_2014_16_47.txt
04=month, 11=day, 2014=year, 16=hours in 24 format, 44=minutes
note that you need to run the set command every time you want to update the date/time stored in the varible "dynamicFname"
the solution is inspired by this url:
http://en.kioskea.net/forum/affich-130043-dos-create-filename-based-on-date
Comment: thanks to all who replied to my question, the response from 'DoubleM' was spot on. It works perfectly.
Answer: c:\systeminformation > \\servername\share\sysinfo%random%.txt

or
set name=%date:/=_%
c:\systeminformation > \\servername\share\sysinfo%name%.txt

Comment: Can you elaborate on your answer?
Comment: Type set /? for the documentation on both commands (even though first one doesn't use set it is still documented there). First is a random number. Second is the date with slashes, illegal in filenames, replaced with underscore.


Two correlated DVs in a multiple regression

Question: I have a multiple regression with an interaction term and I would like to run it on two separate DVs. The two DVs are quite highly intercorrelated (but conceptually different). How can I control for that intercorrelation?
Comment: Under the standard linear regression assumptions, fitting a "joint" (multivariate response) linear regression is the same as fitting single-response linear regressions to each of the response variables separately. This is a standard result that can be found in most any linear-regression text, e.g., G. A. F. Seber and A. Lee (2003), *[Linear Regression Analysis](http://www.amazon.com/Linear-Regression-Analysis-Probability-Statistics/dp/0471415405)*, Wiley, 2nd ed.
Comment: I suggest you think in very precise terms about what you mean by "control" in this context.  Within one multiple regression, control would mean to see how X1 relates to Y while partialling out or holding constant X2.  What does control mean with respect to your situation involving a second Y?
Comment: @Cardinal There may be an issue here with protecting significance: there will be multiple tests which, due to the correlation of the DVs, could be construed to be strongly dependent.
Comment: By control I mean how to account for the common variance shared by the DVs. I'm getting a similar pattern of results for both DVs, atlhough theoretically it should be different. I guess my follow-up question would be weather it could be a solution to control for the other DV, while running each of the regression analyses?
Answer: The original question suggests to me the "seemingly unrelated regression" approach (SUR). As pointed out, the two equations could be estimated separately by ordinary least squares. However, the advantage of this approach over estimating 2 separate equations is that SUR produces more efficient estimates. Moreover, with SUR you have a nice framework to test cross-equation hypotheses.
In R there is a package called systemfit. This package has a nice vignette explaining the different approaches. That could be a good starting point, even if you do not plan to use R. Otherwise, have a look at an econometrics textbook. Most of them cover the estimation of systems of equations.
Be careful. If you obtain results that are not in line with your expectations, there may be many explanations. I do not see why the lack to "control for this correlation" must be the blemish. There can be lots of other reasons, misspecification, measurement error, wrong expectations, ...
Comment: Thanks! I will look into that. Of course I do realize reasons might be many (including wrong theory) but this was the one I did not know how to deal with (or if I can deal with).
Comment: Though I could very well be wrong, it seems like the OP is considering regression on two responses using the same set of regressors. I fail to see how SUR would be different than OLS in this case or how it would be more efficient. Perhaps you can expand on this. The separability of the regressions *does* break down if the covariance of the errors varies by observation.
Answer: As others I do not really understand what you mean by "control for intercorrelation" But from your comment I give it a try with a variant which I can imagine to be possibly meaningful. To show this in principle I begin with a random covariance matrix in the sense of three iv's $x_1,x_2,x_3$ and two dv's $y_1,y_2$
$ \qquad \small
\text{ cov =} \begin{array} {r|rrr|rr}
&x1&x2&x3&y1&y2\\
\hline
x1&1.0&0.6640&0.6160&0.7006&0.6237\\
x2&0.6640&1.0&0.8133&0.9745&0.6906\\
x3&0.6160&0.8133&1.0&0.7633&0.7318\\
\hline
y1&0.7006&0.9745&0.7633&1.0&0.7918\\
y2&0.6237&0.6906&0.7318&0.7918&1.0\\
\hline
     \end{array}
$
From this we get a triangular cholesky-decomposition which shows the "factorloadings" in the sense of principal components analysis.
$ \qquad \small
 \text{ L =} \begin{array} {r|rrr|rr}
  &f1&f2&f3&f4&f5\\
\hline
x1&1.0&.&.&.&.\\
x2&0.6640&0.7477&.&.&.\\
x3&0.6160&0.5407&0.5729&.&.\\
\hline
y1&0.7006&0.6811&-0.0639&0.2028&.\\
y2&0.6237&0.3697&0.2579&0.5891&0.2465\\
\hline
     \end{array}

$
The regression-parameters $\beta$ can be obtained by postmultiplication with the inverse of the correlated x-loadings, the inverse of the 3x3-top-left partial loadingsmatrix:
$ \qquad \small
 L_{xx}^{-1} = \begin{array} {rrr}
1.0& .&.\\
-0.8881&1.3374&.\\
-0.2371&-1.2624&1.7456
     \end{array}
$
and then the $\beta$ occur by postmultiplication into the first three columns and can be taken from the rows of the dv's. The squares of the values in the 4'th and 5'th columns are the unexplained variances of the dv's, where 0.2028*0.5891 is the partial correlation of the dv's which is independent of the iv's and 0.2465^2 is the variance of y2 which is uncorrelated with all.
$ \qquad \small
  \beta = \begin{array} {r|rrr|rr}
&x1&x2&x3&f4&f5\\
\hline
x1&1.0&.&.&.&.\\
x2&.&1.0&.&.&.\\
x3&.&.&1.0&.&.\\
\hline
y1&0.1109&0.9916&-0.1115&0.2028&.\\
y2&0.2342&0.1690&0.4501&0.5891&0.2465\\
\hline
     \end{array}
$
Now we attack the problem of "controlling for intercorrelation".
a) If that means, we want the regression after y1 is partialled out, then we can use this loadings-matrix in a different rotational position. I rotate it such that the variance of the y1 is collected in the first column and the regression can be done on the remaining variance. Here is the rotated loadingsmatrix:
$ \qquad \small
  L_2 = \begin{array} {r|r|rrr|r}
  &f1&f2&f3&f4&f5\\
\hline
x1&0.7006&0.7135&.&.&.\\
x2&0.9745&-0.0263&0.2228&.&.\\
x3&0.7633&0.1138&0.3254&0.5464&.\\
\hline
y1&1.0000&.&.&.&.\\
\hline
y2&0.7918&0.0966&-0.3523&0.4230&0.2465\\
\hline
     \end{array}
$
We see, that the columns 2 to 5 are free of variance of the dv1, and we can do the regression by postmultiplication with the inverse of the partial matrix $L_{1..3,2..4} $ We get the following:
$ \qquad \small
  \beta_2 = \begin{array} {r|r|rrr|r}
  &y1&x1._{y1}&x2._{y1}&x3._{y1}&f5\\
\hline
x1&0.7006&1.0&.&.&.\\
x2&0.9745&.&1.0&.&.\\
x3&0.7633&.&.&1.0&.\\
\hline
y1&1.0&.&.&.&.\\
\hline
y2&0.7918&-0.0880&-2.7114&0.7741&0.2465\\
\hline
     \end{array}
$
and in the last row we find $\beta$-coefficients, which may be understood as the regression where the dv1 is held constant. As well as we partialled out the dv1 we could else partial out the principal component of y1 and y2 (which is then possibly equal to "canonical correlation")
b) Here is such an example. I rotated for the principal components of the dv's only. That variance is now represented in the first two columns.
$ \qquad \small
 L_3= \begin{array} {r|rr|rrr}
  &p1&p2&f3&f4&f5\\
\hline
x1&0.6996&0.1193&-0.4539&-0.2487&-0.4780\\
x2&0.8796&0.4400&-0.1000&0.1487&0.0255\\
x3&0.7898&0.0488&-0.5012&0.2810&0.2091\\
\hline
y1&0.9465&0.3227&.&.&.\\
y2&0.9465&-0.3227&.&.&.\\
\hline
     \end{array}
$
To see the variance of the second principal component of the dv's for the regression on x I rotate the second to 5'th column to the triangular form (this is not really needed for the proceeding)
$ \qquad \small
 L_4 = \begin{array} {r|r|rrr|r}
  &p1&f2&f3&f4&f5\\
\hline
x1&0.6996&0.7146&.&.&.\\
x2&0.8796&0.0681&0.4708&.&.\\
x3&0.7898&0.0889&0.2392&0.5578&.\\
\hline
y1&0.9465&0.0539&0.2937&-0.1063&0.0603\\
y2&0.9465&-0.0539&-0.2937&0.1063&-0.0603\\
\hline
     \end{array}
$
Now we do the regression on the variance of the second principal component only. We get by postmultiplication of the inverse of the partialled x-variance the following matrix of beta-values:
$ \qquad \small
 \beta_4 = \begin{array} {r|r|rrr|r}
  &p1&x1._{p1}&x2.{p1}&x3.{p1}&f5\\
\hline
x1&0.6996&1.0&.&.&.\\
x2&0.8796&.&1.0&.&.\\
x3&0.7898&.&.&1.0&.\\
\hline
y1&0.9465&0.0303&0.7206&-0.1906&0.0603\\
y2&0.9465&-0.0303&-0.7206&0.1906&-0.0603\\
\hline
     \end{array}
$
Now we have regression weights for the second principal component of y1 and y2 on the partialled iv's x1,x2 and x3, and might say, that the "intercorrelation of dv1 and dv2" was controlled - in the sense that the most common variance/their first principal component was held constant.
I don't know whether this line of attack goes in the direction where you want to go to, but perhaps it comes near.


React and Redux this.props.posts is undefined?

Question: I try to follow a tutorial like a Blog with React and Redux but in the PostList I have error in the bind of reducer, just I want render the function renderPost calling the reducer object with a map of posts
What is the error in my code ?
this is my component PostList:
import React from 'react';
import {connect } from 'react-redux';
import {cargaPost} from '../acciones/index';
import {Link} from 'react-router-dom';
class ListaPost extends React.Component {
    componentWillMount() {
        this.props.fetchPost();
    }
    renderPost () {
        return this.props.posts.map( post => {

                {post.categories}

        })
    }
    render() {
        // const { posts } = this.props;
        // if (!posts) {
        //   return
Loading...

        // }
        return (

                    <Link
                    to="/posts/new"
                    >
                    <button
                    type="button"
                    className="btn btn-info">
                    Nuevo Post
                    </button>

                    </Link>

                    {this.renderPost()}

        )
    }
}
function mapStateToProps(state) {
  return { posts: state.todos }
}
export default connect(mapStateToProps, {fetchPost: cargaPost})(ListaPost);

and my reducerPosts
import {FETCH_POST} from '../acciones/index';

const estadoInicial = { todos:[], unPost: null }
// PostReducer
export default function(state=estadoInicial, accion) {
    switch(accion.type) {
        case FETCH_POST:
            return {...state, todos: accion.payload.data }
        default:
            return state;
    }
}

my index file
import {combineReducers} from 'redux';
import PostReducer from './PostReducer';

const rootReducer = combineReducers({
    posts: PostReducer
});

export default rootReducer;

Answer: In your mapStateToProps instead of state.todos it should be state.posts.todos. See below code:
function mapStateToProps(state) {
    return { posts: state.posts.todos }
}

Here your rootReducer will return the state of the store with have key posts inside it (which is for all reducers you are combining into root reducer), and in posts you have your todos.
Comment: i edit the code but keep the error Hriday check my repo please
Comment: @GerardoBautista which repo?
Comment: shouldn't you return action in api callback here? `const solicitud = axios.get(URL)
    .then( res => { console.log(res) })
    return {
        type: FETCH_POST,
        payload: solicitud
    } ` For that you will need to use [redux-thunk](https://www.npmjs.com/package/redux-thunk)
Answer: I think this, in your mapStateToProps,
return { posts: state.todos }

should be
return { posts: state.posts }

or if you want to get just the todos, then:
return { posts: state.posts.todos }

Answer:
and fix the code but I still show the error, please check my repo
https://github.com/emeery/blog
Answer: use this code in your mapStateToProps
const mapStateToProps = (state) => {
    return { posts: state.posts }
}


How to fix a cramped up left hand when playing guitar?

Question: My left hand keeps getting tired and cramped up when playing guitar. Especially when playing a lot of barre chords. It's very frustrating because I always have to stop mid song because it hurts too much.
Is there a way or exercises to increase my left hand strength and stamina?
Comment: What type of guitar? What type of strings? What type of music? How long have you been playing?  How big are your hands roughly?
Comment: You may need to lower the action or use lighter gauge strings, or you could tune down a half step to ease some string tension.  Stretching a bit before playing wouldn't hurt, though.
Comment: One tip I have heard when playing is a bluegrass jam aswell as from a cellist I know is that first of one should relax the hand as much as possible and secondly "hang" (don't know how to describe it properly) on the neck, i.e not just clamping using the fingers but use your whole upper body position.
Comment: Looks like a tension problem to me. If you relax those hands and stop being a nervous wreck then the pain in the hand would probably improve.
Comment: Either non-guitarist exercises or diet… salt in water - lots of salt - for instance, is great for many forms of cramp
Comment: Don't push through the pain, as it could be a RSI (repetitive strain injury) developing, which just leads to medical treatment needing to be done. I knew one guitarist who had to take 3-4 months off due to one!
Answer: Most of us press too hard, especially when playing barre chords.
It may be that the action on your guitar is too high, and/or the strings are very tight, due to being a heavy gauge, that necessitates you pressing harder than you would ordinarily need to. That needs checking and putting right first.
Press the fretted strings as close to the fretwire as possible. The thumb is there more as a guide (Middle of the back of the neck) rather than a clamping mechanism. You should be able to play barre chords with your thumb off the neck completely. Not recommending that, but just to show how little the thumb should add to the successful playing of barre chords.
So not so much increasing strength and stamina, more of adjusting your hand so it doesn't need so much strength and stamina!
Comment: @J... - really think that's over the top. There are many, many guitars that will do for OP without the dubious re-fretting. A good action will generally make a better difference than jumbo frets.
Comment: If it's in budget, sometimes a full re-fret with bigger frets can be worth it (or a new guitar with bigger frets, if it's a trainer not worth putting money into).  Lots of guitars come with small or medium frets and some people find that larger, particularly *taller*, frets are easier to play on and require less hand effort.  Taken to extremes, some will also scallop the fretboard, but I think that's perhaps a more esoteric preference.
Comment: Sure, of course - but there are *some* guitars that are perhaps not well suited for a beginner or for someone with a light playing style.  A bigger fret will also go sharp if you press too hard, so it can also be a good guide to the ear that you're pressing too hard (and can be a reminder to relax).  Obviously it's not make-or-break, but I wouldn't discount the impact of frets on playability.  They can have a big impact on the feel of the instrument.  It's definitely something OP should try out first - I wouldn't suggest a refret without playing on a bigger fret first.
Comment: Learning to play with minimal pressure isn't only better for your hand–it's also better for preventing mistakes.  We tend to get more tense when performing, and since mistakes increase with tension, practice as ultra-relaxed as possible so the tension increase during performance doesn't put you over the top.
Comment: @jschmitter - which is absolutely fine once one uses a guitar with a good action.
Answer: You could really help us help you by posting some pics of your left hand while playing.  As Tim said, many people squeeze too hard.  This is generally due to having very poor posture and incorrect hand position.  Your question is very brief and doesn't provide a lot of background.

Are you taking lessons?

Are you playing electric, acoustic steel string, or classical?

How long is a long time, many hours, 20 min?

How many years have you been playing?

I would say right off the bat NO! There are no exercises for stamina.  If someone tries to sell you a spring loaded grip builder save your money and run for the Hills (Iron Maiden reference).  They key is correct technique and posture.  Clearly one will build stamina over time and no beginner could play for hours without fatigue.  But cramping means you're playing incorrectly and if you fix it you should be able to play for al least a song and not get a cramp.
Everyone needs breaks, even professionals don't play continuously without a break.  I might practice 4-6 hours in a row, but have a 5min break every 1/2 hour.  You need too and that has nothing to do with technique.  But I would not suggest a special exercise other than playing with correct form to build stamina.  If your form is not correct you will create fatigue and other orthopedic problems down the road.
Answer: Make sure your posture is correct.  This means having your guitar at around a 45° angle, back straight, head above your heart, heart above your hips.  Try to keep your head as upright and forward facing as possible, too.  You shouldn't need to look directly at the fretboard at all, instead finding the strings by muscle memory and proprioception.  Obviously this can be kinda difficult, so find or invest in a mirror in front of which to practice.  When you need to look down for a long jump, try to move only the topmost vertebrae to preserve your posture.
You may need an accessory to raise the guitar to the right angle, but I find crossing my right ankle over my left knee, and resting the side of the guitar on my right thigh works very well.  It takes a bit of experimentation to find a position where your leg doesn't fall asleep, but when you find it, it works nicely.
Finally, the secret trick is to not have to use your left thumb.  Your right arm should press the bottom end of the guitar past the edge of your body, levering the neck forwards.  You can then use your fingers on the strings to hold the guitar back, and prevent the guitar shooting onto the floor from you gripping it with your elbow.  Of course, release the pressure with your right arm when you don't need to hold any strings down.  You can rest your left thumb against the back of the neck if you like, and doing so while having it pointing straight towards the head can help with wrist posture, but it could tempt you to use it for pressure.
What the other answers say is also correct.
Answer: I have had the same problem in the past - both with legs cramping at night and hands cramping intermittently during the day. The problem began when I had my right kidney removed for a large tumor - possibly cancerous.  Don't worry, that is most likely not an issue with you.  A few months after the surgery I began getting severe leg cramps at night and hand cramps after going out to eat.  I checked various medical websites on the internet, but got the same answer: "Cause unknown. Consult your local physician."  I talked with several doctors, but got no definitive answer.  I then searched the blogs for people who had had the problem or were related to someone who had.  Two problems kept surfacing - dehydration and too much sugar.  I treated patients in the Navy as a Corpsman, and I always considered dehydration as what the doctor told you when he/she could not figure out the problem, and too much sugar as the opinion of some people who consider anything that tastes good to be bad for you.
Then one night after working outside in the back yard in July, I got the severe cramps again, and it occurred to me that there might be something to the dehydration issue after all.  So I got up, drank a coke, and went back to bed.  The cramps got worse.  Bummer.  I was working outside every day, so the next night I drank several glasses of water right before going to bed.  I still got the cramps.  Just having one kidney, I figured it probably took a while for the water to do its work, so the next night I drank several glasses of water 2 hours before going to bed.  NO CRAMPS!  ZERO!  So for the next few weeks I alternated no water, water, and various types of sweetened drinks before going to bed.  With 1 or 2 glasses of water 1-2 hours before going to bed I consistently had no cramps, but with drinking  no water or drinking sweetened drinks I consistently got cramps.  The worst drinks beginning with the worst were orange juice, apple juice and sodas (cokes, etc).  I once got the cramps after drinking diet coke, but drinking diet drinks afterwards did not result in cramps except sometimes while eating out.  In those cases the cramps were always in my hands, and I think the waiters just gave me the real thing by mistake.  This was a solid solution for me - no ifs, buts, or maybes.
Your problem is likely not nearly as bad as mine as long as you have no kidney problems.  Also elderly people can suffer different degrees of kidney malfunction just from age, resulting in intermittent cramps. But the solution is easy.  Young people in perfect health can still get dehydrated and/or drink too much sugar.  I was on the wrestling team in high school, and we had to weigh in before a match, and if we weighed too much, we would not be able to compete.  So on instructions from the coach we could go into the shower room, turn on the hot water, run in the shower so we would sweat off some weight (please excuse me for not having a video), weigh in again, then drink some orange juice for energy.  One night after doing that, I was in a match and on the way to an easy win, when suddenly I had extreme, paralyzing cramps so that I could not even move, and I lost the match.  Dehydration plus orange juice -- BAAAD!
I think that for you if you make sure you don't drink any sweetened drinks for a while before playing the guitar you should be ok. If not, drinking at least a half glass or more of water 30-60 minutes before playing should help.
Here is my medical reasoning based on what I learned in the 5th grade and in the Navy.
(I was a slow learner, and I never went to kindergarten, so I had to wait until the 5th grade to learn everything I needed to know in life.)
(1) A person can live 3 weeks without food and 3 days without water, but only 3 minutes without air.
(2) When a person goes to sleep, the body focuses primarily on digestion and internal needs.  So it reduces the circulation to the extremities (arms, hands, fingers - including guitar fingers, leg - especially lower legs, feet and toes).
Where I work in the computer industry we do nightly backups on our processors while most users are off the system so the response will be faster, though anyone who works at night may see a much slower response.
So since the volume of blood in your body is extremely critical, when that volume gets lower than desired, the body has to make a decision.  Oxygen transfer is the most critical function and requires virtually no loss of fluids, whereas picking up waste products from the cells requires running the blood through the kidneys and excreting the waste products using lots of water for urine.  That's a No-NO during dehydration, so the body reduces the blood flow through the kidneys, leaving substantial waste products in the blood, resulting in body cramps - sometimes severe, but you still remain alive and oxygenated.
Adding to this misery is the fact that if you are lying down, the blood flow through your extremeties is reduced, adding to the cramps.  I also noticed that the body seems to detect vertical/horizontal position of the extremities independently of each other.  So I don't get lower leg cramps when sitting down (while dehydrated) because my lower legs are vertical, but I often get cramps in my hands and fingers while sitting at the table or driving in my car because my arms are horizontal.  I usually always drink water when eating out, so my hands don't cramp.
Note: I don't have an MD after my name, but this solution works for me - every time.  I have tested all of this over and over and can produce or resolve the cramps at will.  I still drink orange juice and other drinks as long as it is not just before bed and I drink water afterwards.  Of course Half-Price shake night at Sonic is hard to resist and requires me to stay up a little later to wait for the water I drink afterward to do its thing.
If this helps anyone, please let others know so they can benefit also.


Probability that all the heads occur at the end of the sequence

Question: While reading my course handouts, I've found this question :
A fair coin is flipped n times. What's the probability that all the heads occur
at the end of the sequence? (If no heads occur, then "all the heads are at the end of
the sequence" is vacuously true.)
I tried thinking of ways to solve it,but the best i could come up with was :

Where |H| is the number of heads.But the number of heads is not given in the problem.
What would be the correct way to solve it?
Comment: That would be correct for exactly $|H|$ number of heads, however the problem does not specify how many heads there must be.  Take this and range over all possible values of $|H|$ to complete the problem.
Comment: There are $2^n$ possible toss sequences (each equally probable)...for each $k\in \{0,\cdots, n\}$ there is exactly one that has precisely $k$ heads at the end preceded by all tails.  Therefore...
Comment: @August with $n$ flips, you have $0\leq |H|\leq n$
Comment: For future reference, [this page](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) teaches you how to type with MathJax and $\LaTeX$ so you don't need to rely on images for typing math.
Comment: I'll learn how to use it,thank you @JMoravitz
Answer: As pointed out, you have to iterate over all possibilities of number of heads which will give following: $$P(E)=\sum_{k=0}^{n}\frac{1}{2^{n-k}}\frac{1}{2^k}=\frac{n+1}{2^n}$$
Comment: @WillSherwood for a fair coin 50 heads appearing out of 100 flips **in any order** is more common than only one head appearing out of 100 flips **in any order**, however 50 tails followed by 50 heads is exactly as likely to occur as 99 tails followed by 1 head.
Comment: Don't different number of heads appearing have different probabilities? Like for $n=100$, $50$ heads appearing is certainly more common than $1$ head appearing.
Comment: Since the coin is unbiased probabilities are same for getting any sequence of $n$ head and tails. For biased coin, yes the probabilities will be different. For the coin with probability p of getting head $P(E)=\sum_{k=0}^{n}(1-p)^{n-k}p^k$.
Answer: Perhaps easier to describe, remember that the possible sequences of results of a fair coin of the same length are each equally likely.
The "good" sequences where all heads (if any occur) are at the end of the sequence are those sequences:
$$hhh\dots hh,~~thh\dots hh,~~tth\dots hh,~~ ttt\dots hh,~~ttt\dots th,~~ttt\dots tt$$
We can see that there are exactly $n+1$ different "good" sequences.  (If you have a hard time seeing this, recognize that we can describe each sequence as a sequence of $n$ stars and one bar, the stars to the left of the bar represents the tails and to the right of the bar represents heads.  E.g. $\star\star\mid\star\star\star$ represents the sequence $tthhh$.  The number of sequences of $n$ stars and one bar is $n+1$)
As there are $2^n$ possible sequences of $n$ coinflips and each of them are equally likely, we see that the probability is then the ratio of "good" outcomes over the total number of outcomes in the sample space, i.e.
$$\frac{n+1}{2^n}$$

Your method is also the start to a correct solution, noting that you need to iterate over all possible values for $|H|$, and generalizes more nicely to the problem where the coin is not fair.
Letting $p$ be the probability of a head and $(1-p)$ be the probability of a tail, we have the probability all heads appear at the end to be
$$\sum\limits_{k=0}^n(1-p)^kp^{n-k}$$


Temp table to Master table insert or update with auditing and logging

Question: I have to select the records from temptable and insert or update to mastertable. If a single field is changed, then I need to update my history table with the following:

RecordID
ColumnChanged
OldValue
NewValue

While performing the insert or update from the temptable to the mastertable, any errors that's occur due to foreign key violations (or any other errors) should be logged to the error table.
I need the history of changes and logging of errors, so that if a single record fails, I can rerun the process again.
How can I do this using T-SQL? Any code snippets will be helpful.
Here are the tables columns that I'm working with:

TEMPTABLE
COL1, COL2, COL3, COL4, COL5
MASTERTABLE
COL1, COL2, COL3
HISTORY
RecordID, ColumnChanged, OldValue, NewValue
ERROR
ErrorCode, ErrorMsg

I need to use a cursor, as I need to loop through each record when performing the inserts or updates, and to log any errors that happen during the inserting or updating due to bad data.
I need to mark the flagcolumn as "Y" for all successful insert or updates and "N" for all the failed records so that I can reload them again after correcting the data.
I've already used sqlbulkcopy to load the data in to the temptable.
Comment: For this type of auditing you shouldnt need a cursor, Depending on what flavor of SQL Server you have you should be able to use the output clause http://msdn.microsoft.com/en-us/library/ms177564.aspx
Comment: You didn't specify which are the primary keys in the TEMPTABLE and the MASTERTABLE (even if there aren't any primary keys defined, we need to know which columns should be considered as part of the primary keys). Also, there are more columns in the TEMPTABLE than the MASTERTABLE; should we ignore the additional columns?
Answer: Try this one -
Schema:
CREATE TABLE dbo.HistoryTable
(
    HistoryTableID INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
    PKRecordID INT NOT NULL,
    ColumnChanged VARCHAR(50) NOT NULL,
    OldValue VARCHAR(10) NOT NULL,
    NewValue VARCHAR(10) NOT NULL,
    ChangedDate DATETIME NOT NULL DEFAULT (GETDATE())
)
GO

CREATE TABLE dbo.ForeignKeyTableCOL2 (COL2 VARCHAR(10) PRIMARY KEY NOT NULL)
GO

CREATE TABLE dbo.ForeignKeyTableCOL1 (COL1 VARCHAR(10) PRIMARY KEY NOT NULL)
GO

CREATE TABLE dbo.ErrorTable
(
    ErrorTableID INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
    PKRecordID INT NOT NULL,
    TableName VARCHAR(50) NOT NULL,
    TablePK INT NOT NULL,
    ErrorDateTime DATETIME NOT NULL DEFAULT (GETDATE()),
    ErrorCode INT NOT NULL,
    ErrorMsg VARCHAR(2000) NOT NULL
)
GO

CREATE TABLE dbo.TempTable
(
    TempTableID INT IDENTITY(1,1) NOT NULL,
    PKRecordID INT NOT NULL,
    COL1 VARCHAR(10) NOT NULL,
    COL2 VARCHAR(10) NOT NULL,
    COL3 VARCHAR(10) NOT NULL,
    COL4 VARCHAR(10) NOT NULL,
    COL5 VARCHAR(10) NOT NULL,
    Success CHAR(1) NOT NULL DEFAULT ('N')
)
GO

CREATE TABLE dbo.MasterTable
(
    PKRecordID INT NOT NULL,
    COL1 VARCHAR(10) NOT NULL,
    COL2 VARCHAR(10) NOT NULL,
    COL3 VARCHAR(10) NOT NULL,
    COL4 VARCHAR(10) NOT NULL,
    COL5 VARCHAR(10) NOT NULL
)
GO

ALTER TABLE dbo.MasterTable  WITH CHECK ADD  CONSTRAINT FK_MasterTable_ForeignKeyTableCOL1 FOREIGN KEY(COL1)
REFERENCES dbo.ForeignKeyTableCOL1 (COL1)

ALTER TABLE dbo.MasterTable CHECK CONSTRAINT FK_MasterTable_ForeignKeyTableCOL1

ALTER TABLE dbo.MasterTable  WITH CHECK ADD  CONSTRAINT FK_MasterTable_ForeignKeyTableCOL2 FOREIGN KEY(COL2)
REFERENCES dbo.ForeignKeyTableCOL2 (COL2)

ALTER TABLE dbo.MasterTable CHECK CONSTRAINT FK_MasterTable_ForeignKeyTableCOL2

INSERT dbo.ForeignKeyTableCOL1 (COL1)
VALUES ('A'), ('B'), ('C')
INSERT dbo.ForeignKeyTableCOL2 (COL2)
VALUES ('A'), ('B'), ('C')

INSERT dbo.TempTable (PKRecordID, COL1, COL2, COL3, COL4, COL5)
VALUES
    (1, 'A', 'A', 'A', 'A', 'A'),
    (2, 'B', 'B', 'B', 'B', 'B'),
    (3, 'C', 'C', 'C', 'C', 'C'),
    (1, 'D', 'A', 'A', 'A', 'A'),
    (1, 'A', 'D', 'A', 'A', 'A'),
    (1, 'D', 'D', 'A', 'A', 'A'),
    (2, 'A', 'B', 'B', 'B', 'B'),
    (3, 'A', 'B', 'C', 'C', 'C'),
    (4, 'D', 'D', 'D', 'D', 'D')

Query:
SET NOCOUNT ON;

DECLARE
      @PKRecordID INT
    , @COL1 VARCHAR(10)
    , @COL2 VARCHAR(10)
    , @COL3 VARCHAR(10)
    , @COL4 VARCHAR(10)
    , @COL5 VARCHAR(10)
    , @TempTableID INT
    , @New_Row XML
    , @Old_Row XML

DECLARE cur CURSOR LOCAL FAST_FORWARD READ_ONLY FOR
    SELECT
          t.TempTableID
        , t.PKRecordID
        , t.COL1
        , t.COL2
        , t.COL3
        , t.COL4
        , t.COL5
        , New_Row = CAST('<r><s>' + t.COL1 + '</s><s>' + t.COL2 + '</s><s>' + t.COL3 + '</s><s>' + t.COL4 + '</s><s>' + t.COL5 + '</s></r>' AS XML)
        , Old_Row = CAST('<r><s>' + m.COL1 + '</s><s>' + m.COL2 + '</s><s>' + m.COL3 + '</s><s>' + m.COL4 + '</s><s>' + m.COL5 + '</s></r>' AS XML)
    FROM dbo.TempTable t
    LEFT JOIN dbo.MasterTable m ON t.PKRecordID = m.PKRecordID

OPEN cur

FETCH NEXT FROM cur INTO
      @TempTableID
    , @PKRecordID
    , @COL1
    , @COL2
    , @COL3
    , @COL4
    , @COL5
    , @New_Row
    , @Old_Row

WHILE @@FETCH_STATUS = 0 BEGIN

    BEGIN TRY

        IF @Old_Row IS NOT NULL BEGIN

            UPDATE dbo.MasterTable
            SET
                  COL1 = @COL1
                , COL2 = @COL2
                , COL3 = @COL3
                , COL4 = @COL4
                , COL5 = @COL5
            WHERE PKRecordID = @PKRecordID

            INSERT dbo.HistoryTable
            (
                  PKRecordID
                , ColumnChanged
                , OldValue
                , NewValue
            )
            SELECT
                  @PKRecordID
                , 'COL' + CAST(new_id AS VARCHAR(5))
                , old_value
                , new_value
            FROM (
                SELECT
                      new_value = n.value('(.)1', 'VARCHAR(10)')
                    , new_id = 1 + n.value('for $i in . return count(../*. << $i)', 'int')
                    , old_value = o.value('(.)1', 'VARCHAR(10)')
                    , old_id = 1 + o.value('for $i in . return count(../*. << $i)', 'int')
                FROM (SELECT a = 1) d
                CROSS APPLY @New_Row.nodes('/r/s') t(n)
                CROSS APPLY @Old_Row.nodes('/r/s') k(o)
            ) data
            WHERE new_id = old_id
                AND NULLIF(new_value, '') != NULLIF(old_value, '')

            UPDATE dbo.TempTable
            SET Success = 'Y'
            WHERE TempTableID = @TempTableID

        END
        ELSE BEGIN

            INSERT dbo.MasterTable
            (
                  PKRecordID
                , COL1
                , COL2
                , COL3
                , COL4
                , COL5
            )
            SELECT
                  @PKRecordID
                , @COL1
                , @COL2
                , @COL3
                , @COL4
                , @COL5

            UPDATE dbo.TempTable
            SET Success = 'Y'
            WHERE TempTableID = @TempTableID

        END

    END TRY
    BEGIN CATCH

        INSERT dbo.ErrorTable
        (
              PKRecordID
            , TableName
            , TablePK
            , ErrorDateTime
            , ErrorCode
            , ErrorMsg
        )
        SELECT
              @PKRecordID
            , 'TempTable'
            , @TempTableID
            , GETDATE()
            , ERROR_NUMBER()
            , ERROR_MESSAGE()

    END CATCH

    FETCH NEXT FROM cur INTO
          @TempTableID
        , @PKRecordID
        , @COL1
        , @COL2
        , @COL3
        , @COL4
        , @COL5
        , @New_Row
        , @Old_Row

END

CLOSE cur
DEALLOCATE cur

And this possible be helpful for you:
CREATE TRIGGER ...
   ON ...
   INSTEAD OF INSERT, UPDATE
AS
BEGIN

    SET NOCOUNT ON
    SET XACT_ABORT ON

    DECLARE @DocumentUID UNIQUEIDENTIFIER
    ...

    DECLARE cur CURSOR FORWARD_ONLY READ_ONLY LOCAL FOR
        SELECT DocumentUID, ...
        FROM INSERTED

    OPEN cur

    FETCH NEXT FROM cur INTO @DocumentUID, ...

    WHILE @@FETCH_STATUS = 0 BEGIN

        DECLARE
              @BeforeChange NVARCHAR(MAX)
            , @AfterChange NVARCHAR(MAX)

        SELECT
              @BeforeChange = (
                SELECT *
                FROM DELETED
                WHERE DocumentUID = @DocumentUID
                FOR XML RAW, ROOT
              )
            , @AfterChange = (
                SELECT *
                FROM INSERTED
                WHERE DocumentUID = @DocumentUID
                FOR XML RAW, ROOT
              )

        IF EXISTS(
            SELECT 1
            FROM dbo.Documents
            WHERE DocumentUID = @DocumentUID
        )
        BEGIN

            INSERT INTO ...
            SELECT @BeforeChange, @AfterChange

        END
        ELSE BEGIN

            ...

        END

        FETCH NEXT FROM cur INTO @DocumentUID, ...

    END

    CLOSE cur
    DEALLOCATE cur

END

Answer: Setup our schema and tables for testing
SET NOCOUNT ON

IF OBJECT_ID('TempTable', 'U') IS NOT NULL DROP TABLE TempTable;
IF OBJECT_ID('MasterTable', 'U') IS NOT NULL DROP TABLE MasterTable;
IF OBJECT_ID('ForeignKeyTableCOL1', 'U') IS NOT NULL DROP TABLE ForeignKeyTableCOL1;
IF OBJECT_ID('ForeignKeyTableCOL2', 'U') IS NOT NULL DROP TABLE ForeignKeyTableCOL2;
IF OBJECT_ID('HistoryTable', 'U') IS NOT NULL DROP TABLE HistoryTable;
IF OBJECT_ID('ErrorTable', 'U') IS NOT NULL DROP TABLE ErrorTable;

CREATE TABLE ForeignKeyTableCOL1 (COL1 varchar(10) PRIMARY KEY)
CREATE TABLE ForeignKeyTableCOL2 (COL2 varchar(10) PRIMARY KEY)
CREATE TABLE TempTable (TempTableID int IDENTITY(1,1), PKRecordID int, COL1 varchar(10), COL2 varchar(10), COL3 varchar(10), COL4 varchar(10), COL5 varchar(10), Success char(1))
CREATE TABLE MasterTable (PKRecordID int PRIMARY KEY, COL1 varchar(10), COL2 varchar(10), COL3 varchar(10), COL4 varchar(10), COL5 varchar(10))
ALTER TABLE MasterTable ADD CONSTRAINT FK_MasterTable_ForeignKeyTableCOL1 FOREIGN KEY (COL1) REFERENCES ForeignKeyTableCOL1 (COL1)
ALTER TABLE MasterTable ADD CONSTRAINT FK_MasterTable_ForeignKeyTableCOL2 FOREIGN KEY (COL2) REFERENCES ForeignKeyTableCOL2 (COL2)
CREATE TABLE HistoryTable (HistoryTableID int IDENTITY(1,1) PRIMARY KEY, PKRecordID int, ColumnChanged varchar(50), OldValue varchar(10), NewValue varchar(10))
CREATE TABLE ErrorTable (ErrorTableID int IDENTITY(1,1) PRIMARY KEY, PKRecordID int, TableName varchar(50), TablePK int, ErrorDateTime datetime, ErrorCode int, ErrorMsg nvarchar(4000))
GO

INSERT ForeignKeyTableCOL1 SELECT 'A' UNION SELECT 'B' UNION SELECT 'C'
INSERT ForeignKeyTableCOL2 SELECT 'A' UNION SELECT 'B' UNION SELECT 'C'

INSERT TempTable SELECT  1, 'A', 'A', 'A', 'A', 'A', 'N'
INSERT TempTable SELECT  2, 'B', 'B', 'B', 'B', 'B', 'N'
INSERT TempTable SELECT  3, 'C', 'C', 'C', 'C', 'C', 'N'
INSERT TempTable SELECT  1, 'D', 'A', 'A', 'A', 'A', 'N'
INSERT TempTable SELECT  1, 'A', 'D', 'A', 'A', 'A', 'N'
INSERT TempTable SELECT  1, 'D', 'D', 'A', 'A', 'A', 'N'
INSERT TempTable SELECT  2, 'A', 'B', 'B', 'B', 'B', 'N'
INSERT TempTable SELECT  3, 'A', 'B', 'C', 'C', 'C', 'N'
INSERT TempTable SELECT  4, 'D', 'D', 'D', 'D', 'D', 'N'

SET NOCOUNT OFF

Execute the INSERTS and UPDATES with audit/error logging
DECLARE @PKRecordID int, @COL1 varchar(10), @COL2 varchar(10), @COL3 varchar(10), @COL4 varchar(10), @COL5 varchar(10), @TempTableID int
DECLARE @PKRecordID_OLD int, @COL1_OLD varchar(10), @COL2_OLD varchar(10), @COL3_OLD varchar(10), @COL4_OLD varchar(10), @COL5_OLD varchar(10)
DECLARE temp_cursor CURSOR FOR
 SELECT TempTableID, PKRecordID, COL1, COL2, COL3, COL4, COL5
   FROM TempTable
  ORDER BY TempTableID;
OPEN temp_cursor

FETCH NEXT FROM temp_cursor
INTO @TempTableID, @PKRecordID, @COL1, @COL2, @COL3, @COL4, @COL5

WHILE @@FETCH_STATUS = 0
  BEGIN
    --SELECT @idx, @COL1, @COL2, @COL3, @COL4, @COL5

    BEGIN TRY
        IF EXISTS (SELECT * FROM MasterTable WHERE PKRecordID = @PKRecordID)
          BEGIN
            SELECT @COL1_OLD = COL1
                  ,@COL2_OLD = COL2
                  ,@COL3_OLD = COL3
                  ,@COL4_OLD = COL4
                  ,@COL5_OLD = COL5
              FROM MasterTable
             WHERE PKRecordID = @PKRecordID

            UPDATE MasterTable
               SET COL1 = @COL1
                  ,COL2 = @COL2
                  ,COL3 = @COL3
                  ,COL4 = @COL4
                  ,COL5 = @COL5
             WHERE PKRecordID = @PKRecordID

            INSERT HistoryTable (PKRecordID, ColumnChanged, OldValue, NewValue)
            SELECT @PKRecordID, 'COL1', @COL1_OLD, @COL1
             WHERE EXISTS (SELECT @COL1 EXCEPT SELECT @COL1_OLD)

            INSERT HistoryTable (PKRecordID, ColumnChanged, OldValue, NewValue)
            SELECT @PKRecordID, 'COL2', @COL2_OLD, @COL2
             WHERE EXISTS (SELECT @COL2 EXCEPT SELECT @COL2_OLD)

            INSERT HistoryTable (PKRecordID, ColumnChanged, OldValue, NewValue)
            SELECT @PKRecordID, 'COL3', @COL3_OLD, @COL3
             WHERE EXISTS (SELECT @COL3 EXCEPT SELECT @COL3_OLD)

            INSERT HistoryTable (PKRecordID, ColumnChanged, OldValue, NewValue)
            SELECT @PKRecordID, 'COL4', @COL4_OLD, @COL4
             WHERE EXISTS (SELECT @COL4 EXCEPT SELECT @COL4_OLD)

            INSERT HistoryTable (PKRecordID, ColumnChanged, OldValue, NewValue)
            SELECT @PKRecordID, 'COL5', @COL5_OLD, @COL5
             WHERE EXISTS (SELECT @COL5 EXCEPT SELECT @COL5_OLD)

            UPDATE TempTable
               SET Success = 'Y'
             WHERE TempTableID = @TempTableID

          END
        ELSE
          BEGIN
            INSERT MasterTable (PKRecordID, COL1, COL2, COL3, COL4, COL5)
            SELECT @PKRecordID, @COL1, @COL2, @COL3, @COL4, @COL5

            UPDATE TempTable
               SET Success = 'Y'
             WHERE TempTableID = @TempTableID
        END
    END TRY
    BEGIN CATCH
        INSERT ErrorTable (PKRecordID, TableName, TablePK, ErrorDateTime, ErrorCode, ErrorMsg)
        SELECT @PKRecordID, 'TempTable', @TempTableID, GETDATE(), ERROR_NUMBER(), ERROR_MESSAGE()
    END CATCH

    FETCH NEXT FROM temp_cursor
    INTO @TempTableID, @PKRecordID, @COL1, @COL2, @COL3, @COL4, @COL5
END
CLOSE temp_cursor;
DEALLOCATE temp_cursor;

-- VIEW OUTPUT
SELECT * FROM MasterTable
SELECT * FROM ErrorTable
SELECT * FROM HistoryTable
SELECT * FROM TempTable


Is it possible to make a redirect rule in the routerjs file to create a vanity route

Question: To speak specifically, I have a URL to one page on a website but the URL is somewhat long and ugly.
It might look a little bit like this
mywebsite.com/all-products/hats/golf-caps
however, my marketing team feels this URL is too long and wants me to add a "prettified" url like this:
mywebsite.com/golf-caps
But all it would really do is redirect to the original route.
Is there a way to do this in ember.js? Or is this a bad practice? Ideally, I would only need to modify the router file rather than create a completely new route in my application just to perform a redirect.
Comment: Would the link: `mywebsite.com/r/golf-caps` be ok? I'm thinking a generic route `/r/:short` that contains a bunch of re-direct rules.
Answer: If you have control over the server then I would handle this there. It's nice to be able to send the correct 308 permanent redirect header so search indexing lines up and most backend routing solutions seem to have concept this built in.
Answer: As far as I'm aware of you need to create a new route with a beforeModel() hook containing the redirect. But I don't think that this adds a lot of complexity. It's basically ember generate route golf-caps and edit the created app/routes/golf-caps.js to contain:
export default class GolfCapsRoute extends Route {
  beforeModel() {
    this.transitionTo('all-products/hats/golf-caps');
  }
}

You may want to delete the route's template app/templates/golf-caps.hbs as that won't be rendered in any case.
If you have more than one redirect, you may want to consider adding a wild-card route that catches all requests. This could do the redirects based on a map for multiple paths and render a not-found page if there isn't any redirect registered for the path.
Answer: Ember has resetNamespace (guides).
this.route('all-products', { resetNamespace: true, path: '/' }, function() {
  this.route('categories', { resetNamespace: true, path: ':category_id' }, function() {
    this.route('subcategories', { path: ':subcategory_id' });
  });
});

I'm not sure how resetNamespace will work two levels deep like that though. Especially since you have something meaningful in the second level, i.e.,hats`. Your ember router needs that to know which 'category' to request from the server.
For example golf-caps 'subcategory' could be in two 'categories'. If someone navigated directly to mysite.com/golf-caps your server would have no way to know which golf-caps to show, the ones from hats or the ones from accessories.
The only way you'd be able to collapse them down is if all your subcategories were truly unique. In which case, then yes, do just get rid of the category level.
Assuming you still need the category, I think you'll just be able to get rid of all-products in your URL:
this.route('all-products', { resetNamespace: true, path: '/' }, function() {
  this.route('categories', { path: ':category_id' }, function() {
    this.route('subcategories', { path: ':subcategory_id' });
  });
});


Consistency of a System of linear equations using unknowns in the matrix form

Question: Can anyone tell me how would I answer these type of questions?
I already know how to answer the normal way which doesn't include any variables such as Alpha in the question.
Comment: So, how would you go about solving these problems without the variable $\alpha$?
Comment: I would reduce the matrix to row echelon form and then check consistency, whether there is a row of zeros or not would make me determine consistency.
Comment: OK, have you tried doing that here?
Comment: I am not able to compute the row echelon form because of the existence of **α**. Could you please explain how to do this?
Answer: You can proceed via row-reduction, just as you would without the variable. Taking the first problem, subtract 3 times the first row from the second to get $$\begin{bmatrix}1&\alpha&4\\0&6-3\alpha&-4\end{bmatrix}.$$ Examine the last row of this matrix. If $6-3\alpha=0$, the pivot will be in the third column, and you'll end up with an inconsistent system. If $6-3\alpha\ne0$, you can proceed with the reduction to row-ecehlon form, but the lower-right element will remain non-zero, so the system is consistent in the case. Can you solve the other problem yourself now?
Comment: Yes now I can, the solution of the second one is **R** , Thank you so much for your help!
Comment: @AhmedAsaad Are you sure about that? I get the condition $2a+4=0$ for consistency.