unsigned long larger than 0xFFFFFFFF

Question: How test program can result 4294967297 if unsigned long maximum is 4294967295?
#include <iostream>
using namespace std;
unsigned long millis_diff(unsigned long then, unsigned long now) {
    return now < then ? now + then : now - then;
}
int main()
{
    unsigned long now = 2;
    unsigned long then = 4294967295; //unsigned long maximum value
    unsigned long diff = millis_diff(then, now);
    cout << diff;
    return 0;
}

Comment: C++ gives you two guarantees with the integer types. The first is that the condition `sizeof(char) <= sizeof(short) && sizeof(short) <= sizeof(int) && sizeof(int) <= sizeof(long) && sizeof(long) <= sizeof(long long)` will be `true`. The second is that `long` will be *at least* a 32-bit data-type. A `long` could be 64 bits as well.
Comment: The only guarantee you get about `unsigned long` is that it is greater than or equal to `unsigned int`. The actual size is implementation defined.
Comment: "*unsigned long maximum is 4294967295*" this is incorrect premise in general.
Comment: @EugeneX, table of integer sizes is highly architecture-dependent and ABI-dependent. It's not the same across all the platforms.
Comment: There are target systems (typically DPS's) where a `char` could be 16 bits. And there are old systems where a "character" could 6, 7, or 9 bits, and "word" (typically `int`) could be 18 or 36 bits. In short, the integer types does not have a fixed size in the specification, only minimum sizes. And remember, even though `char` could be any number of bits, `sizeof(char)` will *always* equal `1`,
Comment: "unsigned long maximum is 4294967295?"
No it isn't...
Comment: Let me guess, you are using linux?
Comment: How do you know that's the maximum?
Comment: Have you checked `std::numeric_limits::max()` on your system?
Comment: Typically, for 64-bit PC-like targets GCC will have 64-bit `long`. The Visual C++ compiler will have 32 bit `long` even for 64-bit targets.
Comment: I seriously don't checked max sizes...

It's now that table of integer sizes is invalid?

unsigned char is 0..255   (1 byte value)
unsigned short is 0..65535 (2 bytes unsigned value)
unsigned long 0..4294967295 (4 bytes unsigned value)
unsigned long long 0..0xFFFFFFFFFFFFFFFF (8 bytes value)
Answer: The reason is that it seems your compiler defines unsigned long int the same way as it defines unsigned long long int.:)
Here is a demonstrative program
#include <iostream>
#include <limits>

int main()
{
    std::cout << "sizeof( unsigned long ) = " << sizeof( unsigned long ) << '\n';
    std::cout << "The maximum values is " << std::numeric_limits<unsigned long>::max() << '\n';
}

Its output is
sizeof( unsigned long ) = 8
The maximum values is 18446744073709551615

Comment: `Now I will know that ulong is 8 bytes long` You know that it is 8 bytes *on that particular system*. That assumption won't hold on systems where it isn't 8 bytes.
Comment: Thank you about description, Now I will know that ulong is 8 bytes long...
Comment: @EugeneX It's not always this way. The standard only guarantees it to be at least 32 bits.
Comment: @EugeneX It depends on the used compiler. Some implementations define its size as 4 bytes others as 8 bytes.
Answer:
How test program can result 4294967297 if unsigned long maximum is 4294967295?

Given the premise, it can't.
However, there is no guarantee for unsigned long maximum to be exactly 4'294'967'295, so your premise may be invalid. that maximum corresponds to the maximum that a 32 bit number can represent. 32 is the minimum required width for (unsigned) long, but it may be wider than that.
In particular, it is typical for some 64 bit systems to have unsigned long of 64 bits, which has the maximum value of 18'446'744'073'709'551'615.

unsigned long larger than 0xFFFFFFFF


Is this description of "ordinary induction" from Velleman's *How to Prove It* correct?

Question: The following is from How to Prove It: A Structured Approach, 2nd edition, by Daniel J. Velleman, page 289.

To see why strong induction works, it might help if we first review briefly why
  ordinary induction works. Recall that a proof by ordinary induction enables us
  to go through all the natural numbers in order and see that each of them has
  some property $P$. The base case gets the process started, and the induction step
  shows that the process can always be continued from one number to the next.
  But note that in this process, by the time we check that some natural number
  $n$ has the property $P$, we've already checked that all smaller numbers have the property. In other words, we already know that $∀k < nP(k)$. The idea behind
  strong induction is that we should be allowed to use this information in our
  proof of $P(n)$.

That characterization of "ordinary induction" is certainly not how I think of standard (not strong) complete induction.  I think of it as showing that $P\left[1\right]$ holds (the initial case) and then showing that $P\left[n\right]\implies{P\left[n+1\right]}$, where $P\left[n\right]$ is called the induction hypothesis, and $P\left[n\right]\mapsto{P\left[n+1\right]}$ is the induction step.
Are these characterizations of complete induction mutually contradictory?  Are they essentially the same?
Comment: I'm still a bit unclear what the problem is, unless it's a specific method of formalizing the notion, such as functions being "rules of correspondence" vs. "subsets of a Cartesian product". Also, Velleman is explaining things in [natural language](https://en.wikipedia.org/wiki/Natural_language) at this point, and so he's not trying to adhere to any strict method of formalization.
Comment: @StevenHatton Yes, but so? Nowhere in this does natural-language induction appear. I really don't understand what your question is. As far as I can tell, all the relevant points are: $(i)$ what you call "standard complete induction" is often called "weak induction," is on-the-surface distinct from the thing called "strong induction," but is actually equivalent to it (in a precise sense); $(ii)$ both weak and strong induction are *mathematical principles*, not natural-language ideas; $(iii)$ Vellman's infinite-process description is just informal motivation. What does the above **not** address?
Comment: Vellman is choosing to explain mathematical induction as essentially compressing an "infinite task" into an actual mathematical argument. This can in fact be made precise if one wants, so he's not just messing around, but that's beside the point: *it's just flavor.* If you don't like it, ignore it.
Comment: You probably need to explain your concern a little better. There are two forms of (ordinary) mathematical induction, a weak form and a strong form. Velleman is talking about both of them, and you're talking about one of them. Is your concern the use of the terms, or why the seemingly stronger version is equivalent to the weaker version, or something else? Part of the problem is that you say "mutually contradictory". What does "mutually" contribute to simply being contradictory? Also, if P implies Q but Q does not imply P (what I think you're saying), that doesn't make "P and Q" always false.
Comment: @StevenHatton That's the same thing - *nobody* here is using the natural language version of the word. Ordinary and strong induction are two forms of mathematical induction, which are equivalent in a precise sense.
Comment: Dave Renfro's comment is exactly right: Vellman is giving an *informal description* of the idea behind (the usual phrasing of) mathematical induction. It's not literally an infinite process, of course, but one can think of the induction axiom as somehow "compressing" what would normally be an infinite process into a single step (fine, two steps). Is this a *good* informal description? Maybe - in my experience it's usually helpful but sometimes confusing. Is it a *potentially mathematically useful* one? In my opinion, yes (at least in some areas of mathematical logic). Just don't over-think it.
Comment: I added some clarification, but my original question seemed pretty clear to me.
Comment: It's not clear to me, because "*The base case gets ...*" is a fairly standard way of describing what weak induction involves. See the search results for [induction + ladder](https://www.google.com/search?q=induction+ladder) *AND* [induction + dominoes](https://www.google.com/search?q=induction+dominoes). Maybe you're concern is the variable shift from $n$ to $n+1?$ Note that $(\forall n)( P[n] \implies P[n+1])$ is the same as $(\forall n)( P[n+2] \implies P[n+3])$ (modulo appropriate restrictions on the values taken by $n).$
Comment: The consequence of complete induction (Peano's 5th axiom) is that all those cases are true, but it is not the method of proof to move sequentially from one to the next.  We prove the initial case and prove that the property is hereditary.  The rest follows.
Comment: See [Complete (or strong) induction](https://en.wikipedia.org/wiki/Mathematical_induction#Complete_(strong)_induction) : "Complete induction is equivalent to ordinary mathematical induction".
Comment: @MauroALLEGRANZA That is not the definition I learned.  Peano's 5th axiom is the *principle of complete induction*.  It is given that name to distinguish it from the human language definition of the word induction which is by definition incomplete.  Complete induction proves in one stroke a proposition to be true for all natural number.
Comment: [These lecture slides](http://www.cs.bath.ac.uk/~gam23/teaching/DiscreteMaths/03induction.pdf) look pretty good and might be helpful, especially pages 5 and 10-12.
Comment: @NoahSchweber Apparently others distinguish between what I have been calling *standard complete induction* and *strong induction*.  From what I know, the latter is a consequence of the former.
Comment: @NoahSchweber my point in referring to the natural language definition was to explain why mathematical induction is called *complete* induction.  In a situation in which I am applying induction, the first time I encounter the arbitrary number $n$ I determine if the target proposition is hereditary.  Velleman's description makes it seem as if I will always be reaching a new $n$ in an indeterminate state, and I can somehow leverage the previous results to prove the case of $n$.
Comment: @NoahSchweber Velleman's book has been otherwise lucid and pleasant to read, thus far.  (I skipped ahead to the section on strong induction in an effort comprehend the issues discussed here https://math.stackexchange.com/q/3064870/342834 I honestly believe Velleman's characterization of "ordinary induction" is misleading, and could have been stated more accurately and effectively.  I believe I now understand the essence of what he was getting at.  That understanding would not have come from continuing to bleed over Behnke, Bachmann, Fladt, Suess.  The comments here have also been helpful.
Answer: The phrase "recall that" in the quoted paragraph makes it clear that this paragraph is referring back to an earlier explanation of why ordinary induction works.  It would be helpful to go back and look at that earlier explanation.  Induction is introduced on p. 260, and the definition is the usual one:  Prove $P(0)$ (the base case) and then prove $\forall n \in \mathbb{N}(P(n) \to P(n+1))$ (the induction step).  (Some people include 0 in the natural numbers and some don't.  In How To Prove It, 0 is included.)  On p. 262 there is an explanation of why induction works.  That explanation is that the base case proves that $P(0)$ is true.  Plugging in $n=0$ in the induction step you get $P(0) \to P(1)$, and from $P(0)$ and $P(0) \to P(1)$ you get $P(1)$.  Then plugging in $n=1$ in the induction step you get $P(1) \to P(2)$, and from $P(1)$ and $P(1) \to P(2)$ you get $P(2)$, etc.  The explanation ends with the statement "Continuing in this way, you should be able to see that by repeatedly applying the induction step you can show that $P(n)$ must be true for every natural number $n$."  When you carry out this process of starting with the base case and then repeatedly applying the induction step, you confirm first $P(0)$, then $P(1)$, then $P(2)$, and so on.  It is this process that I was referring to in the sentence "Recall that a proof by ordinary induction enables us to go through all the natural numbers in order and see that each of them has some property $P$."
Notice that the quoted passage says that mathematical induction enables us to go through all the natural numbers in order, it doesn't say that a proof by induction consists of going through the natural numbers in order.  A proof by induction consists of a base case and an induction step.  But if you've proven the base case and the induction step, then that would enable you to go through the natural numbers in order and verify that they all have property $P$, as described above.  And that's why induction works.  For example, if you've done a proof by induction, why is, say, $P(10)$ true?  The answer is that you have to start with $P(0)$ and apply the induction step 10 times to work your way from $P(0)$ up through $P(1)$, $P(2)$, and so on up to $P(10)$.


Duvida sobre Excel, como bloquear colunas?

Question: Olá gostaria de saber se existe uma opção no Excel, que de para bloquear certas colunas para que fiquem disponíveis somente colunas que são editadas sempre...
Exemplo: Tenho essa coluna selecionada, e quero bloquear ela, para que toda vez que for fazer alguma alteração, não edite ela sem querer ou algo assim.
Answer: Shift+Ctrl
Selecione a coluna e células desejada, clique com o botão direito-> Formatar células-> Vá até a aba Proteção -> e de um checked marque a seleção em Bloqueadas e de um ok.
Depois vá na aba superior do menu do Excel clique em Revisão proteger planilha e de um ok.
Answer: Olá, da sim. Podem haver variações de acordo com a sua versão do Excel ou procedimentos diferentes. No geral costuma ser assim, mas pode haver de ser algo diferente. Isso é o básico para proteção de planilhas, ai você pode ir alterando as permissões, e ver oque melhor se encaixa na sua necessidade.

Selecione as células e bloqueie as mesmas.

Após bloquear as células, proteja a planilha.

Insira uma senha (opcional) e selecione oque deseja bloquear na planilha.

Caso tenha colocado uma senha, basta repetir a senha e clicar em "OK"

Salve sua senha em algum lugar, pois se precisar modificar alguma célula será necessário desbloquear a planilha.

Caso tente editar uma célula protegida, vai aparecer esse pop-up.


Merge two uneven sets of items

Question: I'm trying to get a fairly even distribution of one set of items into another and am looking for an algorithm that can help.
For example, Group A has 42 items and Group B has 16 items.  I want to mix both groups together so that B is fairly evenly distributed within A.  So, the merged group looks something like: {AA B AAA B AA B AA B AAA.....}  It would be easy, of course, if A was a multiple of B, but that is not often the case for my needs.
Comment: When you "set" your're actually referring to a "list"? Because sets are unordered. Please clarify.
Comment: I was using "set" as a general term.  They are in fact lists of data.  I'm essentially trying to take two sorted card decks of unequal size, and as evenly as possible, shuffle the smaller into the larger.
Answer: You could start by obtaining the number of items from one set between the items of the other set:
float number_between = bigger_set.size() / smaller_set.size();

The iterate over the bigger set, subtracting 1 for each loop from an accumulator (initialized with number_between), inserting an item from the smaller set whenever this accumulator gets below 0, and refreshing it with number_between:
float accumulator = number_between;
foreach(item : bigger_set) {
  result.add(item);
  accumulator = accumulator - 1;
  if (accumulator < 0) {
      result.add(next from smaller_set);
      accumulator = accumulator + number_between;
  }
}

EDIT
Change to:
float number_between = (bigger_set.size() +1) / smaller_set.size();

If you want to be sure that the bigger list both starts and ends the result list.
EDIT 2
Beware that using floating point arithmetic may introduce rounding and underflow errors.
For example, if you're using IEEE single precision (mantissa with 24 bit ~ 7 decimal digits) and the bigger list is greater than the smaller list by a factor of 10^7 or more, the line accumulator = accumulator - 1 will underflow (and you'll get a result entirely made by the bigger set and none of the smaller set).
Also, rounding may lead to an attempt to draw further items from the smaller list when it is exhausted.
Answer: 1) You could concatenate the two groups and do simple sampling from the combined group, for instance by shuffling the elements and iterating through the shuffled combined set.
2) If you'd rather do it sequentialy you could sample from each group with probabilities size(A) / (size(A) + size(B)) and size(B) / (size(A) + size(B)), where size(A) and size(B) are the current numbers of elements in groups A and B, respectively, that haven't yet been sampled.  In other words, if U is a draw from a Uniform(0,1) random number generator:
if U <= size(A) / (size(A) + size(B))
   randomly draw next observation from A
else
   randomly draw next observation from B

In both approaches the A's and the B's end up uniformly distributed across the range, which is the statistical description of a "fairly even distribution".
You didn't specify a language, so here are concrete implementations of both approaches in Ruby.  I've cut the set sizes in half to keep the output length reasonable, and obviously these will both produce different results each time they're run due to the use of randomness.
First approach:
a = ['A'] * 21
b = ['B'] * 8
c = (a + b).shuffle
puts c.join(',')

which, for example, produced the following output:
A,A,A,A,A,B,A,A,A,A,A,B,B,B,A,B,A,A,A,A,A,A,A,A,A,B,B,A,B

Second approach:
a = ['A'] * 21
b = ['B'] * 8
c = []
while a.length > 0 || b.length > 0
  c << (rand <= (a.length / (a.length + b.length).to_f) ? a.shift : b.shift)
end
puts c.join(',')

which, for example, produced the following output:
A,A,B,A,A,A,B,B,A,A,A,A,A,A,A,B,B,B,A,A,A,B,A,A,A,B,A,A,A

Comment: I wasn't really looking for a concrete implementation, more just pseudo code.  Though, I do appreciate your concrete examples.  I will be implementing in VB.Net initially and then porting to Python.
Comment: These should translate pretty straightforwardly to Python.  I wanted to show that the recommendations weren't theoretical, they both can be realized in `O(size(A)+size(B))`.  I'm not sure that can be said of your solution, since I don't know how the `mergedList.Insert` is implemented.
Comment: That mergedList.Insert() is to place the specified item into the list at the given index.  I am not familiar with Ruby, so I'd have to figure out what is going on inside of your while loop.
Comment: Ruby's `shift` is equivalent to python's `list.pop(0)`.  The `<<` is equivalent to python's `list.append(value)`.  The stuff in between is the ternary `?:` operator found in many languages, including C, C++, Java, and Ruby.  `x ? y : z` means if `x` is `true` evaluate `y`, otherwise evaluate `z`.  In other words, the body of the loop evaluates the `if/else` described in pseudocode  in approach 2.  The end result is that `c` gets built up as a merged list of elements from `a` and `b`, where the choice of which type to merge is  proportional to the number of that type in the remaining elements.
Answer: Well, I've been playing around with this and have come up with a solution that will work for my purposes.  I essentially mix the larger items into the smaller items and loop back through until I run out of larger items.
For Each item In smallerList
  mergedList.add(smallerID)
Next

itemsRemaining = biggerList.Count

While itemsRemaining > 0
  index = 0

  For i = 1 To smallerList.Count
    If index >= mergedList.Count or itemsRemaining = 0 Then Continue While

    mergedList.Insert(index , largerID)
    index += 2 + loopCount
    itemsRemaining -= 1
  Next

  loopCount += 1
End While

Then I can replace the IDs with the actual items from the two lists.
So, for my original example (Group 1 with 42 items and Group 2 with 16), I end up with:
111 2 111 2 111 2 111 2 111 2 111 2 111 2 111 2 111 2 111 2 11 2 11 2 11 2 11 2 11 2 11 2
It's a bit front loaded, but for my purposes, this will work out just fine.

Merge two uneven sets of items


About three conjectures concerning the Pythagorean Theorem.

Question: I have two main conjectures relating to the Pythagorean Theorem that I desperately want to find out if they are true or not. Could somebody please help me?

If $ \ a^2 + b^2 = c^2 \ $ for which $c$ is a prime number, then for some $n \in \mathbb{N}, \ c = 4n + 1$.
$\forall \{x, y, z\} \subset \mathbb{N}, \ \big(x^2 + (x + 1)^2\big)^2 = y^2 + z^2 \ $ for which $x \neq y \neq z$.

Tested for $c, x \leqslant 10^6$.

I did also have another conjecture that if $ \ a^2 + b^2 = c^2 \ $ for which $a$ is odd (and greater than $1$), $b$ is even, and $a < b$ then there existed a solution such that $c = b + 1$, but I am $100$% certain this has been discovered before (assuming so, since it was not very difficult to notice). However I am not sure if the other two conjectures have been discovered before, although if it had to be one of them, I would pick the second one. So could somebody also please clarify that for me?
Thank you in advance.
Comment: Not sure what the second one means (as stated it is clearly false).  In general we have $(a^2+b^2)\times (c^2+d^2)=(ac+bd)^2+(ad-bc)^2$.  Is that what you are getting at?
Comment: As a general remark, you should take greater care in stating your assumptions.  For the first, the statement is clearly false unless you require both $a,b>0$.  For instance, $0^2+7^2=7^2$.  I assume you meant to exclude that but you didn't do so explicitly.  For the second, your statement starts with "for all $x,y,z\in \mathbb N$".  Well, then I should be able to take $x=1,y=1,z=1$ but $[1^2+2^2]^2=25\neq 1^2+2^2$.  Again I'm sure you meant something else but it is important to state things clearly.
Comment: @TheMathsGeek  Oh, I think the same thing and the formula I provided shows that the product of any two sums of two squares is again the sum of two squares, which is a stronger claim.
Comment: I think they mean that any $(x^2 + (x+1)^2)^2$ can be written as the sum of two squares, which I imagine will come directly from Fermat's two-squares theorem
Comment: @lulu For sure, plus yours is definitely an easier answer to understand!
Comment: I have never heard of Fermat's Two-Square Theorem, but I will check up on that.
Comment: And lulu, I have edited the question.
Answer: The accepted answer covers the first conjecture.
The second and third conjectures are in fact related. To solve,
$$\big(x^2 + (x + 1)^2\big)^2 = y^2+z^2$$
$$a^2+b^2 = (b+1)^2$$
and turns out to have the solution,
$$\big(x^2 + (x + 1)^2\big)^2  = (2x + 1)^2+(\color{brown}{2x^2 + 2x})^2 =(\color{brown}{2x^2 + 2x}+1)^2$$
Comment: Back when I asked this question, I didn't know that. But I figured the rest of the other conjectures independently. Go here $\longrightarrow$ https://math.stackexchange.com/questions/2620072/trouble-with-a-proof-i-cannot-prove-this-without-infinitely-many-proofs-for-eac to see. Nice answer, though :) (I will upvote in at least $7$ hours)
Answer: Suppose that is $c=4k+3$. Then $c|a^2+b^2$ and since it is prime $c|a$ and $c|b$. Thus $a=mc$ and $b=nc$. But then we get $m^2+n^2=1$ which is impossible if $mn\ne 0$.


Find the posterior density of theta, given prior with exponential density and samples from normal distribution

Question: So the question was the following:

Let $t_1,...,t_n$ be a sample from a normal distribution with an mean that is unknown, $\kappa$, and a known variance $\sigma^2$.
We can assume that the prior density for $\kappa$ is an exp density with the mean of $\kappa_0$. The objective is to fin the posterior density of $\kappa$.

Now my first thought was to use:
\begin{align}
p(\kappa|t) &= \frac{p(\kappa)p(t|\kappa)}{p(t)}  \\[5pt]
            &\qquad\text{where}  \\[5pt]
\bar{t}|\kappa &\sim \mathcal{N}\bigg(\kappa,\ \frac{\sigma^2}{n}\bigg)  \\[5pt]
            &\qquad\text{and}  \\[5pt]
\kappa &\sim \frac{1}{\kappa_0}e^{-\frac{\kappa}{\kappa_0}}
\end{align}
But this turned out to be very tricky to solve. I got the following:
\begin{align}
p(t) &= \int_{-\inf}^{+inf}p(t|\kappa)p(\kappa)d\kappa  \\[5pt]
     &= \int_{0}^{\inf} \frac{1}{\kappa_0} e^{ -\frac{\kappa}{\kappa_0}}\prod_{i=1}^{n}e^{-\frac{(t_i-\kappa)^2}{2\frac{\kappa^2}{n}}}d\kappa
\end{align}
I know that I can get rid of the product by simply putting a sum into the exponential but other than that I have no idea how solve this integral. Am I thinking about this problem the wrong way or is there a trick to solve the integral that I'm not seeing?
Comment: I would try first working with the kernel of the joint $p(y,\theta)$, i.e. just get it down to the terms that involve $\theta$. Pretty sure this will jut be  $e$ to some polynomial of $\theta$, which shouldn't be that hard to integrate.
Comment: Note that $y$ as a vector has variance of $\sigma^2$ in each coordinate, not $\frac{\sigma^2}{n}$. Also, a common trick is the transform the integrand into a known density function times something that does not depend on $\theta$.
Comment: Disregard my comment about the trick.  You don't really need to calculate $p(y)$. For every function there is at most one density function (up to countably infinitely many points) that is proportional to it, so knowing $f\left(\theta, y\right)$ is enough (usually, you can figure out the distribution from it).
Comment: What is the purpose of the edit replacing $y$s by $t$s?  is $p(y\mid \kappa)$ in the penultimate equation intentional or is it supposed to be $p(t\mid \kappa)$?
Comment: I rolled back your edit because the character you inserted for spacing doesn't render correctly in my browser (& doubtless some other people's browsers too) - spattering little boxes all over your post. (The spacing looks all right to me anyway.)
Answer: HINT:
\begin{align*}
\exp\big(-\frac{\theta}{\kappa_0}-\frac{(\bar{t}-\theta)^2}{2\frac{\sigma^2}{n}}\big) &= \exp\big( -\frac{n}{2\sigma^2} \big((\bar{t}-\theta)^2 + 2\frac{\sigma^2 \theta}{n \kappa_0}\big) \big)\\
&= \exp\big( -\frac{n}{2\sigma^2} \big(\bar{t}^2+\theta^2-2\theta\bar{t} +
2\frac{\sigma^2 \theta}{n \kappa_0}\big) \big)\\
&= \exp\big( -\frac{n}{2\sigma^2} \big( \big(\theta-(\bar{t} -  \frac{\sigma^2}{n\kappa_0})\big)^2 + \frac{2\sigma^2}{n\kappa_0} \big( \bar{t} - \frac{\sigma^2}{2n \kappa_0} \big)
\big) \big)\\
&= \exp\big(  -\frac{\big(\theta-(\bar{t} -  \frac{\sigma^2}{n\kappa_0})\big)^2}{\frac{2\sigma^2}{n}} \big) \exp \big(\frac{2\sigma^2}{n\kappa_0} \big( \bar{t} - \frac{\sigma^2}{2n \kappa_0} \big)\big)
\end{align*}
Comment: @user180984 The first term integration is like integrating a gaussian with mean $\bar{y} - \frac{\sigma^2}{n\kappa_0}$ while the second term is just a constant wrt $\theta$


Correct way to show that a Lipschitz condition is satisfied

Question: In one of my homework problems, I have an IVP
$$
y'=e^{t-y}, \hspace{5mm}where\hspace{3mm}0≤t≤1,\hspace{3mm}y(0)=1
$$
And I need to show that
$$
f(t,y)=e^{t-y}
$$
satisfies a Lipshitz condition.
To do this, I used the method shown in class. Same as the one used here: Prove Lipschitz condition
$$
|\dfrac{∂f(t,y)}{∂y}|=e^{t-y}
$$
And
$$
\lim_{y \to -∞}e^{t-y}=∞
$$
So since the function isn't bounded from above, I concluded that the function doesn't satisfy a Lipschitz condition.
But I found a solution online that got a contradictory result. That solution substituted the unique solution to the IVP in for y:
$$
y(t)=ln(e^t+e-1)
$$
$$
⇒e^{t-y}=e^{t-ln(e^t+e-1)}=|\dfrac{e^t}{e^t+e-1}|
$$
$$
max|\dfrac{e^t}{e^t+e-t}| = |\dfrac{e^1}{e^1+e-1}|≈0.6127
$$
$$
⇒ L ≈0.6127
$$
So the second method shows that the Lipschitz condition is met. I'm pretty sure that the first method is correct, but I'm not sure. Could I get some clarification?
Thanks
Answer: I am guessing, the Lipschitz condition is studied here because it is one of the premises of the Picard-Lindelof Theorem.
While the function $e^{t-y}$ fails, as you showed, to be Lipschitz in the variable $y$ if $y$ is allowed to increase without bound, notice that in your IVP problem, the time variable is restricted to a bounded interval: $0 \leq t \leq 1$.
On this closed and bounded interval, the derivative $y'(t)$ of the solution is continuous, hence is bounded.  (This is what is shown in the solution you found online.)  Thus, $y(t)$ restricted to the closed and bounded interval $0 \leq t \leq 1$ is Lipschitz.
Comment: Thanks! That make s a lot of sense. I think the example my professor did in class satisfied the Lipschitz condition globally so there was no need to restrict y.
Comment: I see.  Then I'm glad you are seeing this more general case: it shows that the Picard-Lindelof Theorem is still applicable, since it applies only locally.
Answer: The question is what exactly you are asked to show. Your interpretation of Lipchitz property does not involve the DE at all. What you find online is  a proof of the fact that the solution of the DE is a Lipschitz function of $t$. Certainly $e^{t-y}$ is not a Lipschitz function of $y$ if $y$ is allowed to take all real values.


Convert List of object into another List of object

Question: I have a list as
class Vachel
{
int id{get;set;}
int vachelid {get;set;}
string title {get;set;}
}

List of Vachel
as
id  vachelid  title
1   2         bus
1   3         truck
2   4         cycle
2   5         bike
2   5         bick

And I want to convert List<Vachel> to List<Result>
class Result
{
int id{get;set;}
string vachelid {get;set;}
string title {get;set;}
}

And the result must be as
   id   vachelid    title
    1   2,3         bus,truck
    2   4,5         cycle,bike,bick

I tried as
List<Vachel> V = getList();
List<Result> R = null;
 R = V.GroupBy(x=> new{x.vachelid})
    .Select
       (
       x=> new Result
         {
         id  =x.Key.id,
         vachelid =x.FirstOrDefault().vachelid,
         title   =x.FirstOrDefault().title
         }
       ).ToList();

Here I know I want to put something instead of .FirstOrDefault().vachelid and .FirstOrDefault().title but I don't know what to do.
Answer: R = V.GroupBy(x => x.id)
     .Select(g => new Result(){
        id = g.Key,
        vachelid = string.Join(",", g.Select(x => x.vachelid).Distinct()),
        title = string.Join(",", g.Select(x => x.title).Distinct()),
     }).ToList();

Comment: @user2641905: sorry, I am not following you, could you elaborate more?
Comment: plz have a look question again.
Comment: @user2641905: I have looked again but still did not get your point, please could you use English in decent *if i want uniqes vales only seperet by*?
Comment: here in List Vechle, for vecheleid = 5 there is two Title bike and bick and i want result as vecheleid = 5 and title = bike,bick from your code i get vechelid = 4,5,5 and Title = cycle,bike,bick
but i only want vechelid = 4,5 and Title = cycle,bike,bick
Comment: @user2641905: got it, I have changed my answer
Comment: oww that's great can you refer me 1 exciting link for learning LINQ in depth


HTMLUnit : different code from when view source in Chrome

Question: I'm using HTMLUnit for get a page on a web. In this webpage, there is a form. When i'm loading from Chrome and view source : something like this :
<form name="form" method="post" onsubmit="return checkDate();">
     <input name="check_in_date" id="check_in_date" readonly="readonly" type="text" class="hasDatepicker"/>
     <input name="check_out_date" id="check_out_date" readonly="readonly" type="text" class="hasDatepicker"/>
     <input name="check_availability" value="test condition" type="submit"/>
</form>

But when I'm loading by using HTMLUnit by this code:
String url = "sample link";
WebClient webClient = new WebClient();
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setCssEnabled(false);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
HtmlPage page = webClient.getPage(url);
System.out.println(page.asXML());

I get different HTML Code. More detail :
<form name="form" method="post" onsubmit="return checkDate();">
         <input name="check_in_date" id="check_in_date" readonly="readonly" type="text" class="hasDatepicker"/>
         <input name="check_out_date" id="check_out_date" readonly="readonly" type="text" class="hasDatepicker"/>
         <input name="check_availability" value="test condition" type="text"/>
 </form>

The different here is : last line :  <input name="check_availability" value="test condition" type="text"/> Type now text, instead of submit, so I cannot this kind of code:
HtmlForm form = page.getFormByName("form");
HtmlSubmitInput submit = form.getInputByName("check_availability"); // error at this line
page = submit.click();

Error because now, this field is not a button anymore, it's just a text`. I don't know why there's this difference. Please tell me how to fix this.
Thanks :)
Answer: There are various ways to submit a html form using htmlunit.
Create a submit button and append to the form and then click on it. Something like this :
HtmlElement ele=page.createElement("input");
ele.setAttribute("type","submit");
form.appendChild(ele);
ele.click();

References :
First - Html Page
Second DomNode
Third - DomElement
2nd Method
Just fire javascript to submit the form
String javaScriptCode="document.getElementById("formid").submit()";
Object result = page.executeJavaScript(javaScriptCode).getJavaScriptResult();

The 2nd method won't work, since there's no ID associated with the form, but for completeness of the answer I've mentioned it.
Caution : The above codes are not tested, but shall work fine.
Answer: A few comments before answering your question:
It makes sense that the content you see in Chrome inspector is different from the code returned by HtmlUnit. Furthermore, the code that you see in the Chrome inspector will be different from the code you see when seeing the source code of the page itself (CTRL+U), as the former has already been executed Javascript.
HtmlUnit's javascript engine is different from Chrome's so even if you have enabled JavaScript in HtmlUnit you might get different results. Even the asXml() performs formatting changes in the code.
Having said that I can think of 2 options:

You're comparing a page that has been processed javascript against one that hasn't
You've found a bug

I bet it is the first one. To help you debug play with enabling/disabling JavaScript as well as comparing the result of asXml() with the result of the actual content of the page that HtmlUnit is downloading (I mean, without an processing). To find out more about how to do that check out this question:
How to get the pure raw HTML of a page in HTMLUnit while ignoring JavaScript and CSS?
If you effectively find out that it is HtmlUnit's fault and that the processing of the webpage is failing, please, file a new bug in the SourceForge project. I'll also would like you to provide the test case to reproduce this.


Markov's Inequality for Negative Binomial distribution

Question: Given that $Y$ follows Negative Binomial distribution (counts y successes before $k$th failure), using Markov's inequality show that for any $q \in[p,1]$, there exists constant $C$, such that $\mathbb{P}(Y>x)\leq Cq^x$.
$E(Y)=\frac{kp}{1-p}$ and from Markov's inequality:
\begin{equation}
\mathbb{P}(Y>x)\leq \frac{\mathbb{E}(Y)}{x}=\frac{kp}{(1-p)x}
\end{equation}
HOW to relate $Cq^x$ and $\frac{kp}{(1-p)x}\qquad$?
Comment: The RHS is increasing in $q$, so it suffices to find a $C$ that does it for $q=p$, or not?
Comment: And something else: p is the probability of success or failure?
Comment: @Stefanos $p$ is probability of success, that is $Y$ counts number of successes before $r$th failure, thus \begin{equation} \mathbb{P}(Y=y)=\begin{pmatrix} y+r-1\\ y \end{pmatrix}p^y(1-p)^r\end{equation}
Comment: @Stefanos inconsistency - in above equation should be $k$ instead of $r$, that is $k$ failures
Comment: Ok, thanks for the explanation. I still do not see an answer thouhg
Comment: @Stefanos are you considering Markov's Inequality also?
Comment: Ok firstly, as I said in my first comment, you do not need to consider q>p since RHS is increasing in q. So you can write $p^x$ on the RHS (p is the lower limit of the given interval for q). Do you agree? Secondly, I do not think this is Markov...
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/18377/discussion-between-stefanos-and-ruth90).
Comment: @Stefanos Yes I absolutely agree that we can change $q^p$ to $p^x$
Comment: @Stefanos please tell me what do you think.
Generalised Markov's Inequality:
\begin{equation}
\mathbb{P}(|Y|>x)=\frac{\mathbb{E}f(Y)}{f(x)}
\end{equation}
Since Y is non-negative r.v. we can remove modulus. Moreover, if we take $f(x)=p^x$, then $\mathbb{E}(p^Y)=\Bigg(\frac{1-p}{1-p^2}\Bigg)^r=(1-p)^{-r}$ since the expectation is generating function r.v. $Y$
Comment: @Stefanos Then $\mathbb{P}(Y>x) \leq (1-p)^{-r}p^{-x}=(1-p)^{-r}p^{-2x}p^x$ and hence $C=(1-p)^{-r}p^{-2x}$
Comment: @Stefanos i think the problem with this is that $C$ is not a constant. What do you think?
Comment: @Stefanos please note the typo - general. Markov Ineq. should be $\leq$
Comment: Yes, C is not a constant and that is a problem
Comment: It also works for f(x)=(1/p)^x. Then $E[(1/p)^Y]=(1-1/p)^-r and then you have it. Do you agree?
Comment: @Stefanos well if we take $f(x)=p^{-x)$ then probability generating function
\begin{equation}
\mathbb{E}(p^{-Y})=\sum_{y=0}^{\infty}Bp^{-y}p^y(1-p)^r\end{equation}
where $B$ is appropriate binomial coefficient. Thus in this case $p$ term will disapear and thus series will not converge. Do you agree? Thus I assume we cannot substitute $p$ and $q$ in initial bounds. If we keep $q$ we will get probability generating function $(1-\frac{p}{q})^{-r}$ which will make $C$ constant. Agree?
Comment: $\mathbb{E}((\frac{1}{p})^Y)=\Bigg(\frac{1-p}{1-\frac{1}{p}p}\Bigg)$ actually
Comment: @Stefanos But then it is said that $q\in[p,1]$. So the expectation above would give some incosistency since if $q=p$ we divide by $0$ . do you agree?
Comment: @Stefanos so I think if we set $f(x)=q^{-x}$ then we have $C=\mathbb{E}(q^{-Y})$. Since the question asks to show that there exists a constant C such that $\mathbb{P}(Y>x)\leq Cq^x$ we are done. What do you think??
Comment: I think we are done... you did it ok, I can't think of something else
Answer: Consider a non-negative and increasing function $f$. Then
\begin{align}
\mathbb{E}(f(Y)) &=\sum_{y=0}^{\infty}f(y)\mathbb{P}(Y=y)\\
&= \sum_{y=0}^{x}f(y)\mathbb{P}(Y=y) +\sum_{y=x+1}^{\infty}f(y)\mathbb{P}(Y=y)\\
&\geq \sum_{y=x+1}^{\infty}f(y)\mathbb{P}(Y=y)\\
&\geq f(x)\sum_{y=x+1}^{\infty}\mathbb{P}(Y=y)\\
&= f(x)\mathbb{P}(Y>x)\\
&\implies \mathbb{P}(Y>x) \leq \frac{\mathbb{E}(f(Y))}{f(x)}.
\end{align}
Now let $f(x)=q^{-x}$, then
\begin{equation}
\mathbb{P}(Y>x) \leq \mathbb{E}(q^{-Y})q^x.
\end{equation}
Hence, $C=\mathbb{E}(q^{-Y})$. Moreover, if we set $\alpha=\frac{1}{q}$ we have  $C=\mathbb{E}(\alpha^Y)$ and
\begin{align}
C=\Bigg(\frac{1-p}{1-\frac{p}{q}}\Bigg)^r
\end{align}
Comment: the last equation follows from PGF of the Negative Binomial distribution.


what happen first when i do this kind of Increment in an assignment?

Question: I have this expression:
<code>B[i]=B[++i]*i;
</code>
In C this is undefined?
What happen first? is evaluated the right of the assignment symbol first, or the left?
Comment: @BillLynch is question from a test... they ask about what is the output of a program, and the code have that expression. For me is undefined what happen, and i can I'm right, Thanks...
Comment: So, the test either expects UB as the answer, or it is rubbish. I give ten-to-one odds for the latter.
Comment: It's undefined. And if you can't figure out what it means, why would you ever want to write code like that?
Comment: @exsnake -the only answer is "yes, it is undefined."
Comment: Also somewhat related to: [Assignment operator sequencing in C11 expressions](http://stackoverflow.com/q/22616044/1708801) ... the defect report I cite in my answer gives a good framework for evaluating these type of constructs. If you can understand that proof it will help you understand a lot of these cases.
Comment: The order of evaluation is *unspecified*, so any expression that attempts to modify a variable more than once or tries to read from and modify a variable between sequence points will give different results for different platforms, compiler settings, etc.  The language definition specifically calls this out as *undefined behavior*, meaning the compiler isn't required to handle it any particular way.
Comment: @JohnBode well it is both unspecified and undefined behavior, see [my answer](http://stackoverflow.com/a/18260171/1708801) to the link duplicate. In this case they are orthogonal issues, the unspecified order of evaluation does not make it undefined, the multiple modifications do.
Answer: It is undefined and can be evaluated in any order.
Comment: Any order guarantees that it will be evaluated in some order, but UB means it is simply non-sensical, and anything may happen.
Comment: "Any order" guarantees more than is actually guaranteed, which is nothing.
Comment: @Deduplicator What does "any order" guarantee? To me it looks the same as nothing.


Exibir apenas palavras com 04 letras em Python

Question: Estou aprendendo Python e estou fazendo um exercício, que é esse aqui: Implemente um programa que solicite do usuário uma lista de palavras (ou seja, strings) e depois exiba na tela, uma por linha, todas as strings de 4 letras nessa lista Python
Mas estou enroscado e não consegui fazer com que mais de uma palavra fosse exibida. Se puderem me ajudar a esclarecer, eu agradeço. O código que fiz está abaixo.
nome = []
print('Olá')
nome.append(input('Digite um nome: '))

for n in nome:
    if len(n) == 4:
        print(n)

Comment: Importante você [edit] sua pergunta e explicar de maneira objetiva e pontual a dificuldade encontrada, acompanhada de um [mcve] do problema e tentativa de solução. Para aproveitar melhor o site, entender e evitar fechamentos e negativações vale a pena ler o [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045/70).
Answer: Seu código para validar as palavras com 4 letras e exibi-las está correto, o problema é que você está executando uma vez apenas o código, ou seja, armazena 1 nome, exibe (ou não) e termina o programa com sucesso.
Se você quiser que ele continue pedindo e printando os nomes tem que colocar um laço. Por exemplo, o while, assim, enquanto a condição for verdadeira o processo continua.
Tentei entender seu problema e fiz algumas alterações: Criei uma lista para armazenar todos os nomes, coloquei o while para continuar pedindo novos nomes enquanto não receber um input vazio e coloquei o print no final, após escapar do laço.
Ahh, e na lista só são adicionados os nomes com exatos 4 caracteres.
ListaNome = []
nome = input('Digite um nome: ')

while nome != '':
    if len(nome) == 4:
        ListaNome.append(nome)
    nome = input('Digite um nome: ')

for x in range(len(ListaNome)):
    print(ListaNome[x])

Comment: Obrigado! Até pensei e tentei aplicar o while, mas não acertei. Me falta muito ainda pra aprender. Mais uma vez te agradeço!
Comment: @dougst procure o canal curso em vídeo no YouTube, do professor Guanabara. Tem um curso de python desde o início que é excelente
Answer: A criação da lista vazia 'nome' não é necessária, com o append, vc estava adicionando apenas 1 string na lista, independementemente de quantas palavras fossem inseridas no input, assim, no IF o len(nome) sempre seria 1, não acionando o código dentro do IF.
Segue exemplo:
print('Olá')
nome = input("Digite um nome ").split(' ')
for n in nome:
    if len(nome) == 4:
        print(n)

.
.
.
.
.
.
.


where to download vagrant boxes

Question: I know http://www.vagrantbox.es/ provide many vagrant boxes for us to use, but I found many of their url download address is out of date. vagrantcloud.com or https://atlas.hashicorp.com/boxes/search is alternative to me. But when I run vagrant up ubuntu/trusty64 --provider virtualbox I got this:
sean@apptest:~$ vagrant up ubuntu/trusty64 --provider virtualbox
A Vagrant environment or target machine is required to run this
command. Run `vagrant init` to create a new Vagrant environment. Or,
get an ID of a target machine from `vagrant global-status` to run
this command on. A final option is to change to a directory with a
Vagrantfile and to try again.

sean@apptest:~$ vagrant global-status
id       name   provider state  directory
--------------------------------------------------------------------
There are no active Vagrant environments on this computer! Or,
you haven't destroyed and recreated Vagrant environments that were
started with an older version of Vagrant.

sean@apptest:~$ vagrant init
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.

sean@apptest:~$ vagrant up ubuntu/trusty64 --provider virtualbox
The machine with the name 'ubuntu/trusty64' was not found configured for
this Vagrant environment.

It seems that I can't vagrant up a box from online download. But I do not find download address from https://atlas.hashicorp.com/ubuntu/boxes/trusty64 too. Is there a better way to get these boxes?
And what if I want to download https://atlas.hashicorp.com/laravel/boxes/homestead v0.2.3 ?
Thanks~
Comment: Try upgrading to a newer version of vagrant
Comment: Yeah, it worked! Now I can see the download url https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/14.04/providers/virtualbox.box .
Comment: $ vagrant version
    Installed Version: 1.7.1

Need I upgrade to the latest version is 1.7.2 ?
Comment: That should be high enough. Try `vagrant init ubuntu/trusty64; vagrant up --provider virtualbox`.
Answer: Thanks to @jordanm , the question is solved.
In a clean directory(without Vagrantfile):

vagrant init ubuntu/trusty64

Then run vagrant up --provider virtualbox. This will lead to search box from https://atlas.hashicorp.com/search/boxes .
Or just run vagrant box add ubuntu/trusty64.
If you wanna download box file, you can see complete url address where box locate

where to download vagrant boxes


Calculate average array from four given unsigned char arrays

Question: Suppose I have a toatl of four unsigned char arrays, which are added into a map container like the following:
std::map<std::string, unsigned char*> UCArray;
UCArray.insert(std::make_pair("A1", new unsigned char[10000]));
UCArray.insert(std::make_pair("A2", new unsigned char[10000]));
UCArray.insert(std::make_pair("A3", new unsigned char[10000]));
UCArray.insert(std::make_pair("A4", new unsigned char[10000]));

I want to get an array filled with average values based on UCArray,  in which all four unsigned char buffers are initialized and populated with valid values. I know that I can carry my point through the use of two "for ... loop". Would please tell if there is any other effective way(s) to do that. Thank you in advance.
Comment: `boost::accumulators` and `for_each` ?
Answer: for(std::map<std::string, unsigned char*>::const_iterator iter = UCArray.begin();
    iter != UCArray.end(); ++iter)
{
   int nAverage =  std::accumulate(
             iter->second,
             iter->second+10000,
             0)  / 10000;
}

Comment: That'll calculate the average of A1 only
Comment: @Ajay
Thank you! I want to get an averaged array based on the 4 given arrays. unsigned char* ucAverage = new unsigned char[10000];
Comment: for (int i = 0; < 10000; i++){ unsigned char ucResult = 0; for (int j = 0; j < UCArray.size(); j++) { ucResult = ucResult + unsigned char(UCArray[j][i] / UCArray.size());
Comment: @Armen, That's is implicit. I just gave a simplified example.
Comment: @Ajay, I can't use your example because it can be used to evaluate the average of one array, and the result is the average of the whole array. How could I use std::accumulate to do my above-mentioned job? Thank you.
Comment: @Ajay: Thank you very much! Two questions: (1) What do you make sure the four unsigned char arrays were allocated in consecutive memery like this 0--999 0--999 0--999 0--999? (2) Would you please explain the last statement? Why divided by 10000 not 4?
Comment: Are you new to C++ or STL? You need a foolproof, complete code? Please take the code as sample/reference and derive your own. Nothing personal, don't take my words in wrong sense.
Just have a variable above loop, add into it, eventually average.
Comment: Arrays will be allocated consecutive by `new`. But for the actual allocation size, you need to keep track of. For that, instead of `unsigned char*`, you may use a `pair` or structure that would hold both size and the pointer.
Comment: Sorry. I thought that your code would be a complete one. I'm not famillar with accumulate function.


Cauchy Sequence if $|s_{n+1} - s_n| < 2^{-n}$

Question: Let $s_n$ be a sequence such that
$|s_{n+1} - s_n| < 2^{-n}$
for all $n \in N$. Prove $s_n$ is a Cauchy sequence and hence a convergent sequence.
Here's what I've started with:
Proof:
Take $\epsilon > 0$. Let $N = -\log_2{\epsilon/2}$. Thus,
$ |s_{n+1} - s_n| < 2^{\log_2{\epsilon/2}} = \epsilon/2$
I can't seem to show from this that:
$ |s_m - s_n| <\epsilon$
Some ideas relating to geometric series of $\epsilon/2 + \epsilon/4 ... \epsilon/{2^n} < \epsilon$ are springing up in my mind, but I can't really pin it to the ground (and, I'm not sure if its fair play to use the infinite series formula in this case).
Answer: Here's a sketch; check the details carefully. You need to show that for all $\epsilon > 0$ that there is an $N$ such that for $n,m > N$, $|s_n - s_m| < \epsilon$. Let $\epsilon > 0$ be given. We have to find $N$.
Assume that $m > n$ without loss of generality. Then by the triangle inequality and the given property of the sequence,
$$|s_m - s_n| < \frac{1}{2^m} + \cdots + \frac{1}{2^n} = \frac{1}{2^m}\left(1+\frac{1}{2} + \cdots + \frac{1}{2^{n-m}}\right)$$
and so by the formula for a geometric series,
$$|s_m - s_n| < \frac{1}{2^m} \frac{1-\left(\frac{1}{2}\right)^{n-m}}{1 - \frac{1}{2}} < \frac{1}{2^{m-1}}$$
Now just take $N = \log_2{\epsilon}$. Then for $m > n > N$, we have that
$$|s_m - s_n| < \frac{1}{2^{m-1}} \leq \frac{1}{2^N} = \epsilon$$
Comment: Yes, we only used the finite geometric series, so it's fine. The infinite case would be fine as well, as long as you had verified it beforehand. You were definitely close already...
Comment: That's basically exactly what I was thinking of (except I expanded a bit on the triangle inequality concept). However, is it okay to use the geometric series formula to show something a Cauchy series?
Comment: Thank you for the response and sketch.


How to convert JSON object to file and then response it using ExpressJS

Question: I have an pretty large JSON object (~500MB) and i want to convert it to file before send it to user. What is the best way to achieve this using ExpressJS, any suggestion would be grateful.
Answer: 1- Convert json to string
<code> var json = JSON.stringify(obj);
</code>
2- Use fs to write json on file
<code> var fs = require('fs');
 fs.writeFile('fileName.json', json, 'utf8', callback);
</code>


O que é um manipulador de eventos?

Question: Já li o que é um evento, mas então vi que existem os manipuladores de evento, event handler.

O que é um event handler?
Pra que servem e onde são usados?
Existem em todas linguagens?
Comment: Só pra citar um detalhe `handler` é traduzido para português como "manipulador" e notará essa palavra em muitos lugares da programação, não só eventos, então eu diria que tudo que tem eventos e estes eventos podem ser interceptados são considerados como uma manipulação, então se a linguagem permite interagir quando um evento é registrado/adicionado então terá um handler :) - Só opinião.
Comment: Gosto da tradução de "handler" como "tratador", porque é uma tradução correta e adequada, como em _"let me handle this" ("deixe-me tratar/cuidar disto")_ , e é o que o _handler_ faz, ele trata ou cuida do evento, no sentido de assumir a responsabilidade por lidar com o mesmo. Acho mais precisa porque o objeto do evento (ou mesmo se considerarmos a entidade do evento em si) em geral é um sinal de que algo precisa ser feito, e não necessariamente um item a ser manipulado.
Answer: Grosso modo é a ação que deve ser executada quando um evento deve ser disparado. Em geral é um método ou função com uma assinatura específica que será chamado pelo evento. Ele é um callback.
Como é um manipulador de evento, é ele que responde quando um evento é disparado, é ele que manipula o evento e faz alguma coisa.
Eles costumam estar ligados a objetos que precisam ser notificados de eventos que ocorram com outros objetos para exercer alguma ação.
A forma exata de implementação pode variar. Alguns podem ser criados pela linguagem, biblioteca ou manualmente. A API que gera o evento determinará como precisa ser feito.
As demais perguntas não podem ser respondidas e são informações irrelevantes. Pelo menos na forma perguntada.
Veja mais:

Design pattern Observer aplicado em eventos
O que é a Programação Orientada a Eventos?
Qual a diferença entre event e delegate?
O que é um evento?

Coloquei no GitHub para referência futura.

O que é um manipulador de eventos?


Possible to slice to MIDI *manually* in Ableton?

Question: Is it possible to slice to MIDI manually in Ableton?
Most people just use the slice-to-MIDI feature (right click on clip and Ableton more or less does the rest), but I want to know if it's even possible to slice audio to MIDI w/ out the built-in feature.
The motivation for this question is that I'm using Ableton Lite and slice-to-MIDI is not available for Lite (or Intro).
Answer: You certainly can do this, in fact it's a very common industry practice, and is often called "sampling."
When sampling, you create a sample (smaller audio clip) of the clip, which you can then load into a sampler instrument in Ableton and play back by triggering the instrument.
The samplers included in Ableton (Sampler and Simpler) offer the ability to pitch-shift the sampled clip by playing differently-pitched notes. But by loading a sampler into an instrument rack and defining which keys will trigger it, you can "chain" multiple samplers together into one piano roll, then create MIDI data to trigger them in whatever order you'd like.


F# catch System.Web.Exception

Question: I have written tests with TickSpec (F# version of C# Specflow) to test a web service. When I run the test where I expect the response to come with a 200 OK all is fine. When I intentionally send an incorrect request I receive a 400 Bad Request, but the test fails, although 400 is what I want to get back. So the question is - how do I catch an exception and continue in F#?
This is a snippet of code I have:
let sendRequest(requestBody : HttpRequestBody) =
    let response = Http.Request(url, headers = requestHeaders, body = requestBody)
    let responseStatusCode = response.StatusCode
    let extractedResponseData =
    // code here to extract data from response
(responseStatusCode, extractedResponseData)

The error I am getting is
System.Net.WebException : The remote server returned an error: (400) Bad Request.

I was hoping that putting a try catch (try with in F#?) around the
 let response = Http.Request(url, headers = requestHeaders, body = requestBody)

would solve the problem.
Can I do that and how do I do it?
Comment: What specific part are you stuck on?  Have you read the MSDN page here https://msdn.microsoft.com/en-us/library/dd233194.aspx
Comment: Got it sorted by adding this bit: silentHttpErrors = true to  let response = Http.Request(url, headers = requestHeaders, body = requestBody). That ignores the error and continues.
Comment: @Marta - you are allowed to answer your own questions on SO :)
Comment: @DaveShaw - thanks, will do that.
Answer: Adding:
   silentHttpErrors = true

to:
   let response

as in:
 let response = Http.Request(url, headers = requestHeaders, body = requestBody, silentHttpErrors = true)

sorted the problem. Now the tests ignore the System.Net.WebException and I can test the application for behavior related to a 400 bad request.
More here: http://fsharp.github.io/FSharp.Data/library/Http.html

F# catch System.Web.Exception


Obter Diretório Depois de Compilado JAVA

Question: De antemão gostaria de dizer que já procurei em diversos links indicados aqui no stackoverflow e em outros sites também e ainda não consegui ajuda concreta (pode ser por erro meu também).
Preciso obter um file encontrado na pasta res, essa pasta res esta dentro da pasta do projeto (fora da pasta src para ficar mais claro).
Logo no meu programa eu consigo fazer o seguinte("enquanto no NetBeans")
   public static void obter(){
       File f = new File("res\\file.txt");
   }

no metodo acima ele consegue ler enquanto estiver rodando no netbeans.
Fora do netBeans não.
Erro gerado fora do NetBeans:
res\file.txt (O sistema não pode encontrar o caminho especificado)

Em outro lugar do meu código utilizo o código abaixo e também funciona no netBeans
File f = new File(this.getClass().getResource("/file.txt").getFile());

no metodo acima mesmo sem especificar a pasta res ele ainda consegue encontrar enquanto estiver no netBeans. Porem fora do netBeans me retorna isso:
file:\C:\Users\User\Documents\NetBeansProjects\TEST\dist\TEST.jar!\file.txt (A sintaxe do nome do arquivo, do nome do diretório ou do rótulo do volume está incorreta)

Como obter esse file.txt da pasta res mesmo que eu compile o código e passe pra qualquer computador?
PS: se não deixei claro por favor me avise e tento melhorar minha pergunta.
Answer: Para conseguir rodar o jar depois de compilado tu precisa levar o arquivo junto com ele.
Tu pode ou colocar o jar em uma pasta e dentro dessa pasta criar a pasta res de novo e colocar o arquivo la ou tu pode compilar abrir o .jar com o winrar e botar a pasta res dentro do .jar.
Comment: Caso eu abra o .jar compilado com o winrar e coloque a pasta res la dentro, com o getResourses eu consigo obter acesso ao res? ou simplismente posso criar o File com caminho "res/file.txt" ?
Comment: Na real eu viajei, a parte de botar dentro do jar não da certo foi mal.
mas ainda da pra fazer assim:
deixa o arquivo dentro de uma pasta res dentro da src pra pegar quando tu todar no netbeans.
e depois de compilar tu copia a src so com os arquivos pra mesma pasta que o jar estiver.
e dae tu usa o primeiro comando
File file = new File("src/res/arquivo.txt");
Comment: vou fazer um teste quando estiver com mais tempo, e vejo se vai funcionar, apesar que a pasta res esta na package folder do netbeans, ou seja, se eu colocar File file = new File("res/arquivo.txt") ele ja consegue encontrar, então se eu compilar e colocar somente a pasta res junto com o .jar ele conseguira achar somente fazendo isso certo?  em breve volto com mais resultados..
Comment: Da maneira que comentamos aqui nos comentarios funcionou, é só compilar e criar uma pasta src/res/ e colocar os arquivos la que funciona. mas caso eu não queira usar a pasta src e quiser usar diretamente a pasta res é só incluir ela no package folder do netbeanse depois de compilado incluir essa pasta res aonde esta o .jar, assim nao precisa da pasta src.. Se quiser editar sua resposta e colocar isso eu ja vou sinalizar como resposta. xD vlw
Answer: Eu gostaria de agradecer ao Rafael Guasselli pela ajuda, eu gostaria que ele estivesse corrigido a resposta para eu poder aprovar e deixar mais claro para as futuras pessoas que estivessem com o mesmo problema.
Segue a resposta:
Após compilado o projeto no NetBeans ele gera uma pasta dist e lá contém os arquivos necessários para roda-lo. Logo se seu projeto precisa acessar alguma outra pasta deve-se colocar lá também após compilado.
No exemplo abaixo precisamos encontrar a pasta res.
Ex: digamos que a pasta res está dentro da src....
  Então após compilado, vou até a pasta dist e crio uma pasta src e colo a pasta res lá dentro.
Caso a pasta res esteja fora da src então após compilado é só copia-la para a pasta dist.
Isso serve também para as lib que costumam dar problema na hora de distribuir a aplicação.
Para que suas libs vá junto com o projeto, basta criar uma pasta chamada lib
lá dentro do seu projeto (fora da src).
Ex: C:\Users\User\Documents\NetBeansProjects\MeuProjeto\ (aqui eu crio a pasta lib e colo todas as libs que preciso). (Sim! Colo)
Logo após no NetBeans vou em adicionar Biblioteca >> add JAR/Folder
Aqui encontro a pasta lib que criamos, e dentro dela selecionamos todas as libs que precisamos. NOTA: Deixe Absolute Path(Caminho Absoluto) marcado.
Por que isso?
Após compilado o .jar já vai ter uma pasta chamado lib no mesmo local que ele. Lembram daquela pasta lib criada ao compilar la em dist? Então, assim você garante que o caminho que ele esta buscando é exatamente o que ele vai ter após compilado. Ou seja, lib/"as bibliotecas que inclui"


How to auto start electron app after app quit

Question: In my case after synchronization process finished from backend server app will quit as per below code.
 app.quit();

But after that i need to run app again by manually clicking on (.exe). Now i am looking for solution that can start app automatically after app quit.
Answer: I solved issue by changing code as below
ipcMain.on("exit-app", event => {
      if (process.platform !== "darwin") {
        app.quit();
        app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) })
        app.exit(0)
      }
});

Answer: app.relaunch();
 app.exit();
this will restart your app.


Why do I get PDOException SQLSTATE[42S22] Column not found 1054 Unknown column 'tn.tid' in 'on clause'"?

Question: $rtid = arg(2);

$query = "SELECT node.nid AS nid FROM node
  WHERE (node.nid IN (
    SELECT tn.nid AS nid
    FROM taxonomy_index AS tn
    LEFT OUTER JOIN taxonomy_term_hierarchy AS th ON th.tid = tn.tid
    LEFT OUTER JOIN taxonomy_term_hierarchy AS th1 ON th.parent = th1.tid
    LEFT OUTER JOIN taxonomy_term_hierarchy AS th2 ON th1.parent = th2.tid
    WHERE (tn.tid = :rtid) OR (th1.tid = :rtid) OR (th2.tid = :rtid)
  ))
  AND (node.status = '1') AND (node.type IN ('product'))
  ORDER BY node_created DESC
  LIMIT 1 OFFSET 0";

$result = db_query($query, array(':rtid' => $rtid));

After I tried some times with the help of other users' answers, I got lost. This is the code I tried, but it gives me an error ("PDOException SQLSTATE[42S22] Column not found 1054 Unknown column 'tn.tid' in 'on clause'").
$query = db_select('node', 'n')
  ->condition('n.type', 'product')
  ->condition(
    db_or()
      ->condition('tn.tid',$rtid )
      ->condition('th1.tid',$rtid)
      ->condition('th2.tid',$rtid)
  )
  ->fields('n', array('nid'))
  ->extend('PagerDefault')
  ->limit(1);

$query->join('taxonomy_term_hierarchy', 'th', 'th.tid = tn.tid');
$query->join('taxonomy_term_hierarchy', 'th1', 'th.parent = th1.tid');
$query->join('taxonomy_term_hierarchy', 'th2', 'th1.parent = th2.tid');

$result = $query->execute();

Comment: which table represents tn ?
Comment: FROM taxonomy_index AS tn
Answer: The error you get is caused by the fact you don't use tn as alias of any database table.
The code I would write is the following one.
$tid = arg(2);
$query = db_select('node', 'n');

$tn = $query->join('taxonomy_index', 'ti', '%alias.nid = n.nid');
$th = $query->join('taxonomy_term_hierarchy', 'th', "%alias.tid = $tn.tid");
$th1 = $query->join('taxonomy_term_hierarchy', 'th1', "%alias.tid = $th.parent");
$th2 = $query->join('taxonomy_term_hierarchy', 'th2', "%alias.tid = $th1.parent");

$query->condition('n.type', 'product')
  ->condition(
    db_or()
      ->condition("$tn.tid", $tid)
      ->condition("$th1.parent", $tid)
      ->condition("$th2.parent", $tid)
  )
  ->fields('n', array('nid'))
  ->extend('PagerDefault')
  ->limit(1);

$query->join() is really doing an INNER join; if you need to make a LEFT OUTER join, then the code is the following.
$tid = arg(2);
$query = db_select('node', 'n');

$tn = $query->join('taxonomy_index', 'tn', '%alias.nid = n.nid');
$th = $query->addJoin('LEFT OUTER', 'taxonomy_term_hierarchy', 'th', "%alias.tid = $tn.tid");
$th1 = $query->addJoin('LEFT OUTER', 'taxonomy_term_hierarchy', 'th1', "%alias.tid = $th.parent");
$th2 = $query->addJoin('LEFT OUTER', 'taxonomy_term_hierarchy', 'th2', "%alias.tid = $th1.parent");

$query->condition('n.type', 'product')
  ->condition(
    db_or()
      ->condition("$tn.tid", $tid)
      ->condition("$th1.parent", $tid)
      ->condition("$th2.parent", $tid)
  )
  ->fields('n', array('nid'))
  ->extend('PagerDefault')
  ->limit(1);

As side notes:

$query->join(), and $query->addJoin() returns the alias they used
In the conditions passed to $query->join(), and $query->addJoin() %alias is replaced with the table alias the method is using

SelectQuery::addJoin() avoids conflicts between aliases using the following code.
  $alias_candidate = $alias;
  $count = 2;
  while (!empty($this->tables[$alias_candidate])) {
    $alias_candidate = $alias . '_' . $count++;
  }
  $alias = $alias_candidate;

  if (is_string($condition)) {
    $condition = str_replace('%alias', $alias, $condition);
  }

Writing code similar to the one I used, you are sure not to cause any conflict between aliases, and it is useful in the case the code is changed successively, or part of the query is populated from a function.
In this case, the join part could have written as follows, and it could still work correctly.
$tn = $query->join('taxonomy_index', 'tn', '%alias.nid = n.nid');
$th = $query->join('taxonomy_term_hierarchy', 'th', "%alias.tid = $tn.tid");
$th1 = $query->join('taxonomy_term_hierarchy', 'th', "%alias.tid = $th.parent");
$th2 = $query->join('taxonomy_term_hierarchy', 'th', "%alias.tid = $th1.parent");

Comment: i put your query code in, but there is no any result output. i print the query.  SELECT n.nid AS nid FROM
node AS n INNER JOIN taxonomy_index AS ti
ON ti.nid = n.nid INNER JOIN
taxonomy_term_hierarchy AS th ON th.tid = ti.tid INNER JOIN
taxonomy_term_hierarchy AS th1 ON th1.tid = th.parent
INNER JOIN taxonomy_term_hierarchy AS th2 ON th2.tid = th1.parent
WHERE (n.type = product) AND( (ti.tid = 6)
 OR (th1.parent = 6) OR (th2.parent = 6) )  then test term id=6 run in phpmyadmin, shows 1054 - Unknown column 'product' in 'where clause'
Comment: the second ways with term id =4 test show the same result,  1054 - Unknown column 'product' in 'where clause'                               SELECT n.nid AS nid FROM node AS n
INNER JOIN taxonomy_index AS tn ON tn.nid = n.nid
LEFT OUTER JOIN taxonomy_term_hierarchy AS th
ON th.tid = tn.tid LEFT OUTER JOIN taxonomy_term_hierarchy AS th1
ON th1.tid = th.parent LEFT OUTER JOIN taxonomy_term_hierarchy AS th2 ON th2.tid = th1.parent
WHERE (n.type = product)
 AND( (tn.tid = 4)
OR (th1.parent = 4) OR (th2.parent = 4) )
Comment: after read you code again and again, i don't know where is the error is?thank you
Comment: The error is simply the fact there isn't any database table using tn as alias in `db_select()`, or in `$query->join()`. The error is telling you "I don't know what table is tn."
Comment: taxonomy_index AS tn, but in your code. $tn = $query->join('taxonomy_index', 'tn', '%alias.nid = n.nid'); this line shows tn as alias to the taxonomy_index
Comment: In the code where you use `db_select()`, you are not using tn as alias of any table, not in `db_select()`, nor in `$query->join()`. My code uses tn as alias, but your code doesn't.
Comment: i delete my code instead of run your code,it gives the above which i told error shows;
Comment: would you mind do i test to your code? many thanks. i put it in a template file. it shows nothing.
Comment: If two pagers are being added in the same page, it is probable they are conflicting with each other.


Selenium WebDriver - how to get proxy used?

Question: I use Selenium WebDriver in Python to do web scraping and I often change the proxy and user-agent.
I need to know, at any time during my code execution, which parameters my WebDriver is using.
I know how to get user-agent with:
driver.execute_script("return navigator.userAgent;")

But I can't find the way to get the proxy being used. Is there something like ?:
driver.execute_script("return navigator.proxy;")

Comment: Relevant ==> ? https://stackoverflow.com/a/39810577/6241235
Comment: Thanks, but it does not solve my problem. I need to check which proxy is being used by my current web browser instance. I don't need to change the proxy.
Answer: for java and chrome
    options.addArguments("--proxy-server=socks5://127.0.0.1:"+proxyPort);
    driver = new ChromeDriver(options);
    driver.getCapabilities().merge(options);//need to appear socks in Capabilities

next in code
    UnmodifiableIterator iterator=((ImmutableList)((((TreeMap)((ChromeDriver) driver).getCapabilities().asMap().get("goog:chromeOptions")).get("args")))).iterator();
    while (iterator.hasNext())
    {
        String data=(String) iterator.next();
        if (data.contains("proxy")) {
            return data;
        }
    }


Can I specify the user who is creating a release?

Question: When using create-release can I specify the user who is creating the release independent of the user I'm using to execute octo.exe?
The scenario in mind is our build server will begin a build based on a push (and it knows who made the commit), but as far as Octopus Deploy is concerned the build server created the release, and not the person who committed.
Answer: We use an Octopus Service Account with an API Key, and we call it build-deploy-bot. This is the account that TeamCity uses to create the release in Octo.exe.
When the release is created, we also include Release Notes with links to all commits, as well as the build overview. In doing this, we can see what commits made it into the specific release.
Since a "person" didn't create the release, we don't associate the release with a person.
For reference, here's the script we use to generate releases in Teamcity.
https://gist.github.com/ChaseFlorell/716ffd1e4213ecfc8a8b


Select check boxes with "similar" labels

Question: the html is dynamic, one example is:

                 <input type="checkbox" value="693b32d9-d776-4df2-bf78-bd3412d9945b" name="permissions">
                 A / B
                 X

                 <input type="checkbox" checked="checked" value="b70a2218-6af1-4a5a-a6cf-1454df039d24" name="permissions">
                 A / B / C
                 X

                 <input type="checkbox" value="db5ffc0f-6733-4d65-a5f0-aafd6411cd8e" name="permissions">
                 A / B / C / D
                 Y
                 X

                  <input type="checkbox" value="b08f35be-9e21-4f37-9997-b9dce3b91356" name="permissions">
                  A / B / E
                  Y
                  X

if one item is checked(for example the third one, with text "A / B / C / D"), then the items with the text "A", "A / B" or "A / B / C", its "X" mark will show automatically;
if one item is marked with "Y"(for example the fourth one, with text "A / B / E"), then the items with the text "A" or "A / B", its "X" mark will show automatically too;
All the other "X" mark will hide.
Answer: You could use data attributes.

             <input type="checkbox" value="693b32d9-d776-4df2-bf78-bd3412d9945b" name="permissions" >
             A / B
             X

So when a item with the word "a" changes, all times with the data "a" will change too.
$('[data-a] input').on('change', function() {
    $('ul').find('[data-a] span.label').removeClass('invisible');
}

Comment: Thank you, custom attributes do help.


There is no scrolling and no onclick , for a scroll view inside a custom adapter for a list view

Question: What i have :
i have a listView in which , i am using custom adapter . custom adapter is a resource for views inside listView (https://www.dropbox.com/s/lty9abmss7uq2aw/Untitled_1.png)
what i want to do :
i want , whenever i click in that view (https://www.dropbox.com/s/8umltk95vf2gze9/Untitled.png)  click is not working properly in the whole view (https://www.dropbox.com/s/yz4h2nrwjz36ryf/Untitled_2.png)
Why this is not working :
i know why this is not working , because i am using ScrollView inside that Layout . scrollview in included in Layout .
Layout is : https://www.dropbox.com/s/odxw8ihkcyowngu/activity_custom_list_view.xml
ScrollView is : https://www.dropbox.com/s/kdm1ftbgbje20k4/dialogbox.xml
How to make a Scrollable_View inside a listView which is clickable in whole area .
Comment: you can't scroll listview inside scrollview so,you need extended listview height dynamically on your code!
Comment: i have scrollview inside a list view .
Answer: You only have to add an onclick() to the TextView that is inside the scrollView


How are constructor functions and API interfaces different in javascript?

Question: From this question, I can understand that the API interfaces and constructor functions are two distinct concepts.
In javascript there's no notion of interfaces, so how are these interfaces used in javascript?
I mean they look like constructor functions in my eyes typeof(Node) === 'function' // true
But they are not, we cannot use them to construct elements
So how does javascript use these interfaces or how does it implement them while it doesn't have the concept of interfaces in its core like java or C#?
It has a behaviour with them that emulates that of constructors someElement instanceof HTMLElement // true and they have prototypes like constructors and you can extend them with methods using these prototypes but they aren't constructors because they can't be used to construct dom elements.
Answer: It could be a constructor that fails at construction:
 function Node() {
   throw new TypeError("Illegal constructor");
 }

Comment: @noOne cause `new.target` isnt set.
Comment: maybe a good approach to the point, but can you explain why when we call `HTMLElement` without new, it throws an error which is not `TypeError: Illegal Constructor`? How can it detect that it's not used as a constructor?


Probability of collision in S-box

Question: I'm trying to understand a cryptanalysis of the Blowfish cipher, and I need to calculate the probability of collision in the cipher's S-boxes. Basically an S-box is a list of 256 semi-random 32-bit numbers. We can assume that the values are random for convenience. I need to know how I calculate the probability that
$$
S(a) = S(a')
$$$$
a \neq a'
$$
where a and a' are positions in the S-box.
Comment: no you should accept my answer and post a new question instead of post facto editing to make my answer wrong..
Comment: @caveman Fair enough. [Here](http://math.stackexchange.com/questions/332150/probability-of-a-characteristic-in-blowfish)'s the new question.
Comment: thanks - welcome to the site
Answer: After thinking about it for some time it seems the problem is trivial: The probability is just $\frac{1}{2^{32}}$.
If we're modelling S boxes as random functions from 8 bit numbers (but this doesn't even matter) to 32 bit numbers, then the chance of $a'$ (a number distinct from $a$) having the same $S$ value (which is just a random 32 bit number) as $a$ is just $\frac{1}{2^{32}}$.
Comment: Yes, that does make sense. Makes me wonder if I missinterpreted the analysis though, since they gave another value there. I'll add some information to the question.
Comment: @Psyberion, yeah I'm sure this is useless in the analysis.

Probability of collision in S-box


How would I set up Debian 10 and Postfix security for a limited send-only email setup?

Question: I (me and my wife) run a small Debian 10/Buster web server with a few websites for friends and need to set up outgoing email. I've got to the point where I can send emails from the command line (echo "Message Body" | mail -s "Message Subject" TARGET_EMAIL_HERE).
We need a set up that meets the following requirements:

only a few emails each week are will be sent:

some emails from a Perl contact form on a website (which needs tighter anti-spam protection, was going to use the Google CAPTCHA)
some emails with document attachments from a theatre booking system that only known and trusted users can log into

need a 'reply to' field in outgoing emails so people can hit "reply" in their email client (appears easy when setting up scripts to use mail servers)
we don't want to allow any incoming email to the server

What we have:

user websites are set up in their user directories (which are 755), but we administer the sites and they cannot log in to the server
me and my wife are sudo-ers (two system admins) and the only people who login via SSH/SFTP
root login is disabled
We've changed the SSH port

I'm aware this is the bare minimum of info, but I'd like some guidance on setting up and securing Postfix for this kind of usage.
Answer: First of all you should configure Postfix to bind only to localhost if you are not receiving any email on the server. Then you could use a firewall like UFW (since you're on Debian) to block incoming tcp port 25 (it's not mandatory since Postfix only binds to localhost but it will just block incoming SMTP traffic, since you don't want it).
The website or whatever scripts you have (if they are on the same server), they can be configured to connect via localhost to send emails. When you send emails you have to add a Reply-To header with an email address where you want your users to reply.
Configure UseDNS no in /etc/ssh/sshd_config to prevent reverse DNS mapping on each user connection. I would also disable password authentication via SSH and strictly alllow auth with ssh public keys. Use strictly Protocol 2. If you do not use ipv6 for example, disable it in the SSH server:
AddressFamily inet

Also for SSH:
# Authentication:
LoginGraceTime 15s
PermitRootLogin no
StrictModes yes
MaxAuthTries 3
MaxSessions 5

KerberosAuthentication no
GSSAPIAuthentication no

if a user doesn't authenticate within 15seconds then the connection is closed
only allows three password attempts
maximum 5 users connected simultaneously is allowed
disable Kerberos auth
disable GSSAPI auth

As a good rule of thumb you should strictly allow only necessary incoming ports and drop everything else. Same goes for outgoing. If your server does no forwarding then you can just DROP forwarding by default.
Additionally you could install fail2ban which can be configured according to your needs. There are plenty of tutorials on the internet so you can customize it the way you like and/or need.
It's pretty hard to provide a straight answer since the info provided is pretty general. But these should provide some basic guidance.
Comment: that's exactly the clear and exact guidance I was looking for - thanks. I've already set up UFW and fail2Ban, so the rest of your advice should be easy to follow.


How does linking in an html.erb document work?

Question:
Listing categories

      Name
      Thumburl

    <% @categories.each do |category| %>

        <%= category.name %>
        <%= category.thumburl %>
        <%= link_to 'Show', category_path(category) %>
        <%= link_to 'Edit', edit_category_path(category) %>
        <%= link_to 'Destroy', category, method: :delete, data: { confirm: 'Are you sure?' } %>

    <% end %>

<%= link_to 'New Category', new_category_path %>

So, as I said in my last post, I'm trying to go through Ruby code as I find it on Codecademy's RoR tutorial. Since they have such a straightforward tutorial, I figure it would be ridiculous to not understand everything they throw at me.
In this bit, they have an html.erb file that is supposed to form a tabled-view. Everything seems clear to me until they get to
.
Here, first, we are iterating on an instance variable @categories...now, where this instance variable is found, I don't know. I thought instance variables meant they could only be used within a particular class, yet this is a markup page, i.e. no classes have been defined, so how does Ruby know where or what this instance variable is?
Next: so, as I understand it, the word 'category', here, is serving as a variable because it was specified as such by pipe syntax two lines earlier. Now, whether this variable can be used beyond this html.erb page is beyond me, cause I thought instance variables were denoted with an '@.' With this variable, we call the method 'name'. So, is 'name' a custom method, and if so, where is it defined?
Now, the third  tag contains code that tells Ruby to link to some name 'Show,' yet I'm not sure what this name points to...also, 'category_path' is a method we defined in our routes.rb file, and it has the parameter of our blocked variable 'category.'
Lastly, the final row cell links to some name 'Destroy,' but this comma syntax is something I haven't seen before:
<%= link_to 'Destroy', category, method: :delete, data: { confirm: 'Are you sure?' } %>

Comment: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
Comment: category is a variable containing an element in the @categories collection, which would have been created by the Categories Controller. It's 'existence' is for the duration of the each.do / end loop. Next iteration, it's a different element from the collection. Outside the loop, it doesn't exist. The category path helpers are using some Rails magic, where if you pass it the object, and the path needs an ID, it uses that object's ID attribute (category.id, not the object ID).
Answer: The instance variable @categories should be defined in CategoriesController, which is a subclass of action controller. Ruby's instance variables are not persistent, and any @variables you defined in a controller action is accessible in the action's view. I am not sure if you are familiar with MVC patterns, and if not, you can take a look at this question:
What is MVC in Ruby on Rails?
Name is an attribute of the resource/model category. You should see its class in app/model/category.rb. It is a subclass of ActiveRecord, which acts as a wrapper of the database of your choice. So you probably have a database table called categories with column name 'name'.
And as @JoelL mentioned, the link_to are view helpers that are meant to simplify your syntax in view files,make your code more organized, and save you time. You can define your own view helpers in app/helpers. Some of the helpers are automatically made for you when you define a resources :resource_name in config/routes.rb. In this case, you probably have resources :categories in your config/routes.rb


How can I paginate the Views page itself where all views are listed?

Question: At the url admin/structure/views how can I paginate this list of results?
Comment: what is logic behind it?
Answer: If you have many views I would suggest you go to Views settings (admin/structure/views/settings) and enable Show filters on the list of views. This gives you the possibility to search and filter the list of views in various ways.


Guitar: No sound from second string, but other strings sound normal

Question: I played a Squier Stratocaster last night, and when I plugged into the amp, which was working, my guitar's second string didn't make any sound (well, a bit, actually), but the rest of the strings sounded normal.
Is the problem with the pickup's coil or the guitar wiring? When I tested the other pickup position (I used a Hendrix-like middle+bridge), like bridge or even bridge, the second string still didn't make any sound.
Comment: It would be helpful if you could test all 5 pickup selector switch positions, and report on the outcome; I'm not 100% sure how to interpret the final sentence.
Comment: @Dave actually, your question's answer is in the final sentence, I have a bad grammar, so yea. :D
Comment: So you're saying: "in all pickup positions: no sound from second string, but normal sound from others?"
Comment: Can you hear (or maybe even see) the second string vibrate acoustically, i.e. when it is unplugged?
Comment: @Dave something like that, and yes, I heard it vibrates.
Answer: Swap a string by putting your top string in place of the second. If you take it off carefully and put it onto the second post, and wind it more times, it can still go back on properly, although a new set of strings isn't extortionate.
If this string is still quiet, it's the pick-up, although it's doubtful all three have the same problem. More likely it's the string itself - which you can check by putting it in place of the third string.An acoustic string just doesn't do it on an electric guitar, but it may look alright.
Or, simply get a new set of strings anyway.
Answer: Unless it is an acoustic guitar string (nylon or wound with non-magnetic material) or clearly not vibrating, it's the pickup that's broken: any wiring possibly connected to the strings is just to reduce hum, not change the signal level.  The pickup reacts perfectly fine to an entirely unconnected string if it is an electric guitar string rather than an acoustic one.
I think that the coils are usually wired in series, so if you still get sound from the other strings, there are rather few error scenarios I can think of:
a) coil is shortcircuited.  This will most likely be purely mechanical: two items touching that shouldn't.
b) magnet is dead and/or has fallen out or there is some other break in the magnetic connection in the pickup
c) someone disassembled the pickup at some point of time, the pickup is a double-coil pickup, and one of the coils or one of the magnets was put back in reverse.  Double coil pickups are intended to pick up outer magnetic fields in a manner that the voltage inducted into both coils cancels while the voltage induced from field changes done by the vibrating string to the field from the coil magnets adds up.  Reverse a coil, and you pick up the noise and cancel the sound.  Reverse a magnet, and both noise and sound cancel.
Answer: A guitar pickup in 99% of all guitars including strats is a single coil of wire which senses all strings at the same time. Some pickups use individual magnets for each string, a fender Stratocaster for instance, and some use a single magnet underneath the pickup but have metal slugs or screws directing the field of sensitivity towards the strings, such as a Les Paul. This is irrespective of whether or not the pickup is a single coil or a humbucker, but in most situations it ends up the way I described. However some cheeper pickups such as those found on some squire strats do in fact use a single or double magnet underneath the single coil to create the magnetic field for the pickup to work. What I am getting at is that in all likelihood the fact that the pickup senses the other sttings would indicate that the pickup is perfectly fine. Without seeing the guitar i would guess the string is not resting in the slot properly. Most likely at the bridge. If the problem would be at the nut slot, then fretted notes would sound out well. So make sure the string is seates well and if the problem persists you may need to smooth some type of burr on the bridge saddle that occur sometimes.
Comment: came here to say this. additionally, classic strat bridges press down on two screws, and sometimes one of those screws doesn't make proper contact, or something like that, leading to buzz, poor resonance, etc.
Answer: This happened to me but only on the G string of my middle pickup.  I took the pickguard off and there was a ground screw with a wire not connected to anything in the cavity right below the pickup.  The screw was evidently touching the pickup magnet and making it so it wouldn't sound when plucked.
Answer: This just happened to me:
I thought it would be a good idea to clean the metal particles gathered on my pickup pole pieces with a strong "rare-earth" magnet. After doing this, I completely lost any pickup volume for my A string only. I quickly realized it was because the magnet reversed the polarity of that one pole piece.
The solution:
Touch the other side (other polarity) of the rare-earth magnet back to the top of the pole piece. If this happens to you, it's ok if you get the wrong side at first.
I hope this helps someone out.
Answer: All the electric guitar or bass pickups I've ever seen (1972-present) use one or two coils which cover all the strings. It is possible to make a coil-per-string pickup, and probably somebody does. Fender's famous Precision Bass has two coils which are staggered, one coil under the upper, lower frequency, pair of strings, (E,A) one coil under the lower, upper frequency, pair of strings. (D,G). The lower frequncy pickup is closer to the neck of the instrument, the upper frequency pickup is closer to the bridge. The two coils are adjacent.
If a guitar with multiple pickups produces a very reduced signal for one string only, the problem must lie with that string. Magnetic pickups work by the vibrating string moving through the magnetic lines of force from the magnet(s). Moving any conductor in a magnetic field will induce a current in the conductor. Moving an iron or steel object in a magntic field will change the magnetic field, at the frequency the object is moving, and the coil(s) under the strings will generate a signal at that frequency.
If you replace the string that generates no signal with a steel string, from an adjacent position, or obtained from a friend or a store. you should get a signal from that string. If you replace the problematic string with a classical (not steel) guitar string, it will make no or almost no signal. You can try a plain nylon high string, and get no signal at all. A wound brass wire over fiber core low string will induce a current within itself by vibrating in the magetic field. The induced field, vibrating, will affect the magnetic field created by the magnet, but at a far lower level than a steel string. But you'll get some signal, and since that's what you report. I suspect that's whats on the position.
An easy way to check any string for magnetic effect is to apply a magnet to it. If the magnet sticks, the string is magnetic. If the magnet doesn't stick, the string will only have a small magentic effect from vibrating in the field.
A further demonstration would be comparing the effect of a brass and a steel tuning fork or other vibrating object. A steel tuning fork will strongly affect the magnetic field of the pickup and induce a signal on the coil. A brass tuning fork will weakly affect the magnetic field, and induce a very small signal.


Fibonacci numbers expressed as squares of lower Fibonacci numbers

Question: I am no mathematician so my apologies for my ignorance.
I notice that every number in the Fibonacci series can be expressed as a previous Fibonacci number squared plus or minus (alternating) another previous Fibonacci number squared, and both columns of squares themselves are composed of the Fibonacci sequence, each number appearing twice from 2 onwards. ie
<code>1   1   +   0   1+0
1   1   -   0   1-0
2   1   +   1   1+1
3   2   -   1   4-1
5   2   +   1   4+1
8   3   -   1   9-1
13  3   +   2   9+4
21  5   -   2   25-4
34  5   +   3   25+9
55  8   -   3   64-9
89  8   +   5   64+25
144 13  -   5   169-25
233 13  +   8   169+64
377 21  -   8   441-64
610 21  +   13  441+169
987 34  -   13  1156-169
</code>
and so on.
Is this well known? Is there a proof that it works for all Fibonacci numbers?
Comment: This is not a research level question. There are infinitely many identities with Fibonacci numbers. If this one is true, it should be easily provable using the "$n$-th term formula".
Comment: http://en.wikipedia.org/wiki/Fibonacci_number
Answer: It a derivation from the Catalan and Cassini identity. Cassini identity states that:
$$F_n^2 - F_{n-r} \cdot F_{n+r} = (-1)^{n-r}F_r^2$$
Now set $r=n-1$ and we got:
$$F_n^2 - (-1)^{n-n+1}F_{n-1}^2 = F_{n - n+1}F_{n+n-1}$$
$$F_n^2 + F_{n-1}^2 = F_{2n - 1}$$
But $2n - 1$ is odd, so this covers the case when the Fibonacci index is odd number. Now by setting $r=n-2$ we have:
$$F_n^2 - (-1)^{n-n+2}F_{n-2}^2 = F_{n - n+2}F_{n+n-2}$$
$$F_n^2 - F_{n-2}^2 = F_{2n - 2}$$
This one covers the case when the Fibonacci index is even.


Pagination In Custom APEX REST Endpoint

Question: In my custom APEX REST endpoint, I want to have the exact same pagination as the SFDC REST API.
Is there an easier way to achieve this than implementing the logic from scratch? I would love to just extend abstract base class that holds all this logic and is used by the SFDC REST API as well. Or something similarly convenient, that doesn't involve me re-inventing the wheel.
Thanks in advance,
Peter
Answer: Unfortunately, you won't find a "built-in" paging mechanism in the Apex REST framework.
However, basic paging can be achieved using the LIMIT and OFFSET clauses in your underlying SOQL query.
I'm assuming you're going to apply this to a custom GET request, and one of the drawbacks of this is the lack of a server-side cursor. So, in order to maintain your paging context, you would need to pass an updated offset value on each subsequent query, depending on which way the paging is going.
Also, I would highly consider applying a permanent ordering clause for the SOQL query, as well. Though you can mostly rely on getting the same results in the same order without one, it's not guaranteed to be consistent; better safe than sorry.
Comment: Was hoping for better news, but this seems to be the only option. Accepting it as the correct answer since no one else showed up with better alternatives.

Pagination In Custom APEX REST Endpoint


"D.S., D.S. Al Coda, To Coda" Confusion

Question: I'm having a difficult time grasping "D.S., D.S. Al Coda, To Coda" based on the online explanations I've come across.
Below is the specific example that I'm attempting to play. Does the Dal Segno symbol mean "repeat the previous passage"? Up to where? When do I play the coda? Where it says "To Coda", is the circle with the cross through it hovering above the exact place that you jump to the coda?
I'm probably overcomplicating a fairly straightforward concept here, but I'm confused. If anyone could simplify this for me or explain what to do in this specific example I might be able to wrap my head around it. Thank you.
Comment: I don't see the symbol that is usually referenced in D.S.  is it elsewhere in the music?
Comment: Your understanding seems correct but the music you have places the sign at the same measure as the direction, which I do not understand.
Comment: Who's the publisher? I believe I've seen that faultily-placed segno sign only once before, in the Boosey and Hawkes score of Elgar's Pomp and Circumstance March No. 2 in A Minor...and even then, there was another segno sign much earlier in the score. (Its use of combining a first repeat ending with a "D.S. al Coda" indication was confusing as heck, though, and at that point, I had to rely on interpretations of the piece in order to transcribe it properly.) ...Well, have you found another segno sign elsewhere?
Comment: DS al coda. DS means return to a previous $ sign. Having that $ above DS makes them both redundant. Good question!
Comment: I didn't think about a faultily-placed segno. I was rather suspicious if OP wasn't fooling, sorry, as it seemed to me that he quite clearly knows the meaning of the signs. And he might have listened to the music, this would have been less elaborating than post this question. *but I'm confused. If anyone could simplify this for me or explain what to do in this specific example I might be able to wrap my head around it. Thank you.* But if this is an error in the sheet music I have to apologize! (and I know: of course  it is free to everybody if he wants to post an answer or not ....
Answer: The coda here  is the final bar. Coda means "the tail" In this case of LET IT BE it is only one bar.

Does the Dal Segno symbol mean "repeat the previous passage"?

Yes!
D.S. (Dal Segno) means "from the sign" and this is the sign right above the double barlines (something like an $:

Up to where?

this segno refers to an earlier same segno, probably at the beginning of the 3rd verse of LET IT BE or at the beginning of the refrain.
That means you have to go back to the other sign (segno) and repeat this section until you come to "to coda" (sometimes it's written "last time to Coda").

When do I play the coda?

When you play the refrain for the last time you have to ignore the 3 last bars (before the tail) and skip from "to Coda" directly to the coda and play the final bar.

When do I play the coda? Where it says "To Coda", is the circle with
the cross through it hovering above the exact place that you jump to
the coda?

Yes!

I'm probably overcomplicating a fairly straightforward concept here ...

(Yes!)
look up:
https://www.thoughtco.com/d-s-al-coda-definition-2701445
D.S. al coda, or dal segno al coda, literally means "from the sign to the coda mark." D.S. al coda is an indication to start back at the segno, play until you encounter a coda, then skip to the next coda to continue.
I've found this sheet music by scribd (the added notes/remarks are not mine!)
But you can see here the segno at the double bar line in the beginning of the verse:
https://www.scribd.com/doc/312619090/Let-it-be-Beatles-pdf
Answer: There will be a previous $ symbol which marks where the D$ jumps back to.  Yes, the To Coda jump occurs right where the Ǿ symbol is.
In some older music the complete 'D$ al Coda' instruction is dispensed with, they just put a simple '$' at both the jump and destination points.  Similarly just 'Ǿ' at both the 'To Coda' point and the actual coda.  It's slightly confusing here to mix both conventions, writing both '$' above the stave and 'D$ al Coda' below.  But we know what they mean!
Comment: It looks like there is no $ near the beginning of OP's piece. It sounds like, for the second time through OP's piece, you should start at the beginning ("Whisper words..."). Is OP's piece correct, or should it have $ right before "Whisper"? Thanks!
Comment: It should have several pages of music before 'Whisper words...'!   Including the location of the $ we are intended to jump back to.
Comment: @Laurence Only one page (and one line on the second), but yes, I'd think it quite obvious that the scan included in the question is an excerpt, not the whole song. The sign to jump to is on the first bar, just after pickup. (Wasn't my question, but I think I recognise the engraving.)
Comment: @jrennie It's correct. The sign to jump to is at the very start of the song, just after the pickup measure.
Answer: The easy bit to answer is the coda part. After the words 'to Coda', there is one bar to finish off the previous phrase. Last time, you play the Coda bar instead. It's the same harmony, but finishes the song off. In other words, last time through, play the first 3 bars, then go straight to the 'target' at the end, and there's the final bar of the four.

"D.S., D.S. Al Coda, To Coda" Confusion