Continuous functions vanishing at infinity on a non-locally-compact space

Question: Let $X$ be a topological space which is not locally-compact (e.g., an infinite-dimensional Hilbert space).
Let $C_{0}(X)$ denote the space of complex-valued, continuous functions vanishing at infinity on $X$, that is, an element $f\in C_{0}(X)$ is a complex-valued, continuous function on $X$ such that,for every $\epsilon>0$, there exists a compact $K\subset X$ such that $|f(x)|\leq \epsilon$ outside $K$.
It is my understanding that $C_{0}(X)$ is a Banach space just as $C_{0}(Y)$ with $Y$ a locally-compact space.
However, in the second page of this article, it is stated that  $C_{0}(X)$ only contains the zero function when $X$ is not locally-compact, but the statement is not proved.
On the other hand, at the end of the first page of this article, it is said that $C_{0}(X)$ may be very small (which, I guess, means that there are non-vanishing elements in it), but the statement is also not proved.
Furthermore, in the accepted answer of this question, it is given an example of a non-vanishing functions vanishing at infinity on a non-locally compact space, but nothing is said about its continuity.
Since I have not a strong background in functional analysis, I really do not know where to start to prove/disprove the previous statements, thus I would appreciate any hint, or any suggestion about references dealing with these matters explicitely (that is, by giving explicit proofs).
Comment: Consider the function $f\colon \ell^2\to \mathbb R$ given by $$f(x_1, x_2, x_3, \ldots)=e^{-x_1^2}.$$ Isn't this function in $C_0(\ell^2)$?
Comment: I was thinking to a similar example, however, if we fix $\epsilon$, then $|f(x)|\geq\epsilon$ whenever $x=(x_{1},x_{2},x_{3},...)$ is such that $x_{1}^{2}\leq \ln(\epsilon)$ and $x_{j}$ is arbitrary for $j>1$, and I do not know if this is a compact set.
Comment: Of course that set is not compact. You are totally right. Sorry, my example is stupid; even the function $$f(x_1, x_2)=e^{-x_1^2}$$ is not in $C_0(\mathbb R^2)$.  The **right** example would be $$f(x_1, x_2, \ldots) = e^{-x_1^2 -x_2^2 -\ldots}.$$ And now it is not so obvious that this is in $C_0(\ell^2)$. Actually, I am quite sure it is not.
Answer: The space $C_0(X)$ can certainly be non-trivial even if $X$ is not locally compact. Just take a locally compact space $Y$, a space $Z$ that is not locally compact and let $X$ be the disjoint union of $Y$ and $Z$. Every $f\in C_0(Y)$ induces a a function $F\in C_0(X)$ by setting $F|_Y=f$, $F|_Z=0$.
That $C_0(X)$ may be small if $X$ is not locally compact is not so much a rigorous statement, but gives a good intuition. If $X$ lacks compact sets, then the condition $f\in C_0(X)$ is quite rigid. In the example above there are still enough compact subsets to produce some functions in $C_0(X)$.
In the special case of infinite-dimensional normed spaces, $C_0$ is indeed trivial. To see this, let $f\in C_0(X)$ and $\epsilon>0$. By definition there exists $K\subset X$ compact such that $|f|\leq \epsilon$ on $X\setminus K$. By Riesz's lemma, $K$ has empty interior. Thus $|f|\leq \epsilon$ everywhere. Since $\epsilon>0$ was arbitrary, we conclude $f=0$.
Comment: A very nice and exhaustive answer, thank you very much.
Comment: I agree, great answer, thank you.


Deleting the original content doesn't delete translated one

Question: When I delete original content, the translated one isn't delete and I just can't delete it ("remove" button doesn't appears).
These are the steps to reproduce the issue.

Install the Paragraphs module
Create a PARA-TEST paragraph type with a single text field and unlimited values
Create a CONTENT-TEST content type with PARA-TEST as unique field
Create a new CONTENT-TEST node and insert some random value in the paragraph field, for example test1, test2, and test3
Save and reopen it; click on Translate
Replace the paragraph field values with test1 - UK, test2 - UK, and test3 - UK
Save the translated node
Reopen the original CONTENT-TEST node and delete a value from the paragraph field, for example test3
Reopen the translated node and notice the test3 - UK value is still present.

I would expect test3 - UK were deleted from the translated node. Instead, test3 - UK is still present in the translated node and I can't remove it.
Comment: I'm voting to close this question because bug reports should be filed on the modules issue queue on drupal.org
Comment: Welcome to Drupal Answers!  You've phrased this as a bug report which is likely to get the question closed.  I'd suggest rewriting the question to be about how to manage translated content within paragraphs so that deleting the original paragraph also deletes translations.  Good luck!
Answer: Probably you don't have configured the paragraph field correctly.
On the field settings page of the paragraph field you should see this warning

Paragraphs fields do not support translation. See the online documentation.

This means you should not check the box above this warning, that users may translate the field.
Instead make the paragraph type translatable and translate the field content of the paragraph.


Greatest and least values on a sphere

Question: Show that the greatest and least values of $xy − xz$ on the sphere $x^2 + y^2 + z^2 =1$ are $±\frac{1}{\sqrt{2}}$, and find the points where these values occur.
I'm not entirely sure what this question is asking
Comment: Are you familiar with max-min problems in 1-variable calculus? For example a problem like "Find the greatest and least values of $f(x)=x^2$ on the interval $-2 \le x \le +2$, and find the points where these values occur"?
Comment: Yes, I'm unsure how to proceed with three variables though
Comment: Okay, then the posted answer is what you want, although that means you have to know the Lagrange multiplier method, which is taught in multivariable calculus.
Comment: @S.Jane Please recall that if the OP is solved you can evaluate to accept an answer among the given, more details here https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Answer: HINT
Let use Lagrange's multipliers for $f(x,y,z)=xy-yz$ with the constraint $\phi(x,y,z)=x^2+y^2+z^2-1=0$ that is

$f_x=\lambda \phi_x$
$f_y=\lambda \phi_y$
$f_z=\lambda \phi_z$

As an alternative by spherical coordinates for $r=1$

$x=\sin \phi \cos\theta$
$y=\sin \phi \sin\theta$
$z=\cos \phi$

such that the constraint is satisfied we need to find the extrema for $xy-yz$ that is
$$g(\phi,\theta)=\sin^2\phi\sin\theta\cos\theta-\sin\phi\cos\phi\sin\theta$$
for $\phi\in[0,\pi]$ and $\theta\in[0,2\pi]$.

Greatest and least values on a sphere


solving a recurrence relation - finding the general solution

Question: Solve the recurrence relation:

$u_{n+2} = 2u_{n+1}-u_n$
$u_0 = 1 $ and $u_1 = 4$

My calculations:
I have calculated that the characteristic equation is: $t^2-2t+1 = 0$ so the roots are $r_1=1$ and $r_2=1$
here is where I am stuck. The answer says that the general solution is: $u_n=(A+Bn)1^n$ But how do I know and come to that conclusion?
Comment: If your objective is to solve recurrence relations, that is just a fact which you should know: a second order homogeneous recurrence with equal characteristic roots $r_1=r_2=r$ has general solution $(A+Bn)r^n$.  If you are looking for a **proof** that this is the case, please make that clear in your question.
Answer: $\begin{bmatrix}u_{n+2}\\u_{n+1}\end{bmatrix} = \begin{bmatrix} 2&-1\\1&0\end{bmatrix}\begin{bmatrix}u_{n+1}\\u_{n}\end{bmatrix}$
$\mathbf u_n = B^n \mathbf u_0$
Unfortunately B is not diagonalizable.
$\lambda^2 - 2\lambda + 1 = 0\\(\lambda-1)^2$
Choose $v_1$ such that
$(B-\lambda I)v_1 = 0\\
v_1 = \begin{bmatrix}1\\1\end{bmatrix}$
Choose $v_2$ such that
$(B-I)v_2 = v_1$
$v_2 = \begin{bmatrix}1\\0\end{bmatrix}$
$B\begin{bmatrix}1&1\\1&0\end{bmatrix} = \begin{bmatrix}1&1\\1&0\end{bmatrix}\begin{bmatrix}1&1\\0&1\end{bmatrix}\\
B =
\begin{bmatrix}1&1\\1&0\end{bmatrix}\begin{bmatrix}1&1\\0&1\end{bmatrix}\begin{bmatrix}0&1\\1&-1\end{bmatrix}\\
B^n = \begin{bmatrix}1&1\\1&0\end{bmatrix}\begin{bmatrix}1&1\\0&1\end{bmatrix}^n\begin{bmatrix}0&1\\1&-1\end{bmatrix}= \begin{bmatrix}1&1\\1&0\end{bmatrix}\begin{bmatrix}1&n\\0&1\end{bmatrix}\begin{bmatrix}0&1\\1&-1\end{bmatrix}$
$\begin{bmatrix}u_{n+1}\\u_{n}\end{bmatrix} =$$ \begin{bmatrix}1&1\\1&0\end{bmatrix}\begin{bmatrix}1&n\\0&1\end{bmatrix}\begin{bmatrix}0&1\\1&-1\end{bmatrix}\begin{bmatrix}4\\1\end{bmatrix}\\
\begin{bmatrix}1&1\\1&0\end{bmatrix}\begin{bmatrix}1&n\\0&1\end{bmatrix}\begin{bmatrix}1\\3\end{bmatrix}\\
\begin{bmatrix}1&1\\1&0\end{bmatrix}\begin{bmatrix}1+3n\\3\end{bmatrix}\\
\begin{bmatrix}4+3n\\1+3n\end{bmatrix}\\$
Answer: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

$\ds{u_{0} = 1\,,\quad u_{1} = 4}$.

\begin{align}
0 & =\sum_{n = 0}^{\infty}z^{n + 2}\pars{u_{n + 2} -2u_{n + 1} + u_{n}} =
\sum_{n = 2}^{\infty}u_{n}z^{n} - 2z\sum_{n = 1}^{\infty}u_{n}z^{n} +
z^{2}\sum_{n = 0}^{\infty}u_{n}z^{n}
\\[5mm] = &\
\pars{-u_{0} - u_{1}z + \sum_{n = 0}^{\infty}u_{n}z^{n}} -
2z\pars{-u_{0} + \sum_{n = 0}^{\infty}u_{n}z^{n}} +
z^{2}\sum_{n = 0}^{\infty}u_{n}z^{n}
\\[5mm] = &\
-1 - 2z + \pars{1 - 2z + z^{2}}\sum_{n = 0}^{\infty}u_{n}z^{n}
\\[5mm] \implies &\
\sum_{n = 0}^{\infty}u_{n}z^{n} = {2z + 1 \over 1 - 2z + z^{2}}
= {3 - 2\pars{1 - z} \over \pars{1 - z}^{2}} =
{3 \over \pars{1 - z}^{2}} - {2 \over 1 - z}
\end{align}

\begin{align}
u_{n} & = \bracks{z^{n}}\sum_{k = 0}^{\infty}u_{k}z^{k} =
\bracks{z^{n}}\bracks{{3 \over \pars{1 - z}^{2}} - {2 \over 1 - z}} =
\bracks{z^{n}}\bracks{3\sum_{k = 0}^{\infty}{-2 \choose k}\pars{-z}^{k} -
2\sum_{k = 0}^{\infty}z^{k}}
\\[5mm] = &\
\bracks{z^{n}}\bracks{3\sum_{k = 0}^{\infty}{k + 1 \choose k}z^{k} -
2\sum_{k = 0}^{\infty}z^{k}} =
\bracks{z^{n}}\sum_{k = 0}^{\infty}\pars{3k + 1}z^{k}\implies
\bbox[15px,#ffe,border:1px dotted navy]{\ds{u_{n} = 3n + 1}}
\end{align}
Answer: Hint: rearranging the recurrence and iterating shows an easily recognizable arithmetic progression:
$$
u_{n+2}-u_{n+1} = u_{n+1}-u_n = u_n-u_{n-1} = \cdots = u_1-u_0 = 3
$$


Random selection combobox delphi 7

Question: I have Items listed in my combobox in delphi 7 and I'm referring to them using their respective index numbers and it's working well.
Now what I want is to add a functionality of randomizing selection whereby a user selects random and then one of the items in the combobox will be select.
I have done some research but all the results I get are not close to what I want.
P'se render me some help. Thanks
Answer: You can use the RandomRange function in the Math unit to obtain a random integer within a given range:
procedure TForm1.btnRandomItemClick(Sender: TObject);
begin
  ComboBox1.ItemIndex := RandomRange(0, ComboBox1.Items.Count);
end;

Notice that RandomRange(A, B) yields a random integer in [A, B) ∩ ℤ = {A, A + 1, ..., B − 1}.
Don't forget to call Randomize one time before you need to use random numbers. (You can call it during application startup.)
Update:
If Math.RandomRange is not available in Delphi 7, you can use Random(int) instead:
procedure TForm1.btnRandomItemClick(Sender: TObject);
begin
  ComboBox1.ItemIndex := Random(ComboBox1.Items.Count);
end;

Random(B) yields an integer in [0, B) ∩ ℤ = {0, 1, ..., B − 1}.
Comment: thanks Andreas, is this function available in Delphi 7 as well

Random selection combobox delphi 7


Effect size in contrast analysis

Question: I'm running 2-way repeated measures ANOVA (3 and 5 levels) with planned contrasts afterwards. I'm interested in comparing
1)levels of the first factor among themselves (e.g. A1B with A2B, A2B with A3B)
2)pairwise comparisons (e.g. A1B1 and A2B4)
Question:
Some sources claim that I need to report effect size for each contrast. I wonder if this makes sense since the design is repeated measures. If so, how the contrasts should be calculated? I don't think the standard formula for Cohen's d works in this case since it doesn't take into account the correlation.
Comment: @drknexus As far as I remember MSerror=SS/df, thus it is also affected.
Comment: How many levels per repeated measures factor?  Are your pairwise contrasts just comparing B1 to B2 at level A1 and B1 to B2 at level A2, or do you have something more complex going on?
Comment: Perhaps the answer to this question is tied up in the answer to my first set of questions, but what part of this do you see in the context of a contrast analysis?
Comment: @drknexus I have updated the description of the question. I'm comparing 2 levels of the same factor on average and 2 different pairs (e.g. A1B1 and A2B4)
Comment: What sort of error term are you thinking about using for your contrasts?  Do you think you'll run each as a paired samples t-test, or do you have designs on trying to use the pooled error term.  If the later, what does your test of sphericity look like?
Comment: @drknexus I'm using MSerror from interaction with Greenhouse-Geisser correction (Sphericity is not assumed, p = 0.042).
Comment: Unless I'm mistaken (quite possible) the GG correction applies to your degrees of freedom for the hypothesis tests, it is not a correction to your $MS_{error}$.
Comment: Ah, just looked at Maxwell and Delaney... so it is!  Thank you for the correction.  For some reason I was under the misunderstanding that only $df_{n}$ was affected!
Answer: Your effect sizes for your pairwise contrasts would be derived from the test that is associated with the effect.  For example, if you are doing a pairwise t-test comparing cells of your design, then your effect sizes would be derived from each of those pairwise t-tests (using whatever error term you select for those pairwise tests).  As a pairwise t-test is computationally equivalent to a one-sample t-test, you should be able to calculate the Cohen's d using the formula $\bar{d}\over{s_{d}}$ (although this is what is commonly considered Cohen's d, I understand that Cohen's formulas actually reflected the use of $\sigma$).
Comment: Do you mean that even though I'm using MSe from 2-way ANOVA to calculate contrasts, when calculating Effect Size I can use SD between two cells instead?
Comment: You can't use the between subjects variance in each of those cells.  It doesn't match the test you are doing. You could use the SD of the differences (difference scores) between the two cells... but only if your contrast was actually calculated as a paired samples t-test using the standard deviation of differences as your error term.
Comment: However, since you are using MSe, I think what you would do is use $\sqrt{MSe}$ as your estimate of $s_{d}$.  I tried to spot check my intuition but ezANOVA doesn't like yielding its tasty source table secrets for within subjects designs.  Since you have the values in front of you, you can do a quick sanity check on the procedure by comparing $s_{d}$ calculations with non-GG adjusted $\sqrt{MSe}$ values.  To the extent the assumption of sphericity is correct, these values should be similar.  For your actual calculation you would... I guess... use the GG corrected $MS_{error}$.
Comment: If you wait around a few hours, I'm sure you'll get more skilled and authoritative help than me.
Comment: Thanks for your help. This is actually the only thing that seems to me reasonable. However I'm still not sure if using Cohen's d here is a valid approach.
Comment: That part I am sure about.  Your individual contrasts are just paired samples t-tests.  Paired samples t-tests are just one sample t-tests of difference scores (against $\mu = 0$).  The cohen's d formula for one-sample tests is applicable.  That the numerator is a difference score takes into account the dependence/correlation/relatedness of the measures.
Comment: AFIK, your only other mainstream options are to aggregate your data for the desired comparisons, run it back through the ANOVA machinery to yield a partial eta or partial omega or to convert your t to an r.  However, my money is on all three of the above yielding the same number since k = 2.
Answer: If you are doing this using conventional ANOVA, you are making a mistake. This should be done as a mixed-effect repeated measures (MERM) model. The test of sphericity is 30 years out of date. Using mixed-effects models, you define a proper covariance model (which may include the compound symmetry model, but usually does not), and test things properly. These tests are done using PROC MIXED in SAS, also can be done in R or SPSS. Many programs do not do these correctly. If the program warns you about compound symmetry, you are using a bad program. And for those who are warning about compound symmetry and the GG correction, you need to update your methodology. You are out of date. And if you do use MERM, it is easy to specify contrasts. I do this all the time - in SAS. FInally, do not do repeated paired t-tests. Very much the wrong approach. You need to fit the entire design, define contrasts which properly compare between levels, and use the procedure defined error term.
Comment: A little strongly worded.  Not all fields are at peace with mixed effect models.  Many are far from consensus on how to evaluate effects in regards to NHST.  Sticking a bunch of non-orthogonal contrasts into a single model and then interpreting the results in a NHST framework is certain to lead to tears.  (Of course there is plenty of room to argue the NHST framework is also outdated... however it still is pretty dominant in some fields).
Comment: @russellpierce Could you by any chance point me to bibliography on the (lack of) consensus on what you mention, the problems with non-orthogonal contrasts in NHST?
Comment: The problem of non-orthogonal contrasts is just a gedanken experiment.  Under, most forms, of NHST you're just testing for the presence/absence of an effect.  If your effects are non-orthogonal then you can't be sure about the attribution of the shared variance between two contrasts.  As for the lack of consensus, IDK, I wrote that 7 years ago - perhaps a consensus has formed since then (?).  I was perhaps most influenced by {lme4} which refused to provide p-values.  https://stat.ethz.ch/pipermail/r-sig-mixed-models/2008q2/000904.html is representative, but far from canonical.

Effect size in contrast analysis


What is the correct process for deriving the 'mirror' or 'negative' harmony of a progression?

Question: I recently stumbled upon the concept of negative harmony in these threads:

https://www.talkbass.com/threads/negative-harmony.533862/#post7227335
http://www.jazzguitar.be/forum/theory/30394-negative-harmony.html
http://decipheringmusictheory.com/?page_id=651
http://m-base.com/essays/symmetrical-movement-concept/

I am trying to interpret it in the most basic ways, to get a feel for it.
The most useful post in the talkbass forum offers this info:

(progression I)
Cmaj7 (C E G B) E-7 (E G B D) G7 (G B D F)
(It's Mirror)
Dbmaj7 (Db F Ab C) F#-7 (F# A C# E) A-7(b5) (A C Eb G)
Notice how I got that? I started on the root of the first chord
  progression and spelled down new chords based upon the intervallic
  content of the first ones. C major 7 is C up a major third to E up a
  minor third to G up a major third to B. I took that same order of
  intervals, but used it going down instead of up. C down a major third
  is Ab, down a minor third is F down a major third is Db. This order of
  notes spelled a Db major 7 chord. You can do that with any quality of
  chord, and they will invert to some interesting things. Here's a basic
  list.
Major 7 => Major 7 a half step up (Cmaj7 to Dbmaj7)
  Minor 7 => Minor 7 a whole step up (E-7 to F#-7)
  Dominant 7 => Minor 7(b5) a whole step up (G7 to A-7(b5))
  Minor7 (b5) => Dominant 7 a whole step up (C-7(b5) to D7)
  Diminished 7 => Diminished 7 a minor third up (inverts to itself, essentially)
  Minor major 7 => Augmented major 7 a half step up (C-(maj7) to Db+maj7)
  Augmented major 7 => Minor major 7 a half step up

This seems straightforward enough. Each chord is mirrored around its own root note.
Part of the idea though, the way I heard about it, is that the negative chord will have an equivalent role. So for example a G7 tends to resolve to C. Therefore -G7, i.e. A-7(b5), should equally resolve to C.
But then I started to wonder if this meant the tones of chords in a progression should be mirrored around the key of the piece, rather than the root of each chord?
That would generate different results from above. Can anyone shed any light?
Answer: "Negative harmony" is a term from the theorist Ernst Levy and his book A Theory of Harmony. Here's what's actually happening:
Let's say you're in C. The idea is that the "axis" of C is the perfect fifth C/G. So, when you have a G7, you're actually inverting it around this C/G axis. Or, put another way, the halfway point between C and G is right between E and E♭, so you're actually rotating it around that point.
As such, G becomes C, B becomes A♭, D becomes F, and F becomes D. So in terms of negative harmony, the equivalent of G7 is Dhalfdim7 (or Dm7♭5).
The idea is that the voice-leading tendencies are just inverted. The leading-tone B, which wants to go up by half step, is now A♭, which wants to go down by half step.
What makes this confusing is that it's close to but not the same as other ideas. It's really an evolution of a prior concept (typically connected with 19th-century German thought) called harmonic dualism. From a dualist standpoint, the chords will be inverted around their tonic; thus C major (C E G) inverts around its tonic to become "C dual minor" (F A♭ C). Yes, you read that correctly; harmonic dualists name minor triads by what we consider their fifth!
This is also not to be confused with the twentieth-century notion of pitch (or pitch-class) inversion, where music is simply rotated around a given axis.
Comment: Well, the unfortunate fact is that Levy gets a lot of things wrong in his book. It's also unclear when he's basing something off of prior theories and when he's introducing something new, so as an educated reader we can't always tell exactly what he means. (Truth be told, his book isn't highly regarded by academic music theorists.) I believe you can determine your axis; so the person on talkbass is using a C/C axis (that is, just a C axis), whereas mine is a C/G axis.
Comment: As luck would have it, I just discovered a very recent video where Jacob Collier explains negative harmony: https://youtu.be/DnBr070vcNE?t=1m30s
Comment: In the video Jacob also mentions transforming a sequence of `A7 D7 G7 C` into `Ebm6 Bbm6 Fm6 C` ... this seems to confirm that keeping the C/G axis is the way to go.
Comment: so, to be clear: the info from the post in talkbass forum is wrong? is it referring to one of the similar concepts?
Comment: what you are describing does sound like the concept I was trying to get to grips with.  I will have a think about what it means the C/G axis and see if I can understand
Comment: And his process at 3:12 is in line with my answer, not the post in the talkbass forum. (That doesn't necessarily mean I'm correct, though!)
Comment: Ah yes, that Jacob Collier video is what started me googling this today :)  I am wondering on what basis to choose the axis, for a simple exercise to take a basic chord progression and generate the 'negative' version. Does it make more sense to have an axis per chord, or mirror them all across the I/V axis of the key do you think?
Comment: I guess you could do either one, but I would think you would want to be consistent and stick with one axis.
Comment: Another possibility occurs to me... the axis might be from the 'key' of the piece to the root of the chord you want to mirror. So mirroring the V, i.e. G7 in the key of C, gives you a C/G axis... mirroring whatever flavour of chord you have for the I chord would be on a C/C axis, and the IV chord would have a C/F axis. Or maybe this would be nonsense, and the C/G perfect fifth axis is what represents the 'key' of C and should be used for all of them.
Comment: It's an interesting idea, but, assuming these are "involutions" (i.e., their own inverses) this doesn't seem to work. Following the key/root axis, GM becomes Fm, but then Fm becomes CM. But maybe these aren't meant to be involutions!
Answer: In addition to Richard's excellent answer, which I've accepted, I just wanted to highlight some other approaches to this question I found on the internet.
One problem in investigating this subject, as a casual musician rather than music theory major, is a) not having the Levy book b) not sure if I'd understand it anyway and c) of the few internet sources discussing the topic that aren't way over my head, hard to judge if they're getting it 'right'.
So for point c) I'm going to assume that musical prodigy, Jacob Collier, having apparently discussed it with Herbie Hancock (!) knows how this is supposed to work. With that in mind there's some clues in this video:

He talks about using a C/G "axis" for the key of C, and thus transforming G7 into -G7 = Fm6 (aka Dø).  Furthermore he transforms a VI-II-V-I chord sequence in C (A7 D7 G7 C) into E♭m6 B♭m6 Fm6 C. (I think the C itself is not transformed here).
So with this in mind let's investigate...
1.
Firstly there is this website:
https://personalprojectnegativeharmony.wordpress.com/
They don't talk about the axis at all. Instead they use the idea that the 'negative scale' of C Ionian is G Phrygian.
They also talk about other elements of Levy's theory (I assume it comes from Levy, though it may be saxophonist Steve Coleman's interpretation of Levy) such as a 'generator' as well as the tonic.
I'm still not sure what is the 'generator' but my attempt to follow their method is as follows:

intervals of G7 chord with respect to C major are 5-7-2-4
count 'downwards' in the G Phrygian (i.e. 'negative C major') scale,
starting at G
a five scale steps down from G is C
a seven scale steps from G is A♭
a two scale steps down from G is F
a four scale steps down from G is D
C-A♭-F-D = Fm6

So far so good.
We can try also to generate 'negative A7' (our VI chord). The intervals with respect to C major are 6 ♭2 3 5. Jacob says this should be an E♭m6 = B♭ G♭ E♭ C.

count down six scale steps from G to get B♭
count down two steps from G to get F ...but since it's supposed to be a ♭2 interval and I'm counting down I should sharpen it to G♭ ... ok
count down three scale steps from G to get E♭
count down five steps from G to get C

OK this works too... but I don't think this is how they describe the method in the article!

"As Steve Coleman shows above, the negative version of the C-E-G triad
  is the minor triad F-Ab-C with C being the generator and the tonic. Remembering that the negative version of the C major scale is Gm phrygian, going downwards from G, we can find the F minor triad in that scale."

So what they describe here is to count down 1-3-5 in G Phrygian starting at C rather than G.
EDIT: I think this is a mistake in the blog, perhaps misinterpreting what Steve Coleman was trying to explain here, and that's why I've been so confused. The text says to count down from G but somehow to arrive at an F Minor triad. The negative version of C Major triad should be a C Minor triad C E♭ G. We can arrive at that by counting down 1-3-5 in G Phrygian starting at G as they suggest. The F Minor triad F-A♭-C must be -G in the same way that Fm6 is -G7 (i.e. built off the fifth degree of the negative scale) in order to be consistent with everything discussed elsewhere.
Then they continue:

Now remembering also that we must look at this Fm triad as actually being generated from C and going downwards, the next degree of the Gm Phrygian scale, a third down from F, ie the "7th", would be D.

So 1-3-5-7 (natural 7th) counting down from C gives us the Fm6...

This is why the negative dominant of chord I of a key is a minor sixth chord.

Ok but why did we count 1-3-5-7 to get -G7 for the key of C?
I have to conclude I don't understand how to use the theory as described on that website.
However it might be a purer version of the theory than anything discussed here.  It also has some interesting discussion re Steve Coleman's efforts to relate negative harmony to jazz, and why they prefer to call it Fm6 rather than D half diminished.
EDIT: after re-considering, reading other sources, and correcting the mistake above I think I can answer the question I had; "why did we count 1-3-5-7 (starting at C) to get -G7 for the key of C?"
If we do it first in positive land we find that counting 1-3-5-7 in C Major scale starting at G (the fifth degree) will give us the notes for G7. In negative land the scale is G Phrygian backwards and the fifth degree is C. Counting 1-3-5-7 in that scale, from C, gives us the notes of Fm6.
(Also: it is basically a coincidence that the intervals of C Major scale counting 1-3-5-7 from G to spell G7 are similar to the intervals in the G7 chord relative to its own root, 1-3-5-♭7. This kind of confused me a bit previously. The point is to come up with a way of relating the notes in the chord as intervals in the parent scale, then count the same intervals in the negative scale.)
2.
Going back to the YouTube clip, there was a useful suggestion in a comment from user Huw Price.
He says we can use the Circle of 5ths to get our negative harmony.
Let's try it out.  Assuming we're in the key of C we want to fold our circle in half like so:

We could almost justify calling this a 'C-G axis'
Now we have all 12 notes, and to get the negative of each just find its reflection on the other side of the circle, i.e. C -> G, F -> D etc.
We can find 'negative G7' by reflecting the notes G B D F -> C A♭ F D
We can get Jacob's 'negative VI-II-V-I':

-A7 = B♭ G♭ E♭ C = (E♭m6)
-D7 = F D♭ B♭ G = (B♭m6)
-G7 = C a♭ F D = (Fm6)

This seems like an easy and successful method.
And for another key you'd just draw your axis between the root and fifth and get your reflections that way.
3.
Perhaps because I had a guitar in my hand, instead of a pen and paper, I'd initially found it difficult to see how to apply the method from Richard's answer.
After exploring the Circle of 5ths way, it seemed like this would also be easily done visually.
Write out the twelve notes in a row, starting from the ♭7 of your key and finishing with the 6.
e.g. for C:

In very much the same way as the Circle of 5ths, we can get the negative of each note by picking its opposite from across the reflection line between E--E♭.
4.
Here's some further handy 'shortcut' info, again taken from Huw Price's comments on the YouTube video.
Firstly, let's take the 'chord scale' of C major:
C Dm7 Em7 FΔ7 G7 Am7 BØ
The negative harmony counterparts of these are:

A♭Δ7 (CEGB --> G E♭ C A♭) (taking Cmaj7 as the starting point)
Gm7 (DFAC --> F D B♭ G)`
Fm7 (EGBD --> E♭ C A♭ F)
E♭Δ7 (FACE --> D B♭ G E♭)
Dø (GBDF --> C A♭ F D) aka Fm6
Cm7 (ACEG --> B♭ G E♭ C)
B♭7 (BDFA --> A♭ F D B♭)

Huw points out that these form an E♭Δ chord scale.
We can write the negative transformations in general terms as:

IΔ7 --> ♭VI Δ7
IIm7 --> Vm 7
IIIm7 --> IV m7
IVΔ7 --> ♭III Δ7
V7 --> II ø ...aka... IV m6
Vim7 --> I m7
VIIø --> ♭VII 7

5.
From Adam Spiers's comments, this is another source we can look at:

with accompanying PDF:
http://www.mediafire.com/file/qntuqa7ifa6ex5z/Negative_Harmony_%232+-+Cadences+and+Voice+Leading_Fiorini_Marco.pdf
This basically explains Method 1 but also relates it to the ideas of Barry Harris... i.e. a relationship between diminished chords, dominant 7ths and minor 6ths.
So far in this post I have been referring to eg C -> -C = Cm, G7 -> -G7 = Fm6. And if the positive scale is C Major then "negative C Major" is G Phrygian backwards.
However in the PDF above the author uses a different convention, so you have pairs like C | -C (Cm), G7 | *-C7* (Fm6) and for the scales "C Major" and "negative G Major" (which is still G Phrygian backwards).
So in this scheme the negative chords and scales have the real (i.e. positive) name of the note from the negative scale they are built from as their root note. (i.e. what I called -G7 and they call -C7 is built starting from C, the fifth degree of the negative scale).
But this seems to me more confusing as you have to do an extra mental step to relate it back to the positive key. Also why only translate the root note of the name in this way and not rest of the chord? i.e. -C7 is not a 7th chord in real (positive) terms... the notes of Fm6 with a root of C spells, er, I don't know how you'd call it.  Whereas -G7 has no G in it but at least tells you clearly the chord it was generated from.
I have no idea what the correct convention is for naming the negative chords but -G7 = Fm6 so far seems to make the most sense to me.
However one thing to note is with this scheme the negative names only make sense in relation to a positive key. For example in the key of C we have -G7 = Fm6. If we transpose down to B♭ then we will have -G7 = D♭m6 (G7 being now in the VI chord position).
Whereas, according to the method in the PDF, if we have -C7 = Fm6 in C and we transpose up to D then we still have -C7 = Fm6, where this represents the negative B7 (the VI chord again). Or if we transpose to G then we have -C7 = Fm6 again, this time as the negative of A7 (the II chord).
So this stable naming seems an argument in favour of the convention used in the PDF above and is maybe more correct. I would welcome further comments on this.
Comment: After reading the PDF linked from the Youtube video and thinking it through some more I think I can answer some of my questions (and correct an error) in the part about "method 1" above.  I did not find anything to suggest naming the fourth chord `G-♭6`... it's named either `-FΔ7` or `-DΔ7`... from the method in the linked PDF they would call it `-DΔ7` based on the fact that the "negative C Major" scale is actually G Phrygian counted backwards and the fourth degree of that is `D`. But `-FΔ7` would make more sense to me. I'm not sure which is correct. Either way the notes are `D B♭ G E♭`.
Comment: I have edited the post with more info: maybe `-DΔ7` is the correct 'negative' name for the fourth chord after all. And I agree it makes sense to call it `G-♭6` (in positive harmony sense) for the reason you describe (this also leads to naming the fifth as `Fm6` rather than `Dø` and that seems to be preferred in all sources). Although I think `E♭Δ7` also has some merit as detailed in "method 4".
Comment: Lots of great stuff in this answer, but the last section is not quite right because your chords have the wrong roots.  For example IΔ7 translates to I-♭6 (i.e. the root stays as C).  This is explained in more detail in [this video](https://youtu.be/yU2IPzIz_HI).
Comment: @AdamSpiers if I understand, you're advocating to give each chord I have spelled a different name so as to preserve their roots. I haven't watched the video yet, but how does this apply to say the 4th chord in the sequence `-FΔ7` (`E♭Δ7`)?  There is no `F` to serve as root in the resulting chord.
Comment: IIUC the root would be G, since it's a negative 4th away from C in the circle of 5ths. So the chord is G Bb D Eb, i.e. `G-♭6`. But I strongly recommend you watch the video ;-)
Answer: I think another way to look at it is to think of the intervals of each note with respect to E and then apply those same intervals from Eb and there would form each negative chord.
Comment: I think you mean `C` on the left hand side (not `E`)?  And on the right-hand side E♭ major scale is the same as G Phrygian, so this is like the method from https://personalprojectnegativeharmony.wordpress.com/
Answer: As Collier points out the axis is between the minor and major 3rd of a key, E and Eb in the key of C. That means you simply count an iterval upwards from E (or the major third of your key) and then reflect it downwards from Eb (or the minor third of your key).
A simple way is to start with the chord tone closest to the axis and calculate the relative intervals from there. In the case of A7 you would start with E (right on the positive axis), then up a minor 3rd to G, major 2nd to A and major 3rd to C#.  E-G-A-C#=A7
The reflection starts on Eb (right on the negative axis), down a minor 3rd to C, down a mjor 2nd to Bb and down a major 3rd to Gb. Eb-C-Bb-Gb= Ebm6.
G7 starts on F (1/2 step up from E) etc.
Its refletion starts on D (1/2 step down from Eb) etc.
Comment: I think this is basically method 3. from my answer


What is this linear programming trying to do?

Question: Given $G=(V,E)$, let $\mathbb{R}^V$ be the set of all real vectors $x=(x_v)_{v\in V}$ where each component $x_v$ corresponds to a vertex $v\in V$. Let $Q_G$ be defined
$$Q_G:=\{x\in\mathbb{R}^V\;|\;x_u+x_v\geq1\text{ for all }\{u,v\}\in E\text{ and }x_v\geq0\text{ for all }v\in V\}$$
Consider the linear program
$$\text{min}\left\{\sum_{v\in V}x_v\;|\;x\in Q_G\right\}$$
Explain what this LP is trying to do.
I was told that this is a famous graph theory problem, but I can't find the name of it.
Just interpreting the notation, I think we are summing up all the costs of the vertices denoted $x_v$ and minimizing the edge costs between vertices.
Answer: Jean Marie mentioned this is the minimum vertex cover problem, which is correct. However, the problem you formulated has no integrality constraints (e.g. $x_v\in \{0,1\}$), so it is the linear relaxation of the minimum vertex cover problem. So answering your question, it is trying to find a fractional minimum vertex cover.
Answer: It is the minimum vertex cover issue as explained in paragraph 4 of this clearly written document.


Language specific settings for field formatters

Question: I've created a custom field formatter widget for numeric fields. The formatter has A LOT of settings to customize the visual output of that number, to whatever designers/marketing wants (adding a lot of HTML markup, with[out] leading/trailing zeros, zeros as dash, one or two fractions, rounding, prefixes/infixes/suffixes,... ).  Some of those settings are language-dependant though, so I'd like to enter different formatter settings in
/en/admin/structure/types/manage/MY_CONTENT_TYPE/display
/de/admin/structure/types/manage/MY_CONTENT_TYPE/display
/fr/admin/structure/types/manage/MY_CONTENT_TYPE/display
I've noticed that there is a $langcode parameter in
FormatterInterface::viewElements(FieldItemListInterface $items, $langcode)
but I don't know how to make
FormatterInterface.php FormatterInterface::settingsForm(array $form, FormStateInterface $form_state)
language-aware.
Is it possible at all to have language-specific settings in a field formatter? If yes, how to I store and retrieve those settings in the correct language?
Answer:
Define a schema in your module
config/schema/mymodule.schema.yml.
Example from the date range module:
core/modules/datetime_range/config/schema/datetime_range.schema.yml
field.formatter.settings.daterange_default:
  type: field.formatter.settings.datetime_default
  label: 'Date range default display format settings'
  mapping:
    separator:
      type: label
      label: 'Separator'
      translation context: 'Date range separator'

For more information see
Block configuration form values are not translated
You need an UI to translate, which is unfortunately not ready
yet, see this issue:
Entity view/form mode formatter/widget settings have no translation
UI
Until then you can edit the translated yaml file of an exported
config in config/sync/language/[LanguageID] or install the patch from the
issue.
Comment: My module already has a working schema file, used for global settings though (same options, but not "per-node-bundle-scope"). I've added a top level key `field.formatter.settings.MY_MODULE` of `type: mapping` with all my translatable labels and did a config export. But in which config files are the per-nodebundle-specific formatter settings supposed to be stored? I did not find any additional keys except my already existing (global) module config.
Comment: The translated yaml files in `language/[LanguageID]` are named identically as the untranslated ones in the main sync folder. The main difference is that they only contain the translatable values. But why not fork your local site and try out the patch. You don't need the patch later in production when you deploy the config.
Comment: OK, got it by trial & error. Even after creating the schema, no config for the field formatter was exported in the 2nd lang. I manually copied `core.entity_view_display.node.NODE_TYPE.VIEW_MODE.yml` to `config/lang/ISO2CODE`, deleted all keys except those marked for translation and reimported the config. Then it worked.


2-form associated with a skew map

Question: Given a two-form $\omega\in \Lambda^2V$ for some (say finite dimensional) vector space $V$ we may associate with $\omega$ a skew map $f_{\omega}:V\rightarrow V^*$ given by $X\mapsto \iota_X\omega$, where $V^*$ is the dual space to $V$ and $\iota_x\omega$ is the linear functional $\omega(X,\cdot)$. My question is how do we go the other way, i.e., given a skew map $f:V\rightarrow V^*$ (by skew I mean $f^*:(V^*)^*=V\rightarrow V^*$ satisfies $f^*=-f$) how do we explicitly associate with $f$ a two-form $\omega_f\in \Lambda^2V^*$ ?
Answer: You can define $\omega_f$ by
$$\omega_f(u, v) = f(u)(v),$$
i.e. you take the action of $f(u) \in V^\ast$ on the vector $v \in V$. Since $f$ is a skew map, we have that
$$\omega_f(v, u) = f(v)(u) = f^\ast(u)(v) = -f(u)(v) = -\omega_f(u,v),$$
so $\omega_f$ is skew-symmetric. Presumably $f$ is also linear, from which the bilinearity of $\omega_f$ follows. Hence $\omega_f$ is a $2$-form on $V$.

2-form associated with a skew map


How to train for edge tpu on google cloud vision with object detection?

Question: When I try to export a model for the Google Coral, the option that should exist doesn't exist. As per this link, there should be an option to export for the Coral, but for me only TF Lite, Tensorflow.js and Container exist as options.
Answer: The link you passed to the documentation [1] refers to image classification models (single label or multi-label classification). In the case of object detection  exporting to EdgeTPU [2] is not supported and there is no current workaround.
Thus, it is normal that you do not see the option.
[1] https://cloud.google.com/vision/automl/docs/export-edge#edge-tpu
[2] https://cloud.google.com/vision/automl/object-detection/docs/export-edge


Just-audio in Flutter Web

Question: It seems that using Flutter Web on iOS device(Safari and Chrome tried so far) with this plugin, if the audio is not ready(still buffering) if you try to play it, will block the execution. Should be handle or should be something to update in the documentation?
Same case on Flutter Web but on desktop device does not cause the same issue.
Answer: I experienced the very same issue but on flutter web.  In my case, it turned out to be a wrong path.  It worked in Chrome and Firefox, but not Safari.  Once I removed assets/ from the path (which was in the example I found), then it worked on all the browsers.

Just-audio in Flutter Web


Reportbuilder - Test Connection Succeeds but still get Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'

Question: I'm setting up my connection in Report builder and all goes as plans

But then after accepting the connection properties, when I try and test it It gives me that error.

Why would report builder default to the that login credentials?? I am logged on as the user that has access to the database and I've confirmed it. (Logged onto sql with my credentials.)
Might there be something im not seeing?
Answer: Click on the credentials tab and make sure the credentials used to log on is correct.
Also make sure that Use as Windows credentials is checked.
Comment: Awesome. Thank you. Didn't even see that.
Answer: This was the same case for me. For security reasons I could not use sql account so I must use my windows credentials. So what I have done is just clicked on "Disconnect" link in bottom-left of report designer which was showing my report server link. That did the trick for me. Hope this helps some one.


Modificar elemento visual por outra thread

Question: Quero definir por um Thread o conteúdo numa RichTextBox mas recebo um erro dizendo

Não é possível realizar chamadas de um outro thread distindo do mesmo TextBox

Ouvi falar que é possível utilizar a opção Control.Invoke ai fiquei muito na dúvida nesse ponto.
Resumindo, eu quero desenvolver um APP que sem iniciar o CMD com a janela, acompanhe comandos e possa enviar comandos ao CMD, já tenho o código pronto mas na hora que eu configuro RedirectStandardOutput=true acaba que apenas quando o processo fecha ele mostra o log.
Por isso eu gostaria de implementar um Thread em cima da textbox para com sem precisar o processo fechar e mostrar o "log".
Answer: Como você não mostrou o código do que está tentando fazer, irei dar uma resposta mais genérica.
Você pode fazer isso
this.Invoke(new MethodInvoker(() => textBox.Text = "NovoTexto"));

Eu faria uma função para trocar o valor do TextBox, onde na própria função verificaria se é preciso usar o Invoke ou não. Isso é mais questão de gosto. Se te interessa, ficaria dessa forma.
public void SetText(TextBox txtbox, string texto)
{
    if (txtbox.InvokeRequired)
        txtbox.Invoke(new MethodInvoker(() => txtbox.Text = texto));
    else
        txtbox.Text = texto;
}

Uso
SetText(textBox, "Novo Texto");


Exchange 2013 DAG Cluster Unable to add second sever

Question: I have two servers (EXCH1 and EXCH2) running Exchange Server 2013 Standard, and a third file server that is a DAG Witness.
The first server is a Windows Server 2012 R2 Standard machine and the second server is a Windows Server 2008 R2 Enterprise machine (on an HP Proliant DL360 G4). Both servers have Client Access and Mailbox Roles on them.
I am able to successfully add only one of the two servers as a member server. When I try to add the second server, (regardless of which one ends up being the second server) it fails. It stalls after being at "Adding Server (EXCH1 or EXCH2) to the cluster for an extended amount of time".. Then an error message displays...

error
A server-side database availability group administrative operation
  failed. Error The operation failed. CreateCluster errors may result
  from incorrectly configured static addresses. Error: The operation
  failed. CreateCluster errors may result from incorrectly configured
  static addresses. Error: An error occurred while attempting a cluster
  operation. Error: Cluster API '"AddClusterNode() (MaxPercentage=100)
  failed with 0x5b4. Error: This operation returned because the timeout
  period expired"' failed.. [Server: (SERVER FQDN)

I have taken these additional steps also:

Ensured that each server is updated appropriately (Windows Update)
Admin account with proper credentials used.
IP and NIC settings on each server OK.
DNS listings of each host also OK.
Exchange Server 2013 running as normal on each server.
Cluster Manager service(s) started and running on each server.
All Windows Firewall ports added to list, Windows Firewall has even been completely disabled to troubleshoot.

It seems like the two servers don't like talking to each other (regardless of which direction the communication is)
Answer: Mixed OS version clusters are not supported. Get all of your servers on the same version.
See: Planning for high availability and site resilience (Microsoft Technet)

Each member of a DAG must be running the same operating system.
Comment: ...and here I was the whole time trying to figure this whole things out. haha. I deployed a VM with Server 2012 R2 and wit works fine in the DAG. Thank you.
Answer: If you face same problem in Exchange 2019 server:
Clear-ClusterNode -Name XXXXXX (Problematic Server) -Force (PowerShall)

Restart the server
Add-DatabaseAvailabilityGroupServer -Identity "DAG Name" -MailboxServer XXXXXX(Problematic Server)

Server should be added and validate the DAG members and FileShare.
Answer: First of all we have to tackle the access denied part of it and it can be cleared by checking and assigning the required permissions.
Error is also showing that static IP has miss-configured so ensure that it is assigned perfectly as per the necessity
There might not be a DAG1 account created by whereas DAG account could be there which an Exchange Console formulate without any problems/error. So ensure that DAG1 account has created in the place.
Read more here : http://www.tips.omsaitech.co.in/a-server-side-database-availability-group-administrative-operation-failed-error-the-computer-account-dag1-could-not-be-validated-access-was-denied-check-that-the-current-user-nt-authoritysy/


SQL Server backup strategy consequences

Question: In simple terms, I need point-in-time restore between full backups - what are the consequences in the following plan - the database is in full recovery mode:

1:00 AM Transaction Log Backup (no Truncation or Shrinking)
1:30 AM Full Backup
2:00 AM Transaction Log Backup (Truncate and Shrink)
Then every 30 Minutes Transaction Log Backup (no Truncation or Shrinking)

Will this provide me with the ability to point-in-time restore the database at any point except for the time between 1:30am and 2am?
Answer: That is a good many log backups to keep up with, if from 2:00 AM till 1:30 AM the next morning you are taking log backups. You might through in a differential backup if you have the window to do so during the day.
Your plan will allow for no more than 30 minutes of data loss. If the database goes down between those 30 minute log backups that is the amount of data you can loose. If your business or application can handle that much data loss then your plan is good for your environment.
Why truncate/shrink? If you are doing log backups that is what helps control the log file growth so there should be no reason to truncate the log. Are you shrinking just the log file or the complete database? Neither is suggested or really needed if you are maintaining a sufficient log backup schedule to control log growth.
Comment: Thanks, have removed shrinking. On the Truncation feedback, I have changed the transaction log backup to no init without truncation etc, presumably that will still control log growth?
Comment: Actually I just remembered now from reading that WITH TRUNCATE_ONLY and WITH NO_LOG have been discontinued and do not work after SQL Server 2008. --Yes to your question a log backup on a regular basis will help control the log file growth. That is not to say it may not still grow during heavy activity, but it keeps it from going out of control.
Comment: Agreed.  Not sure why the shrinking is in there.
Comment: Agreed.  In fact, if I'm reading correctly the scenario proposed by the question won't actually work.  If you truncate the log AFTER the full backup, you're going to break the log sequence and every subsequent transaction log backup will be unusable.  So you'll be able to do point in time recovery between 1:30AM and 2:00AM, but not thereafter.

SQL Server backup strategy consequences


Syntax errors in my code, Android application-ping IP

Question: I have my App's Andoid Code I have a little problem,
I do not understand why there are two Errors,
in line: button.setOnclickListener I have Multiple markers at this line
    - Syntax error, insert ")" to complete
     MethodInvocation
    - Syntax error, insert ";" to complete Statement
     - Syntax error, insert "}" to complete ClassBody
and
in Curly brace (in end code)  Syntax error on token "}", invalid ConstructorHeaderName
what should i do
kind regards, Thanks
this is my code:
package com.example.ping;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

EditText edit;
TextView text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    edit = (EditText)findViewById(R.id.editText1);
    edit.setText("192.xxx.x.x");
    text = (TextView)findViewById(R.id.textView1);

    pingIP();

}

private void pingIP() {
Button button = (Button)findViewById(R.id.button1); // HERE ERROR
     /**Multiple markers at this line
- Syntax error, insert ")" to complete
 MethodInvocation
- Syntax error, insert ";" to complete Statement
 - Syntax error, insert "}" to complete ClassBody **/

    button.setOnClickListener(new View.OnClickListener() {

            try {
                Object host;
                addr = InetAddress.getByName(host.toString());
                InetAddress addr = null;
            addr = InetAddress.getByName(host.toString());
            } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
            try {
            if(addr.isReachable(5000)) {
            text.append("\n" + host + " - Respond OK");
            } else {
            text.append("\n" + host);
            }
            } catch (IOException e) {

            text.append("\n" + e.toString());
            }
            }
        public void onClick(View v) {

            Editable host = edit.getText();
        }
    } //HERE ERROR - Syntax error on token "}", invalid ConstructorHeaderName
)
;
}

Answer: You should import your R class, ie.:
import com.example.ping.R;

also make sure all your braces are properly closed, and finally:
whole your code block:
  try {
                Object host;
                addr = InetAddress.getByName(host.toString());
                InetAddress addr = null;
            addr = InetAddress.getByName(host.toString());
            } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
            try {
            if(addr.isReachable(5000)) {
            text.append("\n" + host + " - Respond OK");
            } else {
            text.append("\n" + host);
            }
            } catch (IOException e) {

            text.append("\n" + e.toString());
            }
            }

is outside your method public void onClick(View v) { :-)
and last hint, dont try do network operations on GUI thread, you will get exceptions, put it inside AsyncTask


hook_form_alter to create table field

Question: I created a form which takes user input for fields: title, link, date and description, however I have another field which is guid and it cannot be user created. This field needs to be created with hook_form_alter() which takes the user inputted link and concatenates a string to the front and then return it to the submit handler for db_insert. How can I go onto doing this? here is my submit handler
function rss_list_creator_form_submit($form, &$form_alter) {
//$GUID = returns GUID from hook_form_alter()
$query = db_merge('rss_table')
->key( array('GUID' => $GUID))
->fields( array(
'title' => $form_state['values']['title'],
'link' => $form_state['values']['url'],
//'GUID' => $GUID,
'date' => $form_state['values']['date'],
'description' => $form_state['values']['description'],
))
->execute();
}

**I solved my problem, since I have two forms available I needed to enclose the code in a switch statement. Here is the code block:
function rss_list_form_alter(&$form, &$form_state, $form_id) {
 switch ($form_id) {
  case 'rss_list_creator_form':
  if(isset($form_state['values']['url'])){
    $guid = 'tag:news.google.com,2005:cluster=' . $form_state['values']['url'];
  }
  $form['guid'] = array(
    '#type' => 'hidden',
    '#default_value' => !empty($guid) ? $guid : '',
  );
  break;
 }
}

Answer: you can try with hidden field. You can make #guid field a hidden field. in your hook_form_alter() #guid initially will hold the default value to empty on submission, you can make #guid fields value to whatever you want to make.
funciton mymodule_form_alter(&$form, &$form_state, $form_id){
  if(isset($form_state['values']['url']){
    $guid = 'extra string' . $form_state['values']['url'];
  }
  $form['#guid'] = array(
    '#type' => 'hidden',
    '#default_value' => !empty($guid) ? $guid : '';
    );
}

Comment: I have another issue, since guid is a primary key, it is giving me this error:

Notice: Undefined variable: guid in rss_list_creator_form_submit() (line 252 of C:\wamp\www\internarias\sites\default\modules\rss_list\rss_list.module).
Notice: Undefined index: guid in rss_list_creator_form_submit() (line 256 of C:\wamp\www\internarias\sites\default\modules\rss_list\rss_list.module).
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'GUID' cannot be null:
Comment: Are you calling hook_form_alter manually as displayed in your submit handler? you should not call that manually. this hook will be called automatically. simple get the guid value as `$guid = $form_state['values']['guid']`. From your error _error: Notice: Undefined variable: guid in rss_list_creator_form_submit() (line 252 of_ it looks like there is no value in $guid variable. make sure that it have some value before you do db_insert. As $guid is primary key and it doesn't have any value that's why its throwing _PDOException._
Comment: cool. I forget to mention the condition which check `$form_id` because `hook_form_alter` will be called for each form on the page.

hook_form_alter to create table field


fetch backbone model inside a foreach loop

Question:     this.shipperModel = new shipperModel();
    this.collection = new packetListCollection(this.options.packetData);
    this.listenTo(this.collection, "change", this.render);
    this.listenTo(this.collection, "add", this.render);
    this.finalArry = [];
    self.collection.each(function (modelData) {
        self.shipperModel.fetch({
            data: {
                facility_id: modelData.facility_id ? modelData.facility_id : 0
            }
        }).then(function (response) {
            console.log(response.records);
            self.finalArry.push(response.records);
        })

    });
    console.log(self.finalArry);

my array always comes as blank even though there is data in the response how do i make sure the result gets display only after all the above fetches are done.
Answer: This is because you're logging the array outside of your then() closure.
this.finalArry = [];
self.collection.each(function (modelData) {
  self.model.fetch({
    data: {
      facility_id: modelData.facility_id ? modelData.facility_id : 0
    }
  })
  .then(function (response) {
    console.log(response.records);
    self.finalArry.push(response.records);
    console.log(self.finalArry);
  });
});

fetch() is an async method, so your original console.log() fires before any of the network calls succeed.
Oscar Linde's answer is notable — this is probably not the way you want to do initial data hydration.
Answer: Wouldn't it be better to completely refetch the whole collection instead of refetching each model?
Anyway, back to the original question, what you are looking for is javascript promises. I think it could be a bit confusing if i'm going to explain it in a comment. Maybe you could take a look at https://api.jquery.com/category/deferred-object/ or just google javascript promises and i'm sure you'll find something.
Maybe this is what you're looking for(untested):
var requests = [],
  self = this;
this.finalArry = [];

self.collection.each(function (modelData) {
  // Push all requests wrapped in a function into an array
  requests.push(function () {
    return self.model.fetch({
      data: {
        facility_id: modelData.facility_id ? modelData.facility_id : 0
      }
    }).then(function (response) {
      console.log(response.records);
      self.finalArry.push(response.records);
    });
  });
});

// Run all requests and map the return value(a promise)
requests = _.map(requests, function (req) {
  return req();
});

// When all requests are done, log
$.when.apply($, requests).then(function (response) {
    console.log(self.finalArry);
});

At least i wouldn't recommend using async: false, it contributes to a bad user experience.
Comment: @vini: I added some example code now. I don't think `async: false` is a great idea. Maybe you could do something like i did in the example code. A general readup on promises wouldn't hurt because it's really good to know!
Comment: the model i am fetching is not the same type as that of the collection sorry my naming is screwed up have updated
Comment: Alright, i'll be back in a sec with some example code!


laravel load view from a folder name with actual dot

Question: I am creating a multi-domain Laravel app, so my view files are in separate folders per domain. For example, the following:
return view('pages/' . $_SERVER['SERVER_NAME'] . '/public/home', []);

should load a view under
pages/domain.com/public/home.blade.php

but instead it attempts to load
pages/domain/co/public/home.blade.php

because of the dot notation.
How do I get around this?
Answer: You'd need to add a view namespace to set up hints for a particular folder if there're dots in the name.
$domain = 'domain.com';

View::addNamespace($domain, config('view.paths')[0]."/{$domain}/");

Route::get('example', function() use ($domain) {
    return view("{$domain}::home");
});

You could use base_path('resources/views') instead of in the example above config('view.paths')[0] which is probably a bit more sensible in case someone reorders or changes the value of config('view.paths')
Answer: Maybe you could replace the dot with underscore:
$domain = str_replace('.', '_', $_SERVER['SERVER_NAME']);
return view('pages/' . $domain . '/public/home');

and load the view under:
pages/domain_com/public/home.blade.php

Answer: It should work
return view('pages/domain.com/public/home',[]);

Comment: While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations!


Neural network for multiple output regression

Question: I have a dataset containing 34 input columns and 8 output columns. One way to solve the problem is to take the 34 inputs and build individual regression model for each output column. I am wondering if this problem can be solved using just one model particularly using Neural Network.
I have used a multilayer perceptron, but that needs multiple models just like linear regression. Can sequence to sequence1 learning be a viable option? I tried using TensorFlow it does not appears to be able handle float values.
Any suggestion to tackle this problem by using just one unified model specially using neural network will be appreciated.

Ilya Sutskever, Oriol Vinyals, & Quoc V. Le (2014). Sequence to Sequence Learning with Neural Networks. Advances in Neural Information Processing Systems, 27. (pdf)
Comment: (To any potential close voters: This is not a programming question. It would be off topic on [SO].)
Comment: What is *the* problem?
Comment: Can you clarify the "sequence to sequence" option here? I don't know if it will be familiar to people who work w/ NNs, but it isn't to me.
Comment: Sequence to Sequence modelling using RNN.

https://papers.nips.cc/paper/5346-sequence-to-sequence-learning-with-neural-networks.pdf
Comment: You can try MultiOutputRegressor(). This works for this type of problems
Comment: please refer to website machine learning mastery
https://machinelearningmastery.com/multi-output-regression-models-with-python/
Answer: At first I thought generic_user's comment was a show-stopper, but I just realized it isn't:
If I train d different networks on d different outputs, then each one will be fit to that dimension with no regard for the others.
But if I train one network with d outputs and use all outputs for backpropagation, then each weight in every layer in the network will be adjusted so that all d outputs are more accurate.
That is: Each network parameter will be adjusted by a sum of gradients (how each output varies with a "wiggle" in this parameter) such that adjusting it in the chosen up or down direction causes more accurate output overall--even if adjusting the weight that way causes some dimensions of the output to be less accurate.
So, yes, the thing that ultimately distinguishes each output is just a linear equation encoded in the last layer, but in training one multi-output network every layer will become better at presenting that last layer with something that allows it to do its job better. And so it follows that the relationships between outputs will be accounted for by this architecture.
You might be able to do better than a fully-connected net by making your architecture reflect any known relationships in the output, just as deep networks do better than shallow ones by exploiting "compositional" relationships between inputs.
Comment: A multivariate regression assumes there is some (unknown) covariance matrix that relates that target variables to each other. Are you suggesting that just having one dense layer is enough to capture this covariance without the need for explicitly including hidden layer(s)?
Comment: I'm suggesting that hidden layers must capture some of that covariance. One dense output layer alone is just a bunch of parallel linear-regressors-through-activation-functions. No relationship between outputs can be established when there isn't a hidden layer for them to mutually tune and take as input/pass as input to other output nodes.
Answer: A neural net with multiple outcomes takes the form
$$
\mathbf{Y} = \mathbf{\gamma} + \mathbf{V}_1\Gamma_1 + \epsilon\\
\mathbf{V}_1 = a\left(\gamma_2 +\mathbf{V}_2\Gamma_2\right)\\
\mathbf{V}_2 = a\left(\gamma_3 +\mathbf{V}_3\Gamma_3\right)\\
\vdots \\
\mathbf{V}_{L-1} = a\left(\gamma_L+ \mathbf{X}\Gamma_L\right)\\
$$
If your outcome has the dimension $N\times 8$, then $[\gamma_1, \Gamma_1]$ will have the dimension $(p_{V1}+1) \times 8$.
Which is to say that you'd be assuming that each outcome shares ALL of the parameters in the hidden layers, and only has different parameters for taking the uppermost derived variable and relating it to the outcome.
Is this a realistic assumption for your context?
Answer: You can do it with only one Neural Network. But your Neural Network should look like this:
Input Layer: 34 Nodes(one per your input column)
Output Layer: 8 Nodes(one per your output column)
You can add as many as and as big as hidden layers you want in the Neural Network. So Neural Network outputs 8 predicted values and each value will be a different regression of the inputs.
Comment: which package of which language supports so??
Answer: I was wondering the same; here are my ideas:
I suppose that if the outputs share some hidden patterns, then training can benefit from simultaneously learning the regression for all the outputs.
It would be interesting to try an architecture where you build a neural network for each output, but all the neural networks share some layers (the first half layers for example). Then you could train each neural network at the same time: inside the learning loop, each neural network is trained one step (with one batch) sequentially.
This would be similar to knowledge transfer, but with the difference that in knowledge transfer each neural network is fully trained before reusing some part of it to train another neural network.
I bet someone has thought about this before, but I have no reference to it.


Why is a Moving Average Process not just noise?

Question: I was studying Moving Average Processes, and wanted to ask why adding a bunch of weighted noise terms is not just a noise term. I understand the operations involving mean and variance in a mathematical pov, but I want to address this doubt more intuitively. Could someone help please?
Comment: Could you please tell us what your concept of a "noise term" might be?  From some perspectives the answer to "is not just a..." is *yes* and from other perspectives it is *no.*  We need to understand your perspective.
Comment: @whuber I really apologize for the late reply; I was caught up in college submissions so could not get onto this site. Onto your question, apart from the obvious mathematical definition which has been given to me, I understand noise as just a random value.
Comment: "Just a random value" is not sufficiently specific.  "Noise" usually refers to certain models of error or uncertainty.  The [Wikipedia article on "white noise"](https://en.wikipedia.org/wiki/White_noise) might be a good place to begin reading about the distinction.
Comment: @whuber I recommend thus question be reopened. It made enough sense that it two thumbs up and two answers.
Answer: You know that ordinary regression will be failed if there is no data about $X$ whichs explain the $Y$. Well, MA is kind of regression using the noise as idependent variables, it's under the assumption that we don't know what is the noise exactly but there are some correlations.
Answer: To elaborate on another answer, "noise" it is, but once there are correlations, we can use it to predict.
Consider
$${{y}_{t}}={{\theta }_{0}}{{\varepsilon }_{t-1}}+\,\,{{\varepsilon }_{t}},\,\,\,\,\,\,{{\varepsilon }_{t}}\sim \text{WN}\left( \sigma _{\varepsilon }^{2}=1 \right),\,\,\,\,{{\theta }_{0}}\in \mathbb{R}$$
The autocovariance function is
$$E\left( {{y}_{t}}{{y}_{t-k}} \right)=\left\{ \begin{matrix}
   1+\theta _{0}^{2}\qquad k=0  \\
   {{\theta }_{0}}\qquad k=1  \\
   0\qquad k>1  \\
\end{matrix} \right.\Rightarrow \,\,\,\,\left\{ \begin{matrix}
   E\left( y_{t}^{2} \right)=1+\theta _{0}^{2}  \\
   E\left( {{y}_{t}}{{y}_{t-1}} \right)={{\theta }_{0}}  \\
\end{matrix} \right.$$
You can use either moment condition, or both in an overidentified Generalized Method of Moments approach, to estimate $\theta_0$, and then we can predict $y_t$ after observing $y_{t-1}$, through, for example,
$$\left\{ \begin{matrix}
   {{y}_{t}}={{\theta }_{0}}{{\varepsilon }_{t-1}}+\,\,{{\varepsilon }_{t}}  \\
   {{y}_{t-1}}={{\theta }_{0}}{{\varepsilon }_{t-2}}+\,\,{{\varepsilon }_{t-1}}
\end{matrix} \right.\Rightarrow \,\,\,\,y_t = \theta_0y_{t-1} - \theta_0^2 \varepsilon_{t-2} + \varepsilon_t.$$
OP'S COMMENT,

what I was asking was not the mathematical framework which explains
the correlations, but more specifically, WHY those correlations exist
when we are effectively adding a bunch of noise terms.

RESPONSE TO OP's comment
What we model here is a) the assumption of per-period white noise ($\varepsilon_t$) but b) that there is some other phenomenon ($y_t$) that is determined as a linear function of these white noises. So the "correlations" do not exist a priori, but they arise because each $y_t$ is determined by a portion of the same history of the white noise process. This is what creates the correlation, e.g between $y_{t+1}$ and $y_{t}$ - they both are partly determined by $\varepsilon_t$, with different strengths.
They are not correlations between the white noises but between they $y$-s, because by construction, the partly depend on the same $\varepsilon$. This is what my last mathematics shows, and it is what allows prediction, on the data we have (the $y$-s alone).
Maybe what you are asking is: "is it reasonable to assume that such a $y_t$-process exists in the real world?"
But that is a question always haunting a model.
Comment: @Glen_b Ah, thanks for spotting this stupid mistake Glen. Corrected.
Comment: Alecos, I posted a few [questions](https://stats.stackexchange.com/search?tab=newest&q=user%3a53690%20is%3aquestion&searchOn=3) during the period you were less active. There are several that remain unanswered, and I hope some of them are up your alley. I would appreciate if you could take a look.
Comment: @RichardHardy Thanks for the invitation Richard, I will have a look.
Comment: Hi Alecos, what I was asking was not the mathematical framework which explains the correlations, but more specifically, WHY those correlations exist when we are effectively adding a bunch of noise terms.
Comment: @insipidintegrator I included a response in my answer.


OpenLdap LDAP admin group ALC

Question: I have the following LDIF file to create ldapadmins.
dn: ou=Manager,dc=example,dc=org
objectClass: organizationalUnit
objectClass: top
ou: Manager

dn: ou=Customers,dc=example,dc=org
objectClass: organizationalUnit
objectClass: top
ou: Customers

dn: cn=customerAccountAdmin,ou=Manager,dc=example,dc=org
cn: customerAccountAdmin
objectClass: organizationalRole
objectClass: simpleSecurityObject
objectClass: top
userPassword: {SSHA}*removed*

dn: ou=Users,ou=Customers,dc=example,dc=org
objectClass: organizationalUnit
objectClass: top
ou: Users

dn: ou=Groups,ou=Customers,dc=example,dc=org
objectClass: organizationalUnit
objectClass: top
ou: Groups

I created the following ldif to allow multiple admins for phpldap admin. (they will manage multiple customers)
dn: olcDatabase={1}mdb,cn=config
changetype: modify
delete: olcAccess
-
add: olcAccess
olcAccess: {0}to attrs=userPassword,shadowLastChange by self write by dn="cn=admin,dc=example,dc=org" write by anonymous auth by * none
olcAccess: {1}to * by self read by dn="cn=admin,dc=example,dc=org" write by * none
olcAccess: {2}to * by dn.base="cn=customerAccountAdmin,ou=Manager,dc=example,dc=org" write

Afer logging in to the phpldap admin the customerAccountAdmin cannot see the tree. but from the ALC view it should have every permission.
Do i miss something?
Is it easier way to achieve this?
Answer: Your problem comes from the order in which the access directives are evaluated:

Within this priority, access directives are examined in the order in which they appear in the config file. Slapd stops with the first <what> selector that matches the entry and/or attribute. The corresponding access directive is the one slapd will use to evaluate access.

(cf. Access Control Evaluation). That means that your second to * directive is never evaluated and the first one applies to all entries.
You should modify the access rules to look like:
dn: olcDatabase={1}mdb,cn=config
changetype: modify
replace: olcAccess
olcAccess: to attrs=userPassword,shadowLastChange
  by self write
  by dn="cn=admin,dc=example,dc=org" write
  by anonymous auth
  by * none
olcAccess: to *
  by self read
  by dn="cn=admin,dc=example,dc=org" write
  by dn.base="cn=customerAccountAdmin,ou=Manager,dc=example,dc=org" write
  by * none

An alternative (which combines with your previous question) is to create a cn=Administrators,dc=example,dc=org group and give write access to everything to the members of this group:
dn: cn=Administrators,dc=example,dc=org
changetype: add
cn: Administrators
objectClass: groupOfNames
member: cn=customerAccountAdmin,ou=Manager,dc=example,dc=org
member: cn=admin,dc=example,dc=org

dn: olcDatabase={1}mdb,cn=config
changetype: modify
replace: olcAccess
olcAccess: to dn.exact="cn=Administrators,dc=example,dc=org"
  by dn.exact="cn=admin,dc=example,dc=org" write
  by * none
olcAccess: to attrs=userPassword,shadowLastChange
  by self write
  by group.exact="cn=Administrators,dc=example,dc=org" write
  by anonymous auth
  by * none
olcAccess: to *
  by self read
  by group.exact="cn=Administrators,dc=example,dc=org" write
  by * none

EDIT: Worth mentioning, it is important that you use replace: olcAccess or delete before adding if you're still using the default olcAccess. add: olcAccess without removing the default olcAccess does not work since it won't override it.

OpenLdap LDAP admin group ALC


Combination Algorithm in Excel VBA

Question: I need an algorithm which generates all possible combination of a set number and output all of them onto Excel spreadsheet.
For example, with n = 5(1,2,3,4,5) and r = 2(created a small gui for this), it will generate all possible combinations and output them into excel spreadsheet like this...
1,2
1,3
1,4
...

The order in which it prints doesn't matter. It can first print (5,1), then (1,2).
Can anyone show me how to do this?
Thank you very much.
Comment: Can't believe nobody has asked this one yet: Have you tried anything yourself? The answer is basically two nested `For Next` loops.
Comment: Is order important? Is 5,1 the same as 1,5 ?
Comment: If order (as Tim asked it) is important, then "all possible combinations" can grow quickly.  If n and r are both 8, that's factorial 8, or over 40,000 permutations.  Do you have a limit for n in mind?
Comment: Yes the order is important. Sorry for not putting that in. 1,5 is same as 5,1.
Comment: No I don't have limits for n or r. I want to make it dynamic so any user can put in any number and it will generate the spreadsheet with all possible combinations.
Comment: It's similar to what this does.
http://www.calculatorsoup.com/calculators/discretemathematics/combinations.php
Except I want to do it on Excel and print all possible combinations into the spreadsheet instead of finding how many combinations there are.
Comment: Two nested `For Next`loops when r=2. Six when r=6. And I have no idea how to nest r `For Next` loops if r is variable. (actually I do: recursion)
Comment: @adamleerich: I guess I still prefer mine ;-) but you're right, I mentionned "recursion" only because you did, so in all fairness I should upvote your answer. There you go.
Comment: @Joubarc: Thanks.  Your solution is more general, so, I can see why you prefer it.
Answer: How about this code...
Option Explicit

Private c As Integer

Sub test_print_nCr()
  print_nCr 5, 3, Range("A1")
End Sub

Function print_nCr(n As Integer, r As Integer, p As Range)
  c = 1
  internal_print_nCr n, r, p, 1, 1
End Function

Private Function internal_print_nCr(n As Integer, r As Integer, ByVal p As Range, Optional i As Integer, Optional l As Integer) As Integer

  ' n is the number of items we are choosing from
  ' r is the number of items to choose
  ' p is the upper corner of the output range
  ' i is the minimum item we are allowed to pick
  ' l is how many levels we are in to the choosing
  ' c is the complete set we are working on

  If n < 1 Or r > n Or r < 0 Then Err.Raise 1
  If i < 1 Then i = 1
  If l < 1 Then l = 1
  If c < 1 Then c = 1
  If r = 0 then
    p = 1
    Exit Function
  End If

  Dim x As Integer
  Dim y As Integer

  For x = i To n - r + 1
    If r = 1 Then
      If c > 1 Then
        For y = 0 To l - 2
          If p.Offset(c - 1, y) = "" Then p.Offset(c - 1, y) = p.Offset(c - 2, y)
        Next
      End If
      p.Offset(c - 1, l - 1) = x
      c = c + 1
    Else
      p.Offset(c - 1, l - 1) = x
      internal_print_nCr n, r - 1, p, x + 1, l + 1
    End If
  Next

End Function

Comment: Thanks! Now I just need to figure out how to print them on one cells each. I'm new to VBA so I've been learning it for past 2 days.
Answer: I had to do this once and ended up adapting this algorithm. It's somewhat different from nested loops, so you may find it interesting. Translated to VB, this would be something like this:
Public Sub printCombinations(ByRef pool() As Integer, ByVal r As Integer)
    Dim n As Integer
    n = UBound(pool) - LBound(pool) + 1

   ' Please do add error handling for when r>n

    Dim idx() As Integer
    ReDim idx(1 To r)
    For i = 1 To r
        idx(i) = i
    Next i

    Do
        'Write current combination
        For j = 1 To r
            Debug.Print pool(idx(j));
            'or whatever you want to do with the numbers
        Next j
        Debug.Print

        ' Locate last non-max index
        i = r
        While (idx(i) = n - r + i)
            i = i - 1
            If i = 0 Then
                'All indexes have reached their max, so we're done
                Exit Sub
            End If
        Wend

        'Increase it and populate the following indexes accordingly
        idx(i) = idx(i) + 1
        For j = i + 1 To r
            idx(j) = idx(i) + j - i
        Next j
    Loop
End Sub

Comment: Thank you. I tried it and it works fine but array input in Excel spreadsheet wasn't what I was looking for. But I tried it and it works perfectly for anyone else who might need this.
Comment: That's why I say "something like" :-)
Comment: @Joubarc Is it going to work for something like this: array(2,3,4,5,7,10),where r=3?
Answer: These combination algorithms are best made with nested loops with recursion. I have wrote some 4 years ago the exactly needed code to carry this out (https://vitoshacademy.com/vba-nested-loops-with-recursion). The idea is to change the size variable in the Main and the input array in the same Sub. Then run it:
Sub Main()

    Static size         As Long
    Static c            As Variant
    Static arr          As Variant
    Static n            As Long

    size = 2
    c = Array(1, 2, 3, 4, 5, 6)

    n = UBound(c) + 1
    ReDim arr(size - 1)

    EmbeddedLoops 0, size, c, n, arr

End Sub

Function EmbeddedLoops(index, k, c, n, arr)

    Dim i                   As Variant

    If index >= k Then
        PrintArrayOnSingleLine arr
    Else
        For Each i In c
            arr(index) = i
            EmbeddedLoops index + 1, k, c, n, arr
        Next i
    End If

End Function

The debug.print has built-in limit in VBA, displaying only the last 200 values in the Immediate Window (Ctrl+G). Thus, if you have more than 200 lines of results, it is better to write to Excel spreadsheet, to a txt.file or to a database:
Public Sub PrintArrayOnSingleLine(myArray As Variant)

    Dim counter     As Integer
    Dim textArray     As String

    For counter = LBound(myArray) To UBound(myArray)
        textArray = textArray & myArray(counter)
    Next counter

    Debug.Print textArray

End Sub

Answer: This is my solution with arrays vba
Private Sub UserForm_Initialize()

Dim matriz_origen() As Variant

Dim matriz_destino() As Variant

Dim n As Long

Dim k As Long

n = 6

k = 2

Call combinatoria(matriz_origen, matriz_destino, n, k)

'Def titulo

Title = "Matriz Combinatoria"

'FUnction Calling

Call despliegue_2D(matriz_destino, Style, Title)

End Sub

Function combinatoria(matriz() As Variant, comb As Long, _
                      matriz_origen() As Variant, matriz_destino() As Variant, _
                      n As Long, k As Long)

'This function is calculating all possible combinations.

comb = Application.WorksheetFunction.Combin(n, k) 'Sin repeticion

ReDim matriz_origen(1 To n, 1 To k)

'Loops

For j = 1 To k

     For i = 1 To n

         matriz_origen(i, j) = i

     Next i

Next j

ReDim matriz_destino(1 To comb, 1 To k) 'comb

If (k = 2) Then

cont1 = 1

'Loops

For j = 1 To k - 1

pos1 = j + 1

For i = 1 To n

For iter1 = 1 To n

 If matriz_origen(i, j) < matriz_origen(iter1, pos1) Then

    matriz_destino(cont1, j) = matriz_origen(i, j)

    matriz_destino(cont1, pos1) = matriz_origen(iter1, j)

    cont1 = cont1 + 1

 End If

Next iter1

Next i

Next j

End If

If (k = 3) Then

cont1 = 1

'Loops

For j = 1 To k - 2

pos1 = j + 1

pos2 = j + 2

For i = 1 To n

For iter1 = 1 To n

 If matriz_origen(i, j) < matriz_origen(iter1, pos1) Then

  For iter2 = 1 To n

   If matriz_origen(iter1, pos1) < matriz_origen(iter2, pos2) Then

    matriz_destino(cont1, j) = matriz_origen(i, j)

    matriz_destino(cont1, pos1) = matriz_origen(iter1, j)

    matriz_destino(cont1, pos2) = matriz_origen(iter2, j)

    cont1 = cont1 + 1

   End If

 Next iter2

 End If

Next iter1

Next i

Next j

End If

If (k = 4) Then

cont1 = 1

'Loops

For j = 1 To k - 3

pos1 = j + 1

pos2 = j + 2

pos3 = j + 3

For i = 1 To n

For iter1 = 1 To n

 If matriz_origen(i, j) < matriz_origen(iter1, pos1) Then

  For iter2 = 1 To n

  If matriz_origen(iter1, pos1) < matriz_origen(iter2, pos2) Then

    For iter3 = 1 To n

      If matriz_origen(iter2, j) < matriz_origen(iter3, pos1) Then

       matriz_destino(cont1, j) = matriz_origen(i, j)

       matriz_destino(cont1, pos1) = matriz_origen(iter1, j)

       matriz_destino(cont1, pos2) = matriz_origen(iter2, j)

       matriz_destino(cont1, pos3) = matriz_origen(iter3, j)

       cont1 = cont1 + 1

       End If

    Next iter3

   End If

 Next iter2

 End If

Next iter1

Next i

Next j

End If

End Function

Function despliegue_2D(matriz() As Variant, Style As String, Title As String)

'Esta funcion permite el despliegue de un arreglo multidimentinal de 2 dimensiones.

'Declaration

Dim msg As String

Dim iter1 As Integer, iter2 As Integer

'Declaration

filas = UBound(matriz, 1)

columnas = UBound(matriz, 2)

'Loops

For iter1 = 1 To filas

    For iter2 = 1 To columnas

        msg = msg & matriz(iter1, iter2) & vbTab

    Next iter2

    msg = msg & vbCrLf

Next iter1

Response = MsgBox(msg, Style, Title)

End Function

Comment: Welcome to SO! When you post a reply, try to check that it is an answer to the original question. In your case, we cannot knot if it is, as part of your code is calling procedures that are not expose as despliegue_1D. You are fixing the number of items, that is variable... Edit your reply and complete your code.
Comment: finally  join the arrays
Comment: Thank you for your comments, i will complete my code with additional functions and ,matrices.

Combination Algorithm in Excel VBA


How do I set `OutputPath` in a Visual Studio 2017 project (new .csproj file format) without the target framework cluttering the resolved path?

Question: Setting OutputPath in the new Visual Studio 2017 project format automatically adds the target framework in the path. For example, if I have these set in the project file:
<TargetFramework>net462</TargetFramework>
<OutputPath>/build/debug/<OutputPath>

The actual output folder will resolve to /build/debug/net462/, not /build/debug/ like in the older versions.
How do I solve this without workarounds like moving things around with post build actions?
Comment: Not sure if it help but maybe try to override output settings like this:
`<PropertyGroup  Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU'>
    /build/debug/
$(BaseOutputPath)/`
Comment: I surely hope that there's no heuristic trying to decide what I'd like to get. But in my case it's just plain old .net 4.6.2 as the targetframework states in my example. edit: this is an answer to a question that I don't see anymore.
Comment: `BaseOutputPath` sets the outputpath base for different configurations, so it does not help in this case (I tested this to make sure). Thanks for the suggestion though!
Comment: The first `/` in `/build/debug/` makes it an absolute path (in Ubuntu at least).
Answer: The solution is to use AppendTargetFrameworkToOutputPath https://www.tabsoverspaces.com/233608-stopping-msbuild-appending-targetframework-to-outputpath/
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>

Comment: to remove the runtime identifier:
`false`
`false`
Comment: Leave it to Microsoft to (1) not give "new .csproj format" a name, (2) have VS IDE create code that doesn't work, and (3) not document the real solution. Too bad, because the solution itself is a good one.
Comment: Nowadays there is a note mentioning both these configuration parameters in https://learn.microsoft.com/en-us/visualstudio/ide/how-to-change-the-build-output-directory?view=vs-2019
Answer: The answer above is right, but you may also want to remove the runtime identifier:
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>


How to use the drop side of DropButtons?

Question: I'm having the hardest time using the dropdown list side of Krypton Dropbuttons -- specifically, I don't know how to register that I've actually selected something within the dropdown list.
In my project, I am using a dropbutton to apply a change over time, where simply clicking is immediate and the drop list has various increments of time -- I am using tweener-dotnet for the value change over time, as my calculus is awful and why reinvent the wheel?.
I am able to use the dropbutton as a regular button just fine.  In addition to that, I've been able to set my ContextMenu in the dropbutton, so when I build the solution and click on the dropdown arrow, the list shows up.  What I can't do, however, is figure out how to tell the code that I've actually selected something within the dropdown list.
I've spent a couple hours, collectively, staring at all three iterations of the DropButton examples, and none of them actually show what I'm looking for (seriously, Component Factory?!).
How do I use the dropdown side of the Krypton Dropbutton?
(For open source sake, I may just go back to a regular dropdown list and a regular button, but I really like the simplicity of the Krypton DropButton, and open source isn't really a priority with this project.)
Answer: I know that this is late, but I've been dealing with something similar.
For a KryptonDropButton you need to create a KryptonContextMenu, as @Roberto has stated.
Then I went to add a listener to the manu items that I've added to the assigned KryptonContextMenu and found out that the designer does not support the Name property (or maybe I was too blind to find it).
Anyway, I navigated to the designer file I found that those menu items were generated anyway, with default names.
Something like this:

I then went to rename those and added events like I would normally to respond to user selection, but I won't hide that this is overkill.
Answer: I'm about a year and a half late, but here's a radiobutton click event.
Just select the control and event at the top of the IDE.
Public Sub KryptonContextMenuRadioButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles KryptonContextMenuRadioButton1.Click

'do something

End Sub

Answer: Update 2018: the toolkit has been opensourced here: https://github.com/ComponentFactory/Krypton
Component factory hasn't been actively worked on since 2011. Its still closed source so that is an issue.
The Krypton Toolkit itself is a bit iffy in .net 4 and above. The KryptonContextMenu that you need with the KryptonDropButton is one of the bits that I've been having difficulty getting to work.


Show the following is a linear transformation:

Question: Let $T : \mathbb{R}^3 \rightarrow \mathbb{R}^3$ be defined by $$T(x, y, z) = (2x + y, x − z, x + y^2).$$
Determine whether or not T is a linear transformation. If it is, justify. If not, show why.
I'm mainly just checking my work.
I concluded that $T$ is not a linear transformation. This is because when showing the vector additions are equal, the last term will not work out. This is because of the $y^2$ term.
Is this true?
Comment: Yes! That is true
Comment: A simple counterexample is $T(0, 1, 0) = (1, 0, 1)$, but $T(2 \times (0, 1, 0)) = T(0, 2, 0) = (2, 0, 4) \not= (2, 0, 2) = 2T(0, 1, 0)$.
Comment: As a sanity check, each component of the output should contain only sums of inputs times coefficients (which could be 0). So having constants (i.e. 2x+3y + 7), quadratic, cubic, trig functions, absolute values, logs etc will instantly make it not a linear transformation. The $y^2$ is a dead giveaway
Answer: Yes, the above is not a linear transformation, because of the $y^2$ sitting in the third term. The best way to bring this out is to exhibit a counterexample explicitly showing the issue. $T(0,1,0) = (1,0,1)$ and $T(0,-1,0) = (-1,0,1)$, so $T(0,1,0) + T(0,-1,0) = (0,0,2)$.
However, $T((0,1,0) + (0,-1,0)) = T((0,0,0)) = (0,0,0) \neq (0,0,2)$. Hence, $T$ is not linear.


What does OPT PSEUDOSECTION mean in `dig` response?

Question: This is part of the response when I run dig in terminal:
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512

What does OPT mean? What does PSEUDOSECTION mean?
Comment: Crosspost https://unix.stackexchange.com/questions/588558/what-does-opt-pseudosection-mean-in-dig-response . Good thing I didn't find this first and waste my time -- I would consider that rude, greedy, and abusive, and would remember to not ever again do anything that might help you
Comment: @RyanLv When I wanted to post this question, I wasn't sure which StackExchange was most appropriate, so I posted it on two different ones. Turns out that cross-posting like that is a breach of StackExchange etiquette, which I didn't know before now. That's why it was downvoted. I've taken down the other post, which was on https://unix.stackexchange.com/questions/588558/what-does-opt-pseudosection-mean-in-dig-response.
Comment: It looks like a good question. Why people downvote this post? Does it break some rules?
Answer: So this has to do with something called Extended mechanisms for DNS (EDNS). A DNS message (by which I mean either a request or response) consists of the following five sections that may or may not have values:
- Header
- Question
- Answer
- Authority
- Additional

In the late 90s, people wanted to extend the functionality of DNS, but because of the way it was built, it was not possible to add more sections to the original list of five, nor to add new flags to the header. So EDNS was created, which among other things adds "pseudosections" to DNS. They're called that because they're actually just part of the ADDITIONAL section. They're not full sections in their own right, they're just "pseudosections."
EDNS also adds support for "pseudo- resource records." So far, only one pseudo- resource record type has been created: OPT, which stands for "options." OPT records don't actually carry any DNS information, just info "pertaining to the question-and-answer sequence of a specific transaction." In other words, they simply contain:

the version of EDNS that is being used
any EDNS flags
the size of the UDP packet that is carrying the request.

I recommend the wikipedia article on EDNS as well as the RFC that introduces it:
https://en.wikipedia.org/wiki/Extension_mechanisms_for_DNS
https://www.rfc-editor.org/rfc/rfc6891


How to run test perl script as cgi script with httpd?

Question: I'm trying to follow this tutorial and run sample script under cgi.
Below are steps which I did:
1) Made sample script
$ cat > test.pl <<EOF
> #!/usr/bin/perl
> print "Content-type: text/html\n\n";
> print "Hello, World.";
EOF

2) run httpd docker container and mounted created script as volume in cgi-bin directory:
$ docker run --name cgi_test --rm -p 3000:80 -v $(pwd)/test.pl:/usr/local/apache2/cgi-bin/test.pl httpd

3) check if CGI module is enabled:
$ docker exec -it cgi_test cat /usr/local/apache2/conf/httpd.conf | grep modules/mod_cgid.so
    #LoadModule cgi_module modules/mod_cgid.so

CGI module was turned out so I enabled it:
$ docker exec -it cgi_test sed -i 's,#\(LoadModule cgid_module modules/mod_cgid.so\),\1,g' /usr/local/apache2/conf/httpd.conf

4) Checked ScriptAlias directive and enabling of alias_module :
$ docker exec -it cgi_test cat /usr/local/apache2/conf/httpd.conf | grep "ScriptAlias /cgi-bin/"
    ScriptAlias /cgi-bin/ "/usr/local/apache2/cgi-bin/"
$ docker exec -it cgi_test httpd -M | grep -e cgid -e alias
 cgid_module (shared)
 alias_module (shared)

It was ok
5) Checked exec permissions:
$ docker exec -it cgi_test ls -la /usr/local/apache2/cgi-bin/test.pl
-rwxr-xr-x 1 1000 1000 76 Mar 20 12:41 /usr/local/apache2/cgi-bin/test.pl

It was ok
6) Restarted httpd in docker container:
$ docker kill --signal="USR1" cgi_test

But when I to to http://localhost:3000/cgi-bin/test.pl I see 503 Service Unavailable and this error in log:
[Wed Mar 20 19:03:02.323430 2019] [cgid:error] [pid 1446:tid 139952364902144] (22)Invalid argument: [client 172.17.0.1:34328] AH01257: unable to connect to cgi daemon after multiple tries: /usr/local/apache2/cgi-bin/test.pl

What else I need to do to run script ?
Answer: To run a script under CGI you don't need to change any file in the official httpd Docker image.
Make sure that your script is executable with a chmod +x test.pl and pass to the server program the -c option with the configuration directive to load the CGI module, as described in the following command:
docker run \
  -it \
  --rm \
  -p 127.0.0.1:8080:80 \
  -v $(pwd)/test.pl:/usr/local/apache2/cgi-bin/test.pl \
  httpd:alpine \
  httpd-foreground -c "LoadModule cgid_module modules/mod_cgid.so"

Some explanations:

Alpine variant image is used because it's smaller than the default Debian based image and it's more than enough for our purposes
httpd-foreground script is available in all official httpd images and it allows to execute Apache HTTP Server in foreground mode (it's equivalent to httpd -D FOREGROUND)
publish option -p contains also the loopback IP address to prevent access to this test server from the outside
Answer: To make everything work I was needed to restart httpd twice instead of once :
docker kill --signal="USR1" cgi_test  # (x2)

I thought maybe it's USR1 signal (Graceful Restart) issue , but i had same with HUP signal (Restart Now). To apply changes I need to send signal twice. So looks like httpd container issue.
Comment: You are a genius... It took me lots of time until I saw your answer and ran `apachectl restart` TWICE in my container...