Are there any "esoteric" statistic tests with very low power?

Question: Background
In computer science, mathematics, and sometimes in other fields, "esoteric" examples cannot only be entertaining, but helpful to illustrate certain concepts, for example:

Bogosort and Slowsort are very inefficient sorting algorithms that can be used to understand properties of algorithms, in particular when compared to other sorting algorithms.
Esoteric programming languages demonstrate how far-reaching the concept of a programming language is and help to appreciate good programming languages.
The Weierstraß function and Dirichlet function primarily find use to illustrate certain misconceptions about the concept of continuity.

I am currently preparing some teaching on using hypothesis tests and think that having a test with very low power (but no other flaws) would help to illustrate the concept of statistical power.
(Of course, I still have to decide myself whether a given example is didactically useful for my audience or just confusing.)
Actual Question
Are there any statistical test with intentionally low power, more specifically:

The test fits in the general framework of hypothesis tests, i.e., it works with a null hypothesis, has requirements, and returns a (correct) p value.
It is not intended/proposed for serious application.
It has an very low power (due to an intentional design flaw and not due to low sample or effect size).

If you can fundamentally argue that such a test cannot exist, I would also consider this a valid answer to my question.
If on the other hand, a plethora of such tests exists, I am interested in the most didactically efficient one, i.e., it should be easily accessible and have a striking effect.
Note that I am not asking for a general selection of statistical mistakes (cherry picking, etc.) or similar.
What I found so far
Internet searches returned nothing for me.
Every attempt to construct something like this ended either up in some (useful) existing test or the format is not that of a regular test.
For example, I thought about a test whether a population has a positive median that returns only yes if all samples are positive; but that test does not return a p value and thus does not fit within the usual test framework.
If I just count the positive and negative signs as a test statistic (and compute the p values accordingly), I end up with the sign test, which is a reasonable test.
Comment: An example test used in a class I was a student in (many years ago) was "roll a fair 20 sided die and reject if you roll a 1" (as part of a discussion of power curves). This of course completely ignores the data, but is a "valid" test in that it doesn't have higher than the desired type I error rate (which was 5% in the context the example was given in) .
Comment: Being more mathematical, "esoteric" examples (which abound) tend to be specific counterexamples to popular misunderstandings; a number of textbooks contain such examples. As it stands, your question is essentially a "big list" type question and so is too broad (though you should note that several users have concluded the question is unclear); if you can clarify your question and narrow its scope it may fit the site better.
Comment: Any of the silly estimators to which you apply Rao-Blackwellization could be used as a test statistic. For example, there's the first observation in the sample, used as an estimator of the mean. When Rao-Blackwellized, you obtain the sample mean. I had to do many exercises like this in class. Anyway, this statistic could be used instead of the sample mean in something like a $t$ test. But no, I can't think of anything directly in the form you're looking for, or I'd be writing an answer, not a comment. But there must be something, illustrating failure of a general method for test construction.
Comment: Low power compared to what? Lehmann gave an example of a generalized likelihood-ratio test that had lower power under any alternative hypothesis than under the null.
Comment: I'll dig out the Lehmann paper when I'm at a computer. The power of a test under the null is just the size of the test.
Comment: See Romano & Siegel (1986), *Counterexamples in Probability And Statistics*, Ch. 10, for ideas.
Comment: The signed rank test is indeed more powerful than the sign test, and used in the same circumstances, so that is good to land on. They aren't tests, but the Holm (and Holm-Sidak) adjustment for multiple comparisons preserves more power than Dunn's Bonferroni (and the Sidak) adjustment, and the Benjamini-Hochberg adjustment for multiple comparisons has yet more power, and does not suffer from some of the conceptual incoherence of the former. Understanding how these methods evolved is instructive: https://www.youtube.com/watch?v=oONHlua2gBY.
Comment: The Conover-Iman test is an obscure *post hoc* pairwise test following rejection of the Kruskal-Wallis omnibus test, but has strictly *more* power than the comparable and much better known Dunn's test (also *post hoc* to Kruskal-Wallis).
Comment: [Chebyshev's inequality](https://en.wikipedia.org/wiki/Chebyshev%27s_inequality) fits the bill, but I doubt many would agree with me. It's very popular in academic literature, but virtually powerless to be practical
Comment: @Glen_b: I am not specifically looking for a list of statistical mistakes or similar; this would be indeed too broad and the Internet is full of those already. So far, I failed to find a single instance of what I am looking for (and nothing was proposed as a comment or answer to this question, when open), so I expect this question to yield a short list at best. Still, I narrowed it down further to test with a low power (which is honestly the only thing I can conceive while staying within the framework for regular tests).
Comment: As for the unclarity, I tried to make a few points more restrictive or prominent, but it would probably help if one of those who think it is unclear could articulate their confusion.
Comment: The question would admit any example, so any answer that provided an example would be a correct answer. Thanks for the edits, though. While I still think it's overly broad I think the scope is better and I will reopen.
Comment: I find [this question](https://stats.stackexchange.com/questions/391580/checking-if-a-coin-is-fair)  about whether some number of observations of the pattern 'heads-tails-tails' indicates an unfair coin is a good example. The p value is low but the strenght of proof is small.
Comment: @Glen_b: I added some criterion that allows to compare answers. This way, this should not be less broad than other questions asking for didactic explanations or examples.
Comment: @MartijnWeterings: (I read that example more thoroughly now and deleted my previous comment.) Thanks. That indeed is an example of what I am looking for. You may want to turn this into an answer (possibly generalising or extremifying it).
Comment: @Scortchi: *Low power compared to what?* – Well, to any reasonable test for the same scenario. — *Lehmann gave an example of a likelihood-ratio test that had lower power under any alternative hypothesis than under the null.* – I cannot find the specific test you are alluding to (Lehman's œuvre seems to be focused on likelihood ratio tests). Moreover, I fail to make sense of the notion of "power under the null".
Comment: @Wrzlprmft: It seems as if you're just asking for examples of inadmissible tests, of which there are indeed a plethora. An easy way to find a quite useless test - one whose power doesn't depend at all on the parameter value - would be to use any non-constant function of an ancillary statistic as the test statistic. For example to use the sample range in a test concerning location parameter. I think it would help to describe more precisely the lesson you want to impart.
Comment: Lehmann (1950), "Some principles of the theory of testing statistical hypotheses", *Ann. Math. Statist.*, **21**,  1. He credits Stein for the example (which I'd forgotten), but still deserves the credit for the famous "worse than useless" verdict on the test. BTW, you ought to be able to generate worse-than-useless tests from your "reasonable" tests by changing the test statistic from $T$ to $-T$. As @user54038 suggested, what's interesting is "failure of a general method of test construction", or of intuition at least.
Answer: There's a little-remarked-on corollary to the Neyman–Pearson lemma (proof in Geisser (2006), Modes of Parametric Statistical Inference, Ch 4.4):
$$
\operatorname{E}\phi(X)=\alpha
$$
$$
\phi(x)  = \begin{cases}
  0\ & \text{when $f_0(x) < kf_1(x)$} \\
  1\ & \text{when $f_0(x) > kf_1(x)$}
\end{cases}
$$
defines the least powerful level-$\alpha$ test, $\phi$, of the null hypothesis $H_0:$ density $f_0$ vs $H_1:$ density $f_1$ from data $x$.
From this result you can derive uniformly least powerful, locally least powerful, uniformly least powerful similar, & least powerful "totally biased" tests (I mean those with lower power under any alternative than under the null). If you already have a uniformly most powerful, &c. test, simply multiply your test statistic by -1 to maintain the partitioning of the sample space it induces while reversing the ordering of the partitions.

Perhaps, as @user54038 suggests, "failure of a general method of test construction" might be more interesting. Lehmann (1950), "Some principles of the theory of testing statistical hypotheses", Ann. Math. Statist., 21,  1, attributes the following example to Stein:

Let $X$ be a random variable capable of taking on the values $0, \pm
 1, \pm 2$ with probabilities as indicated:
$$ \begin{array}{r c c c c c} & -2 & 2 & -1 & 1 & 0 \\ \hline
 \text{Hypothesis $H$:} & \frac{\alpha}{2} & \frac{\alpha}{2} &
 \frac{1}{2} - \alpha & \frac{1}{2} - \alpha & \alpha\\ \hline
 \text{Alternatives:} & pC & (1-p)C &
 \frac{1-C}{1-\alpha}\left(\frac{1}{2}-\alpha\right) &
 \frac{1-C}{1-\alpha}\left(\frac{1}{2}-\alpha\right) &
 \alpha\frac{1-c}{1-\alpha}\\  \end{array} $$
Here, $\alpha$, $C$, are
constants $0 < \alpha \leq \frac{1}{2}$, $\frac{\alpha}{2-\alpha}< C
 <\alpha$, and $p$ ranges over the interval $[0,1]$.
It is desired to test the hypothesis $H$ at significance level
$\alpha$. The likelihood ratio test rejects when $X=\pm2$, and hence
its power is $C$ against each alternative. Since $C<\alpha$, this test
is literally worse than useless, for a test with power $\alpha$ can be
obtained without observing $X$ at all, simply by the use of a table of
random numbers.

Note that it's the generalized likelihood ratio test he's considering, with $p$ in the role of a nuisance parameter to be maximized over. So when $X=-2$ or $X=2$, $\hat p=1$ or $\hat p=0$ respectively, & the likelihood ratio comes to $\frac{2C}{\alpha}$ in either case; for any other value of $X$ it's the lower value of $\frac{1-C}{1-\alpha}$.
Answer: (Related to the comment by @Scortchi)
Suppose $X \sim N(\mu, 1)$ and we want to test the hypothesis
\begin{align*}
H_0&: \mu = 0 \\
H_1&: \mu \neq 0
\end{align*}
For the sake of esetoricism, let's augment our data with an independent "coin flip"
$Z \sim Bernoulli(p)$ where $p$ is known and no smaller than the significance level $\alpha$ (i.e. $p \in [\alpha, 1]$). Consider rejection regions of the form:
$$R = \left\{(X, Z) \ | \ z = 1 \ \wedge |x| > \Phi^{-1}\left(\frac{\alpha}{2p}\right) \right\}$$
By construction, this is a valid test of size $\alpha$.
\begin{align*}
P(X\in R \ | \ \mu=0) &= P\left(Z=1 \ , \ |X| > \Phi^{-1}\left(\frac{\alpha}{2p}\right)\right) \\
&= P(Z=1)P\left(|X| > \Phi^{-1}\left(\frac{\alpha}{2p}\right)\right) \\
&= p\frac{\alpha}{p} = \alpha
\end{align*}
The power of this test however can never be more than $p$. For instance, suppose that our observed data is $(x, z) = (1000000, 0)$. It is obvious that the null hypothesis should be rejected, but since our coin "shows tails" we fail to reject the null. Setting $p=\alpha$ leads to an even sillier example where the rejection region doesn't depend on $X$ at all, but is still a valid Rejection region with size $\alpha$.
A similar question could be given as homework by changing intersection to union in the rejection region. This region is uniformly less powerful than the one without $Z$, but is more reasonable in the sense that power doesn't have an upper bound.
Comment: (+1) Closely related because having a one-dimensional ancillary statistic $S$, you can dispense with the coin flip by letting $Z=\boldsymbol{1}(S<F_S^{-1}(p))$, where $F_S(\cdot)$ is the distribution function of $S$.

Are there any “esoteric” statistic tests with very low power?


construct single CSS rule with @each

Question: I am looking for a way to construct a single CSS rule using severals parameters with Sass.
Let's say I want to create a mixin transition that takes targets as parameters to write one transition CSS rule (other parameters like transition time, etc. are constant).
@mixin transition($targets...) {
    @each $t in $targets {
        // construct the rule target by target
    }
    // and then transition: $rule; or something similar
}

I want to call it like
.foo {
    @include transition(color, width);
}

and get
.foo {
    transition: color 100ms ease-out, width 100ms ease-out;
}

Problem is, I was not able to find a way to construct a string by concatenation. Is it even possible, or is there a different way to do this?
Answer: Here's one way:
@mixin transition($targets...) {
    $items: "";
    @each $item in $targets {
        $i: index($targets, $item);
        @if $i == length($targets) {
          $items: $items + $item + " 100ms ease-out";
        }

        @else {
          $items: $items + $item + " 100ms ease-out, ";
        }
    }
    transition: unquote($items);
}

Codepen (see compiled css)
1) Set a variable to hold the string
$items: "";
2) In the $each loop iteration get the index:
$i: index($targets, $item);

3) Concatenate each item to the $items variable. If it's the last item - then the string won't end with a comma - otherwise it will
@if $i == length($targets) {
  $items: $items + $item + " 100ms ease-out";
}

@else {
  $items: $items + $item + " 100ms ease-out, ";
}

4) Finally remove the quotes from the string with unquote
transition: unquote($items);

Usage:
.foo {
    @include transition(color, width);
}

Which produces compiled CSS:
.foo {
  transition: color 100ms ease-out, width 100ms ease-out;
}

Comment: Exactly what I was looking for. Thanks a lot!

construct single CSS rule with @each


Prove every infinite recursively enumerable subset of $\Bbb N$ contains an infinite recursive subset

Question: Given that:

An infinite subset of $\Bbb N$ is recursive if and only if it is the range of a strictly increasing recursive function.

Now I wonder if It can be proved that:

Every infinite recursively enumerable subset of $\Bbb N$ contains an infinite recursive subset.

From the definition of recursively enumerable set, it is the range of a recursive function $f$. Although in the definition, the $f$ is not necessarily strictly increasing, I wonder if I can use this function to define a new one which is strictly increasing recursive function and whose image is a subset of $im(f)$. And hence reach the conclusion.
So may I please ask if it can be done? How to do that exactly? Thanks in advance!
Note: It is from a math course. And I have not learnt about the related things about computer science (for instance, I have not learnt about the Turing machine). So sorry I cannot understand explanations which involves the usage of terms in computer science. May I please ask for a mathematical approch please?
Thanks!
EDIT: The definition of recursive function is given by:
Comment: Let $A$ be an infinite r.e. subset of $\mathbb N;$ so $A$ is the range of a recursive function $f:\mathbb N\to\mathbb N.$ For $n\in\mathbb N$ let $g(n)=\max\{f(1),f(2),\dots,f(n)\};$ then $g$ is a recursive function, and the range of $g$ is an infinite recursive subset of $A.$
Comment: What you gave is not the right definition of recursive function.
Comment: No, that's not the right definition.
Comment: @AndrésE.Caicedo I have been given that a recursive function is recursive if it is both partial recursive and total. I'll edit to add the orginal version of the definition.
Comment: @AndrésE.Caicedo So may I please ask what is the right one? It is given by my textbook and we are taught to use this version...
Comment: @AndrésE.Caicedo What do you mean? That seems right to me.
Comment: @Noah Conditions 1-5 are not enough. In particular, all functions obtained that way are total, and Ackermann's function would not be recursive.
Comment: @AndrésE.Caicedo Minimalisation is allowed to be used, which can allow partial recursive function to be generated.
Comment: Ah, I missed that. Sorry, ignore the noise.
Comment: What is the definition of "minimalisation"?
Comment: @RobArthan I have edited to give a definition.
Comment: @PropositionX: thanks. The $\mu$ operator you have defined should be referred to as  "minimisation" or "minimization". Your textbook is wrong to refer to it as "minimalisation".  Using $\mu$ and the given recursive function $f`(x)$ whose range is infinite, you can define a function $g(x)$ that enumerates a strictly increasing subset of the range of $f$.
Comment: @RobArthan I am trying on this track and is it applying minimalization to find the least value of the characteristic function is true and greater then the former output number? Is the idea correct? I have trouble how to formalize it and write it out.
Answer: Actually, it looks like your definition of partial recursive function is indeed incorrect: it is missing the primitive recursion clause. Without this clause, we get a strictly smaller class of functions. In fact, it's not hard to show that the function $f(n)=n^n$ grows faster than every function you can express using your system.
So how do we solve the problem with the correct definition? Suppose I have an r.e. set $X$. Since $X$ is r.e., we have $X=ran(f)$ for some recursive function $f$.  Intuitively, I can find an infinite recursive subset $S\subseteq X$ as follows: each time I see $f$ enumerate some element of $X$ bigger than every element previously, I put it in $S$. The "bigger than every element previously" means that this set is in fact intuitively recursive: if I want to know whether $n\in S$, I wait until this process either puts $n$ into $S$ (in which case $n\in S$) or puts something bigger than $n$ into $S$ (in which case $n\not\in S$ since we can never "come back" to it).
Now we have to implement this strategy. We first define an auxiliary function $i$ which counts when $f$ "goes up":

$i(0)=0$,
$i(n+1)$ is the least $x$ such that $f(x)>f(i(n))$. (We could add the requirement that $x>i(n)$ but by induction we can show that this won't be necessary).

If we can show that $i$ is recursive, then we'll let $g(x)=f(i(x))$; it's clear that $g$ is increasing, and $ran(g)\subseteq X$, so we'll be done.
So how do we show that $i$ is recursive? This is where the primitive recursion scheme comes in handy. We have $i(n+1)=x$ iff $x$ is the least number such that $f(x)>i(n)$, that is, the least $x$ such that $i(n)+1-f(x)=0$ (I use "$-$" to denote natural subtraction here). So $i$ can be defined by primitive recursion as:

$i(0)=0$,
$i(n+1)=h(i(n))$, where $h(a)=\mu x (a+1-f(x)=0)$.

And now we're done.
Comment: Thanks a lot. My textbook does mention that primitive recursive functions are recursive latter.
Comment: @PropositionX I'm curious, what textbook are you using? (I'm curious whether they just forgot to add the prim. rec. scheme, or whether there's something else going on.)
Comment: This is a 500-page notes given by our lecture, which has 3 chapters on recursion theory. Latter in the notes we will learn about computability and Godel's incompleteness theorem.
Comment: As mentioned in the book, wherever a minimalisation is used, it can be shown that it can be replaced somehow with a primitive recursion. I think that is a reason why it discuss primitive recursion latter.
Comment: What is $\mu$ representing here?
Comment: @David $\mu$ is the [$\mu$ operator](https://en.wikipedia.org/wiki/%CE%9C_operator) - "$\mu x(P(x))$" denotes (if it exists) the smallest number with property $P$. So in this case, the smallest $x$ such that $a+1-f(x)=0$.
Comment: @NoahSchweber Thank you, I was just making sure!
Comment: @NoahSchweber: I was also stuck with the same problem. I was trying to find out explicitly an infinite computable subset of the diagonal halting set but couldn't succeed.
Comment: Are you sure that the definition is wrong? As far as I know, Gödel's beta function can be coded using only minimization, multiplication and addition (and constants), and it can in turn be used to code sequences, which can be used to emulate prmitive recursion.
Comment: @Veky I am pretty sure of this. Try writing out the details of your approach, I am highly confident that it will break down.
Comment: I'm quite sure the burden of proof should be on you (you claim that published material is wrong) but so be it. From minimization, subtraction and addition define ordering (<=). From it and multiplication define equality (=). From minimization, ordering and multiplication define quotient. From it, multiplication and subtraction define remainder. From it define beta function. From beta and minimization define coding of sequences. From it and minimization define (.)_ and lh. From it define primitive recursion in a standard way (last item in a minimal inductive sequence satisfying initial cond).
Comment: @NoahSchweber I may be mistaken, but perhaps the 6th line from the bottom of your answer s/b $f(x)>f(i(n))$, since $i(n)$ is a function for finding the x's where $f$ increases. $i$ is not a subset of the range of $f$. The 5th line from bottom s/b something different too. Maybe $f(i(n+1))-f(x)>0$? Also, the second line from the bottom is wrong, I believe. Otherwise, $i(1) = h(i(0)) = \mu x (0+1-f(x)=0)$. But we aren't guaranteed that there exists an $f(x)$ that equals 1.

Prove every inﬁnite recursively enumerable subset of $\Bbb N$ contains an inﬁnite recursive subset


JS/CSS 3dtransform constant movement

Question: I'd like to use the wheel script I found here: http://codepen.io/Aldlevine/pen/yGLqd and add something to allow it to be always slowly rotating until it's hovered/clicked. Can anyone suggest how to do this?
<code>$( '.wheel > div' ).each( function( i ) {
                var angle = -( coords.y / 2 ) + ( 360 / 10 ) * i;
                $( this ).css( 'transform', 'perspective(3000px) rotate3d(1,0,0,' + angle + 'deg) translate3d(0,0,75px)' );
</code>
Answer: You could listen for the transitionend-event and restart the animation once that happens. This will make it run "forever". As soon as you notice a :hover, you can stop the ongoing transition.
Take a look over here for a reference how to better control the CSS3 transitions.
Comment: But the animation would have to start for the event to happen. It doesnt do anything currently until interacted with. What to call to make it start spinning is where I'm most confused.
Comment: Then listen for the document to have loaded, then start the animation at that point. Take a look at the window loaded event.
Comment: I know it would be run on pageload, what I'm asking is what command/function would I run?? Since the existing onchange function loops thru each div and sets a css transform on each, would I have to basically duplicate that into an onload?
Comment: Since the existing code uses #s from the mousewheel or drag operation, i dont understand the best way to set an initial arbitrary rotation & speed.

JS/CSS 3dtransform constant movement


Overwrite float:left property in span

Question: I want the submit button to appear below the map. I can achieve this by deactivating float:left. How could I achieve this?
I tried overwriting the properties of .

{{ form.media }}

And modifying the properties of the widget. Neither worked.
widgets = {
    'Location':  OsmPointWidget(attrs={
      'map_width': 300,
      'map_height': 300,
      'style':'float:none'}),

Answer: Using custom css (in a custom css file or in the header), you can override the float:left by adding:
#id_Location_span_map {
  float: none!important;
}

Overwrite float:left property in span


Is it possible to change the position of the frets of an electric guitar?

Question: Is it possible, and how would I go about changing the position of the frets of an electric guitar, for example making some frets a quarter tone sharp or flat? As another more difficult example, would it be possible to slightly correct the pitch of one fret by moving it by a distance on the scale of millimeters?
The reasoning behind this is that I'm really interested in microtonal music, not necessarily quarter tonal. There are a lot of cool equal temperament tunings that I can choose from, and some would very probably require placing some frets very close to where there is an existing one. I could just leave them slightly out of tune because I'm not familiar with microtonal tunings anyway, but if I'm doing this I want to do it a bit better than that.
Answer: Yes, this is absolutely possible. I think Tolgahan Çoğulu is probably the outstanding practitioner of this (although Steve Vai has done some work in this area)
Tolgahan uses variable fret positions for microtonal reasons and for playing with differing intonations and temperament. See this video for an example.

As you can see, his technique has been to insert slots allowing each fret-let to be moved independently of the others. As he points out in one of his videos, this is not easy, so I wouldn't recommend it if you don't need it.
Yes, you can absolutely make tiny pitch changes by moving frets.
Comment: Note: he's also done some work on just adding additional partial frets to, what seem to me to be, standard guitars.  https://youtu.be/XT4oOYj4SwQ
Comment: The hardest part of this seems to be the movable frets. if one were to pick specific spots and use a drill, one can make "peg-like" fret pieces using fret wire that could fit those holes. Might involve welding or soldering a peg onto fret wire
Answer: A quick Google search found plenty of fretless guitars.  These should let you play any fraction of a semitone.
For a limited range, you could use non-standard tuning and raise or flatten a string by a quarter tone.  Then using two strings, you could play super-chromatically.  For a quarter tone super-chromatic scale you would need to alternate between two adjacent strings. Of course, by tuning some strings close together, your total range would be reduced.
Comment: Fretless guitars sound rather different, require a much more specialized technique, and render many chords very difficult or impossible to play.  It's not really the same instrument.
Comment: @ScottWallace What do you mean by "they are not really the same instrument"? My ex-bandmate played a fretless electric guitar. He could play any chord that I could and the sound was no different than his fretted counterpart...
Comment: @Cypher- I have yet to see anyone be able to play chords on a fretless guitar and get them tuned exactly as on a fretted guitar- just look where your fingers are in, say, an E major chord.  And the sound of fingered strings is also different with or without frets- they are more damped without.  That, and the ease of playing in tune, is why there are frets at all.
Comment: @CarlWitthoft- not only do you not have to play sextuple stops on cello, you also play (usually) with a bow, which continually puts energy into the strings.  The sounding time of plucked strings is considerably less without frets, and they are also quite a bit more damped.  This is not bad, but it's different.
Comment: @housemdwonderer filing down the frets on an old guitar will create a fretless guitar.
Answer: It's quite possible, and doable, although I can't see why.Given that the sonic distance between one fret (any fret) and the next is a semitone, taking the higher fret wire out and cutting a small slot with a hacksaw exactly half way between will give the position for a quarter tone note.
Actually, it's not exactly half way, as each fret going up is approximately 94.5% of the measurement of the previous fret. So, 55%/45% would be a better proportion. Note, these measurements are aproximate, and can be worked out more accurately by someone who did maths O level less than 50 yrs ago...
Millimetres on the lowest frets, perhaps several thous on the upper ones.
Answer: For setting up quarter-tone divisions, and even down to realizing alternate temperaments, you probably do not need to remove the existing frets; i.e. you don't need to "move" the frets, just add additional ones at the appropriate places.  This process of placing (partial) frets between the existing ones has been demonstrated to be practical by Tolgahan Çoğulu, see this video, and related content.
For your smaller scale problem, shifting the point of contact between the string and the fret by a millimeter or two can probably be accomplished by installing custom shaped frets within the existing slots.  By shaping the frets to peak at one side or the other, instead of being symmetrically crowned.   Note that this degree of tone adjustment can probably be effected by just pressing harder, pulling on the string (along the neck) or bending the string (across the neck) without modifying the frets themselves.
Comment: @Tim if his goal is to be able to produce (a subset of) quarter tones, then he doesn't need to "move" the existing frets at all -- he just needs to add additional frets at the appropriate place.  Tolgahan shows that this is practical.
Comment: Can't see how this answers the question.
Comment: I don't see how you can adjust the position of a guitar fret by "a millimeter or two" by reshaping, given that guitar frets are usually about two millimeters wide max, and crowned in the middle.  If you want to shift a fret by two millimeters, you need a new fret.
Comment: Since standard frets are crowned in the middle, you would need a fret at least four millimeters wide, and not already crowned, to be able to shift the position two millimeters, and that only if you made the highest point at the extreme edge of the fret.  Not doable with normal frets.
Comment: So don't move the existing wires, but there still needs to be an exact spot where any additional fretwires will go, which I think is the reasoning behind the question.
Answer: Installing additional frets is a fair bit of work and you really should have some experience in fretted instrument repair and construction. Assuming you have that, consider approaching this the way it's done on a harp. If what you really want is to be able to play exact 1/4 tones or some other absolute value, consider creating a device to sharpen each string exactly by 1/4 tone by changing its tension. Something like a mini-tremolo-bar for each string, but with a fixed, lockable position. This will allow you to sharpen any or all of the notes on each string with a single operation, rather than requiring you to install many, many new frets for each string. This also avoids the issue of "how wide is each fret". If you're not sure what I'm describing, find a friend with a harp, or research harp construction. A trade off of course, is that when playing you have an additional movement to make each time you want to switch from 'sharped' to 'non-sharped' on a string. Concert harps do this with a convenient foot pedal, simpler harps have a lever by the tuning pin for each string.
Answer: My wife plays the pipa, which has lots of awsome frets going all the way down the body, not just the neck, and I say awsome because the ones on the neck are huge chunks of cow horn or obsidian, not just little wires.
Anyway, the low-end instrument I got her to rekindle her interest developed a creep or bend in one end of one fret and it was a little off.
But, she can compensate by pushing to one edge and rolling her finger off the fret and onto the string, essentially holding it some distance from the fret's position.  I suspect you can do the same with a guitar.
Meanwhile, our band features another instrument that has fully movable tips that bridge the strings, and it is re-tuned between numbers.  Take a look at the Guzheng!  One style of playing reminds me of the steel guitar.  That article mentions "Experimental, atonal pieces have been composed since the 1980s" as well.

Update:  I happen to have just uploaded a video that shows this feature of the guzheng.  The performer explains how the scale used can tell you something about the region of the music, and then retunes the instrument from the pentonic scale to (not stated) on-stage.  At the marked position:

Also, note that this instrument facilitates microtone playing by pushing on the string on the other side of the bridge.  This does not act as a fret, but adds tension to the string.  It's used commonly for a viberto effect, but she can be seen doing it on a couple notes besides that — presumably to get a sharp or other note that there's no string for.
Answer: It may depend on what type of guitar you want this for. On an electric with a bolt on neck, it probably would not be too hard. You may have to commission a lutherie to build you such a neck, maybe the CAD drawings of such a neck already exist, who knows?
If they do not exist it may take a fair bit of expense and coercion to get your lutherie to commit to such a project. To pay a hundred dollars for some drawing of an already proven concept is one thing, but to develop this with no way of really knowing if more than one person is ever going to be interested in the concept is going to be hard to justify.
Maybe you find that the first luthier you contact about this is so intruged by the concept that he decides to make it his life work to build such a guitar, just dont count on it.
In my experience luthiers are purists, they are set in their ways. The want to build their guitars. They tolerate the things people pay for because they do need a certain amount of work to survive, but only to a point.
Contact your local lutheries and see what their response is, maybe your experience with them is totally different than what mine is. Maybe your luthier has the policy of willing buyer, willing seller, again who knows?
If you do not find a person who shares your vision then really consider becoming a luthier yourself. This so sounds like a Herman Hauser-esque anecdote that is just 30 years away from completion?


Redirect domain to www, but on subdomain do not use www

Question: I have a multilanguage website. The main language is English and the second language is Spanish.
I need to have all the traffic using this domains:

English domain: www.example.com
Spanish domain: es.example.com

If I use the .htaccess rules from Drupal, I can redirect all the traffic to www, but it includes the Spanish traffic too. Or I can remove www to use es.example.com, but again, it would redirect the English traffic to use example.com (without www).
I have tried a lot of .htaccess combinations but I finish in a worst situation that is redirecting the Spanish traffic to the Encglish URL, so... I need to know what rules can I use to have these redirections:

example.com to www.example.com
www.es.example.com to es.example.com
Answer: These rules must be included in Drupal's .htaccess file, before the RewriteBase / line.
<code>RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ http%{ENV:protossl}://www.example.com%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} ^www\.es\.example\.com$ [NC]
RewriteRule ^ http%{ENV:protossl}://es.example.com%{REQUEST_URI} [L,R=301]
</code>


Is there a formal relation between weight regularization and compression?

Question: In my understanding, compression, strictly speaking, means that we diminish the amount of data required to describe something, such as a model. E.g. compressing an image file means to create a file that is literally smaller in terms of bits but contains (almost) the same information.
In the context of machine learning, it seems to me that compression literally means that we decrease the amount of bits required to describe a model. For example:

L1 weight regularization of a statistical model results in a subset of parameters being $0$, so that we require less information to describe it. (We can just remove those variables for example)

However, other regularization techniques have a similar effect in terms of making the model "simpler". E.g. L2 regularization also makes the model "simpler" and generally less overfitty, but it doesnt tend to set the parameters literally to $0$, only to "small". So we aren't actually literally compressing the model.
Yet there intuitively is a sense in which $L2$ also "compresses" the model: it intuitively causes the distribution of parameters to be tighter around "simple" models.
Is there a way that this intuition can be formalized, so that we can see even methods like L2 as compression?

it seems like this is more of a "probabilistic" notion of compression, as we are not literally getting a smaller data file for the resulting parameters of the model, but there is nevertheless less information (in the sense of information theory) in the distribution over models (prior to observing the data).
if we round the parameters to the nearest nth decimal digit (as is necessary in any computer implementation), we may in some cases literally get a smaller set of possible parameters for a given problem distribution
Comment: you may be interested in this paper https://arxiv.org/abs/1705.08665
Answer: If you assume some gaussian prior on weights, and are willing to accept some small quantization error, then you can do the following:

Quantize your weights/prior to some very fine tolerance
Encode them with the optimal code corresponding to your prior. This should take $-\log P(\theta)$ bits where $P$ is your prior and $\theta$ are your parameters

Of course negative log density of the standard gaussian is proportional to $||\theta||_2^2$, so the number of bits it takes to express your model is proportional to the L2 regularization term.
Regarding the quantization part: while this may at first seem like an ugly workaround to the impossibility of encoding real numbers in a finite amount of bits, you can take a more bayesian approach and say that you have a posterior distribution over the model weights.
In that case, a wider posterior corresponds to a lower coding cost and a narrower posterior corresponds to a higher cost. Hinton and Camp show via the "bits back" argument that you can actually quantize as finely as you want in this case without spending any bits at all (technically you still have to spend them, you just get a refund)!


Ubuntu : 'ANDROID_HOME' environment variable is set to non-existent path

Question: My android sdk path is : /home/iassureit-02/Android/sdk
.bash_profile file was not there so created the one with touch command and put below lines in it.
<code># Android
export ANDROID_HOME=/home/iassureit-02/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
</code>
After running meteor run android command I am getting below error:
<code>✓ Java JDK
✗ Android SDK: 'ANDROID_HOME' environment variable is set to non-existent path:
  /home/iassureit-02/Library/Android/sdk
  Try to update it manually to point to valid SDK directory.
✗ Android target: Android SDK not found. Make sure that it is installed. If it
  is not at the default location, set the ANDROID_HOME environment variable.
✗ Gradle: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK.

  Looked here:
  /home/iassureit-02/Library/Android/sdk/tools/templates/gradle/wrapper
</code>
Why is it looking for SDK in library folder?
I am not getting what is the problem.
Answer: Maybe try to export this environment variable in .bashrc if you find it ? Because if .bash_profile did not exist, your Pc may have his variables set to .bashrc. (mine did not have .bash_profile either, so I added it to .bashrc and it works).
Comment: PS : The sdk folder is the one with the "tools" and "platform-tools" folders, check if this is the case in your "/home/iassureit-02/Android/Sdk" folder :)


How to convert CGPoint to SCNVector3

Question: How to convert CGPoint to SCNVector3?
I want to transfer the touchpoints in UIView to the SceneView. But how?
I couldn't find any resources in the forum.
Answer: Just look at your SCNView class, there is a lot of juicy stuff in there.
/*!
@method hitTest:options:
@abstract Returns an array of SCNHitTestResult for each node that contains a specified point.
@param point A point in the coordinate system of the receiver.
@param options Optional parameters (see the "Hit test options" group for the available options).
*/
let hitResults:[SCNHitTestResult] = mySCNView.hitTest(point, options:[:])

https://developer.apple.com/documentation/scenekit/scnhittestresult
https://developer.apple.com/documentation/scenekit/scnhittestresult/1523058-worldcoordinates

How to convert CGPoint to SCNVector3


redirect old url to new url

Question: I am facing a problem in redirecting a old url to a new one.
This is the old url: http://www.abc.com/department.asp?dept=Minimal%20cloth
the new url should be: http://www.abc.com/Minimal-cloth
Please suggest me the best possible way
Comment: do you whant to do this in a webpage redirect or using server side redirect?
Comment: Hi,I don't want to use it in a webpage or using any server side redirect....I want to use .htaccess..
Answer: Can you try following rules in your .htaccess file:
Options +FollowSymLinks
RewriteEngine on

# to take care of /department.asp?dept=Minimal%20cloth or
# /department.asp?dept=Minimal cloth tyoe of URLs
RewriteCond %{QUERY_STRING} ^dept=(.+)(\s|%20)(.+)$ [NC]
RewriteRule ^department\.asp$ /%1-%3? [R=302,L,NC]

# to take care of /department.asp?dept=MinimalCloth type URLs
RewriteCond %{QUERY_STRING} ^dept=(.+)$ [NC]
RewriteRule ^department\.asp$ /%1? [R=302,L,NC]

Remember RewriteRule doesn't match query string.
Comment: Hi Anubhava,sorry to reply late.I tried with it but again it takes me to the 404 page...Is there anything with the %20
Comment: Hi Anubhava....the code is working well sorry my mistake,I missed an operator.But its not what I am trying to do...Is it not possible to use mod alias i mean using 301 redirect.I have to redirect one by one suppose a category from old site which doesn't exist in new site so in that case it will not find and send me to 404 but at a same time I want to redirect that old category in a new one.I don't know how to do it.
Comment: Actually if you make a minor change to have rewrite rule like this: `RewriteRule ^.+\.asp$ /%1-%3? [R=302,L,NC]` then you don't need to have a rule for each category.
Answer: Apache's mod_rewrite is perfect for this. Excellent tutorial here.
Comment: Hi..thanks...ya I have gone through that tutorial but no luck :(
Comment: Well, I don't know what you expect me to suggest, because and mod_rewrite is how you would do this if you wanted to use .htaccess. Either mod_rewrite does not work on your server or you are doing something incorrectly. Either way, mod_rewrite DOES work and is in use on hundreds of thousands of websites all around the world. So ya, read the tutorial again.
Comment: mod_rewrite is working in my server and I was trying to use something like this

Redirect 301 "/department.asp?dept=Minimal/ expense/" http://www.abc.com/Minimal-expense

How can I achieve this using htaccess
Comment: That isn't mod_rewrite. The module uses RedirectRule and RedirectCond directives in the .htaccess file, so I don't think you have read and followed the tutorial (it's on the third page, btw :).
Answer: Depending on which modules are enabled in the apache server's config, you can use either mod_alias or mod_rewrite for this. To use mod_alias, use something like
RedirectMatch 301 ^/department\.asp\?dept=(.*) /$1

To use mod_rewrite try something like:
RewriteCond %{QUERY_STRING} ^dept=(.*)$ [NC]
RewriteRule ^/department\.asp/%1 [R=301]

These haven't been tested, but hope they get you started.
Comment: RewriteRule doesn't match query string only REQUEST_URI is matched.
Comment: oops, thanks @anubhava, forgot that RewriteRule doesn't look at query string....I updated my answer
Comment: Hi Dave...sorry to reply late....I have tried this one too but same as before...its taking me to 404

redirect old url to new url


How to evaluate $\frac{\partial}{\partial x}\Gamma(f(x))$?

Question: If my math is correct:
$$\Gamma(f(x))=\displaystyle \int_0^\infty e^{-t}t^{f(x)-1}dt$$
$$\frac{\partial}{\partial x}\Gamma(f(x))=\displaystyle \int_0^\infty e^{-t}f^\prime (x)\textrm{ln}(t)t^{f(x)-1}dt$$
$$=f^\prime (x)\displaystyle \int_0^\infty e^{-t}\textrm{ln}(t)t^{f(x)-1}dt$$
But here I get stuck. The integral is tantalizingly close to the definition of $\Gamma(f(x))$, except for the $\textrm{ln}(t)$ term. I've tried integration by parts to resolve the integral but no luck so far.
I'm hoping to find a formula for $\frac{\partial}{\partial x}\Gamma(f(x))$ that can be expressed from the terms: $\Gamma(f(x))$, $\Gamma^\prime(x)$, or $\Gamma(x)$ and therefore can be calculated in the R program I'm running.
Answer: By the chain rule for derivatives.
$$\partial_x\Gamma(f(x))=\Gamma^\prime(f(x))f^\prime(x).
$$
Now using the digamma function defined by $\psi(x)=\partial_x\log\Gamma(x)$ we easily derive  $\Gamma^\prime(x)=\Gamma(x)\psi(x)$; hence,
$$\partial_x\Gamma(f(x))=\Gamma(f(x))\psi(f(x))f^\prime(x).
$$
Edit:
Based on OPs comments we may also use this approach:
By the chain rule and definition of digamma
$$\partial_x\log\Gamma(f(x))=\psi(f(x))f^\prime(x).
$$
But it is also true that
$$\partial_x\log\Gamma(f(x))=\frac{\partial_x\Gamma(f(x))}{\Gamma(f(x))}.
$$
Combining these equalities and rearranging to solve for $\partial_x\Gamma(f(x))$ gives the desired result.
Comment: Using the chain rule again, if we want to find $\frac{\partial}{\partial x}\textrm{ln}(\Gamma(f(x))$:$\frac{\partial}{\partial x}\textrm{ln}(\Gamma(f(x))=\psi(f(x))=\frac{\Gamma^\prime(f(x))}{\Gamma(f(x))}=\frac{\psi(f(x))\Gamma(f(x))f^\prime(x)}{\Gamma(f(x))}=\psi(f(x))f^\prime(x)$, is that correct?
Comment: @RobertF Almost, we still need to use the chain rule: $\partial_x\log\Gamma(f(x))=\psi(f(x)) f^\prime(x)$. But, $\partial_x\log\Gamma(f(x))=(\partial_x\Gamma(f(x)))/\Gamma(f(x))$ and so the result follows.
Comment: Yes if I break it out as $t=\textrm{ln}(u)$, $u=\Gamma(v)$, $v=f(x)$ then $\frac{\partial}{\partial x}\textrm{ln}(\Gamma(f(x))=\frac{\partial t}{\partial u}\frac{\partial u}{\partial v}\frac{\partial u}{\partial x}=\frac{1}{\Gamma(f(x))}\cdot\Gamma^\prime(f(x))\cdot f^\prime(x)=\psi(f(x))\cdot f^\prime(x)$. I think that's right.


Probability of getting the required pattern on rolling a die

Question: I have a fair six-sided die and I keep rolling it til I get a pattern of 3 consecutive numbers say 1-2-3. I want to find the probability of me rolling the die an odd number of times till I achieve my required pattern.
I am unable to comprehend the outcomes that are in my favor.
Answer: For $0\le k\le 2$, let $p_k$ be the probability that the first occurrence of the roll sequence $1,2,3$ occurs after an odd number of (future) rolls, given that the prior $k$ rolls (from oldest to most recent) match the first $k$ terms of $1,2,3$.

Our goal is to find $p_0$.

Then we have the following system
$$
\begin{cases}
p_0=\left({\large{\frac{1}{6}}}\right)(1-p_1)+\left({\large{\frac{5}{6}}}\right)(1-p_0)\\[4pt]
p_1=
\left({\large{\frac{1}{6}}}\right)(1-p_2)
+\left({\large{\frac{1}{6}}}\right)(1-p_1)
+\left({\large{\frac{2}{3}}}\right)(1-p_0)
\\[4pt]
p_2={\large{\frac{1}{6}}}
+\left({\large{\frac{1}{6}}}\right)(1-p_1)
+\left({\large{\frac{2}{3}}}\right)(1-p_0)
\end{cases}
$$
of $3$ linear equations, in $3$ unknowns.

Solving the system, we get $p_0={\large{\frac{216}{431}}}$.

Explanation:

Initially, there are no prior live terms to keep track of.

At any point before the first occurrence of the roll sequence $1,2,3$, the number of prior live terms is either $0$, $1$, or $2$.

If the prior roll is $1$, then $k=1$ (we have one prior live term).$\\[4pt]$
If the last two rolls (oldest to most recent) are $1,2$, then $k=2$ (we have two prior live terms).$\\[4pt]$
Otherwise, we have $k=0$ (the number of prior live terms is zero).

The number of prior live terms (i.e., the value of $k$) can be regarded as the state of the game.

Note that $p_k$ is the probability of success, given state $k$, in an odd number of future rolls. Hence, after the next roll, we want the probability of failure, not success. That explains the expressions of the form $(1-p_j)$ on the right-hand side of each equation.

Now let's consider the equations, one at a time . . .

When $k=0$, there are two possibilies:

If the next roll is $1$ (probability ${\large{\frac{1}{6}}}$), the state changes to $k=1$.$\\[4pt]$
Otherwise (probability ${\large{\frac{5}{6}}}$), the state remains at $k=0$.

Therefore we have $p_0=\left({\large{\frac{1}{6}}}\right)(1-p_1)+\left({\large{\frac{5}{6}}}\right)(1-p_0)$.

When $k=1$, there are three possibilies:

If the next roll is $2$ (probability ${\large{\frac{1}{6}}}$), the state changes to $k=2$.$\\[4pt]$

If the next roll is $1$ (probability ${\large{\frac{1}{6}}}$), the state remains at $k=1$.$\\[4pt]$
Otherwise (probability ${\large{\frac{2}{3}}}$), the state changes to $k=0$.

Therefore we have
$
p_1=
\left({\large{\frac{1}{6}}}\right)(1-p_2)
+\left({\large{\frac{1}{6}}}\right)(1-p_1)
+\left({\large{\frac{2}{3}}}\right)(1-p_0)
$.

When $k=2$, there are three possibilies:

If the next roll is $3$ (probability ${\large{\frac{1}{6}}}$), the game is over, and we have success.
If the next roll is $1$ (probability ${\large{\frac{1}{6}}}$), the state changes to $k=1$.$\\[4pt]$
Otherwise (probability ${\large{\frac{2}{3}}}$), the state changes to $k=0$.

Therefore we have
$
p_2={\large{\frac{1}{6}}}
+\left({\large{\frac{1}{6}}}\right)(1-p_1)
+\left({\large{\frac{2}{3}}}\right)(1-p_0)
$.
Comment: Cool!  I was going to say 'darn close to $\frac{1}{2}$ so might as well set to that and call it a day' ... but that's great you got the exact answer
Comment: How did you get that system of equations?
Comment: @saisanjeev: I edited in an explanation.


Show ticker text without a notification

Question: I have a requirement i my project. We want to show a text in the status bar where we have time and network signal icons. But we don't want to have notification. the text just display, scroll as usual and then disappear completely. There should be no notification in the panel. Any idea how to achieve  this? I know there is no straightforward way to do this. Can any one provide any hack ??
Update:
I am able to generate notification and cancel it after some time. For this i have created a handler and cancel it after some time. But the problem is now to calculate time based on text size. I want to cancel the notification only when it completely rolled out.
final NotificationManager mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                context)
                .setSmallIcon(R.drawable.icon)
                .setTicker("abcd efgh ijkl mnop qrst uvwx yz abcd efgh ijkl mnop qrst uvwx yz abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz")

                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                .setOnlyAlertOnce(true);

        mNotificationManager.notify(SharedPreferenceUtil.getInstance()
                .getNotificationId(context), mBuilder.build());

        Handler handler = new Handler();

        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                Utility.Log("Notification Removed", Log.VERBOSE);
                mNotificationManager.cancel(id);
            }
        }, 10000);

        Utility.Log("Notification Posted", Log.VERBOSE);

Answer: Yes, you can do it
You set the notification like this:
notificationManager.notify(0, notification);

And After that you can remove from the notification list like this
NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationmanager.cancel(0);

Answer: Have you tried posting notification, and instantly dismissing it?
Comment: Yes i have tried it but the problem is it shows only that text which can reside in one line on status bar. If i have a text which would come in 3-4 line in status bar then it will show only one line. After that it disappear.

Show ticker text without a notification


Finding an angle between the side of a triangle and a segment from a point inside the triangle.

Question: Question given below:

ABC is a triangle and D is a point inside ABC such that:
$$
m(\widehat{DCB})=m(\widehat{CBD})=18^{\circ}\\
m(\widehat{ACD})=24^{\circ}\\
m(\widehat{DBA})=12^{\circ}\\
m(\widehat{DAC})=\alpha=?
$$
This is supposed to be a high-school level question. But i can't find the α. Is there something obvious i'm missing?
I checked that question is well-posed and α = 78 degrees. If i can just show that $|CD|=|CA|$ then i'm done. But that's the only step i can take in this question (If this can be called a step at all.).
Comment: Are you sure there is no more info about the point $D$? Like it being circumcenter or something?
Comment: what else is given?
Comment: @taninamdar Nope. That's all given. No more information other than that. Also, i checked now (out of curiosity) and D is not circumcenter in this question.
Answer: By the Trig Ceva Theorem,
$$\frac{\sin(12^\circ)}{\sin(18^\circ)}\cdot \frac{\sin(18^\circ)}{\sin(24^\circ)}\cdot\frac{\sin(\alpha)}{\sin(108^\circ-\alpha)}=1$$
hence:
$$\sin(96^\circ-\alpha)+\sin(120^\circ-\alpha)=2\cos(12^\circ)\sin(108^\circ-\alpha)=\sin(\alpha)$$
or:
$$2\cos(12^\circ)\sin(108^\circ)\cos(\alpha)=(2\cos(12^\circ)\cos(108^\circ)+1)\sin(\alpha)$$
or:
$$\tan(\alpha)=\frac{2\cos(12^\circ)\sin(108^\circ)}{2\cos(12^\circ)\cos(108^\circ)+1}$$
from which it is tedious (but not difficult) to check that $\alpha=78^\circ$ is the wanted solution.
The identity:
$$\sin(18^\circ)+\sin(42^\circ)=\sin(78^\circ)=\cos(12^\circ)$$
is interesting in itself, but just follows from the Briggs formulas.
Comment: Thanks for the answer. But i was looking for more elementary methods. I was hoping maybe i can reduce your answer to that, but nothing comes up. Do you have any idea how can i find an elementary solution to this question?
Comment: @Alistair: Honestly I don't know. It is sufficient to prove that $DAC$ is an isosceles triangle, or that the angle bisector of $\widehat{DAC}$ is perpendicular to $AD$, but it isn't so obvious to me at the first glance.
Comment: Okay. But, in your $\tan\alpha$ formula, how am i going to find out that $\alpha=78^\circ$ without calculator? It seems all things come down to a comparison between algebraic representation of $\tan78^\circ$ and some formula involving (at least) algebraic representation of $\sin6^\circ$ (or something close to it).
Answer: I solved this with elementary methods. In case of anyone interested comes and looking for answer and for archiving reasons, i post the solution:

Draw angle bisector of $\widehat{ACD}$ making $\overset{\Delta}{BEC}$ isosceles. Draw perpendicular from $E$ to $[BC]$ trisecting $\widehat{BEA}$ and making $\overset{\square}{ACDE}$ kite, therefore proving $|CA|=|CD|$.


Convert value to string using #define

Question: My task is to convert a float or integer value to string in C. I can't use sprintf since I am working in embedded platform. So I thought to use something like this.
#define CURRENT(STRING,S_NO,VALUE) (str = "S"#S_NO#VALUE"A")

and invoking it like this
int a=10,b=20;
CURRENT(str,a,b);

So str should be S1020A. But I am getting SabA.
What am I doing wrong here?
Comment: The C preprocessor run at compile time. When you `#define` things, you aren't making a function.
Answer: Macros are evaluated before compilation so CURRENT(str,a,b); is expanded using the variable names a and b rather than their values which may only be available at runtime.
To convert an int to a char array at runtime without use of sprintf etc. use itoa if available or you could write a function like the following (untested!)
#define MAX_INT_STRING_BYTES (11)

void IntToString(int val, char* str)
{
    char reversed[MAX_INT_STRING_BYTES]
    int index, i = 0;
    bool negative = false;
    if (val == 0) {
        *str++ = '0';
        *str = '\0';
        return;
    }
    if (val < 0) {
        negative = true;
    }
    while(val != 0) {
        reversed[index++] = (char)('0' + abs(val % 10));
        val /= 10;
    }
    if (negative) {
        *str++ = '-';
    }
    for (i = index; i > 0; i--) {
        *str++ = reversed[i - 1]);
    }
    *str = '\0';
}

Comment: `itoa` is nonstandard (win-only) and a very bad api anyway. Always use `snprintf`.
Comment: @R.. Thanks, I hadn't realised it was windows only. The OP isn't able to use `sprintf` so I guess that leaves him with some variant of my suggested code...
Answer: It only knows what the value of a and b is at runtime, and preprocessor directives are resolved at compile time. Thus what you're trying to do won't work.
You can however do something like:
#define CURRENT(STRING,S_NO,VALUE) sprintf(STRING, "S%i%iA", S_NO, VALUE)

Or just make it a function.
Or just call the sprintf directly instead of CURRENT.

Convert value to string using #define


RouterLink url changes to default url while opening new tab

Question: Routerlink url should not change to default url..
When I use  RouterModule.forRoot(appRoutes, { useHash: true }); its working fine.. but I changed to useHash = false, its not working
In html I have used this code:
{{recentMenu.applicationMasterName}} - {{recentMenu.applicationCode}}

Routing page:
const appRoutes: Routes = [
       .....
 {
   path: 'applicationredirect', component: ApplicationRedirectComponent,
 },
  {
path: 'home', component: HomeComponent,
   }
  ...
// otherwise redirect to home
{ path: '**', redirectTo: 'home' }
  ];
const StartupRouting = RouterModule.forRoot(appRoutes, { useHash: false });

When I open in new tab,
First I got,
localhost:4200/applicationredirect?appId=1084518
then it changes to this,
localhost:4200#/home
finally I got this default page
localhost:4200/home#/home
I want (localhost:4200/applicationredirect?appId=1084518) url to be open..
Answer: That's a normal behavior. Several points:

If you want to call routes without the hash, don't provide the second argument  { useHash: ... }
You didn't declared the applicationredirect segment in your router config object, so until you declare it, it will fallback to the /home route as you set it to { path: '**', redirectTo: 'home' }.
Remove this if you have it in any module: { provide: LocationStrategy, useClass: HashLocationStrategy } since PathLocationStrategy is default strategy


Executing Javascript to populate a drop down before HTML page loads

Question: I have 2 Drop Downs in a HTML form. The first dropdown needs to be populated with a list of usernames present in the DATABASE.
Secondly, Depending upon the selection made in the first drop down, I then need to run another JS script to make another call to the DB to retrieve the list of associated addresses to that username.
Can you please let me know whats the best way to achieve this objective?
1) How can I run a JSscript before the HTML form loads to return that list?
2) Should I get both the usernames and associated addresses in one Db call or just get the usernames first and then use onChange event on the first dropdown to execute the second call?
Any code would be most appreciated.
Thanks
Answer: well if you have all the info in same table then why dont you get all data in one go by querying as to the DB and then sort and put up data in the elements the way you want.
the other way will need to query DB 2 times.
Comment: I suppose querying the Db once makes sense but then how do I populate the other drop down depending upon the selection in the first drop down. I can currenlty get all the usernames in a buffered string where each new username is comma separated.
Comment: for drop down lists ther is the value property, you can check which option was selected, then with some if statements you can determine which drop down menu to show
Comment: The data resides in 2 different tables:

1) Users table for Username, UserID (that are active)

2) Address table contains UserID and AddressID)

So, usernames are displayed in the first dropdpwn list and depending on the username selected, the associated UserID will be then used to query Address table to get the addressID for that userID.
Comment: then you wil definately have to query twice right!! depending on the value of selected drop down menu. so on selection populate your another drop down with the required fields
Answer: <code>here you can create your HTML to server call OR you can make HTML locally.
i have created options for selectbox at server and innerhtml to locally.

<select id="selectbox1" onchange="getData(this)"></select>
<select id="selectbox1"></select>

$(document).ready(function() {

$.ajax({
  url: 'http://localhost/getUsername.php',
  success: function(data) {
    $('#selectbox1').html(data);
    alert('Load was performed.');
  }
});

});

function getData(selData) {

$.ajax({
  url: 'http://localhost/getSecoundCall.php?id='+selData,
  success: function(data) {
    $('#selectbox2').html(data);
    alert('Load was performed.');
  }
});

}
</code>


How to redirect VPN traffic on OS X

Question: I have following problem: I need to connect to VPN and access specific resources (ip addresses). When I connect to VPN all network traffic goes through VPN but in fact I need only specific destinations to be accessed over VPN and the rest of the traffic to go through default route and avoid VPN.
Here is the result of netstat -nr
Before I connect to VPN:
Routing tables

Internet:
Destination        Gateway            Flags        Refs      Use   Netif Expire
default            192.168.0.1        UGScI          19        0     en1

After I connect to VPN:
Routing tables

Internet:
Destination        Gateway            Flags        Refs      Use   Netif Expire
default            10.1.1.1        UGSc          123     3744    jnc0
default            192.168.0.1        UGScI          19        0     en1

So as you can see I have 2 default routes after VPN connected.
All internet traffic goes through the first default route which is undesirable behaviour.
Is there a way to set priority for the default route? So all traffic by default doesn't go through VPN but only manually created routes redirect to VPN i.e. sudo route -n add 184.108.40.206 10.1.1.1
Comment: Talk with your VPN provider and ask them to enable split tunnelling.
Comment: It seems it is enabled because under ubuntu I have a script which creates appropriate routes and set priority to custom split route table but I am not sure how to do this on OS X. If interested take a look at  http://apple.stackexchange.com/questions/217700/how-to-set-up-routing-tables-on-os-x-to-redirect-vpn-traffic
Comment: Please provide details on the VPN server configuration.
Comment: Are you using L2TP VPN configured in the OS X Network System Preferences? If so, have you verified that if you go to  > System Preferences > Network > select your VPN interface on the left pane > Advanced... > Options > deselect the "Send all traffic over VPN connection" option?
Comment: Duplicate of http://serverfault.com/questions/247135/force-juniper-network-client-to-use-split-routing
Comment: I am using Juniper client to connect to VPN network
Answer: Yes, you can delete the default route (for the VPN) and then set up new route(s) for only those networks/address that you want to get routed through the VPN.  Use sudo route delete to delete routes.

How to redirect VPN traffic on OS X


.htaccess rule seemingly ignored

Question: I have a Marionette application that manages routes, but I don't want it handling them for api call requests to server.com/api/anything/at/all
My rule looks like this at the moment, but Marionette seems to be always catching it, even when it's for /api/*
# ------------------------------------------------------------------------------
# | Marionette                                                                    |
# | If it's not for /api/*, then handle it                                        |
# ------------------------------------------------------------------------------

<ifModule mod_rewrite.c>
    DirectorySlash Off
    RewriteEngine On
    RewriteCond %{THE_REQUEST} ^.*/index.php
    RewriteCond %{REQUEST_URI} !^/api/ [NC]
    RewriteRule ^(.*)index.php $1 [R,L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/index\.php
    RewriteRule (.*) index.php
</ifModule>
# ------------------------------------------------------------------------------
# | Phalcon                                                                    |
# | If it fell through, handle with Phalcon                                    |
# ------------------------------------------------------------------------------

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
</IfModule>

Can anyone tell me what I've done wrong here please? Thanks.
Edit: If it gives any clarity, the above .htaccess is in my /public folder. In the root folder I have:
# ------------------------------------------------------------------------------
# | Phalcon                                                                    |
# ------------------------------------------------------------------------------

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule  ^$ public/    [L]
    RewriteRule  (.*) public/$1 [L]
</IfModule>

That public rewrite works fine. I just thought I'd share it in case there's something about it affecting the one in public that I'm not thinking of. Thanks!
Answer: You Marionette rule should be like this:
<ifModule mod_rewrite.c>
    DirectorySlash Off
    RewriteEngine On
    RewriteCond %{THE_REQUEST} ^.*/index.php
    RewriteCond %{REQUEST_URI} !^/api/ [NC]
    RewriteRule ^(.*)index.php $1 [R,L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{THE_REQUEST} !\s/+(index\.php|api/) [NC]
    RewriteRule ^ index.php [L]
</ifModule>

Comment: I replaced my block with yours and I still get the same response.

server.com/ -- Marionette
server.com/api/ -- Marionette
server.com/api/test -- Marionette
Comment: Yes, that worked - thank you. Any idea on how I ensure that it's only working for server.com/api/x/y/z? I tested with server.com/marionette/api/ and because it contained 'api' it feel through the rule to phalcon. So I'm looking to make the rule say that /api/ is at the start?
Comment: I tweaked rule further to match `/api/` only at start.

.htaccess rule seemingly ignored


Nginx Wildcard for try_files

Question: So I'm trying to setup a default nginx config file that can be deployed across numerous docker image with different website configs in each container. It is currently set as below:
server {
   listen 80 default_server;

   root /var/www/;
   index index.php index.html;

   server_name localhost;
   include php5-fpm.conf;

   location / {
           try_files $uri $uri/ /index.php?q=$request_uri;
   }

   location /status {
           stub_status on;
           access_log   off;
           allow 127.0.0.1;
           deny all;
   }

}
The problem is that it doesn't work for static sites that use index.htm or index.html
I can edit the location section like below and then the site will work. Is there any way to get nginx to use a wildcard, so index.* and it will use whichever index file it finds? index.* by itself does not work so not sure what needs to be added/removed...
       location / {
           try_files $uri /index.htm?q=$request_uri;
   }

Answer: You're fixated on the wrong part of try_files.
The part relevant to what you want is $uri/, with the trailing slash, which you seem to have removed. This bit causes nginx to try all of the files listed in the index directive.
You should put this part back in try_files and then edit the index directive to include the filenames you want.
Comment: Thanks, Yes I added index.htm to the index directive and it works 100%. I was fixated on the wrong part as you said.

Nginx Wildcard for try_files


A problem concerning combinatorics and probability

Question: Here is the problem, I think perhaps I cannot distinguish the differences between the following circumstance clearly and I am not sure of my answers and analysis either!
There are 400 dormitory rooms along with 400 distinct room numbers for 60 math students. Any math student can stay in any of the 400 dormitory rooms.

Suppose you are a math student and are recording the room number for all math students, one at a time until you have found a match (This means that a room number has already been recorded).

i) What is the probability that it takes more than 30 students for this to happen?
ii) What is the probability that is takes exactly 25 people for this to happen?

Suppose you are a math student and are recording the room number for all math students, one at a time you have found a student who shares the same dormitory room with you. What is the probability that it takes exactly 28 math students for this to happen?

Well, I think that for 1(i), I may first select 30 persons out of 400 students as the numerator, then all those 30 students have 400 choices, so the denominator would be 400^30.
As for 1(ii), I just did it in the same way as (i) but to change 30 into 25. I also multiply 25 since 1 out of 25 has the same choice.
As for 2,  I think that everyone just make a different choice than me so i put (399/400)^28 as my answer.
However, I am really not sure of these! I cannot judge the differences between those circumstances clear in my head and it's confusing for me.
Answer: The first situation has a changing probability as rooms are recorded. There's no chance of a match on the first student ($p$(non-match)$=1$), then (assuming always failing) the second student has $399/400$ chance of nonmatch, the third student has $398/400$ chance of non-match, and so on. The probability of reaching the situation where the thirtieth student has also failed to match any of the earlier $29$ dormitory numbers is thus
$$\frac{400!}{370!}\frac{1}{400^{30}} \approx 0.327828$$
If you need to remove the case where there is never a match, do the same calculation for the case of 60 failures-to-match:
$$\frac{400!}{340!}\frac{1}{400^{60}} \approx 0.009444$$
The second case is similar, except you need to adjust to make the final pick successful.
For question $2$, you are not trying to match an increasing population of rooms, so the problem just involves trying to match one number, with the same probability of failure or success on each trial - effectively the "second student" case, above, over and over again, with one success at the given endpoint.
Comment: so the 1(II) should be 400!/(376!*24*400^25) ?
Comment: Why is P(non-match for first room) = 1 , i.e. why can't the first student be in the first room ?
Comment: In question 1, the first student can't match any previous student, because there is no previous student.


Problemas ao receber lista de valores do Storage em uma variável (Ionic)

Question:

Eu tenho os dados armazenados no Storage da forma que está na primeira imagem e na segunda imagem o código que deveria atribuir os valores do Storage a variável prods. Esse código está em um método que irei chamar no clique de um botão. Porém depois que chamo o método e vou imprimir o valor da variável prods, está como undefined. :(

Código do botão, onde é chamado o método (add ou update) dependendo da situação.
    <ion-button expand="block" icon-start (click)='add_or_update()'>

      <ng-template *ngIf="product.id;then btn_update; else btn_add"></ng-template>

      <ng-template #btn_update>
        <ion-icon name="create"></ion-icon>
        Atualizar
      </ng-template>

      <ng-template #btn_add>
        <ion-icon name="add"></ion-icon>
        Adicionar
      </ng-template>

    </ion-button>

Método que faz a verificação de qual ação executar (add ou update)
add_or_update() {
  this.product.id ? this.update() : this.add();
}

Método add que vai chamar o método que contem o código com problema
add() {
    this.loadingService.present();
    this.product.profile = this.auth.user.profile_id;

    this.checkProductTagStorage(); // #### AQUI ####

    this.productService.add(this.product).subscribe(
      data => {
        this.loadingService.dismiss();
        this.toastService.success('Animal cadastrado com sucesso!');
        this.products.unshift(this.product);
        this.clear();
      },
      error => {
        this.loadingService.dismiss();
        this.toastService.error('Erro ao cadastrar produto!');
      }
    );
  }

Método em que ocorre o problema
  checkProductTagStorage() {
    this.prods = [];

    this.storage.get('coovita-prods-list-type-1').then((data) => {
      this.prods = data;
      console.log(this.prods); // Imprimindo a variavel está com os dados corretos
    });

    console.log(this.prods); // Imprimindo aqui a variavel está vazia []
  }

Comment: Seria possível por favor informar mais detalhes para reproduzirmos o problema? Talvez montar um exemplo no stackblitz ajude as outras pessoas a entenderem melhor o problema.
Comment: Recebo uma lista de produtos de uma API e depois armazeno no storage. Depois eu quero passar esses dados do storage para uma variável. O estranho é que dentro desse get da imagem se eu mandar imprimir a variável prods vai imprimir os valores corretamente. Porem fora, mesmo depois de chamar o método que faz essa requisição, se eu mandar imprimir a variável está como undefined. O que seria realmente interessante eu mostrar para ajudar?
Comment: Seria legal postar o trecho do seu template onde a variável `prods` é utilizada e o botão que ativa a função `get`. Pelo que vi até agora está tudo correto! após chamar o `get` a variável `prods` é preenchida e pode ser utilizada em outras partes do código.
Comment: Não utilizo a variável no template, eu quero esses dados só para fazer uma verificação se já existe alguma tag cadastrada com o mesmo valor. Editei a descrição e adicionei os métodos. Eu estou sem entender porque os dados estão sendo recebidos corretamente só dentro da função get. :(
Comment: Agora ficou mais claro. Vou deixar a resposta com os detalhes. Espero que ajude :)
Answer: Ao chamar a função add() o navegador vai interpretando linha a linha deste método.
Quando ele chega no this.checkProductTagStorage() ele chama essa função e já vai para a próxima
linha this.productService.add(this.product).subscribe(....
Seu problema está justamente aí porque dentro do método checkProductTagStorage o trecho this.storage.get
é executado de forma assíncrona. Logo, this.prods é atualizado depois que o método add() já foi executado.
Um exemplo do que está acontecendo com seu código:

let prods = null;

function add1() {
  checkProductTagStorage1();
  console.log(prods);
}

function checkProductTagStorage1() {
  // Atualiza o prods depois de 200ms
  setTimeout(() => { prods = 1; }, 200);
}

add1();
setTimeout(() => { console.log(prods); }, 200);

Uma das formas de resolver é utilizar uma Promise com o async\await:

    let prods = null;

    async function add1() {
      await checkProductTagStorage1();
      console.log(prods);
    }

    function checkProductTagStorage1() {
      return new Promise(resolve => {
        // Atualiza o prods depois de 200ms
        setTimeout(() => {
          prods = 1;
          resolve();
        }, 200);
      });
    }

    add1();
    setTimeout(() => { console.log(prods); }, 200);

No seu código seria algo do tipo:
async add() {
    this.loadingService.present();
    this.product.profile = this.auth.user.profile_id;

    await this.checkProductTagStorage(); // #### AQUI ####

    this.productService.add(this.product).subscribe(
        data => {
            this.loadingService.dismiss();
            this.toastService.success('Animal cadastrado com sucesso!');
            this.products.unshift(this.product);
            this.clear();
        },
        error => {
            this.loadingService.dismiss();
            this.toastService.error('Erro ao cadastrar produto!');
        }
    );
}

checkProductTagStorage() {
    return new Promise(resolve => {
        this.prods = [];

        this.storage.get('coovita-prods-list-type-1').then((data) => {
            this.prods = data;
            console.log(this.prods); // Imprimindo a variavel está com os dados corretos

            resolve(); // Indica que a promise foi resolvida
        });

        console.log(this.prods); // Imprimindo aqui a variavel está vazia []
    });
}

Comment: Perfeito. Eu já tinha visto o carregamento dos dados na variável sendo feito da maneira correta quando eu executava o **storage.get** no método **ionViewWillEnter**. Já estava até buscando uma explicação pra isso. Sua explicação resolveu tudo aqui :) Muito obrigado !!


Increasing a version between a XML Tag

Question: I have made a application to update my other applications. I am using autoupdater.net library to handle the updates. My question is how can I get the version of one application from another?
<?xml version="1.0" encoding="UTF-8"?>
<item>
    <version>184.108.40.206</version> // I would like to update this with the assembly version of another application
    <url></url>
    <changelog></changelog>
    <mandatory mode="2">true</mandatory>
</item>

What this application does is deletes the current zip, zips up the release folder and then the last step would be updating this xml document with the new version number.
Comment: Does this answer your question? [Modify XML existing content in C#](https://stackoverflow.com/questions/2551307/modify-xml-existing-content-in-c-sharp)
Comment: @HereticMonkey that helps with the edit but then I need to be able to get the version number of the other assembly to write to the note.
Comment: Doing some research on your own would be nice... [Getting the Version of my C# app?](https://stackoverflow.com/q/36351866/215552)
Comment: @HereticMonkey reading the question would be nice... Not trying to get the version number of the application updater application just the version of the application it is updating...
Comment: Considering your question includes no code, and doesn't reference what application is getting what version where. This was a tough one. I had to add "another" to the search phrase "how to get the version of another assembly": [How to get Assembly Version (not File Version) for another EXE?](https://stackoverflow.com/q/2724546/215552)
Answer: This should work:
XmlDocument doc = new XmlDocument();
doc.Load(@"filepath");

var versionNode = doc.SelectSingleNode("item/version");
versionNode.InnerText = Assembly.GetExecutingAssembly().GetName().Version.ToString();
doc.Save(@"filepath");

You can also load the xml from a string directly if you don't have a file on your disk. Also this gets the version string of the executing assembly. Replace this with the version number if needed.
Comment: Or if you need to get the version of an assembly without even loading it, try this: https://stackoverflow.com/questions/187999/how-do-i-get-the-version-of-an-assembly-without-loading-it
Comment: I tested it with the xml you provided, works for me. To navigate through the nodes with SelectSingleNode, you can just use xpath syntax. Here's a list of available options: https://www.w3schools.com/xml/xpath_syntax.asp
Comment: Very close, but I am trying to get the assembly version of a entirely different assembly
Comment: You can also use Assembly.GetAssembly(someTypeInTargetAssembly) to get another assembly version

Increasing a version between a XML Tag


How to compile PushNotifications code for ios only not for android in Titanium

Question: I am using Push-notifications code its working fine for ios but because of that not running in Android is there any way so that I can put any condition so that that particular code compile/run for ios and for android skip that particular code?
Comment: Done Successfully..follow my communication with Robert on below url..

http://developer.appcelerator.com/question/131680/sdk-181-android-modules-problem
Answer: try Titanium.Platform.osname != "android"
or Titanium.Platform.osname == "iphone"
you can find more options here


(Absolute) convergence of $\sum_{k=1}^n (-1)^k \frac{3^k+2}{4^k -6}$

Question: We want to check if the following sequence converges (absolutely):
$$\sum_{k=1}^n (-1)^k \frac{3^k+2}{4^k -6}$$
Since we have $(-1)^k$, we can use the Leibniz criterion.
We have to prove that $a_n$ is a null sequence and that it is monotonically decreasing.
$$\lim_{k \to \infty} \frac{3^k+2}{4^k-6} = \lim_{k \to \infty} \frac{(\frac{3}{4})^k + \frac{2}{4^k}}{1 - \frac{6}{4^k}} = 0$$
To prove that it is monotonous decreasing, we have to show $a_n \geq a_{n+1}$
$$a_n \geq a_{n+1} \\ \Leftrightarrow \frac{3^k+2}{4^k-6} \geq \frac{3^{k+1} +2}{4^{k+1}-6} $$
But how do we continue from here?
Comment: Does Leibniz criterion really deduce absolute convergence? For the sum you are considering, one can get away with some simple estimates. Notice that for all $k \geq 1$ we have, say, $3^k + 2 \leq 2 \cdot 3^k$. Can you find a similar estimate for the denominator?
Answer: As Lionel Ricci's comment indicates, rather than trying to use the Leibniz criterion (note that, as described in Leibniz Criterion, this criterion (also called the alternating series test) only indicates the series converges, not that it necessarily converges absolutely), instead use that, for $k \ge 2$, we have $4^k - 6 \gt 4^{k-1}$ and $3^k + 2 \lt 3^{k+1}$. Thus,
$$\frac{3^k+2}{4^k-6} \lt \frac{3^{k+1}}{4^{k-1}} = \frac{3^2(3^{k-1})}{4^{k-1}} = 3^2\left(\frac{3}{4}\right)^{k-1} \tag{1}\label{eq1A}$$
Therefore,
$$\sum_{k=1}^{\infty}\left|(-1)^k\left(\frac{3^k+2}{4^k-6}\right)\right| \lt \frac{5}{2} + \sum_{k=2}^{\infty}9\left(\frac{3}{4}\right)^{k-1} = \frac{5}{2} + \frac{9\left(\frac{3}{4}\right)}{1 - \frac{3}{4}} = \frac{59}{2} \tag{2}\label{eq2A}$$
Comment: @user1234567890 Note $\frac{3^k + 2}{4^k - 6}$ at $k = 1$ becomes $\frac{3 + 2}{4 - 6} = \frac{5}{-2} = -\frac{5}{2}$, i.e., the first term in the series. However, I forgot $(-1)^1$ makes it positive, and with *absolute* convergence, we need to have absolute values around each of the terms, it should be $\frac{5}{2}$ instead. I've now fixed this. I apologize for the confusion with my mistake. Finally, as for other ways to do this, using some sort of comparison is, I believe, the simplest & easiest way, although there are different comparisons you may use, e.g., as the other answer indicates.
Comment: Thank you. How do we get to $3^2 (\frac{3}{4})^{k-1}$ and what is this approach called?
Comment: @user1234567890 You're welcome. Regarding how to get $3^2\left(\frac{3}{4}\right)^{k-1}$, I have added an extra detail in that equation. Note that $3^{k+1} = 3^2(3^{k-1})$, so I removed that factor so both the numerator and denominator were to the power of $k-1$, then moved that power outside, i.e., $\frac{3^{k-1}}{4^{k-1}} = \left(\frac{3}{4}\right)^{k-1}$. Finally, I'm not quite sure what you mean by the "approach", but I'm using a comparison test here, with a strictly increasing series (i.e., the partial sums) have an upper bound and, thus, they converge.
Comment: @user1234567890 As long as all values are defined (i.e., there's no value where there's a division by $0$), then the sum of any finite number of terms is finite and, thus, doesn't affect whether or not the series converges, either normally or absolutely. Thus, one can start the series at any index value when checking for convergence, which is why I didn't originally include $k = 1$ in the summation. Nonetheless, for completeness, I've updated my answer to include that as well.
Comment: Sorry, this is confusing me. Where does the $-\frac{5}{2}$ come from? Is there really no other way to do this? This question gave only 4 points in my exam
Answer: The series $\sum_{k=1}^\infty a_k$ is said to converge absolutely if $\sum_{k=1}^\infty \vert a_k \vert < \infty$, or rather
$$
\lim_{n \to \infty} \sum_{k = 1}^n \vert a_k \vert < \infty.
$$
Notice that the Leibniz test determines whether the series converges, not whether it converges absolutely. A typical example when this test is used is to determine whether the series with $a_k = (-1)^k n^{-1}$ (i.e. the so-called alternating harmonic series) converges or not (it does, but not absolutely!).
To figure out if your series converges or not, one can consider some rather simple estimates. You can check that for all $k \geq 1$ we have $3^k + 2 \leq 2\cdot 3^k$, and for all $k \geq 2$ we have $4^k - 6 \geq (1/2)4^k$. Therefore
$$
\sum_{k=1}^n \left\vert (-1)^k \frac{3^k + 2}{4^k - 6} \right\vert \leq \frac{5}{2} + 4 \cdot \sum_{k=2}^n \left( \frac{3}{4} \right)^k.
$$
What can you say about this rightmost sum?


My code returns a JSONDecodeError but the only thing in the file is {}

Question: Please read to the bottom before answering.
My code loads the JSON from a file called reference.json. Then it adds different object to file, then dumps it back to the file. But when it does that return this error:
Ignoring exception in command import:
Traceback (most recent call last):
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\code\nexus-developments\workflow-discord-bot\cogs\import_test_suite.py", line 120, in attach_command
    self.dump_json(json_content, new_file, new_channel, message=message)
  File "C:\code\nexus-developments\workflow-discord-bot\cogs\import_test_suite.py", line 61, in dump_json
    reference_content = json.load(reference_file)
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\__init__.py", line 299, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)

JSON file:
{}

Coding Snippet:
    def dump_json(self, json_content, new_file, channel, message=None):
        if new_file:
            reference_file = open("json/reference.json", "w+")

            reference_content = json.load(reference_file)

            reference_content[str(channel.name)] = {}
            reference_content[str(channel.name)]["guild_id"] = int(channel.guild.id)
            reference_content[str(channel.name)]["channel_id"] = int(channel.id)
            reference_content[str(channel.name)]["message_id"] = int(message.id)

            json.dump(reference_content, reference_file, indent=4)

        file = open(f"json/{channel.name}.json", "w")

        json.dump(json_content, file, indent=4)

Full Code:
from discord.ext import commands
from os import path
import utils
import discord
import json

class ImportTestSuite(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    async def get_json_content(self, ctx):
        attachments = ctx.message.attachments

        if len(attachments) == 0:
            embed = discord.Embed(description="You need to provide 1 JSON attachment",
                                  timestamp=ctx.message.created_at,
                                  colour=discord.colour.Colour.red())

            embed = utils.add_promotion_footer(embed)

            await ctx.send(embed=embed)

            return None

        attachment = attachments[0]

        if attachment.filename.split(".")[1] != "json":
            embed = discord.Embed(description="You must attach a `.json` file",
                                  timestamp=ctx.message.created_at,
                                  colour=discord.colour.Colour.red())

            embed = utils.add_promotion_footer(embed)

            await ctx.send(embed=embed)

            return None

        attachment_content = await attachment.read()

        try:
            json_content = json.loads(attachment_content)
        except json.JSONDecodeError:
            embed = discord.Embed(description="You must attach valid JSON.\nUse "
                                              "https://jsonformatter.curiousconcept.com/ or an alternative to"
                                              " validate JSON",
                                  timestamp=ctx.message.created_at,
                                  colour=discord.colour.Colour.red())

            embed = utils.add_promotion_footer(embed)

            await ctx.send(embed=embed)

            return None

        return json_content

    def dump_json(self, json_content, new_file, channel, message=None):
        if new_file:
            print(message)
            print(channel.id)
            reference_file = open("json/reference.json", "w+")

            reference_content = json.load(reference_file)

            reference_content[str(channel.name)] = {}
            reference_content[str(channel.name)]["guild_id"] = int(channel.guild.id)
            reference_content[str(channel.name)]["channel_id"] = int(channel.id)
            reference_content[str(channel.name)]["message_id"] = int(message.id)

            json.dump(reference_content, reference_file, indent=4)

        file = open(f"json/{channel.name}.json", "w")

        json.dump(json_content, file, indent=4)

    async def setup_new_channel(self, ctx, channel):
        new_channel = await channel.category.create_text_channel(channel.name,
                                                                 overwrites=channel.overwrites,
                                                                 position=channel.position,
                                                                 topic=channel.topic,
                                                                 nsfw=channel.is_nsfw())

        await channel.delete()

        embed = discord.Embed(description="React with ✅ to start the test",
                              timestamp=ctx.message.created_at,
                              colour=discord.colour.Colour.green())

        embed = utils.add_promotion_footer(embed)

        message = await new_channel.send(embed=embed)

        await message.add_reaction("✅")

        return message, new_channel

    def check_if_new_file(self, channel):
        new_file = False

        if not path.exists(f"json/{channel.name}.json"):
            new_file = True

        return new_file

    @commands.command(name="import")
    async def attach_command(self, ctx, channel: discord.TextChannel = None):
        if channel is None:
            channel = ctx.message.channel

        json_content = await self.get_json_content(ctx)

        if json_content is None:
            return

        new_file = self.check_if_new_file(channel)

        if new_file:
            message, new_channel = await self.setup_new_channel(ctx, channel)

            self.dump_json(json_content, new_file, new_channel, message=message)
        else:
            await ctx.message.delete()

            self.dump_json(json_content, new_file, channel)

def setup(bot):
    bot.add_cog(ImportTestSuite(bot))

I have tried different modes and checked if the data is correct, all that is good.
Thanks in advance
Comment: I'll have a look
Comment: I tried changing the mode `r+` works but it adds it to the end of the file like this: `{
    "general": {
        "guild_id": 669841270482403338,
        "channel_id": 678884597806661632,
        "message_id": 678884600273174538
    }
}{
    "general": {
        "guild_id": 669841270482403338,
        "channel_id": 678884597806661632,
        "message_id": 678884600273174538
    },
    "testing": {
        "guild_id": 669841270482403338,
        "channel_id": 678884755604897802,
        "message_id": 678884757597323286
    }
}`
Answer: The cause is given in this other SO post: Confused by python file mode "w+".
but not closing as duplicate because is may not be evident at first sight.
The error stack trace gives the line in your code that raises the error:
File "C:\code\nexus-developments\workflow-discord-bot\cogs\import_test_suite.py", line 61, in dump_json
reference_content = json.load(reference_file)

Just before, we can find:
reference_file = open("json/reference.json", "w+")

As explained in the referenced post, w+ mode truncates the file to 0 length, and json does not read your initialized data but an empty file and finds nothing since char 0, hence the error message.
Comment: @Jpac14 Then it is a different question. You'd better delete this one (no need to keep it as the cause is already handled in the referenced post) and post a new one with your new code.
Comment: Yeah I tried using r+ but it the JSON was this `{ "general": { "guild_id": 669841270482403338, "channel_id": 678884597806661632, "message_id": 678884600273174538 } }{ "general": { "guild_id": 669841270482403338, "channel_id": 678884597806661632, "message_id": 678884600273174538 }, "testing": { "guild_id": 669841270482403338, "channel_id": 678884755604897802, "message_id": 678884757597323286 } }` Then I tried this: `reference_file_writing = open("json/reference.json", "w")
            reference_file_reading = open("json/reference.json", "r")` but still doesn't work @sergeballesta
Comment: Whats the problem, it can't be the mode or the data being passed so what is it? @SergeBallesta


Importing database in LDAP creates error

Question: I have exported my database using the following function slapcat > ldif
While I am importing database in other LDAP server it creates error. I am using the following function slapadd -l ldif.
This creates the following error
560d7819 The first database does not allow slapadd; using the first available one (2)
560d7819 => hdb_tool_entry_put: id2entry_add failed: BDB0067 DB_KEYEXIST: Key/data pair already exists (-30994)
560d7819 => hdb_tool_entry_put: txn_aborted! BDB0067 DB_KEYEXIST: Key/data pair already exists (-30994)
slapadd: could not add entry dn="dc=dmdomain,dc=com" (line=1): txn_aborted! BDB0067 DB_KEYEXIST: Key/data pair already exists (-30994)
_#####                 26.09% eta   none elapsed            none spd 957.4 k/s
Closing DB...

What should I do??
Comment: `slapadd` exists for very specific reasons. What are you trying to accomplish?
Comment: i have updated my question
Answer: Your LDAP database is not empty. Id what you are trying to do is migrate to a new machine, please read on. If you're trying to add more from previous database to already populated database on new machine please stop.
if you slapcat your new server you'll get your your
dc=dmdomain,dc=com

as an entry. What I suggest you do (please use snapshot or other method to make sure you can recover from any other error before doing this).
delete all content from /etc/ldap/slapd.d. This will make a clean slate on your ldap.
slapadd -l file location


Automated iOS AppStore Upload with On-Demand Resources

Question: What is the correct way to automate an iOS build upload to AppStoreConnect that uses On-Demand Resources? The tools/solutions I have tried are App Center and xcrun cli which only allow uploading an *.ipa.
My understanding is that the ODR resources will not be included in the ipa as it should contain everything except for Resources used as Download on Demand. There is no ASSET_PACK_MANIFEST_URL_PREFIX set as I want to use Apple's Hosting solutions (which happens if an upload is done manually through Xcode). EMBED_ASSET_PACKS_IN_PRODUCT_BUNDLE set to YES will embed the ODR into the ipa but this will increase its size and I "assume" then cause the assets that we're initially Download on Demand to be downloaded by the user in a production setting (TestFlight/AppStore) with the app download.
Answer: For App Store builds, you should set EMBED_ASSET_PACKS_IN_PRODUCT_BUNDLE to YES. This will include them in the IPA, however they will not be downloaded with your App for Test Flight and App Store builds. This will be reflected in the "Compressed File Size" on App Store Connect General Build Information.
Note, it can take quite a while for Apple to process a build with on-demand resources. Ours typically take 3-4 hours.
Comment: Yep. The reason I had confusion was I was exporting a build through CLI and was using an exportOptions file. These values seem to be overridden by defaults if not explicitly set again.