Portia casket logic problem.

Question: Two boxes, one is gold and the other silver. The sign on the gold box reads, "The portrait is not here." The sign on the silver one reads, "Exactly one of the two statements is true." Guess where the portrait is. What I want to see is how you reason the problem.
Comment: "What I want to see is how you reason the problem." is the new cleaver way to ask homework questions :)
Comment: It's a guess according to your question ...
Comment: The portrait is in the gold box.
Comment: This is not a hw question.
Comment: How to reason the question is to assume it is in each box and see if you find a contradiction with the signs.  The poser has promised you that only one location will not lead to a contradiction.
Comment: @RossMillikan This doesn't seem to be a duplicate of that.  In that problem, we assume something about the truth values of the statements.  Also, the answers are different (if you think my answer is wrong, please say why before claiming the question as a duplicate.)
Answer: The portrait could be in either box because anyone could write all kinds of nonsense on a box and it wouldn't affect what's inside!
This is obvious when you think about it for a moment.  But what is not at all obvious is why the seemingly logical argument that the portrait is in the gold box fails.  Indeed, if the inscription on the silver box is true, then the portrait is in the gold box, and if the inscription on the silver box is false, then the portrait is in the gold box.  The only explanation is that the seemingly harmless assumption "either the inscription on the silver box is true, or the inscription on the silver box is false" is not justified.
To understand this explanation, let's first consider the more fundamental "liar paradox." Consider the sentence $\Phi$ which says "this sentence is false."  You can even write it on a box if you like.  If $\Phi$ is true, then it is false, which is a contradiction.  If it is false, then it is true, and again we have a contradiction.  Therefore the assumption "$\Phi$ is true or $\Phi$ is false" leads to a contradiction; in other words, this assumption is wrong somehow.
Although classical mathematical logic admits a rule (the law of excluded middle) saying "$\psi$ is true or $\psi$ is false" for every sentence $\psi$, we must not interpret this rule out of context.  Here "every sentence $\psi$" only applies to sentences in the realm of mathematical logic.
Some English sentences such as "How tall are you?" or "One cup of coffee, please" would not qualify; we cannot deem them either true or false.  One might hope that the sentence "this sentence is false" might qualify, because it seems to make an assertion of fact.  But as we have seen, we can't allow such self-referential statements without being led into contradiction.
Returning to the question, let's observe that the inscription on the silver box is equivalent to the statement $\Phi$ saying "the portrait is not in the gold box if and only if this statement is false."  The argument from this point on can be rephrased as follows.

Assume toward a contradiction that the portrait is not in the gold box. Then $\Phi$ is equivalent to the statement "this statement is false," and when we attempt to evaluate the truth value of this statement, we are led into contradiction.  Therefore the portrait is in the gold box.

So we see that the liar paradox has been cleverly concealed so that it figures into a proof by contradiction, rather than leading to an outright contradiction.  But the mistake is the same as always: we carelessly assumed that a self-referential statement could be assigned a truth value.
To make it clear why this is a mistake, notice that an analogous argument (if it were valid) could be used to prove anything whatsoever.
For example, consider another sentence $\Phi'$ saying "the portrait is not on the moon if and only if this statement is false."  (Again, you can write this on a box if you like.)  Then we can argue as follows.

Assume toward a contradiction that the portrait is not on the moon. Then $\Phi'$ is equivalent to the statement "this statement is false," and when we attempt to evaluate the truth value of this statement, we are led into contradiction.  Therefore the portrait is on the moon.

EDIT:  To see the invalidity of the other answers more directly, let's consider a slight variation of the original problem:

Suppose we have two boxes, one gold and the other silver. The statement on the gold box says "the portrait is not on the moon." The statement on the silver one says "exactly one of these two statements is true." Where is the portrait?

If the statement on the sliver box is true, then the statement on the gold box is false, so the portrait is on the moon.  If the statement on the silver box is false, then again the statement on the gold box is false, so the portrait is also on the moon in this case.  In either case the portrait is on the moon, so the portrait must be on the moon.  If this argument were valid, you could prove the portrait to be anywhere you like, simply by replacing the word "here" (or the words "on the moon") on the gold box with any other location!  So clearly the argument cannot be valid.
Comment: @user11355 Another way to think about the problem is that I can move the portrait between the boxes _after_ the inscriptions were made.  Surely the presence of some words on the box will not hinder me in doing so.
Comment: How do you know that the statements have no truth or falsity?
Comment: @user11355 I didn't say I know the statements have no truth values.  I just said I _don't_ know that they _do_ have truth values.  It is _possible_ that the portrait is in the gold box, the gold statement is false, and the silver statement is true.  However another possibility is that the portrait is not in the gold box, in which case the silver statement is equivalent to "this statement is false," which cannot be consistently assigned a truth value.
Comment: This is a logic problem. No tricks
Comment: @user11355 I hope my latest edit clears things up.
Answer: Suppose the Silver one is true, then the Gold one must be false, so it's in the gold box.
Suppose the Silver one is false, then obviously we can't have both statements be true, so again the gold one must be false. So again it is in the gold box.
Comment: http://lesswrong.com/lw/ne/the_parable_of_the_dagger/
Comment: Note that I am talking in terms of mathematical logic, not "real life."  In mathematical logic, one must be aware that, for a given formal language, not just any old string of symbols counts as a statement in that language.
Comment: So whatever is written on the gold box must be false?  What if I write "Christopher Liu's answer is correct" on the gold box? :-)
Comment: Would you consider rewriting your answer to address the point that your link makes?  It shows that your argument is invalid, does it not?
Comment: I agree with your reasoning that in real life, this is a pointless question. But for my answer, as with all questions given to me in math, I'll assume that the asker is not screwing with me and giving me false information that is not necessarily true.
Comment: I think you misunderstand.  Nowhere in the question does it assert that each of the inscriptions has a definite truth value (true or false.)  There is, in general, no consistent way to define truth values for statements that refer to themselves (_e.g._ "this statement is false") or to each other (_e.g._ statement 1 says "statement 2 is false" and statement 2 says "statement 1 is true.")  Therefore your assumption that either (1) the inscription on the silver box is true, or (2) the inscription on the silver box is false, is not justified.
Answer: One possibility is that the portrait is in the gold box. If the silver one is true, then the gold one is false. If the silver one is false, then the gold one is false. If the gold one is true, that is not possible.
Edit: The other possibility is to ignore what the signs say and the portrait could be in any box.
Comment: Unless you just go ahead and put it in the silver box, ignoring what's written entirely...
Comment: that's true...lol
Comment: Actually the portrait is in the silver casket. The person who inscribe the words on the caskets isn't lying at all.
Comment: I don't want to sound overly critical, but I think you need to fix your answer to address mjqxxxx's objection.  It may be funny but it is also a perfectly legitimate objection.
Comment: I still don't get it. Are you supposed to ignore what the signs say?
Comment: You don't need to ignore what the signs say, but you do need to not make unjustified assumptions about them. (For example, I'm sure you'd agree that we can't just assume that what the gold box says is true.)  The reason the problem is confusing is that the assumption "either what the silver box says is true or what the silver box says is false," which appears to be tautological, is in fact is not justified under the circumstances.  To understand this you have to first understand how the Liar paradox "this sentence is false" is resolved in mathematical logic.
Comment: I will expand my answer to try to explain this further.

Portia casket logic problem.


Domain Controller Blocking SAMR Request

Question: I have a software that is used for monitoring user logins. In the software it uses a SAMR request to get user groups for allowing users in an out of the machine. When the software reaches out with a SAMR request for the groups it looks like it is getting blocked by the Domain Controller. I think maybe from the firewall because if I install it on the Domain Controller, it succeeds.
How can I test the SAMR request and see if I can get logging on it or what Firewall rules do I need to create to allow SAMR to be allowed to complete?
Answer: Check the RestrictRemoteSAM registry value.  The default settings for that were changed in Windows 10 version 1607 and Windows Server 2016.
It may also be a policy setting "Network access: Restrict clients allowed to make remote calls to SAM"
https://blog.netwrix.com/2022/11/18/making-internal-reconnaissance-harder-using-netcease-and-samri1o/
https://learn.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/network-access-restrict-clients-allowed-to-make-remote-sam-calls
Note that SAMR uses tcp/445 as with any other file share, so this typically is not something the host-based firewall would deal with. Additionally, SAMR has a high affinity for a single domain controller (PDCe), so using the legacy SAMR protocol doesn't scale and may cause other difficult to solve problems that linger.  SAMR has one very specific use case, and beyond that, the only usage I have seen over the years has been either inadvertent (that causes huge problems), and threat actors exploiting vulnerabilities in ancient protocols.
Comment: Just to add more information to this answer. The registry where RestrictRemoteSAM is located was set to Administrators on a Domain controller where on Domain controllers it should be not defined.

Domain Controller Blocking SAMR Request


Detecting unsupervised anomalies in time series considering time range

Question: I want to detect anomalies in time series data. For me an anomaly is an abnormal value over a certain period of time.
Let's say in my time series i have usually a value around 100 with small variations, e.g. a smaller value like 90 for 3 seconds. An anomaly for me would be a value of 90 for 1 minute for example.
Of course I don't want to hardcode those thresholds. Is there an unsupervised anomaly detection method, that considers not only the value (like outlier detection), but also the time dimension?
Answer: What you need to do is review http://www.unc.edu/~jbhill/tsay.pdf it discusses the idea of ARIMA modelling and Intervention Detection ( e.g.level/step shifts and pulses and seasonal pulses and local time trends ). Care should be taken to make sure that the final model error variance is homogeneous/constant over time and that the model parameters are also invariant over time.
Some software implementations actually allow you to specify the minimum size of the step and the minimum number of values in the"new group" in order to reduce false positives. At a minimum the user should be able to specify the level of confidence and to also control the kinds of detected interventions that they wish to be enabled/disabled.
Comment: ok thanks, but maybe at first a basic question. What is the correct term of that kind of anomaly detection, where also the time dimension is considered? Is it "Intervention detection"? Are there also clustering approaches to do that?
Comment: An anomaly detection speaks to the issue "what is the probability of an observation before it is observed" . A sequence of values over time can be characterized .. the question is is there an onset of an unusual value (pulse) or a sequence of "unusual values values around a new mean" (level/step shift) . It appears that you trying to automatically detect level/step shifts without hard-coding . In essence a segmentation is indeed a cluster BUT clustering methods as you may know them deal with multiple characteristics where you only have 1 characteristic (y)
Comment: In the last year or so we have implemented a scheme to detect whether or not a level shift meets a size requirement. We have always had the option to specify the minimum # within a group/set in order to call it a step/level shift.


É possível criar uma estrutura de decisão em uma tabela no SQL?

Question: Tenho um banco de dados massivo, possui mais de 2.000 linhas, e a segunda coluna possui um ENUM que permite apenas 'Opcao 1' e 'Opcao 2'. Se eu inserir na tabela 200 linhas e escrever o nome do ENUM errado como exemplo insert into tabela values ('blabla', 'Ocao 2') ele retornara uma área vazia no campo do ENUM e isso iria acarretar em uma grande dor de cabeça. Existe alguma forma no SQL de eu prevenir que isso aconteça, como uma estrutura de verificação, impedindo de eu executar o código?
Answer: Você pode utilizar um trigger que nos eventos UPDATE e INSERT verificam se o dado na coluna ENUM é válido ou não. Caso não o seja, gere uma exceção para ser tratada na aplicação.
Outra opção, é criar uma outra tabela com os possíveis valores do ENUM, e então referncia-la na primeira através de uma chave estrangeira, assegurando através de restrições de integridade que um valor não suportado seja inserido.
Acredito que seja possível fazer isso utilizando DOMAIN, mas não sei se MySQL suporta isto, nem qual a extensão deste suporte.
Comment: Darei uma olhada Vinícius, obrigado pela resposta, verei como funciona esse trigger e mais tarde lhe darei o feedback
Comment: Decidi não usar mais o ENUM, tem muita gente apresentando vários pontos negativos... Mas você respondeu minha pergunta, vlw!


Sub process output not being returned 'real-time'

Question: I'm just testing out the Symfony Process Component and it doesn't seem to do what it says on the tin.
Docs state

When executing a long running command (like rsync-ing files to a remote server), you can give feedback to the end user in real-time by passing an anonymous function to the run() method:

I have 1 file with the following
$process = new Process('php terminal.php');
$process->setTimeout(null);
$process->run( function ( $type, $buffer ) {
    if (Process::ERR === $type) {
        echo 'ERR > '.$buffer;
    } else {
        echo 'OUT > '.$buffer;
    }
});

and another with the following
$x = 10;
while( $x ) {
    echo "{$x}\n";
    sleep(1);
    $x--;
}

While running this via terminal after a 10 second wait the output is
OUT > 10
OUT > 9
OUT > 8
OUT > 7
OUT > 6
OUT > 5
OUT > 4
OUT > 3
OUT > 2
OUT > 1

which shows there are 10 iterations of closure above but there is no output until the process is finished.
Am I missing something here?
Regards, Luke
Comment: I am expecting 10 separate strings of data pushed to the output buffer in real time over a 10 second period, not 1 after 10 seconds
Comment: It actually works for me with your exact code. The doc says: `Support for streaming the output of a process was introduced in Symfony 3.1.`. Do you really have current version?
Comment: just checked: `"name": "symfony/process",  "version": "v3.1.4",  "version_normalized": "126.96.36.199"`
Comment: I tested PHP 5.5 and PHP 7.1 and both work. What version you use and what OS?
Comment: Mac 10.11.6, PHP 5.6.10
Comment: I tested it with PHP 5.6.25 on OSX and it works. I recommend trying it with a different PHP version.
Comment: http://g.recordit.co/OwqfsQ9ntF.gif tried 7, still nothing... hmm
Answer: You need to use :
flush();
ob_flush();

On your first code :
$process = new Process('php terminal.php');
$process->setTimeout(null);
$process->run( function ( $type, $buffer ) {
    if (Process::ERR === $type) {
        echo 'ERR > '.$buffer;
    } else {
        echo 'OUT > '.$buffer;
    }
    flush();
    ob_flush();
});

On the 2nd :
$x = 10;
while( $x ) {
    echo "{$x}\n";
    flush();
    ob_flush();
    sleep(1);
    $x--;
}

More information at php.net : ob_flush and flush


Semantic predicates fail but don't go to the next one

Question: I tried to use ANTLR4 to identify a range notation like <1..100>, and here is my attempt:
@parser::members {
def evalRange(self, minnum, maxnum, num):
    if minnum <= num <= maxnum:
        return True
    return False
}
range_1_100 : INT { self.evalRange(1, 100, $INT.int) }? ;

But it does not work for more than one range like:
some_rule : range_1_100 | range_200_300 ;

When I input a number (200), it just stops at the first rule:
200
line 3:0 rule range_1_100 failed predicate: { self.evalRange(1, 100, $INT.int) }?
(top (range_1_100 200))

It is not as I expected. How can I make the token match the next rule (range_200_300)?
Answer: Here's an excerpt from the docs (emphasis mine):

Predicates can appear anywhere within a parser rule just like actions can, but only those appearing on the left edge of alternatives can affect prediction (choosing between alternatives).
[...]
ANTLR's general decision-making strategy is to find all viable alternatives and then ignore the alternatives guarded with predicates that currently evaluate to false. (A viable alternative is one that matches the current input.) If more than one viable alternative remains, the parser chooses the alternative specified first in the decision.

Which basically means your predicate must be the first item in the alternation to be taken into account during the prediction phase.
Of course, you won't be able to use $INT as it wasn't matched yet at this point, but you can replace it with something like _input.LA(1) instead (lookahead of one token) - the exact syntax depends on your language target.

As a side note, I'd advise you to not validate the input through the grammar, it's easier and better to perform a separate validation pass after the parse. Let the grammar handle the syntax, not the semantics.
Comment: If you want to handle validation after the parse, use just one rule `range: INT;` and then handle the validation with a visitor - ANTLR generates the base classes for those. This way you eliminate the ambiguity and don't mix up syntax and semantics.
Comment: I understand, but it is hard to handle them after the parse. If there are two rules like: `some_rule2 : INT ; some_rule3 : INT ;`. They have different ranges, and it causes the ambiguous syntax. How can I overcome?
Comment: I tried visitor, but I have a big problem. While there is a rule accepts more than one range with different numeric ranges, the psudocode is like `more_than_one : range_1_10 range_20_30? range_40_50?`, and the real rule is `more_than_one : range+`. How can I distinguish those ranges in `visitMore_than_one()`?
Comment: `range+` yields a list of range contexts in the `more_than_one` context, just iterate over the list and perform your validation. You know the first one should be between 1 and 10, the second one between 20 and 30 and so on. If you still can't figure it out, post another question and make sure you include your visitor code.
Comment: The second one is not sure between 20 and 30, because the range_20_30 is optional and range_40_50 is, too. When the length of range list is 2, I can not sure what kind of range is.
Comment: Then see what's the number and accept it if it's between 20 and 30 *or* if it's between 40 and 50. I don't see where's the problem.


Eigenvalues of a tridiagonal stochastic matrix

Question: I've tried to calculate the eigenvalues of this tridiagonal (stochastic) matrix of dimension $n \times n$, but I had some problems to find an explicit form. I only know that 1 is the largest eigenvalue.
$$M=\dfrac{1}{2}\begin{pmatrix}
 1& 1 &  &  &  & \\
 1& 0 &1  &  &  & \\
 & 1 & 0 &1  &  & \\
 &  &  & \dots &  & \\
 &  &  & 1 & 0 & 1\\
 &  &  &  & 1 & 1
\end{pmatrix}$$
(Here, the matrix takes the value 0 where there is no number.)
I'm interested in the value of the second largest eigenvalue as a function of the dimension $n$ of this matrix. I would appreciate any help.
Answer: For a matrix so nicely structured, I will bet that it has been studied thoroughly, but we can do the analysis by ourselves. Let
$$
P=\pmatrix{1&-1\\ &\ddots&\ddots\\ &&\ddots&\ddots\\ &&&\ddots&-1\\ &&&&1}.
$$
Then
$$
PMP^{-1}=\left(\begin{array}{cccc|c}
0&\tfrac12&&\\
\tfrac12&\ddots&\ddots\\
&\ddots&\ddots&\tfrac12\\
&&\tfrac12&0\\
\hline
&&&\tfrac12&1\\
\end{array}\right)
=\pmatrix{C&0\\ \tfrac12e_{n-1}^\top&1}.
$$
$C$ belongs to the class of symmetric tridiagonal Toeplitz matrices. Explicit formula for eigen-decompositions of such matrices are known (cf. the lecture notes written by the late Gene Golub). In particular, the eigenvalues of $C$ are $\cos(k\pi/n)\ (k=1,\,2,\,\ldots,\,n-1)$ and hence the two second largest-sized eigenvalues of $M$ are $\pm\cos(\pi/n)$.
Answer: The second largest eigenvalue is $\cos(\pi /n)$.
hint: show that the eigenvalues are the $\cos(k\pi/n), k=0\cdots n-1$.
Comment: Hi, could you please add some explanation why this is the case, or give a reference?


java injection - how to inject a bean with parametrized constructor

Question: I want to use @inject to inject a bean which has a parametrized constructor. While injecting i need to pass the parameter to the bean. To clearly explain.
class A:
public class A{
  private String name;
  private String id;
  private int age;

  public A(Student student){
    name = student.getName();
    id = student.getId();
    age = student.getAge();
  }

  public String getName(){
     return Name;
  }

  ..

  ..

}

Class B where bean of class A has to be injected:
public class B{

  @inject private Student student;

  //how to inject the below passing student value
  @inject private A a; // new A(student);

  public getNameAndAge(){
      String name = a.getName();
      int age = a.getAge();
      System.out.println(name);
  }

  public sendDetails(){
     sendInWebService(a);
  }

  ..
  ..

}
In class B, the bean A has to be utilized locally in many methods. Hope this code snippets helps to understand my issue. I'm new to Spring and Java dependency injection. Our applciation don't have Spring dependency and hence @inject is the only option to do this.
Thanks in advance.
Comment: Your A seems to be a domain POJO, there'll be no benefit to making a Spring-managed object. Why not instantiate it via `new`?
Answer: Take look at this thread.
java - Pass Parameter to Instance of @Inject Bean - Stack Overflow
It handles your problem with proper explanations.


How do I know if I'm in a Major key or its Relative Minor?

Question: For example, if I compose a chord progression F-G-C-Am.
Can I Assume C as the Key? How do I know I'm not in A minor?
I've seen songs analysis that says a song is in determined key even when the root is not played once in the whole song, how does this works? I understand that by listening how the song resolves I can know the key, but its there any rule?
Comment: I would rather ask: what bad would happen if I considered C and Am practically the same key. What good might happen as a result? What bad would happen, if I couldn't tell with 100 % certainty, what the key "is" at each moment of the progression? Would it be bad if the progression couldn't be said to be in a single key from beginning to end? What is it that you want: make music, or gain status and respect among theory geeks? ;) The "_is_ the key C or Am" question is largely an academic one.
Comment: well, im just curious about how it works, im self-tought , and now i want to profundize on theory cuz i want to play songs by earing (not just looking for the tabs or chords in ultimate-guitar) then this doubt came up... i mean ive seen those people that know the songs key just by listening (even when the root note is not  played in the whole song).. and i want to learn to do that for myself
Comment: @piiperi - V>I (or V>i or even v>i) is a very strong cadence. happens in most pieces at some (or many) points. In C it's G>C. In Am it's E>Am. E isn't diatonic, so would give a rather different feel.
Comment: @JeffCasino - it's pretty unusual that a song would be conceived to be in a key where that root note/chord was never played.
Comment: @Tim so i just need to listen and get familiar with cadences then i would be able to identify dominant, subdominant and deduce the key... thanks to all
Comment: My point is, if you have strong cadences and strong Am - Dm6 - B7 - E7 - Am6 stuff, it's so strong that you definitely feel it, and then the theoretical "Am or C" question feels irrelevant. And on the other hand if you don't get strong feelings about the key, then the "Am or C" question is just as irrelevant. If it's so ambiguous that you need some sort of theoretical "analysis" to decide between Am or C, what musically meaningful could you possibly do with that information? If you clearly feel it, "analysis" is useless, and if you can't clearly feel it, "analysis" is still useless. IMHO. :)
Answer: Saying that a piece of music is "in a key" often (even usually?) isn't a statement of fact, but a statement of perspective.
When you say that a piece is in C major, you're saying that

The tonal centre of the piece is C - that you mostly feel that C is the home note
The set of notes used by the piece is a reasonable fit with the C major scale - that the notes C, D, E, F, G, A, B are the framework that the piece is built around.

The thing about both those statements is that they leave some room for opinion - they are not absolute, factual statements.

I compose a chord progression F-G-C-Am … can I assume C as the Key?

Not necessarily. It depends on the phrasing of those chords. If Am is the most important chord in the phrasing, then it might sounds more to you like A minor. You have to think whether you feel that C, or A, or something else is the 'home note'.

how do I know I'm not in Am

You can't "know" - but you can feel that the piece doesn't come home to A.

I've seen songs analysis that says a song is in determined key even when the root is not played once in the whole song, how does this works?

Because key is a question of perspective, not a question of fact, you can analyse any song from the point of view of any key. It might be useful and interesting to analyse a given piece from the point of view of a key for which the song didn't land on the tonic chord. In such cases, it's unlikely that that would be the only sensible key to think about.

is there any rule?

No, no absolute rule. People often come up with "rules of thumb" that work for them, but none of them are definitive.
The one way in which being "in a key" could be definitive is if the composer labels it as such - e.g. if I write "Scherzo and Trio in A minor", then in that sense it is defined to be "the key" of the piece. But I don't think that's the sense in which you ask the question.
Answer: One shows a key by the main cadences in the piece; especially at the end of the whole composition. Some internal cadences  (at the end of phrases or sections matter too.)
If a piece is in C-major, the piece will probably end with an authentic cadence on a C-maor chord; usually the pattern G-C or G7-C or dm-G-C or dm-G-G or F-G7-G something similar (ii-V-I or IV-V-I).
The cadence generally has a pre-dominant chord (or subdominant, depending on who's doing the analysis), a dominant chord (maybe with a 7th) followed by the tonic chord. Symbolically one has S-D-T (subdominant, dominant, tonic). S stands for things like ii, ii0, ii6, IV; D stands for V or V7, and T for I in a piece-ending cadence.
In a minor key, the same pattern occurs, S-D-T where S now may be iv or ii0 or ii06 etc, and D is V or V7 (just as in the parallel major) and T as i.
So if the piece ends with a G-C chord pattern perhaps preceded by a dm or dm6 or F major, the piece (or at least the previous section) is in C-major.
If the piece ends with an E-a or d-E-a or f#0-E7-a, etc. the piece is in A-minor.
Pieces do change key but the sections (usually are clearly marked).
Comment: Key can feel clearly-established by cadences, but then there are also lots of pieces that don't feature clear cadences - lots of pop, rock, and techno pieces are based around repetitive chord sequences that don't seem to have clear cadence points.


Two tail t-critical value for margin of error for one tail t-test

Question: I have done a one-tailed one-sample t-test with the following setup:
$H_0:\overline{x} = \mu = \$151$
$H_A: \overline{x} < \mu $
$n = 24$
For $\alpha = 0.05$, the t-critical value is $-1.711$ (from the t-table, using degrees of freedom $= 24$), and I calculate $\overline{x} = \$126$ (skipping the details of the calculation). I get t-statistic $=-2.5$ so I reject the $H_0$. So far, so good.
Now, the problem asks to calculate the confidence interval using $\alpha = 0.05$.
I know that the margin of error $\overline{x} = \pm t{\text -}critical \times standard \ error$.
The answer to the problem uses the two-tailed t-critical value, which is $2.064$, for $95\%$ confidence interval.
I am confused about why they use the two-tailed t-critical value rather than the one-tailed one?
Is it because calculating the confidence interval is a separate task, and has nothing to do with the original hypothesis, and they are interested to see the deviation from the mean in both directions?
Answer: Your use of notation is strange.  The hypothesis should be written $$H_0 : \mu = 151 \quad \text{vs.} \quad H_a : \mu < 151.$$  The hypothesis is a statement about the value of the unknown parameter, in this case the mean $\mu$.  We make an inference about its value based on the data, from which we calculate a test statistic, which under the null hypothesis is $$T \mid H_0 = \frac{\bar x - 151}{s/\sqrt{n}},$$ where $\bar x$ is the sample mean and $s$ the sample standard deviation.  A statistic is never included in the hypothesis because it is something that is calculated from the data; there is no uncertainty about the value we get for it.
Given that $\bar x = 126$ and the value of your test statistic is $T = -2.5$, I get $s \approx 48.9898$ (the exact value of which may differ due to the limited precision you reported for the test statistic).
As for the calculation of a confidence interval, this need not be one-sided even if the hypothesis is one-sided.  The two concepts are related, but a confidence interval is nothing more than an interval estimate.  So, rather than using the sample mean as a simple point estimate for the true mean, we can incorporate the variability observed in the data to give a more sophisticated estimate of the true mean.  You can calculate a two-sided interval or a one-sided interval.  The question as stated is not specific about which one is intended.
A two-sided $95\%$ interval is computed as $$\bar x \pm t_{n-1,\alpha/2}^* \frac{s}{\sqrt{n}},$$ where $s/\sqrt{n}$ is the standard error of the mean, and $t_{n-1,\alpha/2}^* $ is the upper $\alpha/2$ quantile of the student $t$ distribution.  In your case, it is $$t_{23,0.025}^* = 2.06866.$$  Thus the two-sided interval is $$[105.31, 146.69].$$  The one-sided interval that is in the same direction as the hypothesis test is $$\left(-\infty, \bar x + t_{n-1,\alpha}^* \frac{s}{\sqrt{n}}\right].$$  Here, $t_{23,0.95}^* = 1.71387$ so the upper confidence limit is $143.14$, which is smaller than the upper confidence limit of the two-sided interval.  This makes sense because we selected the one-sided upper confidence limit in such a way that the probability the interval does not contain the true mean is $\alpha$; i.e., the upper tail probability of the student $t$ distribution is the full $0.05$, rather than the equal-tailed, two-sided interval.
Comment: @Saskia As I stated in my answer, the question is not specific about whether to construct a one- or two-sided CI.  I can't tell you more because I don't have more information.  All I can say is that two-sided intervals are far more common.  There is no inconsistency because you are assuming that if a hypothesis is one-sided, the interval estimate must also be so; and this is not the case.  It is true that the inversion of the one-sided hypothesis is analogous to the one-sided CI, but there is no **requirement** that both the test and the CI must be calculated the same way.
Comment: Is the decision to calculate one-sided or two-sided CI left purely to the statistician, depending purely on what they are interested to see?
Comment: @Saskia one-sided CIs are rarely reported because one-sided hypotheses are uncommon in practice.  To frame it another way, a two-sided test at significance $\alpha$ is the same as a one-sided test at significance $\alpha/2$.  So you might as well test the two-sided hypothesis or construct a two-sided CI.
Comment: I am confused about something else: if we run a one-tailed test, shouldn't we calculate the one-tail CI as well? Just for consistency. I was confused that in the solution, they used a one-tailed test, while then calculated a two-tailed CI. Seemed inconsistent to me, while I understand that it might be ok to do that in general. However, I think it would incorrct to have it another way round: to calculate a one-tailed CI for two-tailed test.


Regex on List Comprehension Not Producing List But List of Lists Instead

Question: I'm trying to clean a table scraped from a website.
I have two questions:

I'm not sure why my code below is producing a list of lists instead of just one list
I'm scraping each column into an individual list and then converting them into a dataframe. Is it a good practice to do the data cleaning in the list or do I do the cleaning after they're converted into a dataframe?

doc_name = driver.find_elements(By.XPATH, "//*[@id='docflow.list_DocFlowList']/tbody/tr/td/table/tbody/tr/td[3]")

doc_name_cleaned = [re.findall(r'\d+',i.text) for i in doc_name]

Comment: What do you think `re.findall` returns?
Comment: re.findall returns a list
Comment: Thank you user2357112 for asking this pertinent question! I can't believe I didn't think of that. I must remember to think of your question each time I'm stuck at a code!
Answer: doc_name_cleaned = [re.findall(r'\d+',i.text) for i in doc_name]

In the above line re.findall() function returns a list of matches(it can be more than one). Since you're matching pattern for a list of texts, the result is a list of lists.
You can try this, if you just want the text.
doc_name_cleaned = []
for i in doc_name:
    matches= re.findall(r'\d+',i.text)
    if matches:
        doc_name_cleaned.append(matches[0])
    else:
        doc_name_cleaned.append('')

Comment: Thank you! I was considering this `for` loop option but was wondering if a list comprehension would be a good way to do what I wanted to do. Guess not.


How do I fix Visual studio 2010 error message "CCHandler uninitialized" when running WP7 XNA projects?

Question: When I try and run a Windows Phone 7 project it fails and displays a message box:
<code>"CCHandler uninitialized"
</code>
In the errors window is a single error:
<code>"No target is available for deploying."
</code>
And it won't run. I've tried a full uninstall+reinstall of both visual studio and all the WP7 tools and the problem remains.
It's the same for totally new projects and for several existing projects I have that run fine on my other PC.
Also, the options for where to deploy (Emulator/Device) seem to be missing from the project properties and toolbar.
WP7 silverlight projects also fail, but with a different popup (and no message in the errors window):
<code>"Exception from HRESULT: 0x89721800"
</code>
I've tried just running the WP7 emulator from the start menu and nothing happens (no error, nothing)
Does anyone have any ideas?
Visual Studio 2010 pro. (I've tried with and without SP1)
Windows 7 pro x64.
Comment: Weird. Did the installation complete with no errors? What version of the Windows Phone tools are you using?
Comment: @liortal: Yes. Completed fine both times, no errors. Downloaded the latest version of the WP 7.0 tools from [app hub](http://create.msdn.com/en-us/home/getting_started), with the Jan 2011 update and the Fix. Not the 7.1 Beta 2 stuff.
Comment: What version of Visual Studio are you using ? Also, can you confirm you have these files, as shown here: http://www.pasteall.org/23081/text
Comment: @liortal: Visual Studio 2010. (Initially with SP1, but after it failed I uninstalled everything and the second time I tried without SP1). I'm using version 7.0 of the tools, so for a start they are in the 7.0/ directory, and I'm also missing some. CapDetect, IsolatedStorageExplorerTool, WPConnect are missing from the tools directory.
Comment: Have you contacted the Windows Phone Developer Tools team? looks like something got screwed with the install.
Comment: @liortal: No, and I've had to send the laptop back for replacement now (unrelated issue, dead pixels on screen) so I can't dig any further. I'm hoping it all just works fine on the replacement, if not I'll get in touch with them directly then. Thanks for the help.
Comment: Great, update if there's anything interesting.
Answer: After some digging this appears to be caused by installation order of SP1.
If you install VS2010 SP1 before the phone 7 tools, it does not appear to correctly install, and even an uninstall and reinstall of VS does not appear to fix the problem. (although perhaps I wasn't finding everything that needed to be uninstalled)
I would recommend that you follow this install sequence:

Visual Studio 2010
Phone tools (all of them, from the app hub site, in the order they recommend)
VS2010 SP1

[This applies to the initial releases of the phone 7 tools, I don't know what the situation is with the mango beta tools]


Verificar se borda está aplicada

Question: Estou fazendo uma verificação em minha página para que o usuário sempre seja obrigado a selecionar uma cor e um tamanho mas o meu script não está funcionando corretamente, mesmo selecionando a cor e clicar no botão adicionar o alert me pede para que a cor seja selecionada.
O que tenho é isso, as opções de cor e tamanho:

SELECIONE A COR

 <?php foreach($ResCor as $ProdCor) { ?>
  <a class="divCor" IdCor="<?php echo $ProdCor->IdCor; ?>" style="background-color:<?php echo $ProdCor->Cor ?>;">
 <?php } ?>

SELECIONE O TAMANHO

 <?php foreach($ResTamanho  as $ProdTam) { ?>
  <a class="divTamanho" IdTamanho="<?php echo $ProdTam->IdTamanho; ?>" ><?php echo $ProdTam->Nome; ?>
 <?php } ?>

Aplicando as bordas nas opções de cor e tamanho:

.selBordaCor {
    border: solid 1px #363131 !important;
}

.selBordaTamanho {
    border: solid 1px #363131 !important;
}

    // APLICANDO BORDA PARA COR
    $(document).ready(function(){
        $(".divCor").on("click", function() {
          $(".divCor").each(function(){
            $(this).removeClass("selBordaCor");
          })
          $(this).addClass("selBordaCor");
        })
    })
    // APLICANDO BORDA PARA TAMANHO
    $(document).ready(function(){
        $(".divTamanho").on("click", function() {
          $(".divTamanho").each(function(){
            $(this).removeClass("selBordaTamanho");
          })
          $(this).addClass("selBordaTamanho");
        })
    })

Fazendo a verificação e dando o alert:

$(document).ready(function () {
    $('#Finalizar').click(function () {
        if (!$(this).hasClass("selBordaCor")) {
            jAlert('COR\nPor favor, selecione a cor para o modelo.', 'Atenção');
            //alert("COR\nPor favor, selecione a cor para o modelo.");
            return false;
        } else if (!$(this).hasClass("selBordaTamanho")) {
            jAlert('TAMANHO\nPor favor, selecione o tamanho para o modelo.', 'Atenção');
                //alert("TAMANHO\nPor favor, selecione o tamanho para o modelo.");
                return false;
            } else {
            // SE TUDO DE CERTO
        }
    });
});

Estou usando hasclass para verificar se as bordas estão sendo aplicadas, mas não deu muito certo.
A página pode ser vista aqui:
Acessa a página de exemplo
Comment: Isso é um form? Pq não usa radio buttons? assim sua aplicação fica acessivel e semântica, e você não precisa ficar verificando as classes, tem um ex aqui: https://codepen.io/rauldronca/pen/EWLeMz
Answer: No teu código estas verificando se o botão tem a classe "selBordaCor", porém estas adicionando em "divCor". Altere esta parte do código:
$(document).ready(function () {
    $('#Finalizar').click(function () {
        if (!$(this).hasClass("selBordaCor")) {
            jAlert('COR\nPor favor, selecione a cor para o modelo.', 'Atenção');
            //alert("COR\nPor favor, selecione a cor para o modelo.");
            return false;
        } else if (!$(this).hasClass("selBordaTamanho")) {
            jAlert('TAMANHO\nPor favor, selecione o tamanho para o modelo.', 'Atenção');
                //alert("TAMANHO\nPor favor, selecione o tamanho para o modelo.");
                return false;
            } else {
            // SE TUDO DE CERTO
        }
    });
});

Para:
$(document).ready(function () {
    $('#Finalizar').click(function () {
        if (!$(".divCor").hasClass("selBordaCor")) {
            jAlert('COR\nPor favor, selecione a cor para o modelo.', 'Atenção');
            //alert("COR\nPor favor, selecione a cor para o modelo.");
            return false;
        } else if (!$(".divCor").hasClass("selBordaTamanho")) {
            jAlert('TAMANHO\nPor favor, selecione o tamanho para o modelo.', 'Atenção');
                //alert("TAMANHO\nPor favor, selecione o tamanho para o modelo.");
                return false;
            } else {
            // SE TUDO DE CERTO
        }
    });
});
Veja se funciona.
Comment: A parte que você viu é apenas o elemento renderizado inicial, ele adiciona mais abaixo a classe exatamente como você postou.
Comment: mas o código que ele verifica está errado por isso sempre vai chamar o alert, não vejo o motivo de negativar?
Comment: Olá @Lucas, como precisa ser essa verificação de forma correta?
Comment: Tem razão, eu havia entendido que estava verificando a classe "divCor"
Comment: coloca $(".divCor").hasClass("selBordaCor") no lugar do $(this).hasClass("selBordaCor")
Comment: Tem como postar uma resposta, assim fica mais fácil de entender e se der certo já aceito a mesma.
Comment: Vou editar aqui
Comment: Não funcionaria apenas com `!$(".divCor").hasClass("selBordaCor")` porque o seletor de classe traz um array de elementos, precisa iterar em cada um, usando o `.each` por exemplo
Comment: acho que não faz mais sentido ficar estendendo aqui. é só comentários e já está longo demais. qualquer coisa manda um pm. No contexto do html dele funcionaria pois ele só tem um elemento com essa classe. caso ele tenha mais concordo que teria de utilizar o each.
Comment: É que ele possui um `forEach`, no link de exemplo cria algumas divCor a mais. Mas se ele marcou como resolvido é porque o guiou até a solução, então tudo certo.
Answer: Você está verificando a classe no elemento errado.
$(document).ready(function () {
    $('#Finalizar').click(function () {
        if (!$(this).hasClass("selBordaCor")) { // <-- Aqui você está verificando se o botão Finalizar possue a classe selBordaCor

O que você deve fazer é verificar se algum filho do elemento que engloba a seleção de cores e de tamanho, possui a classe específica.
Assim:
$('#Finalizar').click(function () {
    if ($('.tovar_color_select').find('.selBordaCor').length != 1) {
      alert('Selecione a cor!');
    }

    else if ($('.tovar_size_select').find('.selBordaCor').length != 1) {
      alert('Selecione o tamanho!');
    }
});

Verificar se borda está aplicada


Is it necessary to retrain a random forest instead of removing trees when comparing accuracy between different numbers of trees?

Question: I have a train data set and a validation set using which I wish to optimize the hyperparameter that is the number of trees in a binary classification random forest (scikit-learn). (As Sycorax explained in the comments, accuracy will only increase with increasing forest size, however I would still like to compare accuracy between different sizes to optimize with regard to runtime/accuracy)
I want to plot the area-under-ROC on the training and validation set for each number of trees considered, to see how the classifier improves with increasing forest size.
Does it make a difference whether I:

Train a complete forest with 100 trees, classify the validation samples starting with the full tree, and then repeat the classification after removing one random tree from the forest in each repetition, or
Completely retrain an entire new forest for every number of trees considered?

The first method is obviously much faster, but does it somehow introduce errors, biases or otherwise invalidate the analysis?
In case someone asks: I am not using cross-validation or bootstrapping to generate the validation set since they are sampled from different domains in this use case. (i.e. the data is the result of some processing of DNA sequencing reads in which the genome's species will differ between training and validation/inference task)
Comment: You don't need to tune the number of trees in a random forest. https://stats.stackexchange.com/questions/348245/do-we-have-to-tune-the-number-of-trees-in-a-random-forest/348246#348246
Comment: @Sycorax Thanks. In that case, I would still like to weigh the runtime and memory cost of a larger forest against the increased accuracy, and perform the analysis for that reason.
Comment: @JMC (I second Sycorax's advice) in that case treat the number of trees as a constraint rather than a variable (e.g. 128 trees) and aim to optimise other hyperparameters)
Comment: That doesn't seem to solve a real problem unless you're able to profit more from spending compute/memory/etc on the larger forest. In my experience, we more often face hard limits, so we have to size the model to fit those hard constraints. In other words, do you realize a profitable return on the marginal cost of each additional tree? If you do, it's worth pricing that out. Otherwise, just use the largest practical model.
Comment: Also, please note that Accuracy (or whatever metric) does not increase as we add more trees. It plateaus at some point. Rather anecdotally: Usually we see very little gains above 500 trees and no gains above 1000 trees. (Assuming we are not put some crazy constraints on our trees, that is.)
Comment: @Sycorax In my use case I cannot know the hard limit at this point in time and as inference complexity is linear in the number of trees it might become an optimization angle once the other bottlenecks in the data pipeline are known (The classifier will be used "live" with fresh data in a larger software) Also, it's interesting for academic reasons.
Answer: No, you do not need to retrain. Because the trees are built independently, removing one tree is (on average) the same as training one fewer tree.
See also
Sycorax's link in comments and this datascience.SE question.
If you're really wanting to compare different numbers of trees, it would probably be more robust to train more than one forest for each number of trees: you'd expecting to see decreasing variance in the ensemble as it grows, so examining some confidence intervals might be interesting.
Comment: While the trees are independent, the datapoints of my (number-trees --> area under roc) curve would be dependent in the first case. Does that not make a difference at all?
Comment: By "on average" do you mean that it doesn't matter if I'm using a large number of sets of trees for each data point but that it might produce a misleading curve when only using one (sub)forest per datapoint?
Comment: @JMC.  Yes, I meant averaging over all the possible additional trees.  And you're also right that the subtrees are dependent, and that it might be worthwhile to consider multiple forests with each number of trees; I've added that into the answer.


Problema com ComboBox - SystemDataRowView

Question: Estou com um problema. Meu software tem uma tela de cadastro de pedidos e nele há alguns Combo Box que puxam determinadas informações de acordo com o que é selecionado no campo Produto (Bolo, Doce ou Cupcake). São 3 combobox: Cobertura, Tipo e Recheio.
No entanto, ele está dando um erro: quando eu seleciono um determinado produto os Combo Box aparecem as informações dos campos relativas ao produto selecionado, mas quando eu troco de produto todos os Combo Box não mostram mais as opções (que vem diretamente do Banco de Dados, relembrando novamente) e mostram o erro SystemDataRowView. Alguém poderia me ajudar com o que estaria dando errado?
private void cmbProduto_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (cmbProduto.Text.Equals("Bolo"))
        {
            //Comando que se for selecionado Bolo no combox Produto dará um select nos combobox TIPO, COBERTURA E RECHEIO das tabelas relacionadas com bolo
            MySqlConnection coni = new MySqlConnection();
            coni.ConnectionString = ("server=localhost; user id=root; database=confeitaria; Password='';");
            coni.Open();
            MySqlCommand come = new MySqlCommand();
            come.Connection = coni;
            come.CommandText = "select nome_bolo_tipo from bolo_tipo";
            MySqlDataReader drt = come.ExecuteReader();
            DataTable dte = new DataTable();
            dte.Load(drt);
            cmbTipo.DisplayMember = "nome_bolo_tipo";
            cmbTipo.DataSource = dte;

            MySqlConnection cono = new MySqlConnection();
            cono.ConnectionString = ("server=localhost; user id=root; database=confeitaria; Password='';");
            cono.Open();
            MySqlCommand comi = new MySqlCommand();
            comi.Connection = cono;
            comi.CommandText = "select nome_bolo_recheio from bolo_recheio";
            MySqlDataReader drte = comi.ExecuteReader();
            DataTable dten = new DataTable();
            dten.Load(drte);
            cmbRecheio.DisplayMember = "nome_bolo_recheio";
            cmbRecheio.DataSource = dten;

            MySqlConnection oi = new MySqlConnection();
            oi.ConnectionString = ("server=localhost; user id=root; database=confeitaria; Password='';");
            oi.Open();
            MySqlCommand tchau = new MySqlCommand();
            tchau.Connection = oi;
            tchau.CommandText = "select nome_bolo_cobertura from bolo_cobertura";
            MySqlDataReader bb = tchau.ExecuteReader();
            DataTable cc = new DataTable();
            cc.Load(bb);
            cmbCobertura.DisplayMember = "nome_bolo_cobertura";
            cmbCobertura.DataSource = cc;
        }
        else if (cmbProduto.Text.Equals("Doce"))
        {
            //Comando que se for selecionado Doce no combox Produto dará um select nos combobox TIPO, COBERTURA E RECHEIO das tabelas relacionadas com doce
            MySqlConnection coniw = new MySqlConnection();
            coniw.ConnectionString = ("server=localhost; user id=root; database=confeitaria; Password='';");
            coniw.Open();
            MySqlCommand comeh = new MySqlCommand();
            comeh.Connection = coniw;
            comeh.CommandText = "select nome_doce_tipo from doce_tipo";
            MySqlDataReader drtv = comeh.ExecuteReader();
            DataTable dtep = new DataTable();
            dtep.Load(drtv);
            cmbTipo.DisplayMember = "nome_doce_tipo";
            cmbTipo.DataSource = dtep;

            MySqlConnection oit = new MySqlConnection();
            oit.ConnectionString = ("server=localhost; user id=root; database=confeitaria; Password='';");
            oit.Open();
            MySqlCommand tchauc = new MySqlCommand();
            tchauc.Connection = oit;
            tchauc.CommandText = "select nome_doce_cobertura from doce_cobertura";
            MySqlDataReader bbj = tchauc.ExecuteReader();
            DataTable ccl = new DataTable();
            ccl.Load(bbj);
            cmbCobertura.DisplayMember = "nome_doce_cobertura";
            cmbCobertura.DataSource = ccl;
        }
        else if (cmbProduto.Text.Equals("Cupcake"))
        {
            //Comando que se for selecionado Cupcake no combox Produto dará um select nos combobox TIPO, COBERTURA E RECHEIO das tabelas relacionadas com cupcake
            //Comando que se for selecionado Bolo no combox Produto dará um select nos combobox TIPO, COBERTURA E RECHEIO das tabelas relacionadas com bolo
            MySqlConnection coni = new MySqlConnection();
            coni.ConnectionString = ("server=localhost; user id=root; database=confeitaria; Password='';");
            coni.Open();
            MySqlCommand come = new MySqlCommand();
            come.Connection = coni;
            come.CommandText = "select nome_cup_tipo from cupcake_tipo";
            MySqlDataReader drto = come.ExecuteReader();
            DataTable dteo = new DataTable();
            dteo.Load(drto);
            cmbTipo.DisplayMember = "nome_cup_tipo";
            cmbTipo.DataSource = dteo;

            MySqlConnection cono = new MySqlConnection();
            cono.ConnectionString = ("server=localhost; user id=root; database=confeitaria; Password='';");
            cono.Open();
            MySqlCommand comi = new MySqlCommand();
            comi.Connection = cono;
            comi.CommandText = "select nome_cup_recheio from cupcake_recheio";
            MySqlDataReader drteu = comi.ExecuteReader();
            DataTable dtenu = new DataTable();
            dtenu.Load(drteu);
            cmbRecheio.DisplayMember = "nome_cup_recheio";
            cmbRecheio.DataSource = dtenu;

            MySqlConnection oi = new MySqlConnection();
            oi.ConnectionString = ("server=localhost; user id=root; database=confeitaria; Password='';");
            oi.Open();
            MySqlCommand tchau = new MySqlCommand();
            tchau.Connection = oi;
            tchau.CommandText = "select nome_cup_cobertura from cupcake_cobertura";
            MySqlDataReader bbz = tchau.ExecuteReader();
            DataTable ccz = new DataTable();
            ccz.Load(bbz);
            cmbCobertura.DisplayMember = "nome_cup_cobertura";
            cmbCobertura.DataSource = ccz;
        }

Answer: Guilherme,
Tenta colocar também o ValueMember.
cmbTipo.ValueMember = "nome_bolo_tipo";


Why Move to a 7-String Guitar?

Question: So, I play a lot of death/heavy metal(core) and I've finally gotten to a place where people tell me they enjoy listening to me play.
I've been getting suggestions from other musicians (maybe musical enthusiast is a better term for me) about what equipment to experiment with next and I keep hearing that I should buy a 7-string guitar.
I'm not really sure about the advantage of the extra string. I get that having another string will add more range potential but is there something less obvious I might be missing?
Comment: [How to be deathcore](http://www.youtube.com/watch?v=G-CG1CBelCM)
Comment: https://www.youtube.com/watch?v=wfPOANlbyWw
Comment: I think I might have just been sold on getting a 7 string. I have been playing rhythm metal for years, and I am now learning lead role. an extra string on the high end could take away from my lack of a whammy bar for the higher octaves and allow me to play with them. 26 frets on most of those models, where do I sign up!
Answer: A seven string guitar might have longer scale length to accommodate lower tunings. A six stringed guitar can usually be made to handle B tuning, but there might be intonation issues, especially with Gibson measure, which is 24.75". If one wants to go lower, a longer scale is preferred. That can be another benefit with a seven string guitar. Seven string guitars have different scale lengths, some are normal scale with just an added string. For low tunings with six strings you can look at a baritone guitar.
A lot of the modern metal material is performed with a seven string, if you want to play those songs it might be hard with a six string. On the other hand, there are much more good six string guitars than seven string, so there is a trade off with "locking" oneself to a seven string.
I play both kinds, but I tend to prefer six strings these days.
Answer: I have my main gigging 7-string guitar tuned to A-D-A-D-G-B-E, which gives me the benefits of a normal Drop-D tuned 6 string, with a duplicated AD AD at the bottom end, which allows for some very full octave barre chords.
Where this really comes into its own is three areas:

Covering some of the bass range - when the bass is doing something else, I can step into the gap
Allowing for some fairly wild two handed tapping patterns
The low tension on the bottom string lets me easily bend up 7 or 8 semitones without even going near my Floyd Rose

And I do just love the low end chug that is possible. I was intending to buy an 8-string, but had difficulty with the width of the neck.
Answer: You have summed it up pretty well. Normally a 7 string guitar will have an extra low B string under the low E. This can be useful for rock and metal because you can add extra low metal tonalities to your power chords without having to tune your whole guitar lower.
I'm primarily a jazz player and I have always wanted an extra high A string for better soloing range, but for chords the lower B would be more useful. I guess it depends what your main musical role in a band is as to which end you should extend the seventh string on.
Comment: why choose why tune "high" or "low", you can split the difference for example DGCFBbDG or CFBbEbAbCF are both options. Also, while it may seem like a downside "transposing", it removes the temptation to view either the 1st or the 7th string as just an afterthought, and makes you play it more like a truly 7 stringed instrument.
Comment: Good point, I hadn't thought of that!
Answer: Why I have one?
I play metal and death metal and metal core, mainly the really crazy stuff, being able to drop tune it into drop A and still have your high E string is a major gain.
Another thing is, I'm tired of tuning to different tunings, so if I leave it in drop A (A-E-A-D-G-B-E), I can just use a guitar capo to go to drop B and Drop C etc. It will sound about the same bc 7 strings usually have a longer scale length, mine has a 26.5 inch length (23.75" Les Paul).
I was always tuning between standard, D, C, B, And A all the time with my thick strings bc of the different songs I play for fun, but tuning down, you lose your higher notes so with an added string, you can still play pretty high with 24 Frets and your high E string.
A 7 string neck inst too hard to get used to or play. I played one for 2 hours at a guitar store and got so familiar so quick. It felt like drop A with another high E string. It will take a full week or two to fully get used to it, but with a lower end makes a wider view in playing.
It could also be useful such as on a Acoustic guitar for smooth full range barre chords, or for some of that Metallica slow-reggae-metal stuff, low strings and harmonics sound reallly good with that stuff. If you don't like the 7th string or use it every once and a wile, you could simply take it off, add a high A, or Ignore it and play the E string below it :)
It just depends on your style and role, go try one out and see for yourself, hope I helped! :)

Why Move to a 7-String Guitar?


Regression using dummy variables

Question: I am working on a credit scoring modelling project and we decided to use dummy variables for regression. The way we create dummy variables are:
For each predicting numeric variable,

We create by default 10 equal-size bins, examine the weights of evidence (WOE) for each bin and merge adjacent bins if their WOEs are similar (meaning their risk signals are similar.
Then we create dummy variables fomr this numeric variable according to the final bins. Say if we end up with 3 bins for this variable, then we create 3 dummy variables representing the bins. Then we pick one dummy variable as reference to avoid perfect multicollinearity.
Then we run logistic regression.

The above is the highlevel description of how we do the modelling. My question is not specific to this procedure but more of a general dummy variable regression question: In the case when we have many variables (~20) for regression, the number of dummy variables will be even more and the regression result often says some dummy variables are insignificant. How do you treat insignificant coefficient estimates? What if a variable is significant in variable level, having some significant dummy variables but not all?
Thank you.
Answer: I am not a big fan of converting a continuous variable to multiple dummy variables. I guess the binning procedure is considered standard practice in score card development.
Regarding dummy variable insignificance:  When you add a dummy variable in regression, the omitted group act as reference group. The reference group is compared to other groups corresponding to the dummy variables. When variables have a nonlinear relationship (e.g. quadratic) with log odds, you may get some dummy variables that are insignificant (the group whose effect is near to the reference group). My suggestion to see the pattern of log-odds in each bin before merging. Either you can make fewer final bins depending one the pattern or change the reference group. I know it is bit abstract. But, I will not be able to go to specific without knowing the case.
You could also drop the insignificant variable. Doing it this way, you are merging the group associated with dropping dummy. It may not be appropriate if the merging of reference group and the dummy group (insignificant) doesn't make business sense.

Regression using dummy variables


Measure distance of a pulley in Arduino/Raspberry PI

Question: I'm trying to measure the distance an object is pulled along a pulley track using arduino (or Rasp Pi) sensors. I have an object that is manually pulled, from a resting position, on a pulley system and I need to be able to track the distance it travels over one pull.
Example: The object traveled 90% (example) of the total pulley distance for 5/10 pulls.
Example: The object traveled 11.53 ft along the pulley.
See the image below for a visual diagram. I have two ideas, but I'm not an Arduino sensor expert. I'd love input on an elegant solution.

Use an arduino sensor to sense how many times the pulley rotates, and then use an equation to determine the distance.
Use a sensor that senses the distance pulled in cord, maybe each direction, and record that distance. I got this idea from pump sensors, no idea if a comparison exists.

Really just looking for advice on what sensors to use, how to implement them (general), and what type of metrics I could record.
Answer: There are at least two ways of doing this:

Use a rotary encoder, which will tell how many rotations the pulley did. There are two disadvantages: line can slip on the pulley, resulting in inaccurate measurement, and there is no way you can now at what actual position the object is. Rotary encoder will give you only position relative to the starting position (unless you only need one rotation of the pulley - then you can use absolute encoders)
Use a distance sensor (ultrasonic, or IR) to measure at what height is the object. That way you will know the exact position of the object, but you may have a problem if your object is too small, has a shape or surface that will impact the measurements, or if the space is limited and a sensor can pick up walls, or other surrounding objects. Also if the objects may swing on the rope, there will probably a problem.

Software implementation for all of these solutions should be pretty simple, just decide on type of sensors - there are plenty of tutorials for all of them.
Comment: Going with a rotary encoder. Should be able to attach to the pulley itself. Thanks!
Answer: Both task 1 and 2 can be done easily using a digital rotary encoder at very nominal cost. It can sense direction and distance of travel quite accurately.


SwiftUI: NSPageController in NSViewControllerRepresentable crashes

Question: Im' trying to put a NSPageController in a SwiftUI NSViewControllerRepresentable programatically, but when the app runs, it crashes with the following error:
 -[NSNib _initWithNibNamed:bundle:options:] could not load the nibName: test.PageController in bundle (null).

This is the smallest example I could think off to demonstrate the problem:
PageView:
struct PageView: NSViewControllerRepresentable {

    let data = ["green", "blue", "red"]

    typealias NSViewControllerType = PageController

    func makeNSViewController(context: Context) -> PageController {
        let pageController = PageController()
        pageController.arrangedObjects = data
        pageController.delegate = pageController
        return pageController
    }

    func updateNSViewController(_ nsViewController: PageController, context: Context) {

    }

}

PageController:
class PageController: NSPageController, NSPageControllerDelegate {

    func pageController(_ pageController: NSPageController, identifierFor object: Any) -> NSPageController.ObjectIdentifier {
        return (object as? String) ?? "green"
    }

    func pageController(_ pageController: NSPageController, viewControllerForIdentifier identifier: NSPageController.ObjectIdentifier) -> NSViewController {
        let rootView: Color
        switch identifier {
        case "green":
            rootView = .green
        case "red":
            rootView = .red
        default:
            rootView = .blue
        }
        return NSHostingController(rootView: rootView)
    }

}

So far I tried creating custom initialisers that call super.init(nibName: nil, bundle: nil) on NSPageController, but that didn't work either. Ive also tried overwriting 'loadView', but I still didn't get it to work.
I did find that the app crashes in the loadView call of the NSPageController inside the makeNSViewController call.
Answer: The convenience initializer for NSViewControllers by default try to load their views from nib.
You need to override loadView and actually supply a view to the Page Controller
override func loadView() {
        self.view = NSView() // the view being controlled
}


How to notice tabbing into a text input field

Question: I need to call a function whenever a user "selects" an input text field, meaning they can type in it. Currenty I am using a click as the trigger, but it occurred to me a user can also tab into the field. What is a more general trigger for a user selecting an input field.
E.g using vue.js
<input type='text' @click='certainFunction'>
// @click doesnt respond to tabbing into the input field.
// What should replace @click?

Comment: What do you want to do? You say, 'selects' that means you have a select tag (for dropdown) and not an input
Answer: A more general trigger is when a user focuses on the input.
It is done by the focus event.
So something like
@focus='certainFunction'
It doesn't matter if he got there by clicking or tabbing, he is still focused on the input.


Should I, and how to, add methods to int in python?

Question: (This is a learning related question, so any advice in why should I do or not do anything, as well as recommended resources to get these things better, are more than wellcome.)
I'm trying to learn about OOP in python, and have done a simple "Time" class like this:
class Time(object):

    """A time representation."""

    def __init__(self, hours=0, minutes=0, seconds=0):
        self.hours = hours
        self.minutes = minutes
        self.seconds = seconds

    def __int__(self):
        return self.hours * 3600 + self.minutes * 60 + self.seconds

Now, that __int__ method lets me get an int from my "Time" instances that represent the time (but in seconds) when I do int(Time(3, 4, 5)). I find that to be kind of awesome, by the way. But, in order to use this, it would be nice to know how to make an "int" have a new method that returns a "Time" object, so something like 3643.time() could be done.
Why?
For various reasons:

Because that way I learn about what for me is like black magic right now. (these underscored things that make things happen... and related stuff)
Because I don't know why I shouldn't. (so tell me please)

I suppose I could do something like the following outside any class:
def time(seconds):
    """Return an HH:MM:SS stamp of "seconds", where "seconds" should be an int."""
    hours, minutes = 0, 0
    if seconds >= 3600:
        hours, seconds = divmod(int, 3600)
    if seconds >= 60:
        minutes, seconds = divmod(int, 60)
    return "{:02d}:{:02d}:{:02d}".format(hours, minutes, seconds)

But that doesn't seem to relate to these objects enough, It doesn't seem that much object oriented... So, I reckon maybe there is a better way to approach this kind of thing.
Comment: Also, something not feeling OO is not necessarily a bad thing. Python allows you to mix and match OOP and good old procedural programming, to avoid getting lost in the [kingdom of nouns](http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html).
Comment: In my opinion, unless the object represents a plain numerical quantity, providing an `__int__` method is probably a Bad Idea. (In your example, I think the semantics of calling `int()` on a Time to get seconds since midnight is confusing).
Comment: You shouldn't and you can't (without cheating at least). Reasons why not include namespacing (what happens if another module also adds a `int.time` method?), separation of concerns (why should an int know how to convert itself into your class?), the fact that it's unnecessary, the non-obviousness of `10 .time()`, that you have to write `10 .time()` instead of `10.time()` because of a lexer quirk, the general hackiness (unreliability, obscurity) of any possible implementation, and the fact that Rubyist do it ;-)
Comment: Oh, and another thing: If the `Time` class is not just an example or for learning, forget about it. Time is **hard**, and the existing solutions (e.g. the `datetime` module) are better in virtually every sense of the word.
Comment: @delnan Thanks, it is for learning. You gave me what I really wanted, concepts to look at.
Answer: No, you cannot really add methods to int.  You could subclass int, and return that from your __int__ method, but that won't help you much, since calling int() on that will still return a regular int.
Your idea of using a regular function to convert back to Time() is right, but it might be nice to make it a classmethod so it's a little more obvious how it relates:
class Time(object):
    @classmethod
    def from_seconds(cls, seconds):
         _hours, _minutes, _seconds = ...
         return cls(_hours, _minutes, _seconds)

Comment: For the record, this is commonly called a *named constructor*.
Comment: You prob want to keep the `Time(object):` since we're all using new style classes nowadays :)
Comment: An alternative is to write your primary constructor to take more than one kind of input.
Comment: Ok, thanks. This is interesting. I'll try to familiarize with more with it.
Comment: well, I guessed that `__int__` meant that ferhtgoldaraz was using python 3.  Yes, in python 2 this method is called `__index__`, and make sure to inherit from `object` in those cases.


Preamp Valve gone in 'hissing' amp?

Question: Roughly 3 years ago, I purchased a VHT Special 6 Ultra (Combo) Valve Amp. It has recently been 'hissing' (not sure if this is the correct description), and this noise increases with higher wattage and higher volume. It also occurs without the guitar plugged in, and with the amp volume set to 0.
I have tried different mains sockets, to no avail, and from reading about a bit it looks like it might be a preamp tube that has gone.
Am I right, or should I be looking at another component? (Or this might be normal, I'm not entirely sure)

I have attached a video - sorry about the mobile phone quality
Comment: Replacing one or all tubes in a tube amp is always a good first step in troubleshoot tube amp sound quality issues.
Comment: Just to reiterate what @ToddWilcox said, try and replace each tube until you find the culprit - the best thing you can do when troubleshooting a tube amp
Answer: If the hissing gets louder as the volume control is increased, the source of the hiss will be before the volume control. I would start looking at the input lead(s) and sound source (guitar).  Swap the guitar and connecting lead with a known good one or even two. It is cheaper than buying a replacement set of valves you might not need.
If the hiss is not less with the new source, lead and plug you know the problem is in the amp's input circuitry.  Start with the socket making sure the soldered joints are not cracked or "dry".  Then work your way towards the volume control.  How far you go will depend on your electronic knowledge.  But my first guess would be a failed capacitor somewhere.  Wiggling components can sometimes reveal a dry or cracked soldered joint.
As this is a Music Stack Exchange and not one for electronics or roadies, don't forget to hum a tune and to curse in a musical manner.

Preamp Valve gone in 'hissing' amp?


Upper bounds of integrals of $1/x^r$

Question: I am trying to get bound  for the following integral
$$
\int_0^{\infty}\frac{1}{|x|^r}dx, \mbox{for } 1\leq r< \infty
$$
In particular, the bound of the form $\frac{constant}{r}$.
Sorry, we can omit the absolute value. And probably consider interval $(a,\infty)$ for some $a$ very close to 0.
So, the integral is
$$
\int_a^{\infty}\frac{1}{x^r}dx, \mbox{for } 1\leq r< \infty
$$
Comment: Do you  want $\int_a^\infty {1\over |x|^r}\,dx$ for some $a>0$? As it stands, the integral never converges.
Comment: I would assume that you can find the exact value of the integral.
Comment: I think that the absolute value signs can be omitted, or should we interpret it as a complex integral?
Answer: Let us first do some inital work. Here we first safely assume $r>1$.
Then our integral turns into (We exclude the limits for now)
$$ \int_{0}^{\infty} \frac{1}{x^r} \, \text{d}x = \left[ \frac{1}{1-r} x^{1-r} \right]_{0}^{\infty} $$
Quite easily we can see that since $r>0$
$$ \lim_{x \to \infty} \frac{1}{1-r}x^{1-r} = 0 $$
This is quite good! Now we know that
$$ \int_{0}^{\infty} \frac{1}{x^r} \, \text{d}x = \left[ \frac{1}{1-r} x^{1-r} \right]_{0}^{\infty} = 0 - \lim_{x \to 0} \frac{1}{1-r}x^{1-r}$$
The problem is that this last limit does not exist for any values of r. It simply tends to $- \infty$ for all values of $r$.
Let us now plot the problem for a few values of r, to really strike home the point

As we can see the problem is how these functions behave at values very close to zero and very close to infinity. In a nuttshell, the problem with evaluating this integral is that
$ \frac{1}{x^r} $
Approaches $\infty$ at a faster rate when r> increases but, approaches 0 at a slower rate when r increases. Similarly
Approaches $\infty$ at a slower rate when r decreases but, approaches 0 at a faster rate when r increases. As can be seen from the graph.
Although a similar integral that does converge is
$$ \int_{0}^{\infty} \frac{1}{k^r} \, \text{d}x = \frac{1}{r - 1} $$
So to sum up
$$ \int_{0}^{\infty} \frac{1}{x^r} \, \text{d}x = -\infty $$
when $1<r<\infty$
Answer: The derivative of $x\mapsto \dfrac1{x^{r-1}}$ is $x\mapsto-\dfrac{r-1}{x^r}$, hence, for every $r\gt1$ and $a\gt0$,
$$
\int_a^{+\infty}\frac{\mathrm dx}{x^r}=\left[-\frac1{(r-1)x^{r-1}}\right]_{x=a}^{x=+\infty}=\frac1{(r-1)a^{r-1}}.$$
There is no upper bound independent on $a\gt0$. If $a=0$ or if $r=1$, the integral diverges.
Answer: The integral is not bounded.
For r=1 the primitive function of the integrand is log(x) which diverges at 0 and infinity.
For r>1 the primitive function of the integrand is $\frac{1-r}{x^{r-1}}$ which diverges at 0.

Upper bounds of integrals of $1/x^r$


problema com evento dblclick

Question: tenho um codigo que estava funcionando e de um dia para o outro parou de funcionar, não estou entendendo o porque disto !!
Não esta nem disparando o evento ...
segui o codigo abaixo:

      Valor

     abc

o js vem aqui:
jQuery(function($) {

            $('#tblEditavel tbody tr td.editavel').dblclick(function(){
      //$('.editavel').dblclick(function(){

                if($('td > input').length > 0){ // verifica se já existe algum input já na
                   return;
                }

          console.log('teste');

                var conteudoOriginal = $(this).text();
                var novoElemento = $("<input type='text' value='"+trim(conteudoOriginal)+"' class='campo_altera' />");

                $(this).html(novoElemento.bind('blur keydown', function(e){

                var keyCode = e.which;
                var conteudoNovo = $(this).val();

                    if(keyCode == 13 && conteudoNovo != '' && conteudoNovo != conteudoOriginal){

                        var objeto = $(this);

                        $.ajax({
                            type:"POST",
                            url:"assets/php/alterar_vt.php",
                            data:{

                                valor_antigo:conteudoOriginal,
                                valor_novo:conteudoNovo

                            },
                            success:function(result){
                                objeto.parent().html(conteudoNovo);
                                $('body').append(result);
                            }
                        })

                    }else if( keyCode == 27 || e.type == 'blur')

                        $(this).parent().html(conteudoOriginal);
                }));

                $(this).children().select();

            });

        });

Comment: vc está utilizando qual navegador ?
aperta f12 e vai em console e veja se está escrito algo e posta aqui
Comment: Utilizo o chrome amg, esta atualizado na ultima versão e o evento nao dispara ... verifique que eu coloquei um console.log() para ver se esta disparando o evento e nada aparece.
Answer: O erro está na aplicação do método .trim() nesta linha:
var novoElemento = $("<input type='text' value='"+trim(conteudoOriginal)+"' class='campo_altera' />");

Altere para:
var novoElemento = $("<input type='text' value='"+conteudoOriginal.trim()+"' class='campo_altera' />");

O método trim em JavaScript possui a seguinte sintaxe:

string.trim()

Documentação
Reprodução:

jQuery(function($) {

            $('#tblEditavel tbody tr td.editavel').dblclick(function(){
      //$('.editavel').dblclick(function(){

                if($('td > input').length > 0){ // verifica se já existe algum input já na
                   return;
                }

          console.log('teste');

                var conteudoOriginal = $(this).text();
                var novoElemento = $("<input type='text' value='"+conteudoOriginal.trim()+"' class='campo_altera' />");

                $(this).html(novoElemento.bind('blur keydown', function(e){

                var keyCode = e.which;
                var conteudoNovo = $(this).val();

                    if(keyCode == 13 && conteudoNovo != '' && conteudoNovo != conteudoOriginal){

                        var objeto = $(this);

                        $.ajax({
                            type:"POST",
                            url:"assets/php/alterar_vt.php",
                            data:{

                                valor_antigo:conteudoOriginal,
                                valor_novo:conteudoNovo

                            },
                            success:function(result){
                                objeto.parent().html(conteudoNovo);
                                $('body').append(result);
                            }
                        })

                    }else if( keyCode == 27 || e.type == 'blur')

                        $(this).parent().html(conteudoOriginal);
                }));

                $(this).children().select();

            });

        });

      Valor

     abc

Comment: fiz a alteração e não surtiu feito, nem o evento console.log() esta mostrando .... e sobre esta alteração, funcionava da forma que estava !!
Comment: Coloquei na resposta uma reprodução do código funcionando. Veja se está errado em algum lugar.
Comment: sim, eu vi que esta funcionando ,,,, porem na minha aplicação continua não dando resposta nenhuma ! ... o que pode ser, muito estranho isso
Comment: Bom, o único erro aparente que tinha no código era o `trim`. Fora isso tinha que analisar todo o código que não está na pergunta. Se quiser criar um JSFiddle com todo o código eu posso analisar pra vc.
Comment: ok amigo .... agora vou embora para casa descansar ..... amanha posto !!! Tenha uma otima noite e obrigado
Comment: realizei alguns teste e encontrei o motivo do erro na seguinte parte:

if($('td > input').length > 0){ // verifica se já existe algum input já na
                   return;
                }

Qual o problema nesta parte ?? pois funcionava e no jsfiddletbm funciona
Answer: Veiriquei seu codigo vc está utilizando o trim de  forma errada a syntax é
string.trim() e não trim(string)
Você pode ver funcionando aqui  https://jsfiddle.net/hq5omaop/4/
jQuery(function($) {

        $('#tblEditavel tbody tr td.editavel').dblclick(function(){
  //$('.editavel').dblclick(function(){
            if($('td > input').length > 0){ // verifica se já existe algum input já na
               return;
            }

      console.log('teste');

            var conteudoOriginal = $(this).text();
            var novoElemento = $("<input type='text' value='"+conteudoOriginal.trim()+"' class='campo_altera' />");

            $(this).html(novoElemento.bind('blur keydown', function(e){

            var keyCode = e.which;
            var conteudoNovo = $(this).val();

                if(keyCode == 13 && conteudoNovo != '' && conteudoNovo != conteudoOriginal){

                    var objeto = $(this);

                    $.ajax({
                        type:"POST",
                        url:"assets/php/alterar_vt.php",
                        data:{

                            valor_antigo:conteudoOriginal,
                            valor_novo:conteudoNovo

                        },
                        success:function(result){
                            objeto.parent().html(conteudoNovo);
                            $('body').append(result);
                        }
                    })

                }else if( keyCode == 27 || e.type == 'blur')

                    $(this).parent().html(conteudoOriginal);
            }));

            $(this).children().select();

        });

    });

problema com evento dblclick


Existence of maximum value of a discontinuous function

Question: If $f(x)$ takes a finite real value for all $x$ on the closed interval $[a,b]$, must there be a real number $M$ such that $M\geq f(x)$ for all $x$ on this interval? It seems that if not, there must be a point $c\in[a,b]$ such that $\lim_{x\to c}f(x)=+\infty$, and so $f(x)$ must be undefined at some point on this interval, but I don't know how to make this rigorous.
Edit: I see that $f(0)=0$, $f(x)=1/x$ on $(0,1]$ is a counterexample. I also see that I have been imprecise with terminology. Let me modify the question: Is there always a sub-interval $[a',b']$ with $a<a'<b'<b$ such that there is an upper bound for $f(x)$ on this sub-interval?
Comment: Your title is different from the question in the post: $M\ge f(x)$ does not mean that $M$ is maximum, it is an upper bound. In the other words, if such $M$ does not exist, $f$ is not bounded from above.
Comment: If $f$ is continuous, then it must be bounded, see [ProofWiki](http://www.proofwiki.org/wiki/Max_and_Min_of_Function_on_Closed_Real_Interval). It seems that in your post you use the assumption $f(c)=\lim\limits_{x\to c}f(x)$, which is an equivalent condition for continuity of a function $f \colon \mathbb R \to \mathbb R$.
Answer: How about: $f(x)$ on $[0, 1]$ where $f(0) = 0$ and, for all other points, $f(x) = 1/x$.
Edit: Since you added an extra part to your question, you could use the following function:
$f(x) = x$ if $x$ is irrational;
$f(x) = n$ if $x$ is rational in lowest terms, where $n:=$ highest power of $2$ dividing $x$'s denominator.
Answer: About your modified questions:

Is there always a sub-interval $[a',b']$ with $a<a'<b'<b$ such that there is an upper bound for $f(x)$ on this sub-interval?

There are real functions, which are unbounded on each interval.
See Function with range equal to whole reals on every open set at MO.
Many functions from this question work too: Can we construct a function $f:\mathbb R\to \mathbb R$ such that it has intermediate value property and discontinuous everywhere?.
Discontinuous solutions of Cauchy functional equation have this property, see e.g. here.
To give a very simple example, we define $f \colon [0,1] \to \mathbb R$ by
$$f(x)=
\begin{cases}
0; & x\notin\mathbb{Q},\\
q; & x=\frac{p}{q}; \gcd(p,q)=1; p\ne 0,\\
1; & x=0.
\end{cases}$$
(We took reciprocals of non-zero values of Thomae's function.)
For each prime number $q$ if you take interval of length greater then $\frac2q$ then
this interval will contain an $x$ such that $f(x)=q$.
Comment: Thank you - I never would've thought of such crazy functions.


Minimum possible number of positive root of the quadratic equation $x^2-(1+\lambda)x+\lambda-2=0,\lambda\in R$ is

Question: Minimum possible number of positive root of the quadratic equation $x^2-(1+\lambda)x+\lambda-2=0,\lambda\in R$ is
$(a)2$
$(b)1$
$(c)0$
$(d)3$

$x^2-(1+\lambda)x+\lambda-2=0$ I changed this equation to $\lambda=\frac{x^2-x-2}{x-1}$.I am stuck now.
Comment: What do you mean by "Minimum possible number of possible root of the quadratic equation"? The minimum number of values $\lambda$ can take on? The minimum value it can take on? And what is $R$ here? The real numbers? There's too much content not present.
Comment: R is real numbers.
Answer: The solutions are
$$x=\frac{\lambda+1\pm \sqrt{(\lambda+1)^2-4(\lambda-2)}}{2}.$$
The factor of 2 plays no role so we can just focus on the numerator. The discriminant is
$$(\lambda+1)^2-4(\lambda-2) = \lambda^2-2\lambda+9=(\lambda-1)^2+8.$$
This is positive, so there are two real roots. Working with the root coming from +discriminant,
$$\lambda+1+\sqrt{(\lambda-1)^2+8} \ge \lambda+1+|\lambda-1|. $$
This is never negative since if $\lambda+1$ is negative, $\lambda-1$ is more negative and thus its absolute value is more positive. Therefore there is at least one positive root.
The -discriminant case is more fun.
$$\lambda+1-\sqrt{(\lambda-1)^2+8} \le \lambda+1-\sqrt{8}.$$
Since the right half can be negative, we see that for at least some choices of $\lambda$ ($\lambda\le \sqrt{8}-1$), this is negative, giving that the minimum number of positive roots is one.
Answer: The discriminant is positive, so the equation has distinct roots for every $\lambda$.
The arithmetic mean of the roots is $(\lambda+1)/2$. Thus $\lambda\le-1$ implies at least a root is negative.
Can both roots be negative? Hint: Descartes' rule of signs.
Answer: If $\lambda = 2 $ then $ x = 0 $ is a non negative solution.


Nginx rewrite question

Question: My goal is that requests for /foobar?key=123 should redirect to /download/foobar.html?key=123.
I currently use the following code to accomplish this:
location /foobar {
  rewrite ^/foobar(.*)$ /download/foobar.html$1 permanent;
}

This does the trick, but we have some old code that also calls /FooBar?key=123 and /Foobar?key=123 which ignores the rewrite rule.
How can I get these to rewrite too?  Could use:
location ~* ^/foobar {
  rewrite ^ /download/foobar.html$1 permanent;
}

but isn't this a bit loose of a rule?
Answer: First off, location is case sensitive by default; location ~* ^/foobar$ will fix this.
For the rewrite, it's always case sensitive, but you can make your expression match both forms:
rewrite ^/[Ff]oo[Bb]ar(.*)$ /download/foobar.html$1 permanent;

Comment: I think without the ^/foobar it could erroneously match somewhere else, like /images/foobar12.png.  Or does the rewrite ^/[Ff]... take care of that?
Comment: @jimg Indeed it will.  And without a trailing `$`, it'll also catch `/foobars`, so we'll add that, too (`location` doesn't look at the query params, so this will work just fine in your case).  Yes, the string limiting in the `rewrite` takes care of that - but if all you're doing in that location block is the rewrite, then you can probably just get rid of the `location` completely.
Comment: Thanks for the update Shane.  so you would suggest just placing it in the location / block to simplify?  Isn't it better to split off rewrites into their own block for performance reasons?
Comment: @jimg Since there'd be a regex match needed for the location anyway, the performance impact to evaluating the rewrite for every request is a minimal increase.

Nginx rewrite question


Getting a 500 error with the Domain Access module

Question: I use Drupal 7.22 with 7.x-3.9 Domain Access Module for multiple subdomains website.
Making of subdomains works fine, but I cannot access to subfolders on subdomains.

example.com works
example.com/admin/ works
sub.example.com works
sub.example.com/admin/ internal server error 500

This error is showing on every sub-folder (content) in every sub-domain. The root domain is fine with all content. Also, theme changing on sub-domains works fine. Am I missing something in documentation?
Answer: To debug WSOD, you need info what exactly went wrong. There is a pretty neat article about fixing them - try to follow it. Around step 2a you should pretty much know what you need to look for in documentation.


array equalizer by multiplication

Question: given set of three numbers and an array of numbers. we can multiply the values in array any number of times by the numbers in set of three numbers. how to detect at any point of time all values in array will be equal or not.
ex. three numbers- [a ,b , c]
array = [1 ,2 ,3 ,4, 5, 6,7]
now we can multiply every value in array any number of times by a , b, c. at any time will the values in the array be equalized or not? what is the condition for that. The three numbers can be any numbers and array can be any array.
Answer: In order to solve this you need to look at the prime factorisation. So the array of three numbers should contain the unique prime factors of the numbers of the other array. However if some prime(s) only occurs as a common factor raised to some power(s), than that factor can be used as well in the first array. For example 12 and 144, which is $2^2\times3$ and $(2^2\times3)^2$.
In your example there are more prime factors that three, so there will be no solution.

array equalizer by multiplication


1-d combined with 2-d array. Need functions calls for within main

Question: I have a 1-d array and a 2-d array. I have them both in a function that I am using to read in information from a .txt file.
I have my arrays all set up and my functions set up correctly to my knowledge I just cannot figure out how to actually call the function that has 2 separate arrays in it. Here is the relevant information, please just let me know what I need to enter in main to call the functions. Thank you!
<code>    void   getSales(double[][QUARTERS], int[]);     // places sales figures into the array
void   printSales(double[][QUARTERS], int[]);   // prints data as a table
void   printTableHeading();                     // prints table heading

int main()

{
    double sales[YEAR_COUNT][QUARTERS]; // 2D array to hold the sales transactions
    int years[YEAR_COUNT];              // 1D array to hold the years
    return 0;
}

void printTableHeading()

{
}

void getSales(double salesTable[][QUARTERS],int yearArray[])
{
}

void   printSales(double salesTable[][QUARTERS], int yearArray[])
{
}
</code>
Answer: <code>int main(
{
      getSales(sales, years);  // Will call your get sales function
      printSales(sales, years); // Will call your print sales function
}
</code>


Enable field inside Manage Display from a .yml file

Question: When I create a field field.field.node.custom.body.yml in my custom module with the following code:
langcode: en
status: true
dependencies:
  config:
    - field.storage.node.body
    - node.type.customblog
  module:
    - text
id: node.customblog.body
field_name: body
entity_type: node
bundle: customblog
label: Body
description: ''
required: false
translatable: true
default_value: {  }
default_value_callback: ''
settings:
  display_summary: true
field_type: text_with_summary

The Body field is created and added to the appropriate CT when installed, but is set as disabled in the manage display. This seems to be default behavior. I would like the field to be enabled as the module is installed through the use of .yml files, is this possible?
Answer: There is a single config entity per entity_type, bundle and view/form mode. If you fully control that, then you can provide those config entities, if you just add a single field to something existing, you need to use the API to add your fields configuration to it.
See core.entity_form_display.node.article.default.yml in standard.profile and various others for examples.


Multiple NSManagedObjectContexts or single context and -performBlock

Question: I have been using Core Data with a single NSManagedObjectContext for a long time, all fetching, saving, background update operations will be done on single context through helper classes, I was planning to implement a multiple NSManagedObjectContext approach (which is the recommended solution in most of my searching).
My question is: is performBlock the only was to execute code for that context? Can't we do something like below:
- (void) checkSyncServer {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        //do something here, check and fetch data
        // create NSManagedObject's
        [_tempContext save:&error];
        //masterContext will merge changes through notification observers
    });
}

(i.e) execute code apart from -performBlock method. How can I execute multiple asynchronous methods and perform a save?
However, I find a single context (which is managed by one singleton NSObject class) simpler to use.
This multiple context with ContextConcurrencyType looks more complicated (in terms of execution flow). Is there a better solution?
Answer: You can access contexts in one of two ways:

On its Thread/Queue.  This applies to confined contexts and main queue contexts.  You can access them freely from their own thread.
With -performBlock: if it is a private queue context or if you are touching the context from a thread other than the one it belongs on.

You cannot use dispatch_async to access a context.  If you want the action to be asynchronous then you need to use -performBlock:.
If you were using a single context before and you were touching it with a dispatch_async you were violating the thread confinement rule.
Update
When you call [[NSManagedObjectContext alloc] init] that is functionally equivalent to [[NSManagedObjectContext alloc] initWithConcurrencyType:NSConfinementConcurrencyType].
The NSManagedObjectContext has always been thread confined.
As for executing multiple methods you can just call them all in the same block:
NSManagedObjectContext *moc = ...;
[moc performBlock:^{
  //Fetch something
  //Process data
  //Save
}];

Or you could nest them if you wanted them to be all async of each other:
NSManagedObjectContext *moc = ...;
[moc performBlock:^{
  //Fetch Something
  [moc performBlock:^{
    //Process Data
  }];
  [moc performBlock:^{
    //Save
  }];
}];

Since -performBlock: is re-entrant safe you can nest them all you want.
Update Async save
To do an async save you should have two contexts (or more):

Main Queue context that the UI talks to
Private Queue context that saves

Private context has a NSPersistentStoreCoordinator and the main queue context has the private as its parent.
All work is done in the main queue context and you can save it safely, normally on the main thread.  That save will be instantaneous.  Afterwards, you do an async save:
NSManagedObjectContext *privateMOC = ...;
NSManagedObjectContext *mainMOC = ...;

//Do something on the mainMOC

NSError *error = nil;
if (![mainMOC save:&error]) {
  NSLog(@"Main MOC save failed: %@\n%@", [error localizedDescription], [error userInfo]);
  abort();
}

[privateMOC performBlock:^{
  NSError *error = nil;
  if (![privateMOC save:&error]) {
    NSLog(@"Private moc failed to write to disk: %@\n%@", [error localizedDescription], [error userInfo]);
    abort();
  }
}];

If you already have an app, all you need to do is:

Create your private moc
Set it as the parent of your main
Change your main's init
Add the private block save method whenever you call save on your main

You can refactor from there but that is all you really need to change.
Comment: i dint create context with any specific concurrency type, rather created with legacy type [[NSManagedObjectContext alloc] init];
Comment: Also, **how to execute multiple asynchronous method and perform save?.** can u tell me how do i achieve this
Comment: FYI, i was trying for Asynchronous Parent-Child Context Saving,
reference http://www.cocoanetics.com/2012/07/multi-context-coredata/
Comment: Thanks for your response, multi performBlock , i knew we could use it, but i felt like this is not that better solution, that why made a question here, you explanation helps to decide to implement it, knowing it is not that bad to use rather it is made that way for its own pros

Thanks
Comment: Can I call performBlock inside another performBlock on different contexts?