How i can print a new line to a text file in mips it just print a space

Question: I have  the following code in MIPS that  i  run it in mars simulator
The code open a text file for writing
The problem with the result it keep printing all strings that i provide in
My code without printing any new line i tried to separate  new line from the string  it did not work it keeping  print space instead of new line
Here is my code
.data

fout:   .asciiz "testout.txt"      # filename for output
buffer: .asciiz "The quick brown fox jumps over the lazy dog."
buffer1:  .asciiz "\n"
 .text
 .globl main
 main:

  ###############################################################
  # Open (for writing) a file that does not exist
  li   $v0, 13       # system call for open file
  la   $a0, fout     # output file name
  li   $a1, 1        # Open for writing (flags are 0: read, 1: write)
  li   $a2, 0        # modeA is ignored
  syscall            # open a file (file descriptor returned in $v0)
  move $s6, $v0      # save the file descriptor

  ###############################################################
  # Write to file just opened
  li   $v0, 15       # system call for write to file
  move $a0, $s6      # file descriptor
  la   $a1, buffer   # address of buffer from which to write
  li   $a2, 46      # hardcoded buffer length
  syscall            # write to file

  ###############################################################
  # Write to file just opened
  li   $v0, 15       # system call for write to file
  move $a0, $s6      # file descriptor
  la   $a1, buffer1 # address of buffer from which to write
  li   $a2, 1     # hardcoded buffer length
  syscall            # write to file

  ###############################################################
  # Write to file just opened
  li   $v0, 15       # system call for write to file
  move $a0, $s6      # file descriptor
  la   $a1, buffer   # address of buffer from which to write
  li   $a2, 44       # hardcoded buffer length
  syscall            # write to file

  ###############################################################
  # Close the file
  li   $v0, 16       # system call for close file
  move $a0, $s6      # file descriptor to close
  syscall            # close
  li $v0,10
  syscall

Answer: Your base code was pretty much correct. And well commented! Good job.
The main issue was that you were hardwiring the string lengths.
In the first syscall for buffer, the length was 46 [too high] and the file got an EOS char on the line. There was a newline output after that.
In the second syscall for buffer, the length was 44 [too low] and the file line was chopped. There was no newline output after that because you didn't do a syscall for one.
So, the simple fix would be to just manually adjust the lengths, but I'd recommend a strlen approach to output of text strings, just like you'd do in C.
I modified your code to add an fputs function that has the strlen as an internal loop [please pardon the gratuitous style cleanup]:
    .data

fout:       .asciiz     "testout.txt"   # filename for output
buffer:     .asciiz     "The quick brown fox jumps over the lazy dog."
nl:         .asciiz     "\n"

    .text
    .globl  main

main:

    ###############################################################
    # Open (for writing) a file that does not exist
    li      $v0,13                  # system call for open file
    la      $a0,fout                # output file name
    li      $a1,1                   # Open for writing (flags are 0: read, 1: write)
    li      $a2,0                   # modeA is ignored
    syscall                         # open a file (file descriptor returned in $v0)
    move    $s6,$v0                 # save the file descriptor

    ###############################################################
    # Write to file just opened

    # output string the first time
    la      $a1,buffer
    jal     fputs

    # output newline
    la      $a1,nl
    jal     fputs

    # output string the second time
    la      $a1,buffer
    jal     fputs

    # output newline
    la      $a1,nl
    jal     fputs

    ###############################################################
    # Close the file
    li      $v0,16                  # system call for close file
    move    $a0,$s6                 # file descriptor to close
    syscall                         # close

    li      $v0,10
    syscall

# fputs -- output string to file
#
# arguments:
#   a1 -- buffer address
#   s6 -- file descriptor
#
# registers:
#   t0 -- current buffer char
#   a2 -- buffer length
fputs:
    move    $a2,$a1                 # get buffer address

fputs_loop:
    lb      $t0,0($a2)              # get next character -- is it EOS?
    addiu   $a2,$a2,1               # pre-increment pointer
    bnez    $t0,fputs_loop          # no, loop

    subu    $a2,$a2,$a1             # get strlen + 1
    subiu   $a2,$a2,1               # compensate for pre-increment

    move    $a0,$s6                 # get file descriptor
    li      $v0,15                  # syscall for write to file
    syscall

    jr      $ra                     # return

UPDATE:

I used your code mars still exists there is no new line to be printed. mars ignores the new line and treat it as a null value.

I'm not sure what is happening on your end. I had tested this in mars and the code is correct. Here is the hex dump of testout.txt [which I had verified before posting]:
00000000: 54686520 71756963 6B206272 6F776E20  The quick brown
00000010: 666F7820 6A756D70 73206F76 65722074  fox jumps over t
00000020: 6865206C 617A7920 646F672E 0A546865  he lazy dog..The
00000030: 20717569 636B2062 726F776E 20666F78   quick brown fox
00000040: 206A756D 7073206F 76657220 74686520   jumps over the
00000050: 6C617A79 20646F67 2E0A               lazy dog..

By contrast, the hex dump for your original code was:
00000000: 54686520 71756963 6B206272 6F776E20  The quick brown
00000010: 666F7820 6A756D70 73206F76 65722074  fox jumps over t
00000020: 6865206C 617A7920 646F672E 000A0A54  he lazy dog....T
00000030: 68652071 7569636B 2062726F 776E2066  he quick brown f
00000040: 6F78206A 756D7073 206F7665 72207468  ox jumps over th
00000050: 65206C61 7A792064 6F672E             e lazy dog.

The only thing I can think of that might make a difference is the OS. I'm using linux. What is your OS? Windows? If so, the nl might need to be:
nl:   .asciiz    "\r\n"

All other OSes should be fine.
Comment: I used your code  mars still exists there is no new line to be printed
Comment: mars ignores the new line and treat it  as a null value
Comment: The problem was because the OS  i am using windows and you should put \r before \n
 thanks for your help
Comment: I figured. If it was windows, simple commands like `type` or `notepad` might have trouble with _just_ `\n`. IIRC, `wordpad` will figure it out. Cygwin utilities will also work.


How to prove continuity of $g(y)=\max_{x\in K} f(x,y)$ when $K$ is compact?

Question: I have a function $f$ that is continuous over the set of variables, $f: \ K \times M \to \mathbb{R}$, where $K$ is a compact domain of a metric space and $M$ is a metric space. And I want to prove that the function $g(y)=\sup_{x\in K} f(x,y)$ is continuous.
As $K$ is a compact, $f$ is uniformly continuous with respect to its first argument. Also, for the same reason, $g(y)=\sup_{x\in K} f(x,y)=\max_{x\in K} f(x,y)$.
For now, I know that for the case of $f$ is continuous with respect of each variable separately, this doesn't work (see an example here Is supremum over a compact domain of separately continuous function continuous?) and there is a proof for the case when $M$ is also a compact, or $f$ is just uniformly continuous on $M$, too (How prove this $g(x)=\sup{\{f(x,y)|0\le y\le 1\}}$ is continuous on $[0,1]$), which I personally doubt as there is no guatantee that y-s will be close there (in my notations they are x-s).
All my tries fail when I come to the point where I need to say something about argmaxes of even close y-s. For example:
I consider a sequence $y_n \to y_0$ with $n\to\infty$. For each $y_n$ there exists $x_n$ such that $g(y_n)=\max_{x\in K} f(x,y_n)=f(x_n,y_n).$ Then, I try to estimate the difference $$|g(y_{n+k})-g(y_n)|=|f(x_{n+k},y_{n+k})-f(x_n,y_n)|=|f(x_{n+k},y_{n+k})-f(x_{n+k},y_{n})+f(x_{n+k},y_{n})-f(x_n,y_n)|\le|f(x_{n+k},y_{n+k})-f(x_{n+k},y_{n})|+|f(x_{n+k},y_{n})-f(x_n,y_n)|.$$ One can easily see that the first component tends to zero with $k\to\infty$, but I have no idea what to do with the second one...
Any help would be very appreciated!
Comment: $K$ is metric, right?
Comment: Just compact (only topology, only hardcore), but if you have a proof for the case K is metric it would be very useful for me as well :))
UPD But actually yes, metric K would be enough. Thank you for the comment. I'll edit the post
Answer: Consider a sequence $(y_n)_{n\in\mathbb{N}}$ in $M$ that converges to some $y \in M$. We will show that

Claim. $g(y_n) \to g(y)$.

Step 1. We first show that $\liminf_{n\to\infty} g(y_n) \geq g(y)$.
This is an immediate consequence of the general fact that the supremum of a family of lower-semicontinuous functions is again lower-semicontinuous. (In particular, this fact does not require any structure on $K$.) Nevertheless, we write out the proof for self-containedness.
Let $\alpha$ be an arbitrary real satisfying $\alpha < g(y)$. Then there exists $x \in K$ such that $f(x, y) > \alpha$. So by the continuity of $f$, there exists $\delta > 0$ such that $f(x, y') > \alpha$ whenever $d(y', y) < \delta$. This then implies that
$$ g(y_n) \geq f(x, y_n) > \alpha \qquad \text{whenever } d(y_n, y) < \delta, $$
and so, we have $\liminf_{n\to\infty} g(y_n) \geq \alpha$. Since this is true for any $\alpha < g(y)$, the desired assertion follows by letting $\alpha \uparrow g(y)$.
Step 2. Next, we show that $\limsup_{n\to\infty} g(y_n) \leq g(y)$.
Indeed, for each $n$, use the compactness of $K$ to choose $x_n \in K$ so that $f(x_n, y_n) = g(y_n)$. Also,

find a subsequence $I \subseteq \mathbb{N}$ so that $(g(y_n))_{n\in I} \to \limsup_{n\to\infty} g(y_n)$, and then

find a further subsequence $J \subseteq I$ such that $(x_n)_{n\in J} \to x $ for some $x \in K$. This is possible by the sequential compactness of $K$.

Then
$$ \limsup_{n\to\infty} g(y_n)
= \lim_{J \ni n \to \infty} g(y_n)
= \lim_{J \ni n \to \infty} f(x_n, y_n)
= f(x, y)
\leq g(y). $$
Conclusion. Combining step 1 and 2, the desired claim follows. $\square$

Discussion. The above proof works whenever $K$ is both compact and sequentially compact. When $K$ is a compact metric space, sequential compactness comes for free. I am not sure if we can come up with a proof that does not rely on sequential compactness.
Comment: I think compactness of $K$ only guarantees that $(x_n)_{n\in I}$ has a convergent subnet. But even if it is so, this does not seem to affect the validity of your proof.
Comment: @Noiril, I guess you are right, thanks for pointing out an interesting fact! :)
Comment: Great! Thank you
Answer: Here's a proof that's more for fun than anything else (especially since there's already a perfectly good answer here).

Let $X$ be a sober space (every metric space is sober) and let $K$ be compact and sober. Then if $f : X \times K \to \mathbb{R}$ is continuous, the function $g(x) = \max_{k \in K} f(x,k)$ is continuous too.

We use the fact that the extreme value theorem is actually constructively true in the following form:

Let $K$ be a compact, positive, overt locale and $f : K \to \mathbb{R}$ continuous. Then $f$ admits a maximum $\max_K f \in \mathbb{R}$.

This is great because it means this statement is true inside the sheaf topos $\text{Sh}(X)$! Externalizing this statement (and cashing out locales for sober spaces everywhere) gives

Let $\pi : K \to X$ be a proper, open surjection and $f : K \to \mathbb{R}$ continuous. Then $x \mapsto \max_{k \in \pi^{-1} x} f(k)$ is a continuous function.

(This is basically because compact locales in $\text{Sh}(X)$ are proper maps to $X$, positive overt locales in $\text{Sh}(X)$ are open surjections to $X$, and a "real number" in $\text{Sh}(X)$ is a continuous function $X \to \mathbb{R}$)
But now let's interpret the above theorem with

$\pi : X \times K \to X$, which one easily checks to be a proper open surjection
$f : X \times K \to \mathbb{R}$, which we're assuming is continuous

Then since $\pi^{-1}(x) = \{x\} \times K$, the theorem tells us that the function $x \mapsto \max_{(x,k)} f(x,k)$ is continuous, as desired.

As a brief soapbox pitch, this is one reason to care about constructive proofs! Constructively true things can be interpreted inside a sheaf topos, which gives us "continuously parameterized" versions of the theorem basically for free!
A few days ago when I saw this question, I recognized it as a version of the usual extreme value theorem where the continuous function $f$ and the resulting max $g$ are both allowed to depend on a bonus parameter from $X$. So I thought if I could find a constructive version of the extreme value theorem, it should give your theorem as a corollary! (Actually it gives something a bit more general than what you asked for). I'm not an expert in locale theory, and I had to wait a few days to find the theorem I cited here, but you can see how, with experience, these kinds of questions can be answered very quickly!

I hope this helps ^_^


Runs se dividindo várias vezes

Question: Bom galera, estou tendo um problema que está me perturbando um pouco, já procurei sobre e não achei nada que me ajudasse.
Estou pesquisando certas variáveis num Template Word para poder realizar uma substituição. O problema ocorre quando algumas variáveis são quebradas em várias Runs, por exemplo:

NT: Nessa imagem fica claro que a variável municipio_sigla é quebrada em duas Runs, sendo a Run1 => munici, e a Run2 => pio_sigla, portando ao procurar ela completa (municipio_sigla) não retornará resultado algum.
Edit1: Aqui vai um exemplo do código:
<code>//Pegando os cabeçalhos
SearchAndReplace(partLists: document.MainDocumentPart.HeaderParts, target: "<municipio_sigla>", replace: municipio.Sigla);

//Método que procura e substitui as variáveis:
private static void SearchAndReplace<T>(IEnumerable<T> partLists, string target, string replace) where T : OpenXmlPart
{
        foreach (var part in partLists)
        {
            foreach (var currentParagraph in part.RootElement.Descendants<DocumentFormat.OpenXml.Wordprocessing.Paragraph>())
            {
                foreach (var currentRun in currentParagraph.Descendants<DocumentFormat.OpenXml.Wordprocessing.Run>())
                {
                    foreach (var currentText in currentRun.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>())
                    {
                        if (currentText.Text.Contains(target))
                        {
                            currentText.Text = currentText.Text.ReplaceInsensitive(target, replace);
                        }
                    }
                }
            }
        }
}
</code>
Alguém já enfretou algo parecido? E se sim, existe alguma solução?
Comment: Será mais fácil de ajudar se você editar a pergunta, incluindo o seu código.
Comment: Pois é kkkkkkk. Um momento.
Comment: @LeandroAngelo, pronto. Adicionei um código de exemplo.
Answer: Bom galera, eu consegui encontrar uma resposta muito interessante no stackoverflow gringo em que dizia que variáveis desse tipo podem trazer problema, pois o OpenXml separa textos assim, que tenham algum caractere especial (<,>,@,#,$...). Essa resposta me levou a esse código do Simon Doodkin.
Ele pega os textos das Runs e concatena em uma string, procura o valor a ser substituído e substitui pelas as posições de cada caractere.
Acabei fazendo um código pra me facilitar na hora de fazer as substituições, e ele se encontra aqui, pra quem tiver interesse...
Exemplo de uso:
<code>wordDoc.MainDocumentPart.Document.ReplaceInElement("from", "to");
</code>

Runs se dividindo várias vezes


Two methods of finding $\int_{0}^{\frac{\pi}{2}} \frac{dx}{1+\sin x}$

Question: Two methods of finding $$I=\int_{0}^{\pi/2} \frac{dx}{1+\sin x}$$
Method $1.$ I used substitution, $\tan \left(\frac{x}{2}\right)=t$ we get
$$I=2\int_{0}^{1}\frac{dt}{(t+1)^2}=\left. \frac{-2}{t+1}\right|_{0}^{1} =1$$
Method $2.$ we have $$I=\int_0^{\pi/2}\frac{1-\sin x}{\cos ^2 x} \,\mathrm dx = \left. \int_0^{\pi/2}\left(\sec^2 x-\sec x\tan x\right)\,\mathrm dx= \tan x-\sec x\right|_0^{\pi/2}$$
What went wrong in method $2$?
Comment: Nothing is "wrong with it."  $\tan x - \sec x$ is not defined at $\frac \pi2,$ but $\lim_\limits{x\to \frac \pi2} \tan x - \sec x$ is defined.
Comment: What do you mean "What went wrong in method 2?" You haven't even finished it.
Comment: $\int_a^b f(x)$ is always $ \lim_{x \to b^-} F(x) - \lim_{x \to a^+}F(x)$. What we do normally are the cases when $F(a)$ and $F(b)$ exist, and are equal to there corresponding limits.
Answer: You are right!
Just $\lim\limits_{x\rightarrow\frac{\pi}{2}}\frac{\sin{x}-1}{\cos x}=0$
Comment: @Umeshshankar In cases such as these, $\int_a^b f(x)\mathrm d x = \lim_{b _0 \to b^-} F(b_0) - F(a)$.
Comment: But we need to have $\int_{a}^{b} f(x) dx=F(b)-F(a)$ right? So here $b=\frac{\pi}{2}$ but $\tan x$ is not defined for $x=\frac{\pi}{2}$
Comment: @Umesh shankar It's not defined for $x=\frac{\pi}{2}$, but if $x\rightarrow\frac{\pi}{2}$ then $x\neq\frac{\pi}{2}$.
Comment: @GeorgeCoote Not in cases such a these, $\int_a^b f(x)$ is always $ \lim_{b _0 \to b^-} F(b_0) - \lim_{a_0 \to a^+}F(a_0)$. What we do normally are the cases when $F(a)$ and $F(b)$ exist, and are equal to there corresponding limits.
Answer: Don't think that discontinuities immediately imply failure. Take the left hand limit, ie.
$$\lim_{x \to \frac \pi 2^-} \frac{\sin x - 1}{\cos x}$$
Which is indeterminate, so apply L'Hopital's rule,
$$\lim_{x \to \frac \pi 2^-} \frac{\sin x - 1}{\cos x} = \lim_{x \to \frac \pi 2^-} \frac{\cos x} {-\sin x} = -\frac 0 1 = 0$$
Hence the result.
Answer: Your second integral is improper.  You divided by $1-\sin x$ which is $0$ at $\pi/2$.  So to evaluate the integral, you have to finish by taking
$$\lim_{x \to \pi/2} (\tan x - \sec x) = 0.$$
Answer: Since you have used an anti-derivative $\tan x-\sec x$ which is not defined at $x=\pi/2$ we need to utilize the following result:

Theorem: If a function $f: [a, b]\to \mathbb{R} $ is Riemann integrable on $[a, b] $ then the function $F: [a, b]\to\mathbb {R} $ defined by $$F(x) =\int_{a} ^{x} f(t) \, dt$$ is continuous on $[a, b] $ and in particular $$\lim_{x\to b^{-}} \int_{a} ^{x} f(t) \, dt=\int_{a}^{b} f(t) \, dt= \lim_{x\to a^{+}} \int_{x} ^{b} f(t) \, dt$$

Using this result we have $$\int_{0}^{\pi/2}\frac{dx}{1+\sin x} =\lim_{x\to(\pi/2)^{-}}\int_{0}^{x}\frac{dt}{1+\sin t} =\lim_{x\to(\pi/2)^{-}}(\tan x-\sec x+1)=1$$ The last limit is easily evaluated using algebra of limits.
Answer: \begin{align}
\tan x - \sec x & = \frac{\sin x -1}{\cos x} = \frac{(\sin x - 1)(-\sin x -1)}{(\cos x)(-\sin x - 1)} = \frac{1-\sin^2 x}{(\cos x)(-\sin x - 1)} \\[10pt]
& = \frac{\cos^2 x}{(\cos x)(-\sin x - 1)} = \frac{-\cos x}{1+\sin x} = \frac 0 2 \text{ if } x = \frac \pi 2.
\end{align}
Or you can use the identity
$$
\tan x \pm \sec x = \tan\left( \frac \pi 4 \pm \frac x 2 \right).
$$


How might one formulate integration over an ordered probability simplex?

Question: Given a probability simplex ($x_i \geq 0$, $i=1,\ldots,n$)
\begin{equation}
\sum_{i=1}^n x_i=1,
\end{equation}
I want to attempt integrations of various ("operator-monotone"-based https://pdfs.semanticscholar.org/d393/21f142432eddd2af0d3bd07235a63aca2019.pdf) functions over that subsection for which
\begin{equation}
x_i \geq x_{i-1}.
\end{equation}
Further, I'm particularly interested in such integrations ($n=4$) with the additional ("absolute separability") constraint (eq. (3) in https://arxiv.org/pdf/quant-ph/0502170.pdf)
\begin{equation}
x_1 \leq x_3+2 \sqrt{x_2 x_4}.
\end{equation}
What are my options for setting up the integrations (coordinate transformations might be of interest)? The particular integrations I have in mind are seemingly very challenging, and I may (probably) have to resort to numerical methods.
Answer: Using the GenericCylindricalDecomposition command of Mathematica, we can express the integral of 1 over the 3-dimensional probability simplex as the sum of three
integrations (for ease of presentation, I replace the subscripted variables $x_i$ by $xi$, $i=1,2,3$)
<code>Integrate[1, {x3, 0, 1/4}, {x2, x3, 1/2 (1 - 2 x3)}, {x1, 1 - x2 - 2 x3, 1 - x2 - x3}] + Integrate[1, {x3, 0, 1/4}, {x2, 1/2 (1 - 2 x3), (1 - x3)/2}, {x1, x2, 1 - x2 - x3}] + Integrate[1, {x3, 1/4, 1/3}, {x2, x3, 1/2 (1 - x3)}, {x1, x2, 1 - x2 - x3}]
</code>
The results of the three integrations are $\left\{\frac{1}{192},\frac{1}{768},\frac{1}{2304}\right\}$, respectively, summing to $\frac{1}{144}$, which is one-twenty-fourth ($\frac{1}{4!}$)of the integration ($\frac{1}{6}$) over the unordered simplex.
It remains now for my investigations to incorporate the absolute separability constraint,
\begin{equation}
x_1 \leq x_3+2 \sqrt{x_2 x_4},
\end{equation}
into the integrations.


Where will they meet?

Question: A and B are running along the wall of a square park. The corners of the park are facing North, South, East and West and are named N, S, E and W respectively. They start at E and run towards S. If the speed of A is 6 times than of B, where do they meet for the 27th time?
a) between S and W
b) at S
c) between W and N
d) at N
Comment: What do they do at the park gates? :)
Answer: Since $A$ runs faster, every time he meets $B$, he will have outruned him by an extra lap. Every lap measures $4$ times the length of the square, so if $x$ is the distance $B$ runs between two encounters with $A$ then:
$6x = 4+x \Rightarrow x = \frac{4}{5}$. So when they meet, $B$ would have ran $4/5$ times the side of the square.
So the $27$th time, $B$ would have run $27·\frac{4}{5} = 21 + \frac{3}{5}$ times the length of the side of the square.
Since every $4$ times, he's back on $E$, He'll be $1+\frac{3}{5}$ lenghts after $E$, i.e. between $S$ and $W$.
Comment: How are you telling that B has ran 5/6 the length of the square wherever they meet? After that I can understand the rest, its brilliant. :)
Comment: @arijitpal2009 sorry, it was ment to be $4/5$. I've edited the answer and added the explanation of why that number.
Answer: Think of the park as a circle. We can think of the distance as degrees.
The distance A has run is 6 times longer than B's: A=6B.
When they meet, they are at the same point, but A has run significantly more degrees. Luckily, A's advantage can only consist of full rounds, so it can be said that they meet when their difference is a multiple of 360:
A-B=360k
Solving equation system (with the equation at the top): B=72k
In other words, they meet every 72 degrees B has run.
(Just take k=1 and you will see how that makes sense.)
The 27th time, B has run 1994 degrees, which corresponds to 5.4 rounds (you have to divide by 360).
$\frac{4}{10}$ of a round correspond to 144 degrees, and that is between S and W.
Answer: Another approach : Consider the unit circle $x^2+y^2=1$ and set
$$E(1,0),S(0,1),W(-1,0),N(0,-1).$$
(Note that I set these points differently.)
Then, let $6\theta,\theta$ be the counterclockwise angle of $A, B$ respectively.
$$6\theta-\theta=2\pi\times 27\Rightarrow \theta=10\pi+\frac{4}{5}\pi$$ tells us the answer is between $S$ and $W$.
Here, note that for the $m$-th meet, $6\theta-\theta=2\pi\times m$ holds.
Comment: How are you setting up the equation?
Comment: @arijitpal2009: For the first meet, we have $6\theta-\theta=2\pi$. If you understand this, then I'm sure you can understand that for the $m$-th meet, we have $6\theta-\theta=2\pi\times m$. Or is $6\theta=\theta+2\pi\times m$ better to understand?
Answer: I would set it up similarly to Darth Geek, but would call $x$ the number of laps that $B$ has covered when they meet for the 27th time. $A$ will have covered $x+27$ laps, so
$$6x=x+27,$$
and hence $x=\frac{27}5=5+\frac25$. Now noting that $\frac14<\frac25<\frac12$, we see that they will be between S and W.
Answer: For $1$ complete round by $B$, $A$ completes 6 rounds of the square park.

Now for $B$ to meet $A$ for $27th$ time, $B$ must be completing $\frac {27} {6}$
rounds that is $4{\frac{1}{2}}$ rounds or
$\text{starting from E towards S, he will be at a position -}\\$
$\text{$a)$ between $S$ and $W$ side of the park}\\$
Comment: I think you mean $4 + 1/2$ and not $4\times 1/2$
Comment: I am learning to write better. I can see that $\frac{27}{6}$ is same as $\frac{9}{2}$ or $4\frac{1}{2}$
Comment: Wouldn't half a round get him to W?
Comment: Additionally, following your calculations, to meet for the first time, B would have to run 1/6 of a round. One can easily see that that is not the case.
Comment: that is it, $B$ is about to reach $W$, while $A$ is about to complete $27th$ round, earlier he has met 26 times, and starts towards $S$ and then $W$, before coming to $N$ and $E$  for completing 27th round.
Comment: If A and B are points, they meet *exactly* at W, not before.
Comment: I feel, they meet initially just near start point, that is before point $1$ of the total $6$ divisions, then for the second time, they meet between $E$ and $S$ that is between point $1$ and point $2$ of the 6 divisions and so on
Comment: For the second time they meet between points 2 and 3 of six divisions, but making 6 divisions isn't practical. What do you mean with reputation? How would you calculate the first time they meet?
Comment: If you dont mind me asking, how do you draw mathematical figures or  write mathematical symbols here?
Comment: @arijitpal2009 See [this](http://meta.math.stackexchange.com/questions/865/how-to-learn-mathjax) and [this](http://meta.math.stackexchange.com/questions/107/faq-for-math-stackexchange/117#117).

Where will they meet?


Instances of note beams across measures

Question: How rare was it, in classical and romantic periods, for composers to notate eighth note and sixteenth note beams across measures? Are there examples from composers other than Schubert?
In two of Schubert's works (that I know of), he has beams between eighth notes across measures.
In "Letzte Hoffnug" from Winterreise (IMSLP):

From the fourth movement of his second piano trio (IMSLP):

In both cases, it is obviously an attempt to bring out the syncopation.
I am assuming this is Schubert's notation, because it is in various versions of these scores I've checked in IMSLP, but it could be that these are all publisher notations. (Presumably, at the end of the line of the Winterreise example, the notator would have preferred putting a beam on the last C flat, extending to the next measure on the next line, but had no ability to typeset a "half bar?")
I've seen this done in a few 20th century pieces, but I'm honestly more of a Schubert-phile, so I haven't seen nearly as many scores from other composers from the classical and romantic periods. Enough to know it isn't common.
But how rare was this during these periods, before and after Schubert? Are there examples from major compositions that I just don't know about due to my narrow score-reading?
Comment: Typesetting has been used to produce musical scores and parts since around 1500.  Petrucci had a process that required multiple impressions: staves, notes, and text were printed separately, so it was necessary to pay a lot of attention to precise alignment.  This proved difficult and did not persist. Later in the 16th century, movable type became popular, leading to staves with telltale gaps between the pieces.  This method was popular in 17C Italy and Germany, but examples may be found (especially hymnals, popular songbooks) into the 19C or early 20C.
Comment: These scores were engraved, not typeset.  You can engrave anything you want.  They may well just have decided that it wasn't possible to make it look good.
Comment: Copper plate engraving seems to have been popular first in France, but by the late 18C it was the dominant way of printing music.  In the notation here the note heads and letters were actually stamped into the plate rather than engraved.  There's a video of the engraving process on [the Wikipedia page](https://en.m.wikipedia.org/wiki/Music_engraving).
Comment: Interesting. The printed scores I've seen seem so regular,  I assumed some advanced type-setting. As a mathematician (by nature, if not profession,) I am well aware of the ways that typesetting limited printed notation, and assumed music had the same limitation.
Comment: I might be off here, but personally I would write the two examples in 6/8 instead. The beat seems to be two beats per bar and this would fit better with note beams over 3 eight notes instead.
Comment: If all the music was like this, you might be right, @ghellquist  But the song, even though the singer is singing eight notes often, is mostly singing strong vowells/words in 3.
Comment: @ghellquist But the trio movement is actually in 6/8. But the bars across measure indicate which of the pairs of notes should be stronger, so Schubert is accenting the off notes, whether in 3/4 or 6/8.
Comment: @Thomas Andrews  Guess I was off then. Should have known better than "improve" on Schubert. Willing to learn though, and continues to do that.
Answer: I wouldn't consider it to be rare in the Romantic period - it's not in every piece, but it shows up fairly frequently; it didn't take me long to find instances in Chopin (Etudes Op.10, No.3):

in Liszt (Reminiscences de Norma):

or in Brahms (Variations on a theme of Paganini):

It's rarer in the pre-Romantic periods, but it still happens. You can find multiple instances of it in Beethoven - reproduced from early editions on IMSLP below, but visible in the first editions uploaded there as well:
Symphony #8, second movement:

Piano sonata #7, second movement:

so it isn't an invention of Schubert. I wouldn't be surprised to see instances of it earlier than Beethoven either, but I haven't found any so far.
Comment: Thanks, these are exactly the kinds of examples I was hoping to see.
Comment: One tip: NEVER beam notes across the barline! Always beam them according to the time signature.
Answer: I don't have a great gauge on how rare beaming across measures was in all Romantic-era music - I do have a strong feeling it was pretty much nonexistent in Baroque and Classical-era music due to their relative lack of syncopation! - but since I wasn't familiar at all with your Schubert examples of beaming across measures despite having seen cross-measure beaming before, I suspect beaming across measures is rare but not unheard of in Romantic-era music.
The first example that popped into my head is the 3rd movement of Alexander Scriabin's Piano Sonata No. 1 in F Minor, Op. 6, which starts off with an 8th note beamed across measures and retains this cross-measure-beaming habit persistently (IMSLP):

A second example is the 1st movement of Charles-Valentin Alkan's Grande Sonate "Les Quatre Ages", "20 ans", which doesn't take long before it uses cross-measure beaming (IMSLP):

I suspect cross-measure beaming is even more common in 20th-century works, albeit still rare: the Music Stack Exchange question Why are notes beamed across the barline in this piece? amusingly brings up a second example of cross-measure beaming, this time by Igor Stravinsky in his Three Pieces for String Quartet:
Comment: I would not use "lack of syncopation" and "classical-era music" in the same sentence.  Syncopation was also prominent, if less so, in baroque music.  But beaming was less standardized, so I wouldn't be surprised at all to see beams crossing bar lines in baroque music.
Comment: Thanks. 20th century examples are not surprising to me - a lot more metric changes and variation start occurring in the 20th century. I don't look at a lot of 20th century scores (fewer freely available online,) and I've still seen a few examples.
Comment: @Dekkadeci: Why 'amusingly' btw?
Comment: @phoog - Ah, now I recall the infamous syncopated opening of the 1st movement of Mozart's Symphony No. 25 in G minor. I'll edit that sentence a little.
Comment: @Dekkadeci and of Mozart's Requiem, and of many other examples.  But these usually do not go over the bar line.  On reflection, I think the beams I recall seeing in baroque music were in vocal music, where beaming is used to show text underlay (even then usually not crossing the bar line, but I believe I've seen some examples where it did).
Answer: I suspect you're right that it was Schubert's innovation rather than his publisher's. (Do publishers innovate?) A way to bring out the syncopation, as you say, or to make the phrasing more emphatic. But it can also be a way to make it fun for the performer(s): something composers try to do more often than is mentioned. (It seems to me something Beethoven considers, for example.)
I'd be surprised to hear of an earlier composer than Schubert doing cross-bar beams.
The end of the Polovtsian Dances popped into my head.

The last movement (marked 'Allegro di molto') of Haydn's 'Surprise' symphony shows how earlier composers might 'spell' a passage to achieve a syncopated result without using cross-bar beams.
Comment: @yo': Haha. Yes. _That_ kind of innovation I _have_ seen. And their letters of apology: 'But we thought that was what you _meant_'. Paul Dessau's music for The Caucasian Chalk Circle is littered with the words, "Not a mistake!"
Comment: I will add, so much of Schubert was published after his death, publisher tinkering would have had no resistance. His G flat impromptu was transcribed and published in G for a whole generation before it was published in Schubert's original key. But I suspect we have enough originals that, if this weren't Schubert's notation, it would have been changed in more modern versions.
Comment: Publishers _do_ innovate, unfortunately (for the most part).
Comment: @yo': Could you mention some examples? A few years ago most of them were using Sibelius.
Comment: @OldBrixtonian Sibelius is an image editor with some music-related layout engines built in. It's not restrictive enough to limit innovation overmuch. (Lilypond might be, but even then, you can do some weird things.)
Comment: @wizzwizz: I've been  using Sibelius since it first appeared: long before it went to **The Dark Side**. I know what it can do. Innovations in Sibelius - and it seldom comes up with any - aren't really the _publishers'_. Composers had more freedom in the days of transparencies. They could make their scores visually interesting: great swirling staves etc. I'm not sure how publishers would reprint works of that kind today, but then they don't get performed today so why _would_ they? (Yes alright: I'll take one of my pills!)
Comment: Oh I meant "innovate" as in "typeset the music differently than the author intended". I saw a few times something done to a music sheet that the author would have never done. To name one: There are sheets of Bach's music that include tempo marks (written in numbers. I don't mean "Grave", "Allegro", etc. -- these are not tempo marks.) It's just a rant.

Instances of note beams across measures


Is there any foreign players represented Ireland in county series

Question: Has any overseas player played for Ireland in matches against English County Sides prior to their admission as a full member of ICC.
Comment: Hi Madhawavish could you confirm do you mean did Ireland have an overseas player when they played Counties in England or something else ?
Comment: @ Ben Whyall yes it's
Answer: As this article suggests, a number have done it in the past when Ireland were not at the level they now play at.
Comment: Once the vague statement is accounted for, this is a link-only answer. Please include your own description of the players you claim to match the condition in the question.


Combination with repetition and no order.

Question: I'm looking for a way to calculate the number of combination of 10 choose 5 => $_5^{10}C$ while allowing any number repetitions and counting 12345 and 54321 only once (order isn't important, ie I count 11355 but not then 35115).
I think this number is majored by $10^5$, but how to remove ordering number ?
Comment: Check "combinations with repetitions" http://users.telenet.be/vdmoortel/dirk/Maths/PermVarComb.html
Comment: @aPaulT I accept both. But I include 11355 but no then 35115 (you may make a mistake on your example)
Comment: Such counting of multisets is possible by the standard "stars-and-bars" method, c.f. the duplicate [How to find unique multisets of n naturals of a given domain and their numbers?](http://math.stackexchange.com/questions/17083/how-to-find-unique-multisets-of-n-naturals-of-a-given-domain-and-their-numbers)
Comment: Would it be just $\left(\begin{array}{c}50\\5\end{array}\right)$?
Comment: Does "allowing any number repetitions" mean you're including, for example, 11355 (but not then also 35153)?
Comment: @EpicGuy Are you sure ? I thought it should be lower than $10^5$
Comment: @Fractaliste Well isn't just choosing 5 numbers from the set: $1,1,1,1,1,2,2,2,2,2,...,10,10,10,10,10$?
Comment: @SJuan76 That's an interesting table to know, thanks !
Comment: Quite right Fractaliste, I did mess up my example. @EpicGuy Your method, for example, counts '11112' twenty-five times (because it counts each of the ways of picking four of the five 1s in your list separately, and for each of those it then counts the five ways of picking one of the five 2s).
Comment: @EpicGuy : it's an interesting way to understand the problem, but the result is far over the expected result. And I'm not able to see the mistake (if there is one). I'm going to think about it !
Comment: @EpicGuy: this is wrong. Notice that you're counting $5,5,5,5,4$ 25 times, for instance.
Comment: @tomasz I am using combinations and I don't get how you got 25 times.
Comment: @EpicGuy: you have 5 copies of $5$ and 5 copies of $4$. So you can draw $\{5,5,5,5,4\}$ in $\binom 5 4\cdot \binom 5 1$ ways.
Comment: ok I realise my mistake thanks for pointing it out
Answer: (Note: I'm using the notation $\binom{n}{k}$ here instead of $^n_kC$.)
A multiset is a collection of things that allows repetition but ignores order. The number of multisets of size $k$ with elements from a set of size $n$ is
$$\left(\!\!\binom{n}{k}\!\!\right) = \binom{n+k-1}{k} = \frac{(n+k-1)!}{k! (n-1)!}.$$
In your case, you'll have $\left(\!\!\binom{10}{5}\!\!\right) = \binom{10+5-1}{5} = 2002$.
Comment: The answer $\binom{14}{5}$ is given by [the standard "stars-and-bars" method](http://math.stackexchange.com/q/17083/3111).  Arrange nine "bars" (separators) and five "stars" (placeholders for elements of multisets) in a line.  Any items to the left of the first bar are counted as zeros; items between the ith and i+1st bar are counted as i's; items after the ninth bar are 9's.
Answer: Since order doesn't matter, we can consider results as different if they differ after sorting.
In other words, when order doesn't matter, generate the results with inherent sorting.
If you build a table, 5 slots wide and 10 slots high, and trace all paths from bottom left to somewhere on the right edge, but only allow paths to go 1 step right and never go down, then a clear pattern emerges. The right hand side of this tabel contains 1,5,15,35.. or (n+3) choose 4. The sum at the right edge is 2002 or 14 ch 5.
The diagonals are Pascal's triangle.


How to estimate False Discovery Rate from p-value distribution?

Question: I have learned many models and I calculated p-values for the cross-validation errors. I want to select significant models based on the false discovery rate (FDR). How can I estimate the FDR from p-value distribution?
Comment: I strongly recommend looking at Andrew Gelman's writings on this. Most statisticians would argue that the true false discovery rate is *always* 0%, because the null hypothesis is always false.
Comment: Why are you trying to estimate the false discovery rate? What's your goal in your study? Are you trying to adjust for multiple comparisons?
Answer: Generally speaking, the false discovery rate correction requires ranking your p-values and then computing a critical value (based on the false discovery rate) that you can compare to your p-values. This website gives a very concrete example: here.
If you're using R, then it's even easier to do the adjustment. The following code is a quick example:
pvals <- c(0.04, 0.03, 0.06, 0.01, 0.02, 0.003)
p.adjust(p = pvals, method = "BH")

In the above code, the object pvals is a list of the p-values that you obtained from your analyses. The function p.adjust provides several different options for adjusting p-values based on multiple observations. In this case, the false discovery rate adjustment can be done by specifying method = "BH" for Benjamin-Hochberg or method = "fdr" for false discovery rate (note: they are the exact same procedure and will give the exact same results).


Postfix rejecting inbound mail to virtual mailboxes

Question: I followed this tutorial to setup an email server that uses virtual users. https://www.rosehosting.com/blog/mailserver-with-virtual-users-and-domains-using-postfix-and-dovecot-on-a-centos-6-vps/
I am able to send emails, but when i try to send an email to one of the virtual mailboxes i get the following error in the maillog.

Recipient address rejected: User unknown in virtual mailbox table;

Based on the research ive done it appears that this line is the cause. Specifically "reject_unauth_destination".
> smtpd_recipient_restrictions = permit_mynetworks,permit_sasl_authenticated, reject_unauth_destination

I tried removing the "reject_unauth_destination" value and i then get the following error.

fatal: in parameter smtpd_relay_restrictions or
  smtpd_recipient_restrictions, specify at least one working instance
  of: reject_unauth_destination, defer_unauth_destination, reject,
  defer, defer_if_permit or check_relay_domains

Anyone know what i can do to fix this error. I can log into the account just fine and send mail. Everything seems fine except for this rejecting of emails.
Here is a full copy of my main.cf postfix file.
queue_directory = /var/spool/postfix
command_directory = /usr/sbin
daemon_directory = /usr/libexec/postfix
data_directory = /var/lib/postfix
mail_owner = postfix
unknown_local_recipient_reject_code = 550
alias_maps = hash:/etc/postfix/aliases
alias_database = $alias_maps

inet_interfaces = all
inet_protocols = ipv4
mydestination = $myhostname, localhost.$mydomain, localhost

debug_peer_level = 2
debugger_command =
         PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
         ddd $daemon_directory/$process_name $process_id & sleep 5

sendmail_path = /usr/sbin/sendmail.postfix
newaliases_path = /usr/bin/newaliases.postfix
mailq_path = /usr/bin/mailq.postfix
setgid_group = postdrop
html_directory = no
manpage_directory = /usr/share/man
sample_directory = /usr/share/doc/postfix-2.6.6/samples
readme_directory = /usr/share/doc/postfix-2.6.6/README_FILES

relay_domains = *
virtual_alias_maps=hash:/etc/postfix/vmail_aliases
virtual_mailbox_domains=hash:/etc/postfix/vmail_domains
virtual_mailbox_maps=hash:/etc/postfix/vmail_mailbox

virtual_mailbox_base = /var/vmail
virtual_minimum_uid = 2222
virtual_transport = virtual
virtual_uid_maps = static:2222
virtual_gid_maps = static:2222

smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noanonymous

smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated
smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated

smtpd_milters = inet:127.0.0.1:8891
non_smtpd_milters = $smtpd_milters
milter_default_action = accept
milter_protocol = 2

I have added records to the 3 vmail files to configure the account
 vmail_domains - mydomain.com OK
 vmail_mailbox - firstname.lastname@example.com mydomain.com/dan/
 vmail_aliases - email@example.com email@example.com

Comment: the error is very clear, did you used postmap? try postmap -q email@example.com hash:/etc/postfix/vmail_mailbox
Comment: use postmap /etc/postfix/vmail_mailbox and service postfix restart and try again
Comment: you populated virtual_mailbox_domains(using your domain) and virtual_mailbox_maps(your user mail) and after postmap and restart or reload postfix?
Comment: i have added a section that shows what i have added to vmail_comains, mailbox and aliases for the email account im currently trying to setup
Comment: the email is already in the vmail_mailbox file and i ran postmap too. When i ran it using the command listed i got the following error. Maybe the DB isnt getting corretly updated? postmap: warning: database /etc/postfix/vmail_mailbox.db is older than source file /etc/postfix/vmail_mailbox

Looking at the timestamp i can see that vmail_mailbox.db hasnt been updated in over a month. It seems postmap isnt writing to this db anymore
Answer: the error is very clear, did you used postmap? try postmap -q firstname.lastname@example.com hash:/etc/postfix/vmail_mailbox.
for solving your problem you need to use "postmap /etc/postfix/vmail_mailbox and service postfix"
If you are using hash table in postfix, every time you change the text file you need to use postmap on the files to regenerate the db files.


Understanding modes

Question: For some time I've been trying to understand modes. - I've read myriad posts, debates, and explanations, and have generally been left confused. But - I think I finally have a handle on it. Can anyone tell me if what I have below is correct, or incorrect?
What we call modes came from something called modal music. Most 20th century music, with the exception of some jazz starting in the 1950's is tonal, rather than modal music. For brevity, I won't discuss the difference, but I think it suffices to say that most current musicans don't need to be concerned with modal music. (I said MOST, not ALL.)
However - just because you're not playing modal music, doesn't mean you can't use modes! For most musicians, the 7 modes (Dorian, Mixolydian, etc.) can be considered scales which can be used (in the right situations), just like any other scale.
What is the best way to learn the modes, as used in tonal music? Just like any scale, they should be considered in the context of the harmony. But here I will only address how to best learn the fingerings of these scales, on guitar.
Many posts suggest that to find the fingering for a mode, take a major (or minor) scale and start it on a different note. After reading much discussion about this, I've concluded this is a waste of time, and is simply a shortcut which confuses people and misses the essential point: each mode has a different sequence of intervals which gives it its particular flavor.
So to learn the fingering of a mode, just learn the intervals, just like any other scale. I do it by categorizing each mode as either major or minor (whichever one it's closest to), then figure out which intervals are different between the mode and the major (or minor) scale it's based on. I then play the modified major (or minor) scale. For example, for A Dorian, I play an A minor natural scale, but raise the 6th a half step. I practice this all over the fingerboard.
There is much more that could be said of course, but I want to keep it simple for those of us that are just starting to learn.
Comment: I'm voting to close this question as off-topic because it's more of an answer than a question.
Comment: Would this be better posted as an answer to some mode question, as it's hardly a question, in its own right?
Comment: What is the question? It would be better to have just the question in the question, and answers in answers. Or are you trying to reverse the logic, have one answer and multiple questions for it? ;)
Comment: its not truly a question, but it is a good answer. I struggled with modes for ages. I just think of Dorian as the "right" scale to play under a II chord.
Comment: @bigbadmouse - I think of Dorian as the 'right' scale to play over a **ii** chord!!
Comment: My question is - is everything I wrote correct? (Stated in the first paragraph.) But understand if people want to close this is a non-question.
Comment: What you could do, @MichaelLee, is post a question, the self-answer that question using the content of this post here.
Comment: @tim yes, but thats because I am *a bass player*. I think in terms of "movement under"
Comment: @bigbadmouse - I, too am a bass player, taught it for many years, too. Never really consider 'movement under', especially referring to modes. Far more likely to use prevalent chordal notes, and movement up or down to the next chord (you know, b7, or tts sort of things). And of course, meshing in with drums in particular, when I have a good drummer... Care to elucidate?
Comment: I've edited my post to make my question more clear. If acceptable, can the person who downvoted please remove their downvote?
Answer: There are really only two ways to regard and understand modes.
One is, as you prefer, to consider each mode as a separate entity, with its own set of notes and flavour, and learn each 'scale' for each mode, which is then movable (on guitar especially) to start on each of the 12 different roots.
The other is to think about one particular major (in this case) key, and thus its scale notes. That's the parent key/scale, and the other six modes which it spawns are all using the same set of notes, but each with a different root. So once one has learned a major scale, one uses exactly the same notes, but starting on a different one from the original parent root. so Dorian will go from note 2 to note 9, so to speak.
I think anyone learning modes will find one better for understanding than the other - intrinsically, they're both valid, and once one has digested the one concept, it's easier, and worth while, starting on the other.
Answer: In German we have the to names for scales called:
absolut names: a,b,c and relative names:  do,re,mi (movable do!)
May be the introduction of "relative names" could be confusing as you understand something different under relative, for this I write it italic. *1)
But this concept of movable do ("relative" -> that is referring to the root key!) is most useful to understand the modes:
there is a "relative" scale existing of 2 equal tetrachords wwh (w) wwh, note that the 2 tetrachords are separated by a whole step (tetrachord = 4 strings -> 4 degrees I ii iii  IV - V vi vii I)
So you can make a scale of a movable do (do,re,mi,fa,so,la,ti,do)  that you can underlay to every of the 12 keys: (sharp and flat).
the modes are nothing else than the 7 scales that we get if we begin with another root note of the do re mi.
do = ionian
re = dorian
mi = phrygian
etc.
finally this concept is quite similar to the intervals but it is historical derived from the church modes (middle age) and their root tones names that have been used since Guido of Arezzo.
As we first learn to sing with the do,re,mi (s. Aristocats) or baby songs and folk songs, it is very easy to apply this concept to a) to the 7 church ladders and then to all other 12 keys.
*1) I don't know if related or referring names would be less confusing?
Comment: The church had 8 modes, in four pairs of authentic and plagal modes, such as Dorian and Hypodorian.  The plagal modes differed from the authentic modes in their range rather than in the set of pitches in use.  Their names were all constructed by prefixing "hypo" to the name of the related authentic mode.  The authentic modes gave their names to the modern modes; they are Dorian, Phrygian, Lydian, and Mixolydian.  The Aeolian and Ionian modes were invented in the 16th century; the Locrian was invented in the 18th century.  Not all of the modern modes have been used since Guido of Arezzo.
Answer: Group together mode and key as types of tonalities.
Treat scale as tonleiter the German word for scale meaning tone ladder, all the tone of the tonality going up or down in step-wise order.
Mode can also have the meaning of the various rotations of a scale: ex. the seventh mode of the melodic minor scale is the altered scale.
Don't confuse mere scales with being in a mode. For example...

...the music is clearly in C major. The passage starting at m. 5 is not the right hand playing in Aeolian, Mixolydian, and the Lydian modes. The mode of the music is not changing. It stays in C major. Describing the passage as a series of mode change really misses the point.
The series of scales is not about changing mode. It just a rhythmic elaboration of this...

...in terms of mode the passage is doing only one thing: affirming the mode is C major.
The main perpetrator of this way of thinking - scalar passages are actual mode changes - is probably the jazz "chord scale system". In that system when given a progression like Dm7 G7 C6 you are told to play Dorian, Mixolydian, and Ionian scales respectively over each chord instead of identifying C: ii V7 I and learning how to play a harmonious part over it.

...for A Dorian, I play an A minor natural scale, but raise the 6th a half step...

I agree. A good way to conceptualize the modes is grouping them in major and minor families and then altering tones from so-called Ionian or Aeolian to get the other modes.

Most 20th century music, with the exception of some jazz starting in the 1950's is tonal, rather than modal music. ...most current musicans don't need to be concerned with modal music.

I think you should be careful here. Tonal just means music organized around a central tone. In the sense that modes have tonics, then modal music is tonal. Music with no tonal center is atonal.
I think current musicians DO need to be aware of modal music, because tons of popular and audience-accessible music is modal. Folk and Americana are heavily modal. Rock has important modal elements definitive of the style. Many essential jazz tunes are modal.
Comment: With regard to "tone ladder" it's worth noting that "scale" derives from the Latin word for "stairway."  The German is probably just a translation of that.
Answer: Reading between the lines, I suspect I come from a similar background to you -- jazz / rock / pop music probably played on guitar. I agree with pretty much everything you said.
For the likes of us (if I haven't misidentified you!) I think what you say here is the key:

So to learn the fingering of a mode, just learn the intervals, just like any other scale. I do it by categorizing each mode as either major or minor (whichever one it's closest to), then figure out which intervals are different between the mode and the major (or minor) scale it's based on. I then play the modified major (or minor) scale. For example, for A Dorian, I play an A minor natural scale, but raise the 6th a half step. I practice this all over the fingerboard.

Yes! The Dorian scale is just a scale. You can think of it as a natural minor scale with a raised sixth. It's no different to thinking of Harmonic Minor as natural minor with a raised seventh. You're doing the right thing.
The idea of "modality" arises when you notice a weird coincidence: the A Dorian scale ends up having the same notes as the G Major scale. This also means they contain the same intervals in the same order (but "starting from a different position"), and this means they probably share important sonic properties. But this is a matter of somewhat deep theory. It's not a helpful "short-cut" for students -- witness the approximately infinite number of internet posts from confused students who've been shown this too early -- and may or may not be of any practical value to a particular musician.
I studied jazz and rock guitar in the 1980s, when modes were all the rage. Your approach is the one I eventually arrived at, after some wasted time early on, and one I've seen widely advocated among modern guitar teachers.
(Note all this is ignoring the history, which supposedly stretches back through the medieval period to Boethius and ultimately the ancient Greeks. In reality, what modern musicians mean by "modes" is indeed mostly a 20th century invention. For example, it only becomes fully operational with the dominance of 12TET as a tuning system.)

Understanding modes


Roots of polynomial equation in geometric progression

Question:
Find the relation between $a, b, c, d$ if the roots of $ax^3+bx^2+cx+d=0$ are in geometric progression.
By considering $(\alpha+\beta)(\beta+\gamma)(\alpha+\gamma)$ show that the above cubic equation has two roots equal in size but opposite in sign if and only if $ad=bc$.

I can do the second part if I am given some hints on the first. I can use $\beta$ as the middle root and make $\alpha=\beta/r$ and $\gamma=r \times \beta$, but haven't got anywhere so far.
Answer: The monic polynomial with roots $\beta/r,\beta, r\beta$ is
$$ x^3-\beta\left(1+r+\frac1r\right) x^2+\beta^2\left(1+r+\frac1r\right)x-\beta^3$$
We find $\beta=-\frac cb$ and $\beta^3=-\frac da$, hence
$$db^3=ac^3$$
as necessary condition. Why is it also sufficient? What additional condition(s) would we need if we wanted the roots to be real?
Answer: If $\alpha, \beta, \gamma$ are the roots of $ax^3+bx^2+cx+d=0$
Using Vieta's Formulas,  $$\alpha+\beta+\gamma=-\frac ba, \alpha\beta+\beta\gamma+\gamma\alpha=\frac ca,\alpha\beta\gamma=-\frac da$$
If $\alpha,\beta,\gamma$ are in Geometric Progression, $\frac\beta\alpha=\frac\gamma\beta$ is constant $=r$(say).
Clearly, $\alpha r\ne 0$
$\implies  \beta=\alpha r, \gamma=\beta r=\alpha r^2$
$$\implies \alpha+\alpha r+\alpha r^2=-\frac ba\implies \alpha(1+r+r^2)=-\frac ba$$
$$\alpha\alpha r+\alpha r\alpha r^2+\alpha r^2\alpha=\frac ca\implies \alpha^2 r(1+r+r^2)=\frac ca$$
$$\alpha\alpha r\alpha r^2=-\frac da\implies \alpha^3 r^3=-\frac da$$
So, $$\frac{\alpha^2 r(1+r+r^2)}{\alpha(1+r+r^2)}=\frac{\frac ca}{-\frac ba}\implies \alpha r=-\frac cb \text{ if }1+r+r^2\ne0$$
Then, $$\left(-\frac cb\right)^3=-\frac da\implies b^3d=c^3a$$
If $1+r+r^2=0,$
$b=c=0$
and $r=\frac{-1\pm\sqrt3}2$ i.e., r is a complex cube root of $1$
So, the equation reduces to $ax^3+d=0$ whose roots are $\left(-\frac da\right)^\frac13,\left(-\frac da\right)^\frac13r, \left(-\frac da\right)^\frac13r^2$.
So, we don't find any relationship among $a,b,c$ and $d$ here.

In the 2nd case, let us find the equation whose roots are $\alpha+\beta,\beta+\gamma, \gamma+\alpha$ using the Transformation of Equations.
If $y=\alpha+\beta=\alpha+\beta+\gamma-\gamma=-\frac ba-\gamma\implies \gamma=-\left(y+\frac ba\right)$
As $\gamma$ is a root of the given equation, $-a\left(y+\frac ba\right)^3+b\left(y+\frac ba\right)^2-c\left(y+\frac ba\right)+d=0$
On simplification, $$ay^3+(\cdots)y^2+(\cdots)y^2+\frac{bc-ad}a=0$$ whose roots are $\alpha+\beta,\beta+\gamma, \gamma+\alpha$
Using Vieta's Formulas again, $(\alpha+\beta)(\beta+\gamma)(\gamma+\alpha)=\frac{ad-bc}{a^2}$
If among $\alpha,\beta,\gamma$ two have same absolute value but opposite sign, $(\alpha+\beta)(\beta+\gamma)(\gamma+\alpha)=0\implies ad=bc$ (the condition is necessary)
Sufficiency: Again, if $ad=bc,$ $\frac ab=\frac cd=t$(say,) so $a=bt,c=dt$
Then the equation becomes $$btx^3+bx^2+dtx+d=0\implies bx^2(tx+1)+d(tx+1)=0$$
So, $$(tx+1)(bx^2+d)=0$$ One root is $-\frac1t$ What about the others?
Comment: $x=\sqrt{-d/b}$ which is not really $1/t$, the thing we need?
Comment: @user52187, I left it for you to find the two roots other than $-\frac1t=-\frac ba=-\frac dc$ to prove the proposition  as it is after all a 'homework'.
Comment: So is what I wrote incorrect?
Comment: @user52187, no. You are right when you say $\frac1t\ne \pm\sqrt{-\frac db}$. But 'homework' is not supposed to be answered fully here as my last comment has pointed out.
Answer: Suppose $a \not = 0$ , let $p=\frac{b}{a},q=\frac{c}{a},r=\frac{d}{a}$, then the equation is $$x^3+px^2+qx+r=0$$
Using Vieta's Formulas,$$\alpha + \beta + \gamma=-p \\ \alpha \beta + \beta \gamma + \alpha \gamma =q \\ \alpha \beta \gamma = -r$$Suppose $\beta^2=\alpha \gamma$, we get $$q^3=p^3r$$that is $$\left \{ \begin{array}{l} ac^3=b^3d \\ a \not = 0 \\ d \not = 0 \end{array} \right.$$
Now we prove it is sufficient.
$$q^3-p^3r \\ =(\alpha \beta + \beta \gamma + \alpha \gamma)^3-\alpha \beta \gamma(\alpha + \beta + \gamma) \\ = \alpha^3\beta^3+\alpha^3\gamma^3+\beta^3\gamma^3-\alpha \beta \gamma(\alpha^3+\beta^3+\gamma^3) \\ = (\alpha^2-\beta \gamma)(\beta^2-\alpha \gamma)(\gamma^2-\alpha \beta) \\=0$$
So the roots are in geometric progression.


conjugate function of log trace of matrix exponential

Question: Given an n-by-n real symmetric matrix X, define
$$e^X = \sum_{k=0}^{n}\frac{X^k}{k!}$$
Derive the Fenchel conjugate of
$$f(X) = log(Tr(e^X))$$
as a function on n-by-n real symmetric matrices. Here Tr denotes the trace function.
Answer: By definition, the Fenchel conjugate of $f(X)$ is given by:
\begin{equation}
\label{eq:f}\tag{1}
f^{*}(Y) = \sup_{X} X\circ Y - f(X).
\end{equation}
It can be shown that $g(X) \overset{\text{def}}{=} X\circ Y - f(X)$ is a concave function in terms of $X$.
(Actually, you can use the second derivative of $f(X)$ with respect to $X$ to show that $f(X)$ is a convex function.)
To compute the supremum of $g(X)$, we take derivative of $g(X)$ with respect to $X$, we have
\begin{equation*}
\begin{aligned}
Y= \frac{(\exp X) }{\text{Tr} (\exp X) }.
\end{aligned}
\end{equation*}
Thus, $I\circ Y=  1$ and $y_{ii}>0$ for $1\le i\le n$.
Using the fact $\log (AB) =\log (A)  + \log (B) $ if $AB=BA$, it follows that
\begin{equation}
\label{eq:y}\tag{2}
Y = \frac{(\exp X) }{\exp f(X)} \implies \log Y + f(X) I  =  X.
\end{equation}
Substitute \eqref{eq:y} into \eqref{eq:f}, we have
\begin{align}
\label{eq:f:final}
f^{*}(Y) & = (\log Y + f(X)  I  ) \circ Y - f(X)\notag \\
& = \log Y \circ Y + f(X)  I \circ Y - f(X) \notag\\
& = \log Y \circ Y. \tag*{using $I\circ Y=  1$.}
\end{align}
Comment: This is a very good answer!


How to set password for file in Google App Script?

Question: I sent a link file via mail to someone in the google app script. I want to ask is there any way to set password for file in google app script? When users enter the link will ask to enter the password.
(sorry, my english is not good)
Answer: Based from this thread, there is no password in Google class yet implemented. You can file this as feature request in this link.


Understanding formula for Short Term / Long Term Degrees of freedom in minitab

Question: Now I'm new to statistics, but the last time I did degrees of freedom, the formula I used was
$df = n-1,$
but I've just been playing with Minitab and reading the help to files, and I noticed it is calculating long-term and short-term degrees of freedom like this:
$df(LT) = \sum_{i=1}^j n_j-1$
$df(ST) = \sum_{i=1}^j (n_j-1)$
I interpret it like this:
Data (1 group): 20, 10 ,10, 23, 25, 20
$df(LT) = (20+10+10+23+25+20) - 1$
$df(LT) = 108$
and
$df(ST) = ((20-1)+(10-1)+(10-1)+(23-1)+(25-1)+(20-1))$
$df(ST) = 102$
I have got this right, or am I way out?
UPDATE:
Looking around other help files, I found that
$n_j$ is the number of obervartions in the jth subgroup.
So with that in mind, and my example with only 1 subgroup, I assume that both LT and ST are the same, which is $n - 1$.
Comment: Does 20, 10 ,10, 23, 25, 20 represent how many observations are in each group, or the dependent variable? Normally n refers to how many observations is in a sample.
Comment: dependent variable, there is only 1 group.
Comment: I'm not sure why they'd have a subscript j if there's only 1 group. Maybe if you posted up where these formulas were found other people might be able to help.
Comment: You can have many groups, but my data only has 1. Just about to update with more info.
Answer: You are close, but off the mark. While "long-term" and "short-term" are new to me (indeed, they seem to be specific to this site and might as well come with a trademark!) I can tell you that you seem to be calculating the whole-sample variance degrees of freedom (LT) and the anova denominator degrees of freedom (ST), which could also be described as the mean squared error (MSE) degrees of freedom.
To be clear, the values of $n_i$ are the number of measurements in group $i$, not the actual measurements. The total number of measurements $n$ of data acquired from $J$ groups is $$n=\sum_{i=1}^J n_i.$$ The LT degrees of freedom seems to be $n-1$, which would be the number used in the unbiased estimate of the whole-sample variance $$s^2=\frac{1}{n-1} \sum_{k=1}^n(x_k-\bar{x})^2.$$ Here the $x_k$ does correspond to the actual data, and $\bar{x}$ is the whole-sample mean, sometimes called the grand mean.
The short-term degrees of freedom correspond to $n-J$, which is the total number of points acquired minus the number of groups (or treatments) $J$. This would be the degrees of freedom used in calculating the variance within treatments for the group-wise model.
$$
MSE = \frac{1}{n-J} \sum_{i=1}^J \sum_{k=1}^{n_i} \left( x_k^{(i)}-\bar{x}^{(i)} \right)^2,
$$
where $i$ is the index for $J$ treatments or groups, $x_k^{(i)}$ is the $k$-th data point in group $i$, and $\bar{x}^{(i)}$ is the sample mean of the $i$-th group. This would be the denominator of the F test of equal means of $J% groups, and $n-J$ would be the denominator degrees of freedom.

I see that the Minitab page uses $\mu$ to describe a sample average. Argh! This is highly non-standard notation. Greek letters are (nearly-universally) reserved for population parameters, not sample statistics. The (nearly-universally) recognized notation for a sample statistic is the Roman letter. In this case, the sample average is $\bar{x}.$ Hopefully you are not confused by this nonstandard notation. Population parameters are only ever estimated by sample statistics. They themselves are not statistics, at all.
Comment: Perfect!, thank you. The doucmentation is not great as I am finding more details about the mathmatical notation in various documents.


Arrangement of letters in VISITING with no pairs of consecutive Is.

Question: Could someone help me understand a book's solution to the following problem?  I am providing my own solution, but I fail to understand theirs.
Question:

How many ways are there to arrange the letters in VISITING with no
  pair of consecutive Is?

My Solution:

There are three Is and five other letters.  I first arrange the five other letters with a space between each one, in the beginning and in the end.  There are $5!$ ways of arranging them:  _X_X_X_X_X_
The previous step creates six empty places in which three Is may be arranged, but only three places must be chosen.  Order does not matter, as all three Is are the same.
Thus, there are $\dbinom{6}{3}$ ways of choosing those places.

My Answer: $5!\cdot\dbinom{6}{3}$
Book's Answer: $\dbinom{(5-2)+4-1}{(5-2)}\cdot5!$
Both answers yield the same numeric result of $2400$, but I don't fully understand their answer or rather how they achieved it.  I'm sure in fact that the second part, $5!$, is the arrangement of five other letters, other than Is.  This leaves the first part of the answer, which is selection with repetitions.  I do not know what $(5-2)$ and $4$ parts represent, especially $4$.
Comment: I like your method better; it's simpler.
Answer: A gentleman on ##math freenode IRC channel was kind enough to explain this to me, so here's the solution for anyone wondering:
Solution:

Arrange three Is such that there is at least one place for other letters between each one: _I_I_I_
Based on that arrangement, there are a total of four places where other letters may be placed, but there must be at least one letter in each of the two middle spots marked by X: _IXIXI _
Since there were five letters other than I to begin with and two of them must be placed in those two marked spots, it leaves three letters to be distributed between the four positions around Is $\dbinom{3+4-1}{3}$
Since the first step was picking the spots, we now must arrange the five letters between those spots and there are $5!$ ways of doing so.
Answer: $\dbinom{3+4−1}{3}\cdot5!$ or $\dbinom{(5-2)+4-1}{(5-2)}\cdot5!$
Answer: Here's one more solution, and solves the general kind of pattern avoidance.
Construct a matrix
\begin{align*}
 A &= \begin{array}{|l|rrrrrr|}\hline
 & \mathrm{V} & \mathrm{I} & \mathrm{S} & \mathrm{T} & \mathrm{N} & \mathrm{G} \\ \hline
\mathrm{V} & v & i & s & t & n & g \\
\mathrm{I} & v & 0 & s & t & n & g \\
\mathrm{S} & v & i & s & t & n & g \\
\mathrm{T} & v & i & s & t & n & g \\
\mathrm{N} & v & i & s & t & n & g \\
\mathrm{G} & v & i & s & t & n & g \\ \hline
\end{array}
\end{align*}
The labels with caps are the unique symbols, and the small letters are the variables indicating the number of such symbols from which the pattern is to be formed.
Since $I$ can't be adjacent to $I$, that entry is made 0.
Now, the recurrence relation can be formed from the matrix by finding the characteristic polynomial:
\begin{align*}
  -g i x^4-g x^5-i n x^4-i s x^4-i t x^4-i v x^4-n x^5-s x^5-t x^5-v x^5+x^6
\end{align*}
and the recurrence is:
\begin{align*}
  f(v,i,s,t,n,g) &= f(v-1,i,s,t,n,g)+f(v,i,s-1,t,n,g)+f(v,i,s,t-1,n,g)+f(v,i,s,t,n-1,g)+f(v,i,s,t,n,g-1)+f(v-1,i-1,s,t,n,g)+f(v,i-1,s-1,t,n,g)+f(v,i-1,s,t-1,n,g)+f(v,i-1,s,t,n-1,g)+f(v,i-1,s,t,n,g-1)
\end{align*}
The following python code solves for the specific case where $i=3$ and the rest is 1
<code>from math import factorial

def f(v,i,s,t,n,g):
    if v<0 or i<0 or s<0 or t<0 or n<0 or g<0:
        return 0
    if v<2 and i<2 and s<2 and t<2 and n<2 and g<2:
        return factorial(v+i+s+t+n+g)
    return f(v-1,i,s,t,n,g)+f(v,i,s-1,t,n,g)+f(v,i,s,t-1,n,g)+f(v,i,s,t,n-1,g)+f(v,i,s,t,n,g-1)+f(v-1,i-1,s,t,n,g)+f(v,i-1,s-1,t,n,g)+f(v,i-1,s,t-1,n,g)+f(v,i-1,s,t,n-1,g)+f(v,i-1,s,t,n,g-1)

print f(1,3,1,1,1,1) # = 2400
</code>
and also the g.f can be found by $\left(I- A\right)^{-1} = \dfrac{i+1}{1-(g (i+1)+i (n+s+t+v)+n+s+t+v)}$
Comment: Oh my... that is pretty impressive.  Thank you!
Comment: You're welcome!


Expected Identifier error while assigning array object

Question: APIElement *ap=[[APIElement alloc]init];
ap=[feeds objectAtIndex:[indexPath.row]];

Above is my snippet in which I want to get the object in feeds(NSMUTABALEARRAY) into ap which is object of APIElement but it is giving me error like "Expected Identifier".
Comment: are you ding this in cellforiNdexpathrow?
Comment: no in didSelectRowAtIndexPath
Answer: You have to remove box from indexPath.row.
ap=[feeds objectAtIndex:indexPath.row];


Why are positions on the Guitar counted by fret?

Question: On most stringed instruments (violin, bass, etc) playing positions are counted by scale degree and not half-steps. On Guitar, you count frets and this makes for 12+ positions to play in, each with limited use.
It would be much simpler if positions were counted by scale degree. So for example, if your first finger is on G (on low E string), that would be second position - whether it's flat, sharp or natural. And in turn, if your first finger is on A, it would be third position. This way there's fewer positions, and you can play in any key in each position.
Why is the convention on Guitar to count playing positions by fret number?
Comment: I don't think at all about positions when I play guitar, either when reading or not, so I don't have a strong opinion. Seems confusing to have "second position" refer to three different possible frets though.
Comment: What do you call it when you're playing at the second or fourth fret? Isn't that system more confusing if you're playing in different keys? Like F# minor? I suspect the reason for the difference with other string instruments is because you're more likely to play chords on guitar.
Comment: FWIW,  on the cello we have a "half-position" .  All other positions are "whole" but based on the notes in the major scale of the string in question.
Comment: @ Todd Wilcox. You don't count frets (half-steps). If you're playing a G on the E string with the index finger it's second position - irrespective of the quality(sharp, flat, nat).  This system makes much more logical sense when you're reading. The whole fret board is then divided into just 7 positions, and you can play each position in any key.
Answer: A guitar is tuned in fourths. You can assign a finger to each fret and are still able to play most (western, one should add) scales (on the first fret: all of them, on higher frets you are missing one finger ;) but then you can stretch the hand a bit and reach up). On a guitar, the logical (or "obvious") unit is the fret (maybe also because one does not (ok: is not forced to) finger as exactly as on a fret-less instrument).
A violin is tuned in fifths. You need to move your fingers up and down the fingerboard in the same position to play a scale, even if the hand stays in the same position! Thus on a violin (viola, cello, etc.) the positions are assigned to a note's base position, or (as I prefer to think about it) to where the "n-th finger" would usually rest: 2nd position is (on the A string) where the c lies, and on the G string where the b lies. Note that the latter is a bit further up the fingerboard (the equivalent spot would be b flat), but the hand position along the neck is pretty similar (depends on the key and what comes next in the melody, though). So to us violinists it is natural that we need to move our fingers (and even the hand position) a bit within one position to account for the different intervals in different scales in the same position. We also have what is called the "half position", in which you move the entire down the fingerboard below first position (note you can indeed play this in first position - in principle, but some transitions or double stops would no longer work as well). This distinction actually matters because it is now virtually impossible (or very difficult, it is quite a stretch, I hate it when I have to do it) to reach the full fifth wrt. the string (so, the e on the A string). However, as you move higher up the fingerboard (towards the regions of perpetual colophonium cover) you can reach bigger intervals and this no longer matters.
As the comment above hinted at: this - together with playing chords being much more common on the guitar - also leads to guitarists thinking more in keys and violinists thinking in scales (if that makes sense?).
Comment: The cello is tuned in fifths like the violin, but an ascending major scale starting on an open string could be played without shifting the hand or fingers up and down.  A two-octave C-major scale, for example, would be played 0-1-3-4-0-1-3-4-0-1-2-4-0-1-2.  The notes on a violin are close enough together that the third finger is used where the cello would use the fourth and the second finger can take the role of either the cellist's second or third finger as needed.
Comment: Being in fifths is significant, however, because the first finger is usually positioned a whole step up from the open string; it's usually easier to think of that as being one whole step above the open string than two half-steps.
Answer: I think you are saying 'if index finger is on G, it's second position'. But that second position has three places in this case - 3rd fret for G, 2nd fret for Gb and 4th fret for G#. How that helps, I cannot work out. A lot of guitarists already know which note is on which fret, and the frets themselves can be counted easily - there are even markers on some of them!
The fact that violins and the rest of their unfretted family use 'positions' is because they don't have frets to follow. Thus hand/finger positions, relative to each other, are more simply called first, second, etc.
Playing a scale on each instrument needs the same pattern idea, (Ab major is the same pattern as G major, but a little higher). it's just that on guitar there are more obvious landmarks.
There is also the ubiquitous if it ain't broke, don't mend it. Each system works independently, and if your suggestion was put the other way, how would that improve life for violinists, etc?
Comment: @William - once I establish a start place on guitar, there's little or no counting of frets going on. It's all relative after that. Agree that tab isn't *that* good - if only for telling us which string and fret to play on - when there are often better options!
Comment: Well, we have the "half" position already ;)
Comment: It makes more sense when looking at staff paper. You only have to think about what note you're playing with what finger as opposed to counting frets. It logically divides the guitar up into fewer positions (7 vs 12). And you can read each position in any key. It's actually much simpler than the tablature-based logic of fret numbers, which makes for too many positions with limited use.
Comment: @William Interesting. I can't play thinking about which finger, I think about which frets, but in a relative sense. Sort of. Some frets are absolute landmarks and then other times I know I'm going up one or two or six frets so I decide very quickly whether to just put my next finger down or go up a string or leave a finger in between or whatever. I am thinking about fretboard positions not fingers when I read.
Answer: I'd look at it the other way and ask why do violins have the position method that they have and my answer would be because they don't have frets that they can use to identify a position on the fret board. It just seems logical to me.


Printing a Boolean result in C

Question: I read that
int c;
while(c = getchar() != EOF)
{
    putchar(c);
}

will print the value 0 or 1 depending on whether the next character is an EOF or not. Because != has a higher precedence than =.
But when I run this program in GCC, I get a character that looks like
|0 0|
|0 1|
as output when I press Enter.
Comment: My understanding is that since the inequality checking happens first the variable c should get the value 0 which is equivalent to false.
Comment: Related: *[What is the printf format specifier for bool?](https://stackoverflow.com/questions/17307275/what-is-the-printf-format-specifier-for-bool)*
Answer: putchar prints a character. By printing the values 0 and 1, you're printing the null and start of heading (SOH) characters, both control characters. You'll need to convert the numbers 0 and 1 to something that's printable, either by calculating a printable value directly from the 0 or 1:
while (...) {
    // note: the C standard (§ 5.2.1-3 of C99) ensures '0'+1 is '1', which is printable
    putchar(c+'0');
}

or using c to decide what to print.
while (...) {
    if (c) {
        ...
    } else {
        ...
    }
    // or:
    //putchar(c ? ... : ...);
    // though feelings on the ternary operator vary.
}

Comment: You can turn that into a macro for readability: #define BOOL_TO_ASCII(c) ((c) ? '1' : '0')
Comment: Character values are numbers, both in C ('char' is an integer type large enough to store the members of the basic character set) and in ASCII (which associates numeric code points and characters). What distinguishes chars from other numeric types in C is that chars have special display semantics. Also, the encoding doesn't need to be ASCII; it's whatever the platform uses (`putchar` simply writes the character to a stream, unconcerned with what the stream does with it).
Comment: `'0' + 1` is `'1'`. The C Standard mandates all digits be sequential from '0' to '9'. There is no such guarantee for letters.
Comment: @pmg: I was not aware of that. Good to know.
Comment: @Santiago: feelings on macros vary, too.
Comment: @outis I didn't mean for my macro to hurt feelings! :( I was just addressing the OP, presenting the option, I didn't mean you should change the answer or anything :).
Comment: @Santiago: on the other hand, why should we care about feelings? We're programmers, after all. Maybe I *should* throw in that macro.
Comment: @santiago-lezica - I think that's a very nice macro. Simple and concise and hopefully put somewhere easily accessible where someone can find it easily.
Comment: thanks. So putchar parameter should be either a valid ascii code or a character(which is also converted to ascii code).
Comment: @John: it basically means rather than displaying a numeric representation of a character value when output (as with other numeric types), a graphic representation of the character that the numeric value encodes is displayed. For the full semantics, see [C99 §5.2.2](http://www.vmunix.com/~gabor/c/draft.html#5.2.2). The stream that putchar writes to interprets whatever numeric values it receives as character codes, mapping them to a graphic representation and outputting those.
Comment: ... Co-founder of SO Joel Spolsky wrote an article on the topic of [encoding and character sets](http://joelonsoftware.com/articles/Unicode.html). It doesn't cover the char type in C, but it should prove enlightening.
Answer: You are using a Unicode console. All non-printable characters (like the bytes with value 0 and 1) are converted to the 2x2-matrix displaying its Unicode value. (Also, for all printable characters for which you have no font installed.)
Answer: In addition to what everyone said about c being a nonprintable character, you would never print out a 0 for EOF anyway, since you're not going to go into the while loop in that case.  You would need an extra putchar after the loop.
Comment: yes. But that's where the problem is. I'm running the program in a terminal (in Ubuntu). Pressing Ctrl+C is the only way to send the EOF value. But immediately the program quits so how do i print it??
Comment: See this answer for more info http://stackoverflow.com/questions/1793616/why-doesnt-getchar-recognise-return-as-eof-in-windows-console
Answer: This is what happens in your program
int c;

reserve space for an int (call that space c) and don't worry about its contents.
while(c = getchar( ) != EOF)

The thing in parenthesis can be written as c = (getchar( ) != EOF) because the assignment operator has lower precedence than the inequality operator.

getchar() waits for a keypress and returns the value of the key pressed
That value is checked against EOF
As it's different, the result of the inequality operator is 1
and the value 1 gets put in the space with name c.

Then, inside the while loop
{
   putchar(c);
}

you're printing the character with value 1. As you've noticed, on your computer, the character with value 1 does not have a beautiful format when displayed :)

If you really want to print the values 0 or 1 with beautiful formats, try this
c = 0; /* or 1 */
putchar('0' + c);

If you want to print a value between 0 and 9 as a character, try this
c = 5; /* or 7, or 0, ... */
putchar('0' + c);

Comment: @John: you send EOF with `Ctrl+D` in *nix or `Ctrl+Z` in windows. `Ctrl+C` send a "quit" signal in both environments: no wonder the program quits :)
Comment: `getchar()` returns EOF only rarely. When it returns regular values they are different and the condition ( `getchar() != EOF` ) is true.
Comment: oh... yes my mistake. It's true.
Comment: I'm running the program in terminal. So ctrl+C is the way to send EOF, right? But my program also quits. So how do we print the last false value.

Printing a Boolean result in C


Android map infowindow on click marker

Question: Hi i have question how to implement info window on click on marker?
the problem is i have many marker on map and each marker have another activity if info window is clicked.enter code here
heres the example

Marker One-----> if clicked infowindow marker one then ActivityOne will show up
Marker Two-----> if clicked infowindow marker two then ActivityTwo will show up

i have tried many code but not solved
       Intent intent = new Intent(ThisActivity.this,OneActivity.class);
          startActivity(intent);
        }
   });

Answer: This is perfectly working:
 mapview.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
           if(marker==marler1){
             Intent intent = new Intent(MapActivity.this,Activity1.class);
             startActivity(intent);
           }else(marker==marler2){
             Intent intent = new Intent(MapActivity.this,Activity2.class);
             startActivity(intent);
           }
        }
    });

Answer: First: Try to search more for a solution.
Hint: (pseudo code)
Marker m1 = map.addMarker(bla bla);
Marker m2 = map.addMarker(bla bla);

onMarkerClicked(Marker m) {
   if(m == m1) {
      //do what you want to do for marker one
   }
   else if(m == m2) {
      //do what you want to do for marker two
   }
}

Comment: Whatever it was, you should keep a reference to marker one and to marker two when you add them. Then in `onMarkerClick` or `onInfoWindowClick`, you can do the check `if(m == m1)` or `if(m==m2)`
Answer: Good idea is setting marker title, and then in listener based on title do actions
marker.getTitle()

Answer: Here is my code.
first add dependency in build.gradle.
    compile 'com.google.android.gms:play-services:8.4.0'
    compile 'com.google.android.gms:play-services-location:8.1.0'
    compile 'com.google.android.gms:play-services-maps:8.4.0'

        public class MapDetailsActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

            private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 1;
            LocationRequest mLocationRequest;
            private GoogleApiClient mGoogleApiClient;
            LatLng latLng;
            GoogleMap mGoogleMap;
            SupportMapFragment mFragment;
            Marker currLocationMarker;
            private double longitude;
            private double latitude;
            private String strname;
            private String strADD;
            private String strLat;
            private String strLng;
            private BreakIterator mLatitudeText;
            private BreakIterator mLongitudeText;
            private MarkerOptions markerOptions;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_map);
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_REQUEST_CODE
                );

                Bundle bundle = getIntent().getExtras();
                strname = bundle.getString("Vname");
                Log.e("444", "NAME--:" + strname);
                strADD = bundle.getString("Address");
                Log.e("444", "ADDRESS:--" + strADD);

                strLat = bundle.getString("Lat");
                Log.e("444", "LATTITUDE:--" + strLat);
                strLng = bundle.getString("Lng");
                Log.e("444", "LNGitudE:--" + strLng);

                mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
                mFragment.getMapAsync(this);

            }

            @Override
            public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
                if (grantResults.length == 0 || grantResults[0] == PackageManager.PERMISSION_DENIED) {
                    return; //permission not granted, could also optionally log an error
                }
                if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
                    //Do whatever you needed the write permissions for
                }
            }

            @Override
            public void onMapReady(GoogleMap gMap) {
                Log.e("RESDY", "^^^6");
                mGoogleMap = gMap;

                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                gMap.setMyLocationEnabled(true);//used to enable location layer which will allow a user to interact with current user location.
                gMap.getUiSettings().setZoomControlsEnabled(true);
                gMap.getUiSettings().setRotateGesturesEnabled(true);
                gMap.getUiSettings().setScrollGesturesEnabled(true);
                gMap.getUiSettings().setTiltGesturesEnabled(true);
                buildGoogleApiClient();
                mGoogleApiClient.connect();
            }

            protected synchronized void buildGoogleApiClient() {
        //        GoogleApiClient.Builder is used to configure client
        //        Toast.makeText(this, "buildGoogleApiClient", Toast.LENGTH_SHORT).show();
                mGoogleApiClient = new GoogleApiClient.Builder(this)
                        .addConnectionCallbacks(this)//called when client connected or disconnected.
                        .addOnConnectionFailedListener(this)//failed attempt of connect client to service.
                        .addApi(LocationServices.API)//adds the LocationServices API endpoint from Google Play Services.
                        .build();
            }

            @Override
            public void onConnected(Bundle bundle) {
        //        Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();

                mLocationRequest = new LocationRequest();
                mLocationRequest.setInterval(5000); //5 seconds
                mLocationRequest.setFastestInterval(3000); //3 seconds
                mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
                //mLocationRequest.setSmallestDisplacement(0.1F); //1/10 meter
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            }

            @Override
            public void onConnectionSuspended(int i) {
                Toast.makeText(this, "onConnectionSuspended", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onConnectionFailed(ConnectionResult connectionResult) {
                Toast.makeText(this, "onConnectionFailed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onLocationChanged(Location location) {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
        //        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

                mGoogleMap.clear();
                if (currLocationMarker != null) {
                    currLocationMarker.remove();
                }

                longitude = Double.parseDouble(strLng);
                latitude = Double.parseDouble(strLat);
                latLng = new LatLng(latitude, longitude);
                mGoogleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
                markerOptions = new MarkerOptions();
                markerOptions.position(latLng);
                markerOptions.title("" + strname);
                markerOptions.snippet("" + strADD);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
                currLocationMarker = mGoogleMap.addMarker(markerOptions);

                //zoom with animation:
        //        CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(13).bearing(90).build();
        //        mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
          mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));

     LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

            }

            public class CustomInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {

                private View view;

                public CustomInfoWindowAdapter() {
                    view = getLayoutInflater().inflate(R.layout.custom_info_window, null);
                }

                @Override
                public View getInfoContents(Marker marker) {

                    if (marker != null
                            && marker.isInfoWindowShown()) {
                        marker.hideInfoWindow();
                        marker.showInfoWindow();
                    }
                    return null;
                }

                @Override
                public View getInfoWindow(Marker marker) {

                    final String title = marker.getTitle();
                    final TextView titleUi = ((TextView) view.findViewById(R.id.title));
                    if (title != null) {
                        titleUi.setText(title);
                    } else {
                        titleUi.setText("");
                    }

                    final String snippet = marker.getSnippet();
                    final TextView snippetUi = ((TextView) view
                            .findViewById(R.id.snippet));
                    if (snippet != null) {
                        snippetUi.setText(snippet);
                    } else {
                        snippetUi.setText("");
                    }

                    return view;
                }

            }
        }

Hope this will help you :-)

Android map infowindow on click marker


Laravel 5 Paginação sem "refresh"?

Question: Possuo um formulário onde exibo uma tabela com dados para auxiliar o funcionário na criação do contrato, essa tabela está sendo paginada:
($seguranças = DB::table('Segurança')
                 ->where('disponibilidade', '=', 'disponível')
                 ->orderBy('name', 'asc')
                 ->Paginate(15);))

Sendo que ao clicar na paginação, renderizando para a outra páginas todos os dados já preenchidos no form são apagados, como posso resolver esse problema?
Comment: qual versão exata do `laravel`?
Comment: quer fazer paginação sem refresh, com ajax? (é isso???)
Answer: Você pode utilizar o dataTables.
Contudo, existe uma abstração do mesmo para o laravel.
Vou escrever um tutorial de como implementei de maneira bem simples e rápida, mas sem abordar todos os aspectos técnicos.
Contudo, há outras formas mais corretas de fazer na documentação, basta consultar.
Segue o projeto no GitHub https://github.com/yajra/laravel-datatables
Segue o link da documentação https://yajrabox.com/docs/laravel-datatables
Segue o link da documentação do DataTables https://datatables.net/
Obs: Neste exato momento que estou escrevendo o tutorial, identifiquei que o site da documentação está fora do ar.
Vamos lá.
Siga os procedimentos de instalação descritos no github, após isso siga os passos abaixo:
No arquivo routes/web.php adicione a seguinte rota:
Route::get('/pagina/listar', 'ControllerAqui@listar')->name('listar');

Ela será responsável por recuperar os dados que serão exibidos na tabela.
Em seguida, vá até seu controller e implemente um método parecido com este:
public function listar(Request $request)
{
    // Consulta os dados a serem exibidos
    $query = PersonModel::select(['id','name', 'cpf', 'rg', 'phone']);
    // Monta os dados de acordo com o datatable
    $datatable =  Datatables::of($query);

    /**
    *
    * Retorna os dados no formato
    * requisitado pelo datatable e
    * impede o envio da coluna action
    * para a tabela.
    *
    * Isso porque a coluna action,
    * não possui dados, e sim os botões
    * de ação editar e excluir.
    **/
    return $datatable->blacklist(['action'])->make(true);
}

Isso já garante que um json seja retornado ao acessar a rota definida.
Após isso, crie uma view com o seguinte conteúdo
@extends('layouts.admin')
@section('page-title','Pessoas')
@section('content')

            Nome
            CPF
            RG
            Telefone
            Ação

@endsection

Caso queira customizar ainda mais sua tabela, basta consultar a documentação do dataTables e a documentação da abstração criada para o laravel.
Sinalize caso consiga fazer funcionar ou não!
Sucesso!

Laravel 5 Paginação sem "refresh"?