Edge length of an equilateral triangle if distances from a point $P$ to its vertices is given

Question: A point $P$ is located inside an equilateral triangle and is at a distance of 5, 12, and 13 from its vertices. Compute the edge length of the triangle.
The answer is $\sqrt{169 + 60\sqrt(3)}$.
If $s$ is the edge length of the triangle, and if $x$ is the measure of the angle with vertex at $P$ and with sides of lengths 5 and 12, and if $y$ is the measure of the angle with vertex at $P$ and with sides of lengths 5 and 13, according to the Law of Cosines,
\begin{equation*}
s^{2} = 169 - 120\cos(x)
\end{equation*}
\begin{equation*}
s^{2} = 194 - 130\cos(y)
\end{equation*}
and since $\cos(360 - (x + y)) = \cos(x + y)$,
\begin{equation*}
s^{2} = 313 - 312\cos(x+y)
\end{equation*}
So,
\begin{align*}
\cos{x} = - \frac{s^{2} - 169}{120} , \\
\cos{y} = - \frac{s^{2} - 194}{130} , \\
\cos(x+y) = - \frac{s^{2} - 313}{312} .
\end{align*}
For any real numbers $\theta$ and $\phi$,
\begin{equation*}
\bigl[\cos{\theta}\cos{\phi} - \cos(\theta + \phi)\bigr]^{2}
= \sin^{2}\theta\sin^{2}\phi
= \bigl(1 - \cos^{2}\theta\bigr)\bigl(1 - \cos^{2}\phi\bigr) .
\end{equation*}
So,
\begin{align*}
&\left[\frac{s^{2} - 169}{120} \cdot \frac{s^{2} - 194}{130} + \frac{s^{2} - 313}{312}\right]^{2} \\
&\qquad \qquad = \left(1 - \left(\frac{s^{2} - 169}{120}\right)^{2}\right)\left(1 - \left(\frac{s^{2} - 194}{130}\right)^{2}\right)
\end{align*}
or equivalently, by multiplying by $(120^{2})(130^{2})312$,
\begin{align*}
&\Bigl[312(s^{2} - 169)(s^{2} - 194) + (120^{2})(130^{2})(s^{2} - 313)\Bigr]^{2} \\
&\qquad \qquad
= 312 \Bigl((120^{2})(130^{2}) - 130^{2}(s^{2} - 194)\Bigr)
\Bigl((120^{2})(130^{2}) - 120^{2}(s^{2} - 194)\Bigr) .
\end{align*}
How is the quartic equation in the variable $s$ to be solved?
Comment: Also see my [answer](https://math.stackexchange.com/a/2301068/59379) to a similar question for distances $3,4,5$ instead. In general, if you have an equilateral triangle of side $\ell$ and the distances of a point inside to the three vertices are $a, b, c$, then $\ell^2 = \frac12(a^2+b^2+c^2) + 2\sqrt{3}\Delta$ where $\Delta$ is the area of a triangle with side $a,b,c$.
Comment: Have a look at page 19 of [these notes](https://drive.google.com/file/d/18EUtwz1_iJftQCJbSzFEfY4WPC9oGU4J/view). The trick is not to perform an algebraic bashing, it is to consider the symmetric of $P$ with respect to the triangle sides and to perform a slick decomposition of the resulting hexagon.
Answer:
Let $ABC$ be an equilateral triangle. $P$ is a point inside $\triangle ABC$ such that $PA=5$, $PB=12$ and $PC=13$. Rotate $C$ and $P$ about $A$ through $60^\circ$ to $B$ and a point $X$. Rotate $A$ and $P$ about $B$ through $60^\circ$ to $C$ and a point $Y$. Rotate $B$ and $P$ through $60^\circ$ to $A$ and a point $Z$.
Since $\triangle ABX\cong\triangle ACP$, $\triangle BCY\cong\triangle BAP$ and $\triangle CAZ\cong\triangle CBP$,
$$[AXBYCZ]=2[\triangle ABC]$$
Note that $\triangle APX$, $\triangle BPY$ and $\triangle CPZ$ are equilateral triangles of sides $5$, $12$ and $13$ respectively. Also, $\triangle PBX$, $\triangle YPC$ and $\triangle AZP$ are right-angled triangles of sides $5$-$12$-$13$.
\begin{align*}
[\triangle ABC]&=\frac{1}{2}\left[\frac{1}{2}(5)^2\sin60^\circ+\frac{1}{2}(12)^2\sin60^\circ+\frac{1}{2}(13)^2\sin60^\circ+3\times\frac{1}{2}(5)(12)\right]\\
&=\frac{169\sqrt{3}}{4}+45
\end{align*}
So,
\begin{align*}
\frac{1}{2}(AB)^2\sin60^\circ&=\frac{169\sqrt{3}}{4}+45\\
AB^2&=169+60\sqrt{3}
\end{align*}
Comment: My apologies.  I did not see your reply. I will look at your solution soon - hopefully today.  (I will delete this message.)
Comment: I appreciate your time to offer this explanation. It is lucid and elegant!
Comment: What is the origin of it?
Comment: By the way, I posted the problem.
Comment: The Google account from which I posted it expired.
Answer:
Given $a,b,c$,
the equilateral triangle
with the internal point $P$,
located at distances $a,b,c$ from its vertices,
can be constructed as follows.
Start with $\triangle ABC$,
$|BC|=a$,
$|CA|=b$,
$|AB|=c$,
$\angle CAB=\alpha$,
$\angle ABC=\beta$,
$\angle BCA=\gamma$.
Construct a helper external equilateral triangle,
based on any side of $\triangle ABC$,
for example, $\triangle ADB$.
Then $|CD|=u$ is the side of sought equilateral triangle,
which can be constructed in-place
as either
$\triangle CFD$ with $P=A$
or $\triangle DEC$ with $P=B$.
Note that the three angles at $P$ are
$\alpha+60^\circ$,
$\beta+60^\circ$,
$\gamma+60^\circ$,
hence such equilateral triangle
with internal point $P$
can be constructed only if
angles of $\triangle ABC$
are less than $120^\circ$.
The length of the side, $u$,
can be found by the cosine rule,
for example:
\begin{align}
\triangle ADC:\quad
u^2&=
b^2+c^2-2bc\cos(\alpha+60^\circ)
\\
&=b^2+c^2-bc(\cos\alpha-\sqrt3\sin\alpha)
\\
&=b^2+c^2-bc\cos\alpha+bc\sqrt3\sin\alpha)
\\
&=b^2+c^2-bc\cos\alpha+2\sqrt3 S_{\triangle ABC}
,\\
\triangle ABC:\quad
\cos\alpha&=\frac1{2bc}\,(b^2+c^2-a^2)
,\\
u^2&=
b^2+c^2-\tfrac12\,(b^2+c^2-a^2)+2\sqrt3 S_{\triangle ABC}
\\
&=\tfrac12\,(a^2+b^2+c^2)
+2\sqrt3 S_{\triangle ABC}
,
\end{align}
where $S_{\triangle ABC}$
is the area of $\triangle ABC$.
Comment: Thanks for your reply.  I will look at your solution soon - hopefully today. I appreciate the time that you took to write an explanation. (I will delete this message.)
Comment: I have now carefully read your argument. I appreciate the construction! Do you know the origin of such a construction?
Comment: I posted the problem. The Google account from which I posted it expired.
Comment: @Adelyn: I'm not aware of the origin,
it just came out naturally.


Naive bayes: Log odds derivation

Question: How does one go from line 17 to 18 in the below picture? i.e. conversion to linear function of the input variable.

Source: http://pages.cs.wisc.edu/~jerryzhu/cs769/nb.pdf
Comment: The reasoning from step 17 to step 18 is the same as the reasoning that leads equation 3 to equation 6, in the referenced document.
Comment: It is probably natural that questions which one cannot understand without consulting offsite material should garner answers/comments which one cannot understand without consulting offsite material.
Answer: The question was: Why is the following true?
$$
\log p(y = 1 | x) - \log p(y = 0 | x) = (\log \theta_1 - \log \theta_0)^T x + (\log p(y = 1) - \log p(y = 0))
$$

From the problem statement, we are given the distribution of the output $x$, given the input $y$. It is:
$$
p (x | y) = \textrm{const}\cdot\prod_{w = 1}^{v} \theta_{y_w}^{c_w}.
$$
From the problem statement,
$$
x = \begin{bmatrix} c_1 & c_2 & \cdots & c_v\end{bmatrix}^T.
$$
Then, notice that $x,\theta_y \in \mathbb{R}^v$.
$$
\begin{aligned}
\log p(x | y) & = \log \textrm{const} + \log \prod_{w = 1}^{v} \theta_{y_w}^{c)w} \\
& = \log \textrm{const} + \sum_{w = 1}^{v} \log \theta_{y_w}^{c_w} \\
& = \log \textrm{const} + \sum_{w = 1}^{v} c_w \log \theta_{y_w} \\
& = \log \textrm{const} + \begin{bmatrix} c_1 & c_2 & \cdots & c_v \end{bmatrix}\begin{bmatrix} \log \theta_{y_1} \\ \log \theta_{y_2} \\ \vdots \\ \log \theta_{y_v}\end{bmatrix} \\
& = \log \textrm{const} + x^T \log \theta_y \\
& = \log \textrm{const} + [\log \theta_y]^T x
\end{aligned}
$$
We have used the substitution:
$$
\log \left(\begin{bmatrix} \theta_{y_1} \\ \theta_{y_2} \\ \vdots \\ \theta_{y_v}\end{bmatrix} \right) = \begin{bmatrix} \log \theta_{y_1} \\ \log \theta_{y_2} \\ \vdots \\ \log\theta_{y_v}\end{bmatrix}
$$
Then,
$$
\log p(x | y = i) = \log \textrm{const} + [\log \theta_i]^T x.
$$
My understanding is if $y$ is denoted as $0$ or $1$, then the entire vector of parameters $\theta_y$ changes to some pre-determined and known vector corresponding to a $0$ state or $1$ state.
Now, going back to the first line of the question,
$$
\begin{aligned}
\log p(y = 1 | x) - \log p(y = 0 | x) & = \log \frac{p(y = 1 | x)}{p(y = 0 | x)} \\
& = \log \left(\frac{\frac{p(y = 1 , x)}{p(x)}} {\frac{p(y = 0 , x)}{p(x)}}\right)\\
& = \log \frac{p(y = 1 , x)}{p(y = 0 , x)} \\
& = \log \frac{p(x | y = 1)\cdot p(y = 1)}{p(x | y = 0)\cdot p(y = 0)} \\
& = \log \frac{p(x | y = 1)}{p(x | y = 0)} + \log \frac{p(y = 1)}{p(y = 0)} \\
& = \log p(x | y = 1) - \log p(x | y = 0) + \log p(y = 1) - \log p(y = 0) \\
& = \log \textrm{const} + [\log \theta_1]^T x - \log \textrm{const} - [\log \theta_0]^T x + \log p(y = 1) - \log p(y = 0) \\
& = ([\log \theta_1]^T - [\log \theta_0]^T)x + \log p(y = 1) - \log p(y = 0) \\
& = (\log \theta_1 - \log \theta_0)^T x + \log p(y = 1) - \log p(y = 0)
\end{aligned}
$$

Naive bayes: Log odds derivation


How do I redirect a domain but keep the URL structure?

Question: I have example.com and example.co.uk. They both point to the same Drupal installation on my server, so both domains load the exact same site.
I am now trying to redirect the .co.uk to the .com domain. I have tried using the following lines in the .htaccess file, but it always redirects to /index.php.
RewriteCond %{HTTP_HOST} ^example.co.uk
RewriteRule ^(.*) https://example.com/$1 [P]

The following lines didn't work either.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.co.uk$ [NC]
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

The site redirects. but it doesn't keep the URL structure as it should. If I go to example.co.uk, I get redirected to example.com. If I go to example.co.uk/node/1, I get redirect to example.com/index.
How can I set up the correct redirect?
Answer: Your second variant is close to the goal. But it needs some edits. Firstly, you should escape all dots in RewriteCond, so it will be
RewriteCond %{HTTP_HOST} ^example\.co\.uk$ [NC]

Secondly you need to edit RewriteRule to change regular expression and append request uri:
RewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]

It also matters where you place the code. Your second variant is right. It's best to place code just after RewriteEngine on
Final code will be:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.co\.uk$ [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]


Fiddler can easily decode responses - how to make this automatic?

Question: In Fiddler I have many responses which I like to view raw.  For each one Fiddler says "Response is encoded and may need to be decoded before inspection.  Click here to transform."
I want not only the current one, but all responses to always be transformed.  Anyone know how to set this?  Rules->Remove all encodings does not do the trick.
Comment: I would prefer a fiddler setting.
Comment: Well, the easiest way to automatically click stuff that is annoying would be [AutoHotkey](http://www.autohotkey.com/).
Answer: If the goal is to remove compression during the processing of a session:

That's what the "Decode" button on the toolbar does.
That's also what Rules menu > "Remove all encodings" does.

If the goal is to remove the encoding after session processing is complete, select all of the sessions (CTRL+A) and use "Decode Selected Sessions" on the Web Sessions list's context menu.
Comment: I concur, this is what I was looking for as well.
Comment: I've added a screenshot to the answer to make it clearer.
Comment: For me, I had it unchecked but Fiddler was decompressing every request anyway.  Toggling it on and off returned it to expected behavior.
Answer: It's very easy. Just click the "Decode" button on Fiddler's toolbar.
Comment: Both answers look identical to me except @EricLaw provided two ways to get to that option.
Comment: This is the original answer. Basically, the solution provided by @EricLaw does not automatically decode all responses, you have to manually select responses and click on decode but the solution provided by Tank Xiao will automatically deocde all responses moving forward without manual intervention.
Comment: Is there a way to configure Fiddler to do this automatically instead of clicking it for each message?


why isn't there a -g option(gdb) when i execute make even if i wrote it in makefile

Question: I am writting a makefile for my tiny project,here is my makefile:
CC=gcc
CFLAGS=-I.
DEPS = parse.h y.tab.h
OBJ = y.tab.o lex.yy.o parse.o
FLAGS = -g -Wall
LDFLAGS = -lpthread

default:all

all: lisod

lex.yy.c: lexer.l
    flex $^

y.tab.c: parser.y
    yacc -d $^

%.o: %.c $(DEPS)
    $(CC) $(FLAGS)  -c -o $@ $< $(CFLAGS)
example: $(OBJ) example.o
    $(CC) -o $@ $^ $(CFLAGS)

lisod: lisod.o csapp.o $(OBJ)   $(LDFLAGS)
    $(CC) -o $@ $^ $(CFLAGS) $(FLAGS)
# hello:
#   echo hello
clean:
    rm -f *~ *.o example lex.yy.c y.tab.c y.tab.h lisod

but when i execute make,it appears that no -g option,thus i can't debug with gdb
here is part of the output of make:
gcc -I.   -c -o lisod.o lisod.c
gcc -I.   -c -o csapp.o csapp.c

Answer:
but when i execute make,it appears that no -g option,thus i can't debug with gdb

If you look carefully at your output, you will realize that the issue is not so much the -g flag specifically, but that the pattern rule you've provided is not being used at all.  The fact that the -I. option appears first instead of last establishes this.
What you are getting is the default rule for building .o files from corresponding .c files.  Rules you provide override built-in ones when both apply, but in make's analysis, your pattern rule does not (always) apply because it designates prerequisites (at least y.tab.h) that may not initially exist and for which there is no build rule.  (See How Patterns Match in the GNU Make manual.)
You're in fact running into a classic problem with make's model of the world: it doesn't deal very cleanly with recipes that generate multiple outputs that serve as prerequisites for other rules.  You might be interested in the Automake manual's discussion of this topic, which is mostly addressed generically at conforming make implementations, and which provides a series of increasingly complex (and increasingly flexible) rules.  This simple pattern is recommended as "enough for most cases":
y.tab.c: parser.y
    yacc -d $^

# Add this, so make knows where y.tab.h comes from:
y.tab.h: y.tab.c

# I assume that parse.h is an ordinary source, not a generated one

%.o: %.c $(DEPS)
    $(CC) $(CFLAGS) $(FLAGS) -c -o $@ $<

Note that I moved the CFLAGS to the beginning of the compile command instead of the end.  Though it probably does not make a difference in your case, it is not entirely stylistic, as the order of options on the build command line is significant.  That effects link commands greatly, but it can effect compile commands too, depending on the options involved.
Update:
As long as you're relying on feature specific to GNU make (pattern rules) anyway, however, you might as well make full use of them.  As @MadScientist observed in comments, GNU make treats pattern rules with multiple targets differently than it (and other makes) treat ordinary rules with multiple targets: it understands and expects one execution of the rule's recipe to create all the targets matched to one set of prerequisites via the pattern.
Thus, if you're going to use pattern rules at all, then as MS observes, this is even better than the above "enough for most cases" alternative:
%.tab.c %.tab.h : parser.%
    yacc -d $^

%.o: %.c $(DEPS)
    $(CC) $(CFLAGS) $(FLAGS) -c -o $@ $<

Comment: In this particular case you can use a pattern rule, which _does_ understand multiple output files: `%.tab.h %.tab.c : parser.% ; yacc -d $<`.  But if your output and input files are not related by some aspect of the filename it does get tricky.
Comment: Thanks @MadScientist, I had not previously appreciated that detail of pattern rules.  I have updated this answer to include that information.
Comment: not totally understand but it really works,thank you!


Extracing JSON from syslog-pefixed lines in C#

Question: I'm trying to parse a syslog (or syslog-like) response to extract only the JSON
<14>1 09 30 2019 15:34:37 UTC logsource {"somejson": "thejson", "details": {"detail1": detail, "detail2": detail"}}

<14>1 09 30 2019 15:34:37 UTC logsource {"somejson": "thejson", "details": {"detail1": detail, "detail2": detail"}}

<14>1 09 30 2019 15:34:37 UTC logsource {"somejson": "thejson", "details": {"detail1": detail, "detail2": detail"}}

I would like to remove the "<14>1 09 30 2019 15:34:37 UTC logsource" prefix so that the remaining data is a valid JSON so I can send each line to a database. I figure the output would look something like this:
{
    "body" [
        {
            "somejson": "thejson",
            "details": {
                "detail1": details,
                "detail2": details.
            }
        },
        {
            "somejson": "thejson",
            "details": {
                "detail1": details,
                "detail2": details.
            }
        },
        {
            "somejson": "thejson",
            "details": {
                "detail1": details,
                "detail2": details.
            }
        }
    ]
}

Perhaps I could loop through the original data and replace the string using String.Replace somehow? I appreciate any help even if it's jut pointing me in the right direction.
Comment: I assume the "<14>1 09 30 2019 15:34:37 UTC logsource" will not be consistent?  so what you need to do, if I understand, is remove everything before the first "{".  is that correct?
Comment: @CaseyCrookston Yes, removing everything before the first { would be ideal. Presumably to make this a valid JSON, I would also need to add in some formatting as well
Comment: Removing everything before the first { is very simple. You can figure that out with a quick google search like `c# remove everything before character`. From there is should be easy to add the opening `{"body" [` and closing `]}`
Comment: @CaseyCrookston I don't think I would have a problem removing something from a short string but how would I remove everything before the first { in each line starting with <14>? I'm a bit lost at being able to loop through each line and do that same action
Comment: Ok, it sounds like there is something going on here that you maybe didn't explain in your post. Do you have a `List` in which you need to modify each string in the list? Also, in the sample you showed us, is this the entire content of the string?
Answer: One way to do this is to using Newtonsoft.Json. You can parse the string into a JObject after you have cut away the log prefix that you don't need. I also went ahead and removed the blank lines in your input. Here is the code that I used to do this:
using System;
using System.Linq;
using System.IO;
using Newtonsoft.Json.Linq;

namespace extractingJSONSyslogQuestion
{
    class Program
    {
        static void Main(string[] args)
        {
            var input = File.ReadAllText("test.txt");
            var lines = input.Split("\n");

            // Remove blank lines
            lines = lines.Where(l => !string.IsNullOrEmpty(l)).ToArray();

            foreach(var line in lines) {
                // Get rid of log prefix
                var data = line.Substring(line.IndexOf("{"));
                var json = JObject.Parse(data);
                Console.WriteLine(json);
            }
        }
    }
}

Here is the input file that I used. Notice that I added double quotes around the string "detail" to make it valid json:
<14>1 09 30 2019 15:34:37 UTC logsource {"somejson": "thejson", "details": {"detail1": "detail", "detail2": "detail"}}

<14>1 09 30 2019 15:34:37 UTC logsource {"somejson": "thejson", "details": {"detail1": "detail", "detail2": "detail"}}

<14>1 09 30 2019 15:34:37 UTC logsource {"somejson": "thejson", "details": {"detail1": "detail", "detail2": "detail"}

Finally, here is the output from my program:
{
  "somejson": "thejson",
  "details": {
    "detail1": "detail",
    "detail2": "detail"
  }
}
{
  "somejson": "thejson",
  "details": {
    "detail1": "detail",
    "detail2": "detail"
  }
}
{
  "somejson": "thejson",
  "details": {
    "detail1": "detail",
    "detail2": "detail"
  }
}

I am happy to answer any questions about the code in more detail if you leave a comment.


Recebendo dados de um Streaming

Question: estou com um pequeno probleminha e gostaria da ajuda de vocês.
Recentemente eu tive uma duvida e comecei a pesquisar a respeito mas não achei nada, notei que os serviços de streaming de vídeo usa um servidor "wowza" e pra isso queria receber o streaming e poder replicar usando php um exemplo é o url a baixo

http://live-hls.rtvcm.stream.flumotion.com:80/rtvcm/hls-multi/main.m3u8

usei esse codigo pra tentar conectar mas ficou dando erro
<code><?php
$fp = fsockopen("http://live-hls.rtvcm.stream.flumotion.com:80/rtvcm/hls-multi/main.m3u8", 80, $errno, $errstr);

fwrite($fp, "GET request HTTP/1.1\r\nConnection: keep-alive\r\n\r\n");

while (!feof($fp)) {
        echo fgets($fp, 1024);
}
    fclose($fp);
?>
</code>
não sei se é possível, tentei usar socket mas não consegui, alguém poderia me ajudar nisso? me desculpem caso não seja apropriado o url mas eu precisava citar um url pra testes.
Obrigado!
Answer: Daniel, sei que essa pergunta já foi a um bom tempo atrás, mas para fins de histórico e outras pessoas com dúvidas similares segue a minha resposta.
Um stream HLS nada mais é do que uma série de requisições HTTP (ou HTTPS), isto porque o stream é segmentado em pequenas partes (exemplo: pequenos vídeos/audios de 30 segundos). Dessa forma, os browsers conseguem consumir o stream sem precisar abrir conexões TCP/UDP como ocorria em streams RTMP/RTSP via Flash.
Sendo assim, se você quiser fazer algum tipo de cache deste stream, para que os seus usuários não batam direto no Wowza (upstream/origin), você poderia simplesmente colocar um proxy reverso (NGinx por exemplo) na frente, o que seria bem mais eficiente do que implementar este proxy em PHP. Outra solução que seria muito mais robusta seria utilizar uma CDN para realizar o cache e entrega deste stream - mas isso vai gerar custos mais altos, então precisa ser considerado bem.
Posso compartilhar alguns exemplos de configuração do NGinx caso alguém tenha interesse no futuro.
Comment: Se possível, coloque exemplos que demonstrem a solução dada ou que comprovem o funcionamento da mesma. Se não for possível, cite referências para que o usuário possa saber como começar.
Comment: Muito obrigado, pensei em fazer em uma linguagem porque possibilita escalar com mais facilidade, isso foi somente um teste que eu estava testando para ver a possibilidade, você poderia postar algum exemplo? pode ser em qualquer linguagem

Recebendo dados de um Streaming


Is it possible to have more than one AD server with FSMO roles installed on it?

Question: It appears that it is relatively easy to have multiple (even all) AD servers equipped with a copy of the Global Catalog. However, is it possible to do the same for FSMO roles?
If not, is it possible to create a failover protocol that will automatically transfer the FSMO roles to another AD server?
Answer: No to both questions. While it is possible to "split" the FSMO roles between Domain Controllers, it isn't possible for two (or more) Domain Controllers to hold the same FSMO role (or roles) simultaneously. If the FSMO role holder goes down there's no automatic process for transferring the FSMO roles to another Domain Controller.
In the event that the Domain Controller holding the FSMO roles goes down, the domain will function normally for a short period of time, certainly long enough to seize the FSMO roles to another Domain Controller and hopefully long enough to resolve the issue with the DC originally holding the FSMO roles. Note that your first step should be to resolve the issue with the Domain Controller originally holding the FSMO roles and if unsuccessful then to seize the FSMO roles. Once that has been undertaken the original Domain Controller should be left disconnected from the network and the domain permanently and should be manually purged from AD. Have a read here, especially the Loss Implications table:
https://www.petri.com/seizing_fsmo_roles
Comment: Thanks Joe. Out of curiosity, why is it possible to have multiple copies of the Global Catalog then?
Comment: The GC isn't a "role" and as such, performs no domain related functions like the FSMO role holder does. in Microsoft's own words; `The global catalog is a distributed data repository that contains a searchable, partial representation of every object in every domain in a multidomain Active Directory Domain Services (AD DS) forest.` - https://technet.microsoft.com/en-us/library/cc728188(v=ws.10).aspx - https://www.petri.com/understanding_fsmo_roles_in_ad
Comment: So, it's essentially just an index of the objects within AD derived from AD itself?
Comment: @toolshed in big if the FSMO's server crash your user will be still able to logging for X day (I seen 90 days delay in my past experience). If the GC was only in that FSMO server, then your user can't log anymore. So I suggest at least two DC with the GC. In resume, you need the GC for any login, but the FSMO's role can be missing for short period of time


If $\gcd(k, p-1) = 1$ show that $x^k \equiv l \pmod{p}$ has at most one solution.

Question: Assume that $k$ is a natural number and $p$ is a prime where $\gcd(k, p-1) = 1$ Let $l$ be an integer show that
$x^k \equiv l \pmod{p}$ has at most one solution. I'm pretty sure I have to somehow use the fact that the order of $x$
modulo $p$ is a factor of $p-1$, or possibly the fact that there exists a primitive root modulo $p$ and $l$ is congruent
to some power of that.
Comment: @Max -  Please prove to us that this is not from a Take-Home exam.
Comment: one solution for $x$?
Answer: If $l \equiv 0 \bmod p$, then $x^k \equiv 0 \bmod p$ and so $x \equiv 0 \bmod p$.
Otherwise, write $1 = ku+(p-1)v$.
Then $x \equiv x^{ku+(p-1)v} \equiv (x^k)^u (x^{p-1})^v \equiv l^u \equiv (y^k)^u (y^{p-1})^v \equiv y^{ku+(p-1)v} \equiv y \bmod p$.

If you can use group theory, then $x \mapsto x^k$ is a group homomorphism $U(p) \mapsto U(p)$ which is injective because $x^k \equiv 1 \bmod p$ implies that $ord(x)$ divides both $k$ and $p-1$, and so divides their gcd, which is $1$.


jQuery, drop image on overlaping target

Question: I am using jQuery to detect drop on target, the target in question is a image. If i drag one image upon another, and then drop it, it shall replace the target source with the dropped source. This works fine until two images lies upon each other.
Some of the images lies next to each other and some times the target images overlap. if i drop, both the visible image and the image beneath is replaced with the dragged image.
<code>$("#drag img").draggable({
  drag: function(event) { //somethings }
});

$("#target img").droppable({
  accept: '#drag img',
  drop: function() {//change src }
});
</code>
A live exampel<-Removed, try to drag an image to the right image
I hope the problem is clear and their is any good solution.
Answer: Use stopImmediatePropagation to keep the event handler from being invoked on the next image.  Which image is affected should be determine by the order of the event handlers.  If you need it to apply only to the top image, then make sure that any image that overlaps another has it's handler applied first.
Comment: Thanks, now i know what to look for, sadly i'm new to this so i don't know how to make sure it's handler applied first. Can you point me in the right direction
Comment: @Cinaird -- not without knowing how the items are placed on the page and how you are getting them to overlap.  It could be as simple as applying a class to the images on top, then first applying the handler to the images with the class, then to those without it.
Comment: i have a live example here http://web.cinaird.se/pdf/test.htm , i have the same class on every image, is there any way to know which image is visible?
Comment: Try $('#Content #placeholder_1 img').add(('#Content #placeholder_0 img').droppable( ... ) with the stopImmediatePropagation call in the drop handler. You might need to check if isImmediatePropagationStopped is set on the event, first and discontinue manually if it is.
Comment: Ok, i did not get the solution but i manage to solve it bit more specific for my problem. Not so good but it works, i used the underlining div to detect drop. Thanks for all the help, would i be a bit beter on jquery I'm sure it would solve my problem
Answer: I manage to solve it bit more specific for my problem. Not so good but it works, i used the underlining div to detect drop like this:
<code>$("#target").droppable({
  accept: '#drag img',
  drop: function() {//change src of image in this div }
});
</code>
I don't think this will help anyone but se @tvanfosson reply for a other solution

jQuery, drop image on overlaping target


mysql update table column from another table with CONCAT

Question: I am trying to work out how to perform an SQL UPDATE table column from Table A into Table B. The problem I have is trying to concat multiple values from Table A Column X into Table B Column Y
TableA Structure
id | Interest
1  | Bowling
2  | Swimming
1  | Basketball
TableB Structure
id | Interest_new
1  | null
2  | null
I want Table B to have following data
TableB
id | Interest_new
1  | Bowling,Basketball
2  | Swimming
This is my attempt with SQL query but it doesn't concat , just updated table B with first match
    UPDATE TableB
INNER JOIN TableA ON TableB.id= TableA.id
SET TableB.id=CONCAT(TableA.id, ',')
where TableA.id= TableB.id;

Answer: You probably intend to use GROUP_CONCAT here, as you want an aggregated CSV output:
UPDATE TableB b
INNER JOIN
(
    SELECT id, GROUP_CONCAT(Interest ORDER BY id) Interests
    FROM TableA
    GROUP BY id
) a
    ON a.id = b.id
SET
    Interest_new = a.Interests;

However, I actually advocate not even doing this, as storing CSV in your SQL tables is a generally bad idea.  Consider just making a view of this data instead:
CREATE VIEW newInterests AS
SELECT id, GROUP_CONCAT(Interest ORDER BY id) Interests
FROM TableA
GROUP BY id;


"Users is not a function" -- Discord.JS and Javascript

Question: I'm a bit new to Javascript and Discord.JS and was wondering if I could get some help? I keep getting "Users is not a function" in my terminal after trying to run the bot. I'm also wondering if I coded the bot correctly or not. My goal is to have the bot privately message someone at a set time every day.
Thank you.
const e = require('express')
const client = new Discord.Client()

const config = require('./config.json')
const privateMessage = require('./private-message')

const cron = require('node-cron');
const express = require('express');

cron.schedule('42 23 * * *', function() {
    console.log('cron is working');
}, {
    scheduled: true,
    timezone: "America/New_York"
});

    client.login(config.token).then(() => {
        console.log('The client is ready!');
        var dm = client.users.fetch('749097582227357839');
        if(users && client.users.fetch('749097582227357839'))
            client.users.fetch('749097582227357839').send("hello").then(() => client.destroy());

         else
        console.log("nope");

        client.destroy();

});

client.login(config.token)

Answer: if you want to make the bot message someone you can do this-
client.users
      .fetch('749097582227357839')
      .then((user) => {
        user.send(`Hello`,);
     });

I hope this fixes your problem :D
Comment: I tried that but I got an error that said DiscordjsError: Request to use token, but token was unavailable to the client. Any ideas? `
Comment: You can check if you are doing anything wrong here: https://discordjs.guide/popular-topics/errors.html#request-to-use-token-but-token-was-unavailable-to-the-client
Comment: Thank you for giving me the first part of the code to message somebody with your original message. I'm going to ask another question to try to fix the token issue, thank you though.


Por que no Angular usamos a tipagem ": void"?

Question: Por que no Angular usamos a tipagem  : void? Exemplo:
ngAfterViewInit(): void {}

Answer: void significa algo inexistente. Não é algo específico do Angular e sim do TypeScript, na verdade até na imensa maioria das linguagens de programação de tipagem estática. Por simplificação as linguagens só criam funções, que pressupõem que sempre haverá um resultado e ele será retornado para quem chamou (existe uma ou outra que preferiu separar e criar procedures que não possuem retorno). Então, o que fazer quando a função não retorna um valor, nem mesmo um valor nulo? Convencionou-se usar o void indicando que nada será retornado.
Isto ocorre em funções que na verdade não são bem funções, são procedimentos a serem executados e só. Angular usa em vários casos, você só manda executar e não espera um resultado. O que você esperaria receber em ngAfterViewInit()? Nada, ele só está inicializando algo, fez isso, acaba e não devolve nada.
Você não pode usar essas funções em expressões.
Coloquei no GitHub para referência futura.


Finite index subgroups in Amalgamated Free products

Question: Are there any results along the following lines:
Let $\Gamma_1$ and $\Gamma_2$ be groups with respective finite index subgroups $\Gamma_0^i$ for $i=1,2$. If $\Gamma_1 \cap \Gamma_2 \leq \Gamma_0^i$ for $i=1,2$ can we conclude that $[\Gamma_1 \ast_{\Gamma_1 \cap \Gamma_2} \Gamma_2: \Gamma_0^1 \ast_{\Gamma_1 \cap \Gamma_2} \Gamma_0^2] < \infty$.
Answer: This is not true, and in fact the exact opposite holds in most cases.
Just as an example, if $\Gamma_1$ and $\Gamma_2$ are infinite cyclic groups, and if just one of $\Gamma^1_0$ or $\Gamma^2_0$ is a proper subgroup, then the index is infinite.
Comment: Thanks for the response. If a non amenability assumption is placed on the $\Gamma_i$'s say they have Property (T) and $|\Gamma_1 \cap \Gamma_2| = \infty$ will we still be in "most cases"?
Comment: Probably Lee's claim holds for $\Gamma_1,\Gamma_2$ arbitrary groups.
Answer: The following example shows that this cannot hold: let $\Gamma = <a_1, a_2 ; >$, the free group on $\{a_1,a_2\}$.  Let $\Gamma_i = gp<a_i>$ for $i=1,2$, where $gp<S>$ means the subgroup of $\Gamma$ generated by $S \subset \Gamma$.  Let $\Gamma_0^i = gp<a_i^2>$ for $i = 1, 2$.  Then $\Gamma_1 \cap \Gamma_2 = \Gamma_0^1 \cap \Gamma_0^2 = \{1\}$ and $[\Gamma_i:\Gamma_0^i] = 2$ for $i=1,2$.  But $\Gamma = \Gamma_1 * \Gamma_2$ and $gp<a^2,b^2> \cong \Gamma_0^1 * \Gamma_0^2$.  The latter group has infinite index in $\Gamma$; for instance, no positive power of $ab$ belongs to $gp<a^2,b^2>$.
From a more geometric point of view, proper finite index subgroups of an amalgamated free product should not be amalgamated free products themselves.  Suppose $\Gamma_i = \pi_1(X_i)$, where $X_i$ is a nice space.  For simplicity, assume $\Gamma_1 \cap \Gamma_2 = \{1\}$.  Then $\pi_1(X_1 \cup [1,2] \cup X_2) = \Gamma_1 * \Gamma_2$, where the segment $[1,2]$ is glued to a basepoint of $X_i$ at the endpoint $i$.  A finite index subgroup of $\Gamma_1 * \Gamma_2$ will give rise to a finite sheeted covering of $X_1 \cup [1,2] \cup X_2$.  But such a covering will have finitely many copies of the segment $[1,2]$.  As such, the space most naturally decomposes as an amalgam of more than two subgroups.  Think about the case where $X_1 = X_2 = S^1$.


HP-UX - Telnet to terminal

Question: I would like to use a run of the mill linux VM to connect to an existing HP-UX server through telnet.
When I connect using the simple:
telnet xxx.xxx.xxx.xxx
I get my login prompt and everything seems fine; however, once I am logged in, the screen display is quite garbled and I am unable to read anything reliably.
Are there telnet settings that can change terminal type or anything? There are other machines on the network using Reflections for HP, but I really only need to be able to log in for about 30 seconds each day, so an additional license seems overkill.
Also, I have found the small program called QC Term, but this is a fairly old piece of software and it does not run reliably on a Win7 machine.
Do I have any other options?
--- edit ---
Screen shot of putty connected is attached (pixelated bit is concealed purposely)
Comment: Oh right - this is Kingdom of Kroz. You don't want to run out of whips, and always keep a couple of teleport scrolls.
Comment: Got a screenshot?
Comment: Vote to move to Arqade : http://gaming.stackexchange.com
Answer: Once logged in set your terminal type to something like (assumming sh,ksh or bash)
  TERM=vt100
  export TERM

Comment: And if there is no command line once logged in? I'm assuming a permanent setting would need to be set on the server?
Comment: put it in your .profile on the HP/UX system
Comment: That's what I was thinking. Unfortunately that is not an option for me. I've tried also using Putty, but changing terminal type is not working.
Comment: I need to set it to HP70092, HP70096 - just not really sure how the string needs to be formed.

HP-UX - Telnet to terminal


$2^{2012}\,|\,m^n-1$

Question: determine the minimum value of $n$ in a way for every odd $ m$, $2^{2012}$ divides $m^n-1$
I think I have to use LTE for the case where $u_2(m^2-1)=3$ but unfortunately, I have already learned LTE lemma and I'm not good at using it.
can you solve it not using LTE?
please share your ideas in comments and post an answer even if your solution isn't complete. thanks
Comment: I have edited title.
Comment: Does "LTE" stand for "lifting the exponent"?
Comment: @DanielFischer yes
Comment: The question text does not match the title, which states something false. You might want to fix that.
Answer: We want the smallest $n$ such that $m^n\equiv 1\pmod{2^{2012}}$. for all odd $m$. This number is known as $\lambda(2^{2012})$, where $\lambda$ is the Carmichael function. Since the modular base is a power of $2$, and greater than $4$, we have $\lambda(2^{2012}) = \phi(2^{2012})/2 = 2^{2010}$

$2^{2012}\,|\,m^n-1$


Perturbation of eigenvalues and eigenfunctions of a linear operator

Question: I came across this Wikipedia page giving approximate formulas for eigenvalues and eigenvectors of a perturbed matrix. Namely,
Let $A' \in \mathbb{R}^{n \times n}$ be a real symmetric positive definite matrix with distinct eigenvalues $\{t_i\}_{i=1}^n$ and their corresponding orthonormal eigenvectors $\{v_i\}_{i=1}^n$. Assume that $t_1 > t_2 > \cdots > t_n$. Let $E \in \mathbb{R}^{n \times n}$ a real symmetric matrix. Consider a perturbation $A$ of $A'$ given by $A=A'+E$, with the eigenpairs of $A$ denoted by $\{(s_i,w_i)\}_{i=1}^n$. The approximated eigenvectors of $A$ are given by
$$ \widetilde{w}_{i} = v_{i} + \sum_{k=1, k \neq i}^{n} \frac{(Ev_i,v_k)}{t_i-t_k}v_k + O(\|E\|_2^2), \quad 1 \leq i \leq n , $$
and the approximated eigenvalues of $A$ are given by
$$\widetilde{s}_i = t_i + v_i^TEv_i + O(\|E\|_2^2), \quad 1 \leq i \leq n $$
My question is if there exists similar formula for the eigenvalues and eigenfunctions of a linear operator? i.e., to linear operators in an infinite dimensional linear space.
Comment: Are you familiar with the [Frechet derivative](https://en.wikipedia.org/wiki/Fr%C3%A9chet_derivative) and/or [Gateux derivative](https://en.wikipedia.org/wiki/Gateaux_derivative)?  (I ask because the equations you recite are the first-order Taylor series, which takes us straight to [functional derivatives](https://en.wikipedia.org/wiki/Functional_derivative).)
Comment: @EricTowers, Not in particular, but I can read about it if the answer depends on it
Answer: See the canonical reference:
Kato, Tosio, Perturbation theory for linear operators., Classics in Mathematics. Berlin: Springer-Verlag. xxi, 619 p. (1995). ZBL0836.47009.
Also see:
Albeverio, Sergio; Kuzhel, Sergei; Nizhnik, Leonid P., On the perturbation theory of self-adjoint operators, Tokyo J. Math. 31, No. 2, 273-292 (2008). ZBL1182.47013.
Comment: Thanks. I actually found this reference myself but couldn't find expressions of the same form... or have I missed / didn't recognize it?
Comment: @catch22 A lot of the theory is devoted to sorting out the various kinds of operators you are perturbing, and the various kinds of perturbations, but when the smoke clears, the theory is pretty similar to the finite-dimensional case.


For what $a$ are the events $\{\max(1-2x,y) < a\}$ and $\{\max(1-2y,x) < a\}$ independent if $x,y \sim Uni(0,1)$?

Question:
Random variables $x,y$ are independently uniformly distributed on $[0,1]$. For what values $a$ does events $\{\max(1-2x,y) < a\}$ and $\{\max(1-2y,x) < a\}$ are independent?

My solution is as following. Let $A = \big\{ \max{(1-2x,y)} < a \big\}$ and $B = \big\{ \max{(1-2y,x)} < a \big\}$. It is easy to plot $A, B$ and $A \cap B$ for fixed $a$. For example, for $a = \frac{3}{4}$ we have:

And from this we can figure out $P(A), P(B)$ and $P(A\cap B)$, calculating them as area of the corresponding rectangles:
$$P(A) = P(B) = a \times (1 - \frac{1-a}{2})$$
$$P(A \cap B) = (a - \frac{1-a}{2})^2$$
And now to get our values of $a$ we just have to solve the equation for identity $P(A \cap B) = P(A)P(B)$:
$$(a - \frac{1-a}{2})^2 = [a \times (1 - \frac{1-a}{2})]^2$$
Solving it, we receive four roots $1; 1; -2 - \sqrt{5}$ and $\sqrt{5} - 2$. We know, that for $a \geq 1$ and $a \leq 0$ we already have independence, because probabilities of our events equal 1 and 0. So the only interesting root for us is $\sqrt{5} - 2$.
So, the final answer is: $A$ and $B$ are independent for $a \geq 1$, $a \leq 0$ and $a = \sqrt{5} - 2$.
Is such a solution correct? On exam I received 0 points for it and do not see why. I can't access my actual solution right now, only grades. Maybe on exam I made a mistake in calculations (in the solution above I derived calculations using wolfram).
Comment: I think you may have forgotten to take into account that $P(A \cap B) = 0$ when $a < (1-a)/2$.
Comment: If I recall properly, in the original question there was no independence assumption.  The solution is correct with the independence assumption (assuming the algebra bit is correct), but this leaves open the question of finding $a$ for \emph{general} (maybe not independent) $X,Y$ in $\operatorname{Unif}[0,1]$.  Maybe this explains no-credit.
Answer: I think you had to use $$P(A \cap B) =
\left(1-a - \frac{1-a}{2}\right)^2$$


Why are these conditions necessary to form a vector bundle from a complex?

Question: I am busy with my thesis and I've encountered a claim about short sequences I don't fully understand. Here x is some value in a complex manifold $M$.
We have two maps $\alpha_x$ and $\beta_x$ such that $\beta_x \circ \alpha_x=0$ and they form a family of complexes as follows: $K_0 \stackrel{\alpha_x}{\rightarrow}K_1\stackrel{\beta_x}{\rightarrow} K_2$. From this family of complexes I want to make a vector bundle by associating $\text{ker }\beta_x /\text{im } \alpha_z$ with each point in $M$.
It is stated that it is necessary for $\alpha_x$ to be injective and $\beta_x$ to be surjective, but why?
I know that they should be injective and surjective if we want an exact short sequence, but if this was exact then our bundle would not really add something.
Comment: "It is stated": by who? Where? I think your question is a little unclear and would benefit from a bit more context and explanation.
Comment: I'm trying to follow a master thesis written by AJ Lindenhovius and this is stated on page 83. The context is that we have two holomorphic bundle maps between trivial vector bundles K_i over M and we want to make a new (non-trivial) bundle by $E_x=\text{ker }\beta_x /\text{Im} \alpha_x$.
Answer: Injectivity of $\alpha$ and surjectivity of $\beta$ are sufficient conditions for the cohomology sheaf
$$
\operatorname{Ker}(\beta)/\operatorname{Im}(\alpha)
$$
to be a vector bundle, but they are not necessary. A more relaxed sufficient condition is that the ranks of $\alpha_x$ and $\beta_x$ are constant, i.e., do not depend on the point $x$.
Comment: Thank you very much! I was so put off by thinking it had to do something with exact sequences.


Using Angularjs ngBind with javascript object

Question: In the following string, parsing the javascript object and placing it into an ngBinding is not evaluated it. I have a string that I am trying to include an specific part of a javascript object inside of, and am switching over to Angular for the relative ease of usage. The string at present is:

...

"You owe ${{datatokens["DB.PMT"]}}"

If I place something like     "You owe ${{600+11}}" inside of the ngBinding it properly evaluates to:
"You owe me $611"

Also, when I open the console it can accurately locate datatokens["DB.PMT"]. Thus, I must be conceptually missing how to make this javascript object available to this Angular application.
Comment: if it's not in angular scope, angular can't evaluate it. If your data is in global namespace, pass it into a scope variable
Comment: SHow your entire HTML instead of just a part of it.
Answer: The {{}} binding operator in angular creates a binding from $scope to view. Any time $scope changes, the view will update based on this binding. It is the shortcut for the ng-bind directive and requires the $scope object to be present . You can use the binding operator in views for evaluating bindings and updating on change. For your case you can use the binding in view as below.
HTML:

You owe $ {{ datatokens}}

Javascript:
var app = angular.module('app', []);

app.controller('controller', function ($scope) {
    $scope.datatokens = 600;
});

This will always update your binding and corresponding view element


How to protect against against data access if USB drive gets lost?

Question: Using any external USB drive under Windows XP, how to encrypt/decrypt files on the fly, but without too much slow-down from the overhead.
Most of the obvious solutions like  Truecrypt won't work because with these the host system needs to have first had some drivers installed by a system administrator.
How to have an encrypted USB drive, so the data will still be accessible on any XP system?
Comment: Truecrypt is really an ideal solution for this, is there any way to get admin to install or grant privileges to do so?  Otherwise, a lot of external usb drives come with standalone encryption software, most of it's not particularly high grade but also mostly shouldn't require admin.
Comment: Not always practicable to have admin rights, for example passing through someplace and having to use a PC in an internet café, with nobody else there having admin rights either.
Comment: Truecrypt is NOT an ideal solution.  It requires admin rights on the local machine.
Answer: As a note, Windows 7's bitlocker will allow for thumb drive encryption, and you can force it to do so.
Answer: I second the vote for TrueCrypt. As to the problem of accessing it on Windows:
You can use FreeOTFE to read TrueCrypt data under Windows. It offers FreeOTFE Explorer, which, unlike regular TrueCrypt (or FreeOTFE) does not need admin privs (it also does not need installation).
Answer: Truecrypt has an traveler mode, maybe it helps?
It will be difficult to do full disk encryption or even on-the-fly-encryption without drivers! The only thing that woudln't decrypt to the harddrive would be some programm that injects itself in userspace in every process and touches open calls etc.
Comment: You need administrator privileges in order to able to run TrueCrypt in traveler mode ... http://www.truecrypt.org/docs/?s=truecrypt-portable
Answer: As already mentioned Truecrypt is not an option that would run on any Windows XP installation. This is due to the fact that creating a "virtual" drive requires administrator privileges.
Without such a virtual drive you cannot:

use files on the usb drive from any software
run programs from it

Afaik the is no solution to overcome this limitation in a easy and secure way.
The simplest solution that would work everywhere is an encrypted archive file. 7Zip for example can use AES256 which is, combined with a sufficient long pass phrase, a good layer of privacy. 7zip is also available as es plain exe, so you could put it one the stick and take it with you.One thing you have to keep in mind: If you access an file from inside the archive it will be copied to the host temporary directory and possible not deleted securely.
Also I recently saw (on the Cebit, which is an Internationale IT fair in Germany) some AES encrypted usb drives which were explicitly advertised as being true AES combined with a host software which fed the encryption key. Sadly I haven't the name of the manufacturer in mind. But I'm convinced that there are some real solution if you are willing to pay the price (both: money and transfer rates).
Answer: I don't have experience with this but you may want to try iron key
Having a secure flash drive doesn't give complete protection, what if someone copys the files from the drive to there personal computer and that computer gets stolen, a trogen horse gets installed on a computer they access the drive from, etc.
Comment: Not looking to have complete protection, just enough to have some security against casual inspection, say if inadvertently leaving the drive available somewhere for a few hours.
Comment: I use an IronKey.  It's great, not just for easy-to-use encryption (without needing admin rights) but also for the identity manager and other inclusions.  It works on both my Windows and Linux PCs.  The enterprise admin is a good addition if you have multiple IronKey users.
Answer: We use Lexar JumpDrive Secure for our USB keys. The key have 2 partitions, one that is accessible by anyone, and one that is encrypted. The public partition contains the software to access the private part, so make sure you use a strong pass phrase. It works well with windows xp, but not on linux. The old versions we have doesn't work on vista, but the new ones are suppose to work fine.
Comment: You can achieve the same with any USB key and TrueCrypt, which works everywhere. The only solution that doesn't involve installing something on the host would be to use a USB key that uses hardware/biometric encryption. Saddly I can't recommend any, but do a search for "biometric USB key" or "hardware encryption USB key".
Answer: Beware a common mistake, reported by Schneier on Security:

Lessons in Key Management
Encrypting your USB drive is smart. Writing the encryption key on a piece of paper and attaching it to the USB drive is not.
Comment: You mean like this?

http://thedailywtf.com/Articles/Security_by_Oblivity.aspx

Although this isn't as bad as it first seems because you must have the 4 digit PIN and given a serial number, there are free utils that will generate the numbers on the SecureID tokens.
Comment: A token costs a little more then a piece of paper, but this story shows it can be just as smart.
Answer: NTFS (one option for file systems in XP, which you can choose when you format the drive) has transparent encryption support built in.
Comment: http://en.wikipedia.org/wiki/Encrypting_File_System
Comment: EFS has been broken and is useless for all practical purposes on the host computer:   http://www.securitysoftwarezone.com/vista-and-windows-server-2008-encryption-broken-review968-6.html .   However it would not be possible to break encryption having only a USB key with EFS protected files.
Answer: Iron key is great, it has encryption hardware inside. It works everywhere because it doesn't need privileges (nothing to install), and is really secure (used by usa military). After 10 bad try, the inside of they key get a fatal liquid free up.
Iron key web site
Answer: Corsair's Flash Padlock might work for you.  It isn't encrypted, but it's better than nothing.
http://www.corsair.com/products/padlock/default.aspx


Prevent Controls in ControlTemplate inheriting global Styles (WPF)

Question: I have this generic style for a custom control with this Template.

But MyControl is an ordinary UserControl containing:
...
<Border .. />

Then the Border in the UserControl (residing in the Template) inherits this style as well (Padding 3 etc.)
Is there any way to say the controls in the ControlTemplate not to inhertit these global styles?
Just to mention. It is a Generic Template
Answer: Not sure if I understood you correctly.
Did some work around as I had similar situation where all my control's styles specified globally and inherited automatically without x:key.
I had to remove styles for some controls and apply different style for some controls.
In that situation I have created separate style (Below e.g. wants remove styles) so just created Empty style and used where ever and to which ever control it was required.
Empty Style:
<Grid.Resources>
    <ResourceDictionary>


How to import DIVs from external HTML file to another html using JQUERY (with saving their original form)?

Question: I searched for inserting some divs (it's business partners carousel) into html code. I need to do this because when amount of articles increase nobody will be willing to correct content on every single html page - instead of doing this there will be only one file to make changes in.
Here I found how to do it with jquery which I was already using:
JQuery: replace DIV contents with html from an external file. Full example? and I'm importing content of this file http://forumnarzedziowe.pl/test/partnerscarousel.html
with
<code>    <script type="text/javascript">
       $(document).ready(function(){
           $('#selectedTarget').load('../partnerscarousel.html');
       });
    </script>
</code>
Script is working and importing, which is great but as you can see on http://forumnarzedziowe.pl/test/krotko/StackOverflowExample.html
imported divs are not "elegant".
I tried importing different parts and the result is unfortunately always the same.
Comment: Have you tried adding `display:inline-block` to the CSS for `.item`?
Comment: Thanks @sideroxylon for fast reply - after your comment I tried, but all it's making is that images are becoming overlap.
Comment: How would you like to display them? now it's just a matter of CSS.. or you need them to slide too?
Comment: thanks @miguelmpn for your interest - I improved look of that example page. Now there are two sliders -
1) embed in the code
2) imported with jquery (not sliding)
Comment: The classes are different, the javascript slider is not applying, I think that is the problem. If the CSS classes are the same they will have the same behaviour as the top on
Answer: I was trying to look through the code on your website, but was unable to find the code that ran the carousel. Often what is the problem with dynamically loaded html elements is that your jquery functions are applied to the DOM before you have loaded this new element. This means that your dynamically loaded HTML will not have the carousel functionality attached to it when you load it into the DOM. I would recomend adding an onload function to your js.
<code><script type="text/javascript">
   $(document).ready(function(){
       $('#selectedTarget').load('../partnerscarousel.html', function (e) {
          // Attach carousel code to this
       });
   });
</script>
</code>


C# Process Start needs Arguments with double quotes - they disappear

Question: I'm trying to run a cmd line application from c# using Process.Start(ProcessStartInfo);
The problem is, the cmd line application is a matlab standalone .exe and has optional arguments meaning that you pass them on the cmd line as such:
app.exe "optional1" optional1value "optional2" optional2value

Where optional1value is a integer or string etc.
The problem we're having is that the double quotes aren't being passed as part of the "optional1" argument and so I believe cmd.exe is getting something like:
app.exe optional1 optional1value optional2 optional2value

or something like that, which matlab's parser obviously gets confused by.
I have tried:
@"""optional1"" optional1value ""optional2" optional2value"""

as suggested by some in other SO questions regarding double quotes in cmd line arguments but it doesn't seem to be working for me, nor does:
"\"optional1\" optional1value \"optional2\" optional2value\""

I have written a small c# command line .exe to print out the arguments it gets. If I put the command line arguments in VS Project->Debug area and run it then it prints them with double quotes but because of all the escaping etc. when I do this in code, the .exe prints the arguments without any double quotes.
I found this article about it maybe being a bug in .NET 3.5's cmd parser but can't seem to find a viable solution.
Does anyone have any ideas?
Thank you for your time,
Poncho
P.S. Is there a way to see what cmd.exe gets when sending arguments over with Process.Start()? I have my Process opening a cmd window but it would be nice to see the line cmd.exe gets such as: "app.exe optional1 optional1value" etc.
Thanks again.
Comment: Can you post the code snippet where you declare the process object and call the start method?
Comment: Why the extra quotes after optional2value? I think your quotes will be unbalanced in the result.
Comment: As a workaround: Could you add the quotes in the c# program? As a solution, perhaps upgrading to .NET 4.0 ? As another workaround: Make all values mandatory and use a fixed order of input arguments?
Comment: If you run a program directly doesn't it change the titlebar of the cmd window to the full path and arguments of whatever you're invoking?
Comment: @DennisJaheruddin based on the matlab tags, it looks like they are trying to launch matlab with some optional command line args, the command line args they are trying to pass require quotes around the option before the value and those quotes are being stripped as they get passed through ProcessStartInfo
Comment: Regarding the article referenced in the question, there was an update at the top of the article stating it was not a bug and actually a "feature"
Comment: Hi, sorry I've been AFK for a while. @DJKRAZE I don't really understand how that works, why only a backslash before optional2?
Comment: @DennisJaheruddin what TaRDy said is correct, we are using matlab and python 'plugins' for our program, the static c# was just created for testing but thanks for the input :)
Comment: @TaRDy Oh yes, I've just seen that update, what a good feature :)
Answer: Quotes in ProcessStartInfo.Arguments must be escaped as three quotes ("""). This is because a single quote is used for passing a string containing spaces as a single argument.
See the documentation here.
var psi = new ProcessStartInfo(
    "cmd_app.exe",
    "\"\"\"optional1\"\"\" optional1value \"\"\"optional2\"\"\" optional2value");
Process.Start(psi);

All cmd_app.exe does is announce its # of args and what the args are, with this input it displays:
"optional1"
optional1value
"optional2"
optional2value

Comment: Ah it looks like this is working with the test app!

I can't try it out with the matlab script until I'm back at work tomorrow but thanks for the glimmer of hope TaRDy :)
Comment: Okay I tried it with the Matlab code and it doesn't work for whatever reason. As a workaround we've changed the Matlab code to not use optional arguments but required arguments that the C# app just fills with defaults if not set by the user. Our problem now though is that one of the parameters is a path to an input file but if this path has spaces then Matlab will treat it as 2 separate arguments and therefore...we need the quotes again...this is again messing it up. Has anyone had any problems with running standalone Matlab .exes with quoted arguments?
Comment: What a life saver.  This was driving me crazy.

For those trying to execute a command from PowerShell that takes an argument that includes quotes, the three-quotation trick works, just be sure to escape each of them with a backtick (`).
Comment: While this didn't work for me. I used `$"app.exe \"{variablename}\""`. Thanks for the pointers though.


Decreasing loading time of HTML5 Video

Question: Live site- http://www.thecompletefinancialplan.com
I use videojs player to add video on my site.
Video: KeithKolinskyCFP.mp4 - 25.5MB,
       KeithKolinskyCFP.webm - 31MB,
       KeithKolinskyCFP.ogv - 50MB
I've waited at least 30 seconds and it still has not begun to play in mozilla, my internet connect is not slow. Any idea how can i decrease loading time of that Video.
My code-
<video id="example_video_1" class="video-js vjs-default-skin" controls preload="none" poster="http://www.thecompletefinancialplan.com/images/video.jpg" width="320" height="240" data-setup="{}">
    <source src="http://www.thecompletefinancialplan.com/Keith_video.mp4" type='video/mp4' />
    <source src="http://www.thecompletefinancialplan.com/Keith_video.webm" type='video/webm' />
    <source src="http://www.thecompletefinancialplan.com/Keith_video.ogv" type='video/ogg' />

   <object type="application/x-shockwave-flash" data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" width="320" height="240">
    <param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" />
    <param name="allowFullScreen" value="true" />
    <param name="wmode" value="transparent" />
    <param name="flashVars" value="config={'playlist':['http%3A%2F%2Fwww.thecompletefinancialplan.com%2FKeith_video.jpg',{'url':'http%3A%2F%2Fwww.thecompletefinancialplan.com%2FKeith_video.mp4','autoPlay':false}]}" />

</object>

</video>

Answer: I´ve tried it few seconds ago with Chrome 32 for Mac and it loaded immediately.
When I try to load it with Firefox it doesn´t load.
I got some very long loading times with Firefox. So maybe there is an failure with the "videojs" Player-framework.
Try it on a test site with the normal html5 video tags or with another video-player framework.
I tested it myself here: http://lucas-recknagel.de/video.html in chrome no problem but in Firefox the standard player show an error with the video type / MIME type.
So you probably try to re-export your webm file.
Hope that helps.

Decreasing loading time of HTML5 Video


Issue with PrestaShop plugin

Question: After installing the plugin on Presta Shop. The user is able to make successful payment but the orders and sales are not recorded in the PrestaShop back office ..How do I fix this?
PrestaShop version :-126.96.36.199
Rave PrestaShop plugin version :- 1.6x
Answer: Reinstall the plugin. It has been updated, sales and orders are recorded in the back office.
find the plugin here

Issue with PrestaShop plugin


JOIN de 3 tabelas +1 tabela de junção JDBC

Question: Tenho um programa em java que retorna a listagem de utentes que têm uma consulta nesse dia, para isso construí uma base de dados que relacionasse alguns dados importantes dos utentes, o nome do médico com a qual vao ter uma consulta e ainda alguns dados como a sala e o piso. Para que a query SQL retorne apenas as consulta desse dia tentei fazer JOIN as 3 tabelas + a tabela de junção com um WHERE para que ele so retorne as consulta que estao agendadas para o dia que é comparado com a variavél dataFinal (var do programa Java que obtém a data no formato yyyy/MM/dd).
O Problema é que esta query só está retornando um único utente que tem um consulta nessa data , mas existem mais utentes que têm as mesmas datas associadas e não estão aparecendo.
Java:
public void componentShown(ComponentEvent arg0) {

            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            Date date = new Date();
            System.out.println(dateFormat.format(date));

            String dataFinal = dateFormat.format(date);

            try {

                Connection lig = DriverManager.getConnection("jdbc:mysql://localhost/htmdb", "root", "");
                PreparedStatement inst = lig

                        .prepareStatement(
                                "SELECT nome, sala_piso, nomeFuncionario, departamento, data, tempo, confirmacao FROM consulta "
                                        + "JOIN utentes ON consulta.utentes_utente_id = utentes.utente_id "
                                        + "JOIN funcionarios_has_consulta ON funcionarios_has_consulta.consulta_consulta_id = consulta.consulta_id "
                                        + "JOIN funcionarios ON funcionarios.funcionario_id = funcionarios_has_consulta.funcionarios_funcionario_id WHERE data ='"
                                        + dataFinal + "'  ");

                ResultSet rs = inst.executeQuery();

                tableAgendadas.setModel(DbUtils.resultSetToTableModel(rs));

                JOptionPane.showMessageDialog(frmHealthTreatmentManager, "Hoje é dia : " + dataFinal);

                lig.close();

            } catch (SQLException e1) {
                JOptionPane.showMessageDialog(frmHealthTreatmentManager,
                        "Impossível ligar à base de dados. " + e1.getLocalizedMessage());

            }

        }

Base de Dados:

Pretendo obter este resultado:
Comment: Editei a pergunta porque "phpmyadmin" não é um "banco de dados", leia isto pra entender as diferenças: [Qual a diferença entre o mysql e o phpmyadmin?](http://pt.stackoverflow.com/a/115692/3635)
Answer: Bom, vamos lá. Aparentemente não há problema na sua query.
Diante do cenário exposto por você só posso imaginar que nem todas as tabelas tem os registros para fazer o JOIN, o que acabaria limitando o retorno da consulta.
Sendo assim, alterei a consulta para usar LEFT JOIN:
SELECT u.nome,
       c.sala_piso,
       f.nomeFuncionario,
       f.departamento,
       c.data,
       c.tempo,
       c.confirmacao
  FROM consulta c
 INNER JOIN utentes u ON c.utentes_utente_id = u.utente_id
  LEFT JOIN funcionarios_has_consulta fhc ON c.consulta_id = fhc.consulta_consulta_id
  LEFT JOIN funcionarios f ON fhc.funcionarios_funcionario_id f.funcionario_id
 WHERE c.data = '2016-06-17';

Algumas observações sobre a tabela funcionario_has_consulta:

já que foi criada esta tabela de relação, quer dizer que você pode ter mais de uma profissional relacionado a uma consulta?
tem necessidade de ter o campo do utente nesta tabela, já que ele está presente na consulta e a chave primária da consulta já está presente nesta tabela?
Comment: Refiz a base de dados e ajustei as queries , está tudo a funcionar como pretendido , muito obrigado ;) .


Tips for trying out effects (at a guitar shop)

Question: I'm about to go shopping, and I decided to buy a multi-effects unit for versatility (I thought a lot and decided I do need it). Now I gotta decide which one (not that it's really relevant, but my 'main candidates' are Boss GT-10 and Line 6 Pod X3 Live).
Obviously, I'll get myself to a guitar shop and try out these units. But how should I approach my "test drive"? I'm meaning specifics here. Like, do I just listen to the preset patches or put everything on bypass to test one at a time? If that's the case, what effects do I try out first? What combinations of effects? What amp settings/guitar (do I even care about those)?
Important note: obviously, "taking an experienced player" is important and I'll do it if I can. But for the sake of the question, let's just assume I'm experienced/detail-aware enough and just wanna set up a "ritual" to get the most efficient try-out possible. =D
Comment: Do not get the GT-10 unless you have spent plenty of time with it and are in absolute love with it. The GT-10 has a flawed pre-amp section that creates a sort of cocked wah sound(look it up on google). It will limit the useful sounds out of it and is somewhat useless for distortion sounds. It does have a lot of nice features but unless you only play clean it will be almost useless for you(you can get around it but why go through the trouble?). For heaven's sake don't buy a pedal until you have spent plenty of time checking them all out with a good amp.
Comment: Make sure you look at the Vox Tonelab LE.  I was an avowed hater of multi-effects pedals until I used that one.  It's not an ideal for me, but it beats carrying 6 to 10 pedals to rehearsal.
Answer: Bring your own guitar to the shop! And preferably play the effects through a similar amp as you have at home.
 If you are going to buy a digital Multi-effect I would try them out in the same situation as you are gonna use them. For example if you mostly will be sitting at home playing with earphones, thats how you should try it in the shop as well. Many try the effects through a totally different amp than they use. Any pedal will sound Awesome in front of a vox Ac30 from 1965 or a huge Marshall stack.
I only have analog pedals so for the testing of a multi effect I'm not the expert.
One bit of advice, though, Don't be fooled by millions of cool effects combined to make a (weird) cool sound you never will use. Spend more time on listening to the real sound. If you can get a good starting sound from the pedal chances are you will be more happy with it in the long run. After you have found a good sound, try adding some gain and effects and so on.
EDIT:
For some reason I can't comment (even on my own answer) so I will write it here..
By Starting sound I actually mean a rather clean sound without any effects or distortion. In this way it is easier to hear the different cabinet/Amp/whatnot settings that can be changed.
Comment: That's some good advice! By "starting sound", you mean just the pre-amp setting?
Comment: "Any pedal will sound Awesome in front of a vox Ac30 from 1965 or a huge Marshall stack" This is absolutely not true. Pedals are very finicky, and take some experimentation to even get good sounds through "awesome" amplifiers. For example, a dimed out fuzz will sound like trash through that Marshall stack you mentioned if the overdrive tones aren't mixed properly.
Comment: Other than that you are right on though :D.
Comment: Good answer :) I would only add - try to download manuals beforehand, and get know how to tweak the unit in home. Otherwise You may spend time to learning this in shop instead of checking how this unit sounds.
Answer: Do not get the GT-10 unless you have spent plenty of time with it and are in absolute love with it. The GT-10 has a flawed pre-amp section that creates a sort of cocked wah sound(look it up on google). It will limit the useful sounds out of it and is somewhat useless for distortion sounds. It does have a lot of nice features but unless you only play clean it will be almost useless for you(you can get around it but why go through the trouble?). For heaven's sake don't buy a pedal until you have spent plenty of time checking them all out with a good amp.
The G-Force/G-Major is a very nice effects unit(very high quality) but AFAIK rack only. They have some newer stuff out like the Axe-FX which I'm not that impressed with but for the versatility is very nice(distortions are good but not better than a quality tube amp). For 1500 it's probably not worth it over a good amp but probably has all the effects you could ever dream of(so it coupled with a good distortion amp would be awesome).
If I were you I would get individual pedals unless you never plan on doing anything more than your bedroom. That or save up for the nicer units(Axe-FX or G-Force or whatever else is out there). The pedals generally sound good and allow you to mix and match. Your not stuck with a pedal that you don't use. It can be more of a hassle though and for simplicity the multi-fx pedals are generally the way to go.
In any case spend a lot of time with them because they generally are not as good as the demo's you see or require a lot of tweaking to get good sounds. This isn't always the case but the GT line has some serious issues. You might love the GT-10 but I can't stand the cocked wah sound.
Most of the effects on these pedals are all the same. They are simple mathematical algorithms that are almost identical for all the units(even the most expensive ones). Generally it is the features that make an effect useful. Having said that, the GT has a nice harmonizer that tracks well and some other effects that work as expected(octaver, chorus, etc..).
What you are looking for is the quality of the clean sound(does it sound too thin or dead) and the distortion. If these suck no amount of fx will make them better(ok, not 100% true but true 99% of the time).
If you're not playing live then get a cheap multi-fx pedal that you like. If you are or will be then save your money for the more expensive quality brands. If you use your computer a lot and are playing near one a lot then you can get a computer based one such as guitar rig which offer just as much if not better sounds than most. I think you can get a free demo for these.
Best advice I can give you is for you to take your time and explore all your options. If you impulse buy you'll most likely be completely unhappy with your choice.
Comment: This is a great answer, but a mix between a recommendation on what to buy and what the asker really wants--which is guidelines on how to test drive something cool. I think the info about the GT-10 is a great thing to have, but belongs in the comment where you originally placed it.
Answer: A lot of what you're looking for depends a lot on you. If you're a rock player, you'll want to try out the distortions. If you're a U2 or Pink Floyd fans, you'll want to look at the echos. If you play freak-out psych, you may want to poke at the ring modulator. We can't tell you what effects to test without knowing how you want to sound.
What you should try is the ease of switching through the presets and the ease of modifying and creating a new setting. If you play out, the last thing you will want is to have to crouch down and poke a lot in the middle of practice or a gig to switch, and if you can't figure out how to save a setting once you've modified, you won't be happy with it.
I started going toward being a pedalboard player rather than multi-effects because I want to be able to have the tremolo on or off no matter what else is going on. With a multi-effects unit, if you don't have the tremolo set up, you can't have it.
And I agree about the gear thing. You may want to ask before you bring it into the shop, but bring your guitar. I know you have to check in stuff at the door at GC and Sam Ash. Jduv's right that not everything will sound great through this holy grail amp, but it will sound different, and you don't want that.
Answer: When I test drive a pedal at a shop, I try and play equipment closest to my actual rig at home as I can, or if they have the exact models of amplifier and guitar I would play through those. If not, then get as close as you can. Be careful, however, what amplifier you choose. Especially when testing overdrive settings on the multi-FX unit. A tube amp reacts entirely differently than a solid state amp--and both will yield interesting results. Also consider that you may like a mix between the amplifier's overdrive and the overdrive of the FX unit. On my board, I have two overdrives and a boost--both of which are blended with my Orange's natural distortion. This way, some of the attributes of the overdrive produced by the pedal make up for some deficiencies in the amplifier's natural overdrive tone. So, there's a bit of a mix and match problem here that you'll have to overcome if you choose to blend overdrives. If you play a tube amp, I highly recommend you test how well the FX unit mixes with the amp's natural overdrive. Some settings will play nice, others won't.
I would approach the test drive from a couple of avenues. First off, what do you want to sound like? Multi-FX units can't really do everything awesome (subject to debate I know), so they do most things really well. Preset patches are a good way to test drive the general tones of the unit and also discover how some settings mix with others, but that doesn't open you up to the creativity of the unit itself. I would first do some research online and find out the specifications of the units you want to play with. Is it software controlled? How easy is it to program my own patch? What are other people saying about this unit? Once I have that information I'd head in to a local guitar shop and plug each one in. Once you're there and test driving the unit play through each tone that you think you would use individually. Keep a list of which tones you like, and which tones you don't like. Do a simple cost analysis on each unit and decide which one you like the best.
In the end, your sound will be an aggregate of many features. The amplifier you use in tandem with your guitar and the multi-FX unit you pick will dictate how easy, or hard, it is to get and use your sound. Have fun with experimenting of course :D. Don't approach it too much like a science. Some of the cooler sounds I have discovered come from taking the knobs on my pedals to places I normally would never go.


GLFW simple triangle is lost?

Question: I modified the "Simple example" example in GLFW3.0.4 in Mac OSX 10.8 as an XCode 4.6 project (runs fine when unchanged). I am having a (2D) rectangle drawn with an external library (which draws via shaders). I can see the rectangle but If I draw the sample triangle (immediate drawn) before it, the triangle is seen in the first splash (frame) and then it is lost. If I try to draw it after, the triangle is never seen. I can only see the rectangle and I don't know what settings/states the library is changing!
I tried to inspect the application with OpenGL Profiler. Stopped before CGLFlushDrawable and could not find the triangle in any of the buffers (front, back, depth, stencil).
Am I doing something (prominently) wrong? The profiler allows only gl-function breakpoints. How can I debug this (more efficiently) and find the problem.
Here is (much of the changed parts of) the code:
void glfw2DViewport(GLFWwindow * window) {
    float ratio;
    int width, height;

    glfwGetFramebufferSize(window, &width, &height);
    ratio = width / (float) height;

    glViewport(0, 0, width, height);
    glClearColor(0.8, 0.8, 0.8, 1.0); // Lets see if something black is drawn!!
    glClear(GL_COLOR_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    // eye is at 0,0,0 looking to positive Z, -1(behind) to 1 are clipping planes:
    //  https://www.opengl.org/sdk/docs/man2/xhtml/glOrtho.xml
    glOrtho(ratio, -ratio, -1.f, 1.f, 1.0f, -1.f);
    glMatrixMode(GL_MODELVIEW);

    glLoadIdentity();

    // ----- 2D settings -----

    glfwSwapInterval(1);

    glEnable(GL_SMOOTH);
    glDisable(GL_DEPTH_TEST);
    //glDisable(GL_STENCIL_TEST); // Disabling changed nothing!!
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glLineWidth(5.0f);
    glEnable(GL_LINE_SMOOTH);
    glPointSize(5.0f);
    glEnable(GL_POINT_SMOOTH);

}

int main(void) {
    GLFWwindow* window;
    glfwSetErrorCallback(error_callback);

    if (!glfwInit())
        exit(EXIT_FAILURE);

    window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL);
    if (!window) {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    glfw2DViewport(window);

    //...

    while (!glfwWindowShouldClose(window)) {
        glMatrixMode(GL_MODELVIEW_MATRIX);
        glLoadIdentity();

        glClear(GL_COLOR_BUFFER_BIT);

        //drawUnitTriangle(); // can be seen just in the first frame!

        glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS); // A vain attempt?
        glPushAttrib(GL_ALL_ATTRIB_BITS); // Another vain attempt??
        external_library_identity_matrix();
        external_library_rectangle(POS,RED);
        external_library_flush();
        glPopAttrib();
        glPopClientAttrib();

        // Other vain attempts:
        glfwMakeContextCurrent(window);
        glMatrixMode(GL_MODELVIEW_MATRIX);
        glLoadIdentity();

        drawUnitTriangle(); // Nothing is Drawn!!

        glfwSwapBuffers(window);

        glfwPollEvents();
    }

    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}

Answer: Are you sure the posted code is exactly what you are building with?  If that's true, please check the argument of glMatrixMode() it should be GL_MODELVIEW, not GL_MODELVIEW_MATRIX. There are two places where you set it like this.
Since you already have glfw2DViewport(), why don't you put it in the while loop and delete other model view setting codes?
Comment: No, I skipped external library functions and `GL_MODELVIEW_MATRIX` was a remnant of my (several) vain attempts; reverted back and nothing has changed. Starting the loop with `glfw2DViewport()` also did change nothing. External library functions change something so that other drawing functions do not work beyond that line, even if I encapsulate them between push-pop stuff...
Comment: Nothing changes even if I use `glfw2DViewport(window)` just before `drawUnitTriangle()`!?

GLFW simple triangle is lost?


Do ordered lists contain more information than unordered lists?

Question: Suppose you have a set of 4 elements {A,B,C,D}, but without specifying their order. Now, if you want to specify which precedes which, that would mean you need to provide more information.
But at the same time, writing down the ordered list {B,C,A,D} doesn't take more text. That's probably because order is implicit when writing down things, even when I say that {A,B,C,D} is unordered, the way I write it down has order, I just tell you to ignore it.
So which is true? Does order carry additional information, and if so, why don't ordered lists take more text to describe than unordered ones?
Comment: See [How to define the entropy of a list of numbers?](http://math.stackexchange.com/q/62501) -- perhaps not exactly a duplicate but close.
Comment: my address is $\{3412\}$ $\{ifstr\}$ street
Answer: Ordered lists do contain more information.
Precisely, you can order $n$ elements in $n!$ different ways, so say you got $4$ elements ${A,B,C,D}$ with no order defined. When writing them down in a particular order, the order itself defines a number from $0$ to $4! = 23$, so you basically stored $log_2 24$ additional bits.
Now when you write down unordered elements, you'll of course need to choose some order (which is "waste" information in that moment). But if you choose a particular order, you can use this to store additional information in the same message. This is actually a neat trick in steganography, i.e. sending hidden messages, in data where order is of no importance (HTML attribues are great!).
On the other hand, if order does matter, you cannot afterwards rearrange the items to store extra information or the original order is lost.


Reading property names from a class in TypeScript?

Question: Having a class (e.g. WikipediaSearchResult) with a few properties in TypeScript, is it possible to access them? Maybe this question is a bit naive, but I'm wondering if I could write following code without duplicated property names:
function mergeTo(from:any, to:any={}, properties:Array<string>=[]) {
  if (!!from) {
    for (var property of properties) {
      // no deep copy here ;-)
      to[property] = from[property];
    }
  }
}

class WikipediaSearchResult /* implements IWikipediaSearchResult */ {

  lang:string;
  summary:string;
  title:string;
  wikipediaUrl:string;

  constructor(obj?:any) {

    mergeTo(obj, this, [
      // --> How to avoid this list? <--
      'lang', 'summary', 'title', 'wikipediaUrl'
    ]);

  }

}

var result = new WikipediaSearchResult({
  title: 'Zürich',
  wikipediaUrl: 'https://en.wikipedia.org/wiki/Z%C3%BCrich'
});

console.log(result);

Of course there are some 3rd party libraries such as Underscore.js, but it differs from e.g. _.clone(...) since I do only want to clone specific properties and ignoring all other properties which may be provided by obj respectively from.
Another way might be using e.g. _.create(WikipediaSearchResult.prototype, { title: 'Zürich' }), haven't tried it yet but it will use the JavaScript prototype property. It would be great to use TypeScript internal mechanism.
An idea which I came up with is to create a "dummy" instance and reading its key. I'm wondering if someone comes up with better variant?
Comment: why don't you iterate over from?
`for (var property in from) {
    to[property] = from[property];
}`
Comment: `from` (`any`) might have more properties which should not be set in `to`
Answer: Initializing the properties of class WikipediaSearchResult allows using this as a "template":
function mergeTo(from:any, to:any={}, properties:Array<string>=[]) {
  // same as in question
}

function mergeTo2(from:Object, to:Object):Object {
  // _.keys from underscore
  return mergeTo(from, to, _.keys(to));
}

class WikipediaSearchResult {

  lang:string = undefined;
  summary:string = undefined;
  title:string = undefined;
  wikipediaUrl:string = undefined;

  constructor(obj?:any) {
     util.mergeTo2(obj, this);
  }

}

var result = new WikipediaSearchResult({
  title: 'Zürich',
  wikipediaUrl: 'https://en.wikipedia.org/wiki/Z%C3%BCrich'
});

console.log(result);

Still looking for other variants...
Answer: You can apply to each of the copiable properties a custom decorator:
  @Copiable
  lang:string;

Then inside @copiable decorator function you will store target property name in some static collection.
function Copiable(target: any, key: string)
{
    CopiableProperties.push(key);
}

Then later in mergeTo method you will be able to iterate over all copiable property names stored in CopiableProperties.
It might be a bit overkill but it will allow you to avoid duplicates.
Hope this helps.
Comment: For my purposes I have a special public helper static class dedicated to contain such 'meta' information.
Comment: Interesting approach but as you stated it's a bit overkill. And another question might arise: Where to store this collection?
Comment: I'll like the idea of using decorators(!) but it does not help to make the code more readable or maintanable. I rather go with my answer because of these reasons. Bring me an argument why your solution is better than mine and I am going to change the accepted answer to yours. ;)


MVVM Listbox ContextMenu

Question: I am trying to fire the command by right clicking and selecting the context menu on wpf mmv light app. The listbox is made up of a datatemplte.
<ListBox.ContextMenu>
     <ContextMenu Width="150" >
         <MenuItem Header="Move to holiday">
              <MenuItem.Icon>
               <TextBlock FontFamily="/BoonManager;component/Fonts/seguisym.ttf#Segoe UI Symbol" Text="🌄" />
              </MenuItem.Icon>

                  <cmd:EventToCommand Command="{Binding DataContext.ComMoveToHoliday ,ElementName=LayoutRoot}"/>

                  </MenuItem>
       </ContextMenu>
</ListBox.ContextMenu>

I have also tried using this
DataContext="{Binding Path=PlacementTarget, RelativeSource={RelativeSource Self}}"

but no luck. Thanks Scott
**Update
I have code running just above the ContextMenu that runs fine.

            <cmd:EventToCommand Command="{Binding DataContext.ComShowPerson, ElementName=LayoutRoot}" CommandParameter="Expected" />

So it must be the contextMenu that is blocking this.
Comment: why not use a command on the menu item itself ?
Comment: thanks. Is the command not already on the menu item? Its nested inside.
Comment: clicking the context menu item didn't work for you ? or you had problems with the DataContext ?
Comment: Clicking the context item should fire the command in the model but its not.
Comment: your command is in the DataContext of the list box ?
Comment: No. Datacontext of the viewmodel. I tried to point it to the root of the window. i.e. Command="{Binding DataContext.ComMoveToHoliday ,ElementName=LayoutRoot}"
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/69401/discussion-between-stsur-and-scottsanpedro).
Answer: I managed to track down an answer from this link.
http://www.codeproject.com/Articles/80632/WPF-Context-Menu-on-List-Item
Worked great. Thanks for any help.Appreciated. Scott
Answer: try to do something like that instead
            <ListView.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Copy" Command="{Binding FullPathCommand}"/>
                </ContextMenu>
            </ListView.ContextMenu>

Comment: No. still not firing. Maybe the issue is complicated by the datatemplate? Though I have similar code  that works above the contextmenu fine. I will add it to the original question.Thanks for your help.

MVVM Listbox ContextMenu


ajax upload não passa variáveis

Question: Não estou conseguindo passar as variáveis no método ajax.
<input type="file" id="id-input-file-2" name="arquivo" class="form-control arquivo" />
<input type="hidden" name="ID_Cotacao" id="ID_Cotacao" value="555">

.
$(function(){
    $('.arquivo').change(function(e){
        if ($('.arquivo').val() != "") {
            e.preventDefault();
            var formData = new FormData();

            formData.append('arquivo', $('.arquivo').prop('files')[0]);
            formData.append('nomeArquivo', $('.arquivo').val());
            formData.append('id_cotacao', $('#ID_Cotacao').val());

            $.ajax({
                url: 'cotacoesEditarUpload.php',
                data: formData,
                type: 'GET',
                success: function(){
                    alert("Enviado com sucesso."),
                    $(".listaArquivo").load(window.location + " .listaArquivo")
                },
                processData: false,
                cache: false,
                contentType: false
            });
        };
    });
});

Como aparece no console do navegador:
cotacoesEditarUpload.php?[object FormData]&_=1441423098339
O que estou fazendo de errado?
Comment: @Brunno não deu certo. Mesmo problema.
Comment: vamos ter que esperar alguém que mexa com php pra te ajudar :PP só dei um palpite azedo hahaha' :DD
Comment: Valeu bruno, muito obrigado pela dica. Se tiver outra vou ficar feliz em testar :)
Comment: Alguma luz no fim do túnel?
Comment: @Brunno assim funcionou as variáveis `data: 'arquivo'+ $('.arquivo').prop('files')[0] +'&nomeArquivo='+ $('.arquivo').val() +'&id_cotacao='+ $('#ID_Cotacao').val(),` mas o arquivo não é enviado, somente as variáveis. Sabe como fazer?
Answer: Estou assumindo que você quer fazer um upload de arquivo.
Upload de arquivo não pode ser realizado em uma requisição GET. Não que seja impossível (seria necessário ler os dados do arquivo e codificá-los em algo como base64 ou alguma outra representação que possa ser colocada em uma query HTTP).
Utilize para fazer upload de arquivo o método POST ou o PUT. Do lado do servidor, cada um deles possui particularidades no processamento dos dados, sendo o POST mais tradicional especialmente se utiliza PHP.
Com exceção do método da requisição, não vejo outro problema no seu código interferindo no envio do FormData.
Trecho do código:
$.ajax({
    url: 'cotacoesEditarUpload.php',
    data: formData,
    type: 'POST',
    success: function(){

ajax upload não passa variáveis


How to solve the recurrence $a_{0}=1 , (n+1)a_{n+1}=a_{n}+(\frac{1}{n!}), n\geq 0$

Question: I know that I should got out the n!, since there is no root for it , if I multiply the both side by n! then it will become like :
$n! (n+1)a_{n+1}=a_{n}n!+1$
And then I have to put $b_n=a_n n!\ \ \ \  $ right ??
Any idea how could I get rid the (n+1) ??
Comment: You've forgot a $+1$.
Answer: You are on the right track. By letting $b_n=a_n n!$ the recursion becomes $b_0=1$ and for $n\geq0$,
$$b_{n+1}=b_n+1.$$
Now find $b_n$ and then $a_n=\frac{b_n}{n!}$.
Answer: Just multiply each side by $n!$, then you get
$$
(n+1)!a_{n+1}=n!a_n+1
$$ or
$$
(n+1)!a_{n+1}-n!a_n=1
$$ which is straightforward to solve by telescoping.
Comment: okay I think I understand .. (n+1)!= n!(n+1) right ??
Comment: how did (n+1) become factorial (n+1)!?
Answer: I will write the equation as $a_{n+1}=\frac1{n+1}a_n+\frac1{(n+1)!}$.
The answer is $a_n=\frac{n+1}{n!}$. One can see this by induction. It is clearly true for $a_0$. Assume true for $a_n$. Then we have that
$a_{n+1}=\frac1{n+1}\frac{n+1}{n!}+\frac1{(n+1)!}$
writing this as a single fraction we have
$a_{n+1}=\frac{n+2}{(n+1)!}$ and we're done.


Como inserir uma String numa Pilha, com Linguagem C

Question: Estou estudando linguagem C, estou na aula de Pilhas, mas estou com uma dúvida simples (acredito)
Meu codigo funciona(da maneira que espero), se eu passar os paramentos de forma manual, como abaixo:
#include <stdio.h>
#include <stdlib.h>

struct Pilha {
    int topo;
    int * proxElemento;
};

void criaPilha (struct Pilha *p){
    p->topo = -1;
    p->proxElemento = (int*) malloc(sizeof(int));
}

void insereItem (struct Pilha *p, char * nome) {
    p->topo++;
    p->proxElemento[p->topo] = nome;
}

int main() {
    struct Pilha *pilhaLivros;
    criaPilha(&pilhaLivros);
    insereItem(&pilhaLivros, "Livro 1");
    insereItem(&pilhaLivros, "Livro 2");
    insereItem(&pilhaLivros, "Livro 3");
    return 0;
}

Quando troco o método de inserção de valores na Pilha, por um scanf ou gets(como abaixo), não dá erro na inserção propriamente dita, os dados são recebidos e inseridos pela função insereItem
int main() {
    char * nome;
    struct Pilha *pilhaLivros;
    criaPilha(&pilhaLivros);

    printf("Digite o livro 1: ");
    scanf("%s", nome);
    insereItem(&pilhaLivros, nome);

    return 0;
}

ou
int main() {
    char * nome;
    struct Pilha *pilhaLivros;
    criaPilha(&pilhaLivros);

    printf("Digite o livro 1: ");
    fflush(stdin);
    gets(nome);
    insereItem(&pilhaLivros, nome);

    return 0;
}

Mas o conteúdo guardado em p->proxElemento[p->topo] não foi o lido pela variavel nome.
Como posso resolver esse problema?
obrigado
Comment: Há alguns problemas no seu código (como passar um endereço de um `ponteiro` ao invés de um endereço de uma `struct Pilha`). Você aparentemente cria um vetor de `int` para armazenar uma `string` em cada posição, isso não vai dar certo, faça uma matriz de `char`. Não utilize o [fflush](https://pt.stackoverflow.com/questions/111697/limpar-buffer-em-c-com-fflush-ou-fpurge) com `stdin` como argumento.
Comment: Oi Julio, obrigado pela ajuda, entendo o que fala, mas no intuito de entender melhor meu código, gostaria(se possível) que me explicasse, pq quando mando a string direto funciona perfeito, mas quando passo a string pela variavel lida, não funciona
Answer: Seu código que você diz funcionar não funciona, na sua máquina ele pode parecer funcionar, mas ele não faz o que você realmente quer (o código gera vários warning e isso significa que seu programa vai rodar de forma inconsistente).
Problemas
Passar um endereço de um ponteiro
Problema
Repare nas suas funções:
void criaPilha (struct Pilha *p)
void insereItem (struct Pilha *p, char * nome)

Ambas precisam de um endereço de uma struct Pilha, entretanto você está passando um endereço de um ponteiro do tipo struct Pilha. Observe:
struct Pilha *pilhaLivros; /* pilhaLivros eh um ponteiro */
criaPilha(&pilhaLivros) /* logo voce esta passando um endereco de um ponteiro */

Solução
Para resolver isso basta que pilhaLivros não seja declarada como ponteiro, assim:
struct Pilha pilhaLivros; /* agora pilhaLivros nao eh um ponteiro */

Utilizar um vetor de int para armazenar string
Problema
Você aparentemente cria um vetor de int para armazenar uma string em cada posição, observe:
struct Pilha {
    int topo;
    int * proxElemento; /* aqui eh seu ponteiro que vai usar como se fosse um vetor */
};

/* aqui eh na funcao criaPilha */
p->proxElemento = (int*) malloc(sizeof(int)); /* entao voce aloca memoria */

/* aqui eh na funcao insereItem */
p->proxElemento[p->topo] = nome; /* e coloca cada string em uma posicao dele */

Aqui temos alguns problemas.
Utilizar um vetor de int para armazenar string
Um vetor de int serve para armazenar várias variáveis do tipo int, se quer armazenar float, então o vetor tem que ser de float e essa lógica segue para qualquer tipo. Não temos algo assim:
string vetor[10];

Para criar um vetor de string precisamos lembrar que uma string já é um vetor, então um vetor de string é um vetor de vetores (uma matriz).
struct Pilha {
    int topo;
    int * proxElemento; /* isso aqui precisa ser uma matriz de char */
    char proxElemento[5][10]; /* uma matriz de char eh o que voce precisa */
};

A matriz acima consegue armazenar 5 string, onde cada uma delas não pode ultrapassar 10 de tamanho. Para criar uma matriz com alocação dinâmica precisamos de um ponteiro de ponteiro, repare:
struct Pilha {
    int topo;
    char **proxElemento; /* vamos usar o malloc para criar uma matriz */
};

Criando uma matriz usando ponteiro de ponteiro
No malloc devemos informar o tamanho de bytes que vamos alocar. Se quiser uma matriz que tenha 10 string então devemos colocar o valor 10 no malloc. Exemplo:
p->proxElemento = (int*) malloc(sizeof char * 10);
p->proxElemento = malloc(10); /* char vale 1 byte entao o sizeof nao eh necessario, a conversao tambem nao eh necessaria */

Sua função criaPilha ficaria assim:
void criaPilha (struct Pilha *p){
    p->topo = -1;
    p->proxElemento = malloc(10);
}

Agora podemos ter 10 string diferentes.
Adicionando uma string
Repare como você estava adicionando uma matriz:
void insereItem (struct Pilha *p, char * nome) {
    p->topo++;
    p->proxElemento[p->topo] = nome;
}

Lembre-se que não podemos atribuir diretamente uma string, veja:
a  = 10; /* valido */
b = 4.7; /* valido */
c = "teste"; /* invalido */

Podemos copiar uma string em outra usando strcpy. Então a função insere ficaria assim:
void insereItem (struct Pilha *p, char * nome) {
    p->topo++;
    strcpy(p->proxElemento[p->topo], nome);
    /* p->proxElemento[p->topo] = nome; */
}

Mas antes de fazer isso é necessário alocar quantos bytes nossa string precisa ter, dessa forma:
void insereItem (struct Pilha *p, char * nome) {
    p->topo++;
    p->proxElemento[p->topo] = malloc(31); /* agora voce pode adicionar um string com ate 30 de tamanho */
    strcpy(p->proxElemento[p->topo], nome);
    /* p->proxElemento[p->topo] = nome; */
}

O ideal é você verificar o tamanho da string nome e alocar somente o necessário (não esqueça de deixar 1 espaço a mais para o \0).
Com essas alterações seu código deve funcionar, você pode colocar um scanf que vai funcionar normalmente.
Veja seu código funcionando aqui.
OBS
Não esqueça de utilizar o free para liberar memória quando deletar uma string ou quando destruir a pilha.
Você pode criar uma variável do tipo int dentro de sua struct para guardar quantas string sua pilha pode armazenar e assim manter o controle.


Compute integral in probability task.

Question: Let's consider $X,Y$ are i.r.v. with $N(0,1)$ distribution. Let $a,b \in \mathbb{R}$. We want to know distribution of $Z = (X-a)^{2} + (Y-b)^{2}$.
My attempt : let $\bar{X} = X-a$ and $\bar{Y} = Y-b$, then $\displaystyle \mathbb{P}(Z\le z) = \int_{\bar{X}^{2} + \bar{Y}^{2} \le z}e^{-\frac{1}{2}\left((\bar{X}+a)^{2} +(\bar{Y}+b)^2)\right)}dxdy$.
I've made a polar substitution, but then stuck with something like $\displaystyle \int_{0}^{2\pi}e^{-r(a\cos\phi + b \sin \phi)}$.
So maybe there is easier approach to solve it , or to compute this integral?
Comment: Is it assumed that the two random variables are independent?
Comment: @callculus yes, they are independent
Answer: Your $Z$ is distributed as a noncentral chi-squared distribution. Information about the distribution can be found here:
https://en.wikipedia.org/wiki/Noncentral_chi-squared_distribution
Unfortunately I doubt you can simplify the integral for the CDF much analytically.

Compute integral in probability task.