Show that a domain is convex or that a path is homologous to zero

Question: I'm studying for an exam in Complex Analysis and I'm stuck with this simple problem:
$\int_{\gamma}(z-1)\cos(e^z) dz$
where
$\gamma(t)=t^2-1+i\sin(\pi t)$, t $\in$ [-1,1]
I don't have a exact image of the domain which $\gamma$ bounds but I'm pretty sure it is at least star-shaped. If I'm not completely wrong it should look like a stretched circle around $-\frac{1}{2}$.  However, I don't know how to show that this domain is convex or star-shaped in a simple way. Another approach would be to show that $\gamma$ is homologous to 0, which is easy to see if my picture of the path is correct but how do I show this? I don't think $f(z)=(z-1)\cos(e^z)$ has a primitive so calculating that won't help. Calculating it the traditional way by integrating $f(\gamma(t))\gamma(t)'$ is the approach they clearly don't want you to take.. if I didn't miss something.
This is a exam question so there should be a somewhat easy way to show that the integral is 0 as $f(z)$ is holomorphic everywhere and $\gamma$ closed, continuous (and the domain inside star-shaped, $\gamma$ homologous to 0). Maybe I also miss a simple argument here... probably even.
Answer: There's some misunderstanding. It's not important if the region bounded by a curve is star-shaped or not, but the relation between the domain of the function and the curve (does the curve surrounds some 'holes'). Here the domain is the whole $\Bbb C$ (star-shaped domain) and $f$ is holomorphic, so we can make use of Cauchy's integral theorem, which gives that the integral is zero.


Navbar Responsivo do Bootstrap não esta funcionando!

Question:

    <meta charset="utf-8">
    <title>HARD PUNK - Strange, The Fish</title>
    <link href="./css/bootstrap.min.css" rel="stylesheet"/>

         HARD PUNK
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarN" aria-expanded="false" aria-label="Toggle navigation">

        </button>

Sobre o Jogo

Desenvolvedores

Contato

Comment: Qual versão do Bootstrap?
Comment: É a versão 4.1 !
Answer: Seu problema é que vc colocou uma referencia de  data-target="#navbarNav" diferente do ID que usou na

Repare que ao colocar o mesmo valor navbarNav no ID da div id="navbarNav" a seu Nav passa a funcionar.
Segue o modelo. Não mudei nada, só arrumei o target com o ID certo.

    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />

             HARD PUNK
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarN"
                aria-expanded="false" aria-label="Toggle navigation">

            </button>

Sobre o Jogo

Desenvolvedores

Contato

Comment: pode deixar, ficarei mais atento, foi o meu primeiro post no site. Agradeço a sua atenção. obrigado
Comment: Muito obrigado meu querido, ajudou demais!
Comment: @FelipeAlves legal jovem que bom que deu certo ai. E cuidado com esses nomes...  Pois eles sempre têm algum propósito rss. Não deixe de consultar a documentação! Uma dica.  Quando for perguntar aqui no StackOverflow, além do código tb coloque mais algum detalhe, sobre o seu problema. tipo: *"Meu menu não está abrindo quando clico no botão"* ou algo assim ajuda a te responder. Boa sorte ai!


Drupal 7.x + Ubercart 3.x + Domain Access

Question: I have a full working Drupal 7 with Ubercart 3 running fine. It is well configured with thousands of products in it. I would like to create a sub-domain where all the contents and users are the same, but some things (theme, views, ubertcart) are configured differently.
Domain Access module seemed to be the best way to acomplish my goal (it can handle differnt views, settings, themes, etc), but there is no such an option for Ubercart.
So, my problem is that I can not set different configuration on my subdomain for my Ubercart.
My questions are:
 - Is there any way to force Ubercart to use maybe an other db prefix, where Im storing the different settings.
 - Is there any other solution (other module) to my multisite problem?
Any help, tip or suggestion is much appreciated!
Answer: There is no working UC_domain module for Ubercart 3 - Drupal 7, and many issues of configuration - including payment methods per domain user are not availble
Comment: Yes, my final workaround is to have two drupal installs in the same db, but with different prefixes and share the common tables. I had to be careful, but now its just working fine.


Tagged Packets on native VLAN General Port

Question: Scenario a)
I have a Switchport (g1) in General-Mode. Say g1 is member of VLAN1 (native, untagged) and VLAN2 (tagged).
Another Port (g2) is in Trunk-Mode, and member of VLAN1 and VLAN2
If i send a packet, tagged with VLAN1 over g2, is this packet leaving port g1 tagged (with VLAN1) or untagged (because native VLAN1) ?
Scenario b)
I have a Switchport (g1) in General-Mode. Say g1 is member of VLAN1 (native, untagged) and VLAN2 (tagged).
Another Port (g2) is also in general mode and member of VLAN1 (native, untagged) and VLAN2
If i send a packet, tagged (before entering the switch) with VLAN1 over g2, is this packet leaving port g1 tagged (with VLAN1) or untagged (because native VLAN1) ?
Answer: Scenario a)  It leaves g1 untagged.
Scenario b)  Again, untagged.
The switch will strip the VLAN tags when packets leave on an untagged interface.
Comment: @int2000 in both cases, packets were leaving a port on it's native vlan.  If you were sending packets on VLAN2, they would leave with VLAN tags.
Comment: So there is no "mix-mode" (Stripping only the Tags of the Native-VLAN and leaving the Tags on non-Native VLANs)?


Can you explain me what this method does?

Question: We found this method in a book.
From what I understand wants to check if a number is ordered ascending.
For example, the number 54321 (all figures have ordered ascending)
However, I do not understand how this method works ... why returns 0 or 1?
Can you explain to me in a simple way what happens in this method?
 static int f(long n)
    {
        while(n>10)
        {
            if (n % 10 > n / 10 % 10) return 0;
            n = n / 10;

        }
        return 1;
    }

Comment: Hint: what does the value `n % 10` represent? What does the value `n / 10 % 10` represent? What does the value `n / 10` represent? (BTW, in the number 54321, the digits are descending, not ascending.)
Comment: Still, I wonder what the author's reason was to not have returned a boolean
Comment: @dcastro On first guess, I would think that the author returns 1, and 0, because that is how it was done in C++.   0 is false and not 0 is true.  It's not really useful in C#, but someone thinking that it works like C would make that assumption.
Comment: @Kevin But an author of a book would surely know the first thing about the language he's using.
Comment: @JeppeStigNielsen `n >= 10` tests that `n` has at least two digits. `n > 10` does not.
Comment: Why don't you try and see?
Comment: N is a number type to greater than 10
Comment: N is inserted in a textblock
Comment: What specifically don't you understand? The `%` operator, the `if`, or something else? If you make a break down for yourself you should be able to figure out what it does.
Comment: I do not understand the IF condition. What happens in this instruction?
Comment: Did you try insert a value and set a break point to see what happens?
Comment: Add `Console.WriteLine` debug statements for the sections you dont understand and see the output.
Comment: It says, as long as `n` is positive and has at least two digits, check if the last digit `n % 10` is greater than the second-to-last digit `(n / 10) % 10`, and return `0` in that case.
Comment: @dcastro: Indeed. And if he does not, you should stop reading that book.
Comment: @dcastro That is a strong assumption.  I've worked with too many people in the technical writing process to ever think that again.
Comment: @hvd True. They could have said `n >= 12` really, because we easily see that `10` and `11` are non-increasing sequences of digits. I do not take responsibility for the ugly code.
Comment: @JeppeStigNielsen Right. `n >= 10` would have made sense to me, for readability. `n >= 12` would have made sense to me as a quick (and probably unnecessary) optimisation. `n >= 11` (or equivalently, `n > 10`) does not really make all that much sense to me.
Comment: A quick read of the C# documentation might help http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx
Comment: This question appears to be off-topic because it can be explained by simply walking through the code with a debugger or a piece of paper. As such, it displays no attempt to solve this, it is unclear where the confusion lies and provides no value to future readers.
Answer: n % 10 gets you the digit in the unit's place and n / 10 % 10 gets you the digit in the ten's place.
The author is comparing these two digits and returning 0 if the digit in the unit's place is larger than the one in the ten's place.
If not, he is dividing n by 10 to discard the number in the unit's place. Now, the number that was in the ten's place is now in the unit's place and the one in the hundred's place is now in the ten's place and the previous steps are repeated.
If the number becomes less than or equal to 10 after you keep discarding the last number, if it hasn't returned 0, it will return 1, which suggests that all the digits in n are in descending order from left to right.


pushing tableview results in cellForRowAtIndexPath exception

Question: I am trying to build a multilayer xmlparser which shows data in a tableview and switches to the next view based on the selected row (most likely to the same viewcontroller).
I started with storyboard segues but as i am using dynamic cells i dont know how to create more than one push segue (because it needs to push to various viewcontrollers). So i kept the storyboard views, deleted all the segues and used the code below instead.
however it throws this exception when the new view tries to pupulate the row:

Terminating app due to uncaught exception
  'NSInternalInconsistencyException', reason: 'UITableView dataSource
  must return a cell from tableView:cellForRowAtIndexPath:'

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"index: %i", indexPath.row);

    switch (indexPath.row) {
        case 0:
        {
            DetailViewController *detailViewController = [DetailViewController alloc];
            [self.navigationController pushViewController:detailViewController animated:YES];
            break;
        }
        //...
        default:
        {
            LayerViewController *layerViewController= [LayerViewController alloc];
            [layerViewController setStartUpWithIndex:indexPath.row andLayer:layercount];
            [self.navigationController pushViewController:layerViewController animated:YES];
            break;
        }

    }

}

setStartUpWithIndex:andLayer: is my init method...
the problem does not occur when im pushing via storyboard segue with the following segue code:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        [[segue destinationViewController] setStartUpWithIndex:indexPath.row andLayer:layercount];
}

i think i am missing something the "segue" method does which i need to include in my didSelectRowAtIndexPath as cellForRowAtIndexPath: works fine in the first layer of the view.
requested edit:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"LayerCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell.textLabel.text = [[articles objectAtIndex:indexPath.row]objectForKey:@"HerstellerName"];
//    cell.textLabel.text = @"ololol";

    return cell;
}

the articles array is working btw
Comment: The error is in the tableView:cellForRowAtIndexPath: method, you should show the code for it. Does it only occur if you select a row other than row 0, or row 0 or all rows?
Answer: You aren't creating any cells. I don't know why Apple didn't include this in the default implementation, but after:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

You need to add:
if (cell==nil){
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

Otherwise you're just relying on dequeued cells which won't exist when the tableView loads.
Edit: And if you're not using ARC, you need to wrap that alloc method with an autorelease.
Answer: You are pushing another viewController to be viewed and this next viewController has no dataSource methods implemented. This what happened.
As far as I understood, you are trying to present an xml node with a table in the way that each table row consist child nodes of presented node. selecting row with chld node gets you to next table view which presents table with child nodes of selected node.
IMO you may need only one view controller to present current xml node, which changes only data to be presented in a table and reloads the table again. So no pushing view controllers is needed. You can use then method
– reloadRowsAtIndexPaths:withRowAnimation:

for all the nodes in the table, setting animation similar to changing view controller (aka sliding old table left)
Comment: i am pushing the same datacontroller....it is pushing itself. the reload thingy seems fine for some rows, but others need a whole new viewcontroller and i am getting the same error when i try to push to another (still quite similar) one
Comment: So the problem could be that you have the same instance of viewController which refers to the same table. You have to choose: reload table without pushing any viewController OR have two separate instances of view controller which are pushing each other. I would try to reload table though.
Comment: Does another view controller conforms to UITableViewDataSource protocol?
Comment: What does it mean that some rows need other view controller? Do you need few separate view controllers in one table?
Comment: no i meant that if u select the first it goes to another layer of the same tableviewcontroller, row 2-5 need another tableviewcontroller and mbe row 6 leads to a detailedviewcontroller, its custom and depends on the layer of the actual tableview


In CFA model, why observed measures operate as dependent variables?

Question: I am curious that why in CFA model, observed measures operate as dependent variables.
In my understanding, observed measures served as data point that estimating other parameters, such as latent variables and errors.
Thanks,
Answer: They're seen as being caused by the latent variables. We hypothesize that you have a certain level of some variable (say, intelligence). The higher your intelligence, the higher the score that you will get on tests of intelligence. So the score on the tests (the measured variables) depend on the level of intelligence (the latent variable).


Having hard time understanding proofs by contradiction.

Question: I am reading an introductory book on mathematical proofs and I don't seem to understand the mechanics of proof by contradiction. Consider the following example.
$\textbf{Theorem:}$ If $P \rightarrow Q$ and $R \rightarrow \neg Q$, then $P \rightarrow \neg R$.
$\textbf{Proof:}$ (by contradiction)
Assume $P$, then it follows that $Q$.
Now, assume $R$, then it follows that $\neg Q$. Contradiction, we have $Q$ and $\neg Q$ at the same time. Hence, $\neg R$.
Therefore, if $P \rightarrow Q$ and $R \rightarrow \neg Q$, then $P \rightarrow \neg R$, as desired.
What I don't understand in this proof, is that why having arrived at contradiction, we decide that our assumption that $R$ is necessarily false? It also could have been that our first assumption, namely, $P$, was false. Or both of them could be false.
So my question is: in general, when proving by contradiction, how do we know which assumption exactly is false? And how do we know that exactly one assumption must be wrong in order to proceed with the proof?
Comment: @reinierpost: "Whole branches of mathematics exist that reject proofs by contradiction as nonsensical!" Interesting! Could you give any examples?
Comment: You're right; from $P\to Q$ and $R\to \lnot Q$ we can *also* conclude that $R\to\lnot P$.  What $P\to \lnot R$ says is that *if* we knew that $P$ was true we would have to conclude that $R$ was false.  And as you point out, *if* we knew that $R$ was true we would know that $P$ was false; this is $R \to \lnot P$.
Comment: Personally, I think the main problem here is simply the phrasing of the proof. I would have said "suppose $P$," i.e., suppose that we *know* that $P$ is true in some context. Then, we *assume* $R$. Thus, when we arrive that the contradiction, we'd know that, in a context where $P$ is true, the *assumption* of $R$ is incorrect. Conversely, supposing $R$ and *assuming* $P$, we would see that in a context where $R$ is true, $P$ must be false. Thus (as in J Marco's answer) you're really proving a disjunction rather than an implication.
Comment: Hm, it looks like I need to study this some more ...
Comment: Rest assured: you are not alone. Whole branches of mathematics exist that reject proofs by contradiction as nonsensical!
Comment: @reinierpost I also would like an example
Comment: Intuitionism rejects proofs by contradiction. See https://en.wikipedia.org/wiki/Intuitionism.
Comment: @mattclarke Intuitionism *does not* reject proof by contradiction.  In intuitionistic logic the deduction above (from $P\to Q$ and $R\to\lnot Q$ deduce $R\to\lnot P$) is perfectly valid.
Comment: @MJD They do reject proof by contradiction because it doesn't use the Principle of bivalence thus no law of the excluded middle. Similarly simple stuff like $P \vee \neg P$ is not provable in Intuitionism.
Comment: @stonemetal $P\lor\lnot P$ is not intuitionistically valid, but this has nothing to do with proof by contradiction. The canonical proof by contradiction is to assume $P$ and show a contradiction, and conclude $\lnot P$.  This is intruitionistically valid; in fact in most intuitionistic logics $\lnot P$ is *defined* to mean that assuming $P$ leads to a contradiction. For further details see [my blog article on this subject](http://blog.plover.com/math/IL-contradiction.html).
Comment: Or here's another article, this time by [Andrej Bauer](http://math.stackexchange.com/users/30711/andrej-bauer), that says the same thing: http://math.andrej.com/2010/03/29/proof-of-negation-and-proof-by-contradiction/
Comment: If MJD is right that Intuitionism does not reject proof by contradiction -- and I think s/he is -- then @reinierpost's claim that "Whole branches of mathematics exist that reject proofs by contradiction as nonsensical!" is possibly wrong. I don't know of any such branch of maths apart from my incorrect assumption that he was referring to Intuitionism.
Answer: In a proof with multiple assumptions you have to choose one of them to be "blamed" for the contradiction.
Think to your example in terms of assumptions; you start with a couple of them (they can be two Lemmas already proved, or two hypotheses) :

$P→Q$ and $R→¬Q$.

Then we proceed "formally" as follows (I'll use the Natural Deduction proof system; for a good explanation of the rules to be used, see : Ian Chiswell & Wilfrid Hodges, Mathematical Logic (2007), Ch.2 : Informal natural deduction, page 5-on) :
1) $P$ --- assumed
2) $Q$ --- from 1) and $P→Q$ by $\rightarrow$-elim (modus ponens)
3) $R$ --- assumed
4) $\lnot Q$ --- from 3) and $R→¬Q$ by $\rightarrow$-elim (modus ponens)
5) $\bot$ --- from 2) and 4) by $\lnot$-elim [i.e. using the rule : "from $\varphi$ and $\lnot \varphi$, infer $\bot$]
6) $\lnot R$ --- from 3) and 5) by $\lnot$-intro [i.e. using the rule : "if from $\varphi$ we have derived $\bot$, then infer $\lnot \varphi$], "discharging" temporary assumption 3)
7) $P \rightarrow \lnot R$ --- from 1) and 6) by $\rightarrow$-intro, "discharging" temporary assumption 1).
Thus we have proved :

$P→Q, R→¬Q \vdash P \rightarrow \lnot R$.

As per the above answer, we can apply contraposition : $\varphi \rightarrow \lnot \psi \vdash \psi \rightarrow \lnot \varphi$ to conclude also :

$P→Q, R→¬Q \vdash R \rightarrow \lnot P$.

In the previous proof, we have chosen the assumptiom $R$ to be "blamed" for the contradiction. We can as well choose $P$.
If you rewrite it introducing $\lnot P$ in step 6) above, you will end exactly with : $R \rightarrow \lnot P$.

Comment
In order to "have a feeling" with the above application of logical rules, modify the above proof using a single assumption $P \land R$.
Due to the fact that :
$P \land R \vdash P$ and $P \land R \vdash R$ [by : $\land$-elim]
we can repeat the same steps until 5) : $\bot$.
In this case, we have only one assumption to be "blamed" : $P \land R$ and we conclude with :

$\lnot (P \land R)$.

This means that, in the presence of the two Lemmas or hypotheses : $P \rightarrow Q$ and $R \rightarrow \lnot Q$, we cannot "jointly assert" $P$ and $R$.
Thus, one of them must be "removed". Which one ? it's up to us ...
Answer: To answer It also could have been that our first assumption, namely, P, was false. Or both of them could be false: yes, it could, but if you assume P, then R must be false, what you write $P\rightarrow\neg R$. You could have concluded $R\rightarrow \neg P$, of course (and it's the contraposition), by assuming $R$ instead of $P$.
Notice that both of these implications are true, even if $P$ and $R$ are false. You do not know which is false, because none is false a priori. You assume one is true, and you conclude something about the other.

When you do that in practice, it's usually not a problem. Example, let's prove $\sqrt{2}$ is irrational, by contradiction.
So, we assume $\sqrt{2}$ is rational, and we will be led to something that is certainly wrong, hence the assumption is wrong.
Since $\sqrt{2}$ is assumed to be rational, we have $\sqrt{2}=\frac pq$ for some integers $p$, $q$ that have no common factor (otherwise, factor them out).
Hence $p^2=2q^2$, so $2$ divides $p$, and $p=2p'$, and you rewrite your equality $4p'\,^2=2q^2$, or $q^2=2p'\,^2$. But then $2$ divides also $q$. It's not possible, since $p$ and $q$ have no common factor.
Hence something must be wrong. What? The only thing we have assumed, that $\sqrt{2}$ is a rational number.
Answer: Note that you don`t want to prove or contradict $P$ or $R$ themselves. What you want to prove is the implication $P\rightarrow\neg R$. So you pick the assumption of this implication, in this case $P$, and use it for further argumentation.
Now you can start your argumentation with another assumption like $R$ or with anything else. Important difference: now you can look for contradictions.
Answer: In proving $A\rightarrow B$ by contradiction, you assume $\neg(A\rightarrow B)$.  The negation of $A\rightarrow B$ is $A\wedge \neg B$ (the one false case of an implication).
In your case this means you get to assume $P\rightarrow Q$, $R\rightarrow \neg Q$, and $\neg(P\rightarrow \neg R)$.  However $\neg(P\rightarrow \neg R)$ is equivalent to $P\wedge R$.  So you get $P$, $R$, $P\rightarrow Q$ and $R\rightarrow\neg Q$.
From that you should be able to get your contradiction.  (There are other ways of proving this problems as well.)
Comment: Can i use the truth table to answer this question. It seems easier using the  truth table?
Answer: Let me give a brief and less formal explanation than the other answers.
If you start with a set of assumptions {A1, A2, ... An} and derive a contradiction, it proves that the set of assumptions is internally inconsistent (or as @J-Marcos phrased it, "jointly incompatible") -- i.e. they can't all be true.
So you can pick any one of the assumptions, let's say Ai, and conclude that on the basis of the other assumptions, Ai must be false.
Answer: Proofs by contradiction prove that your assumptions are jointly incompatible. In this case, from $P\to Q$ and $R\to\neg Q$ you may conclude that $P\uparrow R$, where $\uparrow$ denotes NAND.  Note that $P\uparrow R$ is true iff $P$ and $R$ cannot be simultaneously true. Negation is a particular case of NAND, when a sentence is 'self-incompatible' (i.e., $S\equiv(S\uparrow S)$).  When reasoning by contradiction, you have in general no reason to conclude that a single one of your assumptions is false (in other words, to conclude that its negation is true), unless you have reasons to maintain the truth of all the other assumptions (which appears not to be the case in the statement of your Theorem, where no reason is given for one to prefer $P$ over $R$).
Of course, $P\uparrow R$ is equivalent to $P\to\neg R$ and to $R\to\neg P$ (and to $\neg P\lor\neg R$), but I feel this facile observation does not tell the full story. Because many people seem not to be comfortable with a disjunctive conclusion such as $\neg P\lor\neg R$, they seem to prefer restating this as an implication.
Answer:
So my question is: in general, when proving by contradiction, how do we know which assumption exactly is false? And how do we know that exactly one assumption must be wrong in order to proceed with the proof?

If you make more than one assumption and get a contradiction, you cannot without further argument know which assumption(s) is(are) false.
However IMHO the point (which I cannot see clearly stated in any previous answers) is that if you set up the problem carefully you need only make one assumption: namely, assume that the result as a whole is false.  In this case, assume that

If $P\to Q$ and $R\to\neg Q$, then $P\to\neg R$

is false.  By standard propositional logic equivalences, this means that

$P\to Q$ and $R\to\neg Q$ are both true, and $P\to\neg R$ is false,

that is,

$P\to Q$ and $R\to\neg Q$ are both true, and $P$ is true and $R$ is true.

From this you easily deduce that $Q$ is true and therefore $R$ is false; but $R$ is also true, which is a contradiction.
Therefore, the theorem as a whole cannot be false and must be true.
Comment: You are incorrect. The assumption to be negated is *always* clear. See my answer.
Comment: @DanChristensen You are incorrect.  As you said in your answer, you have to number and order the assumptions.  This is the kind of *further argument* that I was referring to.
Comment: Really? I would think that every formal proof would consist of an ordered list of numbered statements. Otherwise, you would have to have hundreds of arrows flying all over from one page (or screen) to another in any proof of substantial length.
Comment: There are proofs other than formal ones!  A proper formal proof will not contain any words at all, so this is clearly not what the OP is talking about.
Comment: A proper formal proof can and should have comments throughout -- like the comments in the source code for a computer program. In any case, in any well written *informal* proof, it should be obvious which was the last assumption introduced.
Comment: A formal proof in a language $L$ is a sequence of formulae from $L$, subject to certain rules of inference.  That's all it is.  Any comments constitute further argument.
Comment: I put comments in all my formal proofs, just like I put comments in all my program code. For a proof or program of more than half a page, I find them indispensable. You should try it. There is no problem as long as the reader can distinguish the comments from the rest of the text.
Comment: You may think you put comments in your formal proofs, but in fact you don't, because if you put comments in then it is **by definition** no longer a formal proof.  I am beginning to feel that perhaps you don't know what the term "formal proof" means.  I am also beginning to feel that I am repeating myself, which I can very well do without.  If you want to discuss the matter further, open a chat room.
Comment: I have written a proof assistant that allows you to insert comments into formal proofs. The comments are in a blue font to distinguish it from the rest of the proof. Here is a recent sample from my website: http://www.dcproof.com/MultipleBarberParadox.htm
Comment: This is the best Answer and exactly what [I would have done](https://math.stackexchange.com/a/4149381/21813). Alternatively, suppose that $P \Rightarrow Q$ and $R \Rightarrow \neg Q,$ and ASSUME (contrary to the required consequent) that $P \land R;$ then the contradiction $Q\land\lnot Q$ is immediately derived; thus, the assumption must've been false, and so $P\Rightarrow\lnot R$ (the required consequent) as well as $R\Rightarrow\lnot P$ (a bonus consequent of the same two premises/suppositions).
Answer: Great question. The answer is that, at that point in the proof, you're still assuming that $P$ is true. With the assumptions stated more prominently, the proof goes like this:

We are given that $P \to Q$ and that $R \to \neg Q$. Now we begin imagining that $P$ is true. Since $P$ is true and $P \to Q$, we know that $Q$ is true. Now we begin imagining that $R$ is true. Since $R$ is true and $R \to \neg Q$, we know that $\neg Q$ is true as well. So, $Q$ and $\neg Q$ are both true, which is a contradiction. Now we stop imagining that $R$ is true. Since assuming that $R$ is true leads to a contradiction, $R$ must be false. Now we stop imagining that $P$ is true. Since assuming that $P$ is true leads to the conclusion that $R$ is false, $P \to \neg R$.

Sure, either $P$ or $R$ could be false, and the other one true. Why do we say that $R$ is false instead of allowing the possibility that $P$ is false? Because we haven't yet stopped imagining that $P$ is true.
Answer: We are trying to prove that given $P \rightarrow Q$ and $R \rightarrow \neg Q$, we get $P \rightarrow \neg R$
The proof you describe derives a contradiction by assuming $P$ and $R$, so at least one of the assumptions have to be false.
You wonder why we have to select $R$ as the false assumption.  We do not have to do so, but it does not matter.  If $\neg P$ then $P\rightarrow \neg R$ is vacously true.
Answer:
So my question is: in general, when proving by contradiction, how do we know which assumption exactly is false? And how do we know that exactly one assumption must be wrong in order to proceed with the proof?

If you look at a proof as an ordered (numbered) sequence of statements, the assumption that is negated by a contradiction is always the last assumption previously introduced that has yet to be discharged.


$a_n>0$ and $(a_n)$ is decreasing. Suppose that $\sum_{n=1}^{\infty}{a_{2n}}$ converges. Prove that $\sum_{n=1}^{\infty}{a_n}$ also converges.

Question: Let $\sum_{n=1}^{\infty}{a_n}$ be a series such that for each $n$, $a_n>0$ and $(a_n)$ is decreasing. Suppose that $\sum_{n=1}^{\infty}{a_{2n}}$ converges. Prove that $\sum_{n=1}^{\infty}{a_n}$ also converges. I try to prove by using definition but I got nowhere . Can anyone guide me ?
Answer: I will show that the sequence $b_k=\sum_{i=1}^{k} a_i$ is bounded .
As $\sum_{i=1}^{k} a_{2i}$ is convergent so it is bounded and let $\sum_{i=1}^{k} a_{2i}<M,\forall k\in \mathbb{N}$
$b_{2k}=\sum_{i=1}^{2k} a_i=\sum_{i=0}^{k-1} a_{2i+1}+\sum_{i=1}^{k} a_{2i}<a_1+\sum_{i=1}^{k-1} a_{2i}+\sum_{i=1}^{k} a_{2i}<a_1+2\sum_{i=1}^{k} a_{2i}<a_1+2M$
(Similarly for odd index)
So we have the sequence $b_n=\sum_{i=1}^{n} a_i$ is bounded and as it is monotonically increasing (as $a_i>0$) so it is convergent.
Answer: Let $\displaystyle A_n=\sum_{k=1}^n a_{2k}$  and $\displaystyle B_n=\sum_{k=1}^n a_{2k+1}$. Since $a_k>0$, the sequences $(A_n)$ and $(B_n) $ are increasing, we have
$$B_n\leq A_n\leq \sum_{k=1}^{\infty} a_{2k},$$
so $\displaystyle\sum_{k=1}^{\infty} a_{2k+1} $ exists and $\displaystyle \sum_{k=1}^{\infty} a_{k}= \sum_{k=1}^{\infty} a_{2k}+\sum_{k=1}^{\infty} a_{2k+1}$ exists as well.


Htaccess Redirect with domain attributes

Question: I have to write a redirect rule for the below condition.
www.domain.com/custom.aspx?ATTR=VALUE to
www.domain.com/custom?ATTR=VALUE
How can this be achieved using the .htaccess
I have the below set of codes using on the current .htaccess file. Please also suggest where to include your code.
<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine on
    RewriteRule ^api/rest api.php?type=rest [QSA,L]
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    RewriteCond %{REQUEST_METHOD} ^TRAC[EK]
    RewriteRule .* - [L,R=405]
    RewriteCond %{REQUEST_URI} !^/(media|skin|js)/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule .* index.php [L]
</IfModule>

Answer: This could be done using mod_rewrite, eg something like this:
RewriteEngine On
RewriteRule ^(.*)\.aspx(.*)$ /$1$2 [R=301,L]

Comment: Yes! I am using the mod_rewrite. But using the above rule lead me to the 404 page.
Comment: Do you mean that your browser gets properly redirected to www.domain.com/custom?ATTR=VALUE, but that URL returns a 404? If so, then why would you want to redirect there?
Comment: No redirection is happening here. My page stays at `www.domain.com/custom.aspx?ATTR=VALUE`
Comment: I may have been a bit too quick, I just updated my answer. Could you try that variation instead?
Comment: The result is same. The page is not redirecting. I have edited my question with the current .htaccess file. Please check these as well.
Comment: Where did you place my additional RewriteRule? If I am not mistaken, your last rule matches just about anything that would result in a 404 and disables any further rewrite processing. It seems that /custom.aspx?ATTR=VALUE would match that rule as well. Does your index.php file exist?
Comment: This works after I added my code after `RewriteRule .* - [L,R=405]` line


Como evitar a duplicação de registro em uma tabela no mysql

Question: Como faço para nao deixar repetir a placa no cadastro?
<code><?php

  $placa     =     $_POST['placa'];
  $cidade    =     $_POST['cidade'];
  $estado    =     $_POST['estado'];

$query  = "INSERT INTO veiculos (placa, cidade, estado)
  VALUES('$placa','$cidade','$estado')";
  $result = mysqli_query($conn,$query);
</code>
Answer: Acabei fazendo algumas alterações e deu certo. obrigado pela a LUZ que voce me deu....
<code> $query = "SELECT * FROM veiculos WHERE placa = '" . $_POST['placa'] . "'";
 $resulta = mysqli_query($conn, $query) or die (mysqli_error($conn));

 if(mysqli_num_rows($resulta) ==0 ){

 } else {

        echo "Cadastro não realizado";

 }
</code>
Answer: Você pode definir no banco de dados que a coluna 'placa' seja do tipo UNIQUE, o que não irá permitir dados duplicados ou pode criar na sua página um SELECT que verifique se a placa já exista. Se existir ele retorna uma mensagem de erro, senão ele realiza o INSERT.
Para fazer o SELECT você pode:
1 - SELECT * FROM veiculos WHERE placa = $placa
2 - SELECT placa FROM veiculos WHERE placa = $placa
Diferença: na primeira opção você busca todas as informações do veículo, então se quiser mais dados para comparar pode usar essa, se não tiver necessidade, pode usar a debaixo.
Seu código ficaria assim:
<code>$query = "SELECT * FROM veiculos WHERE placa = $placa";
$result = mysqli_query($conn,$query); //Faz select para consultar as placas
if(mysql_num_rows($result) > 0) //checa se a consulta teve alguma linha {
$query  = "INSERT INTO veiculos (placa, cidade, estado)
  VALUES('$placa','$cidade','$estado')";
  $result = mysqli_query($conn,$query);
} else {
echo "Erro";
}
</code>
Comment: como faria esse select?
Comment: @DiogoCarvalho adicionei na resposta
Comment: esta aparecendo esse erro.

    Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in
Comment: Faz um teste pra ver o que ele está retornando. Aparentemente ele retorna false, ou seja, não funcionou sua query. Troca o > 0 por == false e inverte o que ele iria fazer (se aparecer false ele da um echo de erro, senão ele faz o outro query.


Logical circuits functions and designing vhdl code

Question: I don't know if those 2 functions i have found using Karnaugh tables are mathcing the VHDL code below (I am not really good at VHDL).
The functions :
f <= (x3 or x5) and (x2 or x4') and (x4' or x5) and (x1' or x2) and (x2' or x4 or x5')
and
g <= (x2 or x4' or x5') and (x2 or x3' or x4') and (x2' or x4 or x5') and (x1' or x2 or x5') and (x1 or x3' or x4' or x5')
Here is the code:
basic_components.vhd :
library ieee;
use ieee.std_logic_1164.all;
package basic_components is
  -- AND2 declaration
 component myAND2
        port (in1, in2: in std_logic; out1: out std_logic);
 end component;
 -- OR2 declaration
  component myOR2
       port (in1, in2: in std_logic; out1: out std_logic);
 end component;
  --NOT1 declaration
  component myNOT1
       port (in1: in std_logic; out1: out std_logic);
 end component;
end package basic_components;

library ieee;
use ieee.std_logic_1164.all;

 -- 2 input AND gate
 entity myAND2 is

       port (in1, in2: in std_logic; out1: out std_logic);
 end myAND2;
 architecture model_conc of myAND2 is
       begin

                 out1 <= in1 and in2;
 end model_conc;
  -- 2 input OR gate
library ieee;
use ieee.std_logic_1164.all;
  entity myOR2 is

       port (in1, in2: in std_logic; out1: out std_logic);
 end myOR2;
 architecture model_conc2 of myOR2 is
       begin

                 out1 <= in1 or in2;
 end model_conc2;
  -- 1 input NOT gate
library ieee;
use ieee.std_logic_1164.all;
  entity myNOT1 is

       port (in1: in std_logic; out1: out std_logic);
 end myNOT1;
 architecture model_conc3 of myNOT1 is
       begin

                 out1 <= not in1;
 end model_conc3;

problem1.vhd:
    library ieee, basic_components;
use ieee.std_logic_1164.all;
use work.basic_components.all;
entity Problem1 is
    port (x1, x2, x3,x4,x5: in std_logic;
    f,g: out std_logic);
end Problem1;

architecture structural of Problem1 is
signal not_x1,not_x2,not_x3,not_x4,not_x5,pos1,pos2,pos3,pos4,pos5,pos6,pos7,pos8,pos9: std_logic;

begin

I0: myNOT1 port map(x1,not_x1);
I1: myNOT1 port map(x2,not_x2);
I2: myNOT1 port map(x3,not_x3);
I3: myNOT1 port map(x4,not_x4);
I4: myNOT1 port map(x5,not_x5);
I5: myOR2 port map(x2,not_x4,pos1);
I6: myOR2 port map(x3,x5,pos2);
I7: myOR2 port map(not_x4,x5,pos3);
I8: myOR2 port map(not_x1,x2,pos4);
I9: myOR3 port map(not_x2,x4,not_x5,pos5);
I10: myOR3 port map(not_x2,not_x4,not_x5,pos6);
I11: myOR3 port map(x2,not_x3,not_x4,pos7);
I12: myOR3 port map(not_x1,x2,not_x5,pos8);
I13: myOR4 port map(not_x1,not_x3,not_x4,x5,pos9);
I14: myAND5 port map(pos1,pos2,pos3,pos4,pos5,f);
I15:myAND5 port map(pos5,pos6,pos7,pos8,pos9,g);

end structural;

Comment: Why don't you write `f <= (x3 or x5) and (x2 or x4) ...` etc.? Then it would be trivial to check if the code matches the formula. The `basic_components` are pretty useless if they only wrap the built-in operators, and only obfuscate the code.
Comment: Unfortunately they teach VHDL code in school like this which IMHO is pretty dumb. Because I've seen people who are supposedly experienced do this crap code because they were never corrected in a professional setting.
Comment: Your bold expressions with apostrophes apparently meaning logical negation match those found in grorel's answer (to an unstated problem) for f1 and g1. "*I don't know if those 2 functions i have found using Karnaugh tables are mathcing the VHDL code below ...", can you ask a specific question?
Comment: You don't supply entity and architecture pairs nor component declarations for all your primitives (myOR3, myOR5, myAND5). It's not possible for a second party to verify your implementation matches the bold expressions.
Answer: As the comments in your post say, this way of writing VHDL is not "practical". But you can write your equations in a better way and compile/simulate both results at the same time to compare.
library ieee, basic_components;
  use ieee.std_logic_1164.all;
  use work.basic_components.all;

entity Problem1 is
    port (x1, x2, x3,x4,x5: in std_logic;
    f,g: out std_logic);
end Problem1;

architecture structural of Problem1 is
signal not_x1,not_x2,not_x3,not_x4,not_x5,pos1,pos2,pos3,pos4,pos5,pos6,pos7,pos8,pos9,f1,f2,g1,g2: std_logic;

begin
-- First equations the way VHDL is meaned to be used
f1 <= (x3 or x5) and (x2 or not x4) and (not x4 or x5) and (not x1 or x2) and (not x2 or x4 or not x5);
g1 <= (x2 or not x4 or not x5) and (x2 or not x3 or not x4) and (not x2 or x4 or not x5) and (not x1 or x2 or not x5) and (x1 or not x3 or not x4 or not x5);

-- Second equations, your school problem
I0: myNOT1 port map(x1,not_x1);
I1: myNOT1 port map(x2,not_x2);
I2: myNOT1 port map(x3,not_x3);
I3: myNOT1 port map(x4,not_x4);
I4: myNOT1 port map(x5,not_x5);
I5: myOR2 port map(x2,not_x4,pos1);
I6: myOR2 port map(x3,x5,pos2);
I7: myOR2 port map(not_x4,x5,pos3);
I8: myOR2 port map(not_x1,x2,pos4);
I9: myOR3 port map(not_x2,x4,not_x5,pos5);
I10: myOR3 port map(not_x2,not_x4,not_x5,pos6);
I11: myOR3 port map(x2,not_x3,not_x4,pos7);
I12: myOR3 port map(not_x1,x2,not_x5,pos8);
I13: myOR4 port map(not_x1,not_x3,not_x4,x5,pos9);
I14: myAND5 port map(pos1,pos2,pos3,pos4,pos5,f2);  -- Here, f is replaced by f2
I15:myAND5 port map(pos5,pos6,pos7,pos8,pos9,g2);  -- Here, g is replaced by g2

-- process for auto-test
process(f1,f2,g1,g2)
begin
  -- this will test the equation f1=f2, if wrong the simulator will stop with the message "F calcul is wrong"
  assert (f1 = f2) report "F calcul is wrong" severity failure;
  -- this will test the equation g1=g2, if wrong the simulator will stop with the message "G calcul is wrong"
  assert (g1 = g2) report "G calcul is wrong" severity failure;
end process;

-- output is linked to your school solution
f <= f2;
g <= g2;

end architecture;

Now you have to write a testbench to give the 32 possible inputs to your entity and see if the simulator complains about anything.
Comment: You're missing an end statement for the architecture body.
Comment: @user1155120 : totally agree ! That's how to make mistake writing code directly on SO. :s


Error: Execution failed for task ': app: processDebugGoogleServices

Question: I have a bug in Android Studio.
New activity blank application, I add "build.gradle (project)"
 dependencies {
     classpath 'com.android.tools.build:gradle:2.0.0-alpha9'
     classpath 'com.google.gms: google-services: 2.0.0-alpha9'
 }

And in "build.gradle (app)"
dependencies {
     compile FileTree (dir: 'libs', include: ['* .jar'])
     compile 'com.android.support:appcompat-v7:23.0.1'
     compile 'com.android.support:design:23.0.1'

     // Dependency for Google Sign-In
     compile 'com.google.android.gms: play-auth-services: 8.4.0'
}

apply plugin: 'com.google.gms.google-services'

Compile, and the error is:

"Error: Execution failed for task ': app: processDebugGoogleServices'.
   Com.google.gson.stream.MalformedJsonException: Expected name at line 28, column 20 "

I reinstalled Android Studio, SDK, and always the same, any ideas?
Comment: possible duplicate of http://stackoverflow.com/questions/32212623/adding-google-services-execution-failed-for-task-appprocessdebugresources
Comment: Estás equivocado, revisa bien, el error lo puedes replicar fácilmente al crear un nuevo proyecto con actividad en blanco, agregar el classpath y apply plugin; compilas y error.
Comment: I managed the operation of Google SignIn removing "apply plugin: 'com.google.gms.google-services'' I do not know what consequences have but so far get user data. Regards.
Answer: It looks like you are doing Google Sign-in in your app.
The apply plugin: 'com.google.gms.google-services' statement would try to parse your google-services.json file (normally located  in the app folder)
Open that file and look for any malformed JSON at line 28.
(Possibly copy/paste it into an online JSON validator).
Answer: Sometimes the editor use to modify the 'google-services.json' also will cause the issue. I use OS X TextEdit to edit, the issue happened, but after I use UltraEdit, the issue is solved. I think maybe the file coding issue.


Android loading contact images with UniversalImageLoader

Question: In my app iam trying to load the contact images using UniversaImageLoader, i ran into few problems, and have few queries
1) Eventhough when iam running the Uniimagloader alone on my phone iam  getting the list but no images,
   what am i doing wrong?
2) i used some of the code from that proj , and also loaded the jarfile but still iam getting folloing error
FATAL EXCEPTION: main
12-19 20:37:22.050: E/AndroidRuntime(10152): java.lang.NoClassDefFoundError: com.nostra13.universalimageloader.core.ImageLoader
12-19 20:37:22.050: E/AndroidRuntime(10152):    at org.app.activity.BaseActivity.<init>(BaseActivity.java:11)
12-19 20:37:22.050: E/AndroidRuntime(10152):    at org.app.activity.ProfileActivity.<init>(ProfileActivity.java:39)
12-19 20:37:22.050: E/AndroidRuntime(10152):    at java.lang.Class.newInstanceImpl(Native Method)
12-19 20:37:22.050: E/AndroidRuntime(10152):    at java.lang.Class.newInstance(Class.java:1301)
12-19 20:37:22.050: E/AndroidRuntime(10152):    at android.app.Instrumentation.newActivity(Instrumentation.java:1022)

3) configuration for ImageLoader : iam doing this in my adapter , can i do that? doing this iam getting error at maxImageWidthForMemoryCache(800) it says Add cast to method reciever.
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                    .maxImageWidthForMemoryCache(800)
                    .maxImageHeightForMemoryCache(800)
                    .httpConnectTimeout(5000)
                    .httpReadTimeout(30000)
                    .threadPoolSize(5)
                    .threadPriority(Thread.MIN_PRIORITY + 2)
                    .denyCacheImageMultipleSizesInMemory()
                    .memoryCache(new UsingFreqLimitedMemoryCache(2000000))
                    .discCache(new UnlimitedDiscCache(cacheDir))
                    .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
                    .build();

I am struck. Any help is appreciated.
Answer: Try to make sure that context variable is an Activity instance. It has this kind of error in the past.


Prove only using set theory laws and probability definition that $P(A \setminus C)+P(B \setminus A)+P(C\setminus B) \leq P(A \cup B \cup C)$.

Question: I am having trouble proving that $P(A \setminus C)+P(B \setminus A)+P(C\setminus B) \leq P(A \cup B \cup C)$. Can I get some help?
Comment: I have learnt it so that $P(\Omega)=1, P( \emptyset )=0, P(A) \geq0$ and that $\sigma$-additivity applies.
Comment: $\sigma$-additivity (indeed even finite additivity) implies that $P(A)\le P(B)$ whenever $A\subseteq B$.
Comment: Draw a diagram. You are only excluding $A \cap B \cap C$. Also, the definition of probability varies; it's probably best to include what you have learnt it to be.
Comment: I have drawn the diagram and understand that it is true, although the Venn diagram is not considered a proof.
Comment: Presumably the definition of probability you're using either defines or implies that $A\subseteq B\implies P(A) \leq P(B)$? If so, just show the inclusion holds.
Answer: The same idea as in Stefanos's answer, but simpler: we have
$$
(A\setminus C)\cup(B\setminus A)\cup(C\setminus B)\cup(A\cap B\cap C) = A\cup B\cup C,
$$
and the four sets on the left-hand side are pairwise disjoint. (Verifying these statements is a quick set theory exercise.) Therefore by additivity of probabilities,
$$
P(A\setminus C)+P(B\setminus A)+P(C\setminus B)+P(A\cap B\cap C) = P(A\cup B\cup C),
$$
and you only need to note that $P(A\cap B\cap C)\ge0$ to finish the proof.
Comment: No, of course you should show the set identity is true. It's common to prove that two sets are equal by proving both inclusions: left-hand side $\subseteq$ right-hand side, and right-hand side $\subseteq$ left-hand side. Probably the latter is less straightforward: what can you say about a point $x$ that is in $A\cup B\cup C$ but is not in $A\cap B\cap C$?
Comment: I understand this solution well, however I would need to prove the first equation we have, probably using set theory, how would I start? I can't seem to just presume that this is true. Thank you!


Server Request URL appears wrong when doing reverse proxy

Question: My goal is so when somebody visits main_site.com/blog, they get served content from other_site.com/example_blog. Both sites run Apache 2.4 and Ubuntu (14.04 and 16.04 respectively).
I have the following code in the top of an index.php at the root of the /var/www/html/ folder for the other_site.com server.
// http://stackoverflow.com/a/6768831/3774582
echo (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
die();

When I visit main_site.com/blog in the browser, I get this mismatch between what the browser believes is the full URL, and what PHP believes is the full URL.

It drops off "blog" from the URL. This causes the software (WordPress in this case), to believe the user should be redirected to main_site.com/blog (a redirect to the URL we're already on) and it repeats this until it hits a too many redirects error.
The apache for other_site.com has not been customized other than SSL configuration. Here's the relevant apache for main_site.com
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule ssl_module modules/mod_ssl.so

SSLProxyEngine On

ProxyPreserveHost On
ProxyRequests Off
<Location /blog>
        ProxyPass https://blog.main_site.com
        ProxyPassReverse https://blog.main_site.com
        Order allow,deny
         Allow from all
</Location>

Answer: WordPress doesn't just believe the /example_blog is missing: it actually is missing.
You should have:
ServerName example.com

<Location /blog>
    ProxyPass https://example.org/example_blog
    ProxyPassReverse https://example.org/example_blog

And you may also need to adjust Domain and Path strings in Set-Cookie headers:
    ProxyPassReverseCookieDomain  "example.org"  "example.com"
    ProxyPassReverseCookiePath  "/example_blog/"  "/blog/"
</Location>

Comment: I actually figured this out right before you posted this (although I'm now having other issues but that's a separate question). I don't understand the second part however. Where did example.org come from? Can you edit the question to reflect main_site.com and other_site.com respectively so I don't mix them up.
Comment: No. Instead, you should edit your question to use [RFC 6761 Example Domains](https://tools.ietf.org/html/rfc6761#section-6.5) reserved for this purpose, just like in my answer.


Large amounts of tension in my lower singing range

Question: I'm a pretty novice singer, but am a fairly accomplished instrumentalist. I'll be singing in a choir over the next year or so, and I'm trying to be at least semi-prepared tone-wise. I probably fit somewhere into the upper baritone/lower tenor category, although I've never really been classified.
My issue? It seems like I have the opposite problem of a lot of people. I have a fairly easy high range (I can get to a Bb4 without straining), but my low range gets immediately strangled below an Ab2 or so. When I hum a descending Bb scale, I can see and feel my neck tensing and almost immediately lose flexibility and tone across all of my range.
Anyone got any tips to relax down low?
Answer: Chris,
The secret here is to relax your throat and neck.  This picture helps me.  Think of your esophagus as a long pipe running from the stomach, where you breath from, to your mouth.  Your throat is just a valve in the pipe that has to stay open so the air can get through.  So you breathe in deeply through your stomach (some people might say diaphragm), the air travels up the pipe to your mouth and vocal cords, and you form the sound you want to make primarily with your mouth, involving your throat as little as possible.
Hope this makes sense!  By the way, if you're a new singer, I think you would really like the course "Singing For The Stars" by Seth Riggs.  Seth is a famous vocal coach who has taught a lot of superstars how to sing better.  I've been singing for years - I learned popular singing from this course, working with a teacher, many years ago, and I still go back to it for a refresher a couple of times a year.
Answer: You don't to strain your voice or push yourself too much when hitting the low notes. My suggestion is doing some warmups to gradually get used to singing lower tones. It'll take a bit of time but it's worth it. I'm a choir kid and it took me some practice to generate the vocal range I have now. Before I could only span about 17 keys on the piano with my voice, now I can do 28 keys, with a bit more practice I might even go for more. Another thing is breath support and posture. Usually when you sing low notes you have a tendency to squeeze down a bit, standing or sitting tall is your best option. And get a good breath by breathing from the diagram. So yeah just vocal warmups, breathing exercises, and good posture can help.


Como criar dois menus diferentes e ativar responsivo com medidas diferentes?

Question: Criei dois menus em bootstrap e queria que um a baixo dos 1200px se torna-se com i con toggle e o segundo a baixo de 768px, só ai fica-se responsivo, no entanto nos dois ficam com o icon aos 1200px
Answer: Você pode usar as classes css ".hidden-xs", ".hidden-sm", ".hidden-md".
Segue o link na documentação: http://getbootstrap.com/css/#responsive-utilities


Qual a melhor forma de transformar um formulário de contacto seguro?

Question: Tenho um formulário de contacto a funcionar mas acusa falha de segurança de crossscripting no sitelock. Alguma ajuda com ultrapassar o problema?
Obrigado
<?php
            header('Content-Type: text/html; charset=utf-8');

            if(isset($_POST['email'])) {

                // EDIT THE 2 LINES BELOW AS REQUIRED

                $email_to = "mail que recebe";

                $email_subject = "Mensagem vindo do site";

                $first_name = $_POST['first_name']; // required
                $email_from = $_POST['email']; // required
                                $telephone_from = $_POST['telephone']; // required
                $subject = $_POST['subject']; // required
                $comments = $_POST['message']; // required

                $email_message = "Mensagem vindo do site\n\n";

                function clean_string($string) {
                    $bad = array("content-type","bcc:","to:","cc:","href");
                    return str_replace($bad,"",$string);
                }

                $email_message .= "Name: ".clean_string($first_name)."\n";
                $email_message .= "Email Address: ".clean_string($email_from)."\n";
                                $email_message .= "Telephone: ".clean_string($telephone_from)."\n";
                $email_message .= "Subject: ".clean_string($subject)."\n";
                $email_message .= "Message: ".clean_string($comments)."\n";

                // create email headers

                $headers = 'From: '.$email_from."\r\n".

                'Reply-To: '.$email_from."\r\n" .

                'X-Mailer: PHP/' . phpversion();

                @mail($email_to, $email_subject, $email_message, $headers);

                ?>

                <?php

                }

                ?>

<form id="contact-form" action="contact.php" name="contactform" class="row" method="post">

<input type="text" name="first_name" id="name" class="form-control triggerAnimation animated" data-animate="bounceIn" placeholder="Nome">

<input type="text" name="telephone" id="telephone" class="form-control triggerAnimation animated" data-animate="bounceIn" placeholder="Telefone">

<input type="text" name="email" id="email" class="form-control triggerAnimation animated" data-animate="bounceIn" placeholder="Email">

<input type="text" name="subject" id="subject" class="form-control triggerAnimation animated" data-animate="bounceIn" placeholder="Assunto">

<textarea class="form-control triggerAnimation animated" data-animate="bounceIn" name="message" id="comments" rows="6" placeholder="Gostaria de ser contactado(a) para mais informações"></textarea>

<input type="submit" value="Quero ser contactado(a)" id="submit" class="btn btn-theme triggerAnimation animated" data-animate="bounceIn">

<input type="hidden" name="CSRF" value="<?= $_SESSION['CSRF'] ?>">
</form>

Comment: Falta o CSRF Token, possivelmente seja isso. Mas, o parâmetro $headers é extremamente perigoso, um atacante pode simplesmente inserir um "\r\n" e inserir quaisquer informações. Você deve, pelo menos remover o "\r\n", uma vez que esta é a forma (CRLF) com que cada header adicional é dividido.
Answer:
Não garanto que esta resposta corrija todos os problemas, pode ainda haver outros problemas de segurança!

Esta é a função:
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )

O que ocorre é EXATAMENTE nos dois últimos parâmetros do mail(), que é o $additional_headers e o $additional_parameters, este quinto parâmetro é ainda pior e nem irei falar dele.
O $additional_headers informa os cabeçalhos dividos por um CRLF (\r\n) exatamente como você está fazendo ao final de cada linha.

Como atacar:
Como o ataque funciona, a melhor forma de se proteger é saber como exatamente o ataque funciona.
Isto é o que você tem:
$headers = 'From: '.$email_from."\r\n".
           'Reply-To: '.$email_from."\r\n" .
           'X-Mailer: PHP/' . phpversion();

Observe que se o valor do $email_from for:
firstname.lastname@example.com\r\nBcc:email@example.com
Ele irá fazer com que:
$headers = 'From: firstname.lastname@example.com\r\n'.
            Bcc:email@example.com\r\n'.   // <<<
           'Reply-To: email@example.com\r\n'.
           'Bcc:email@example.com\r\n" .  // <<<
           'X-Mailer: PHP/' . phpversion();

Isto será o resultado.

Prova:
curl ^
-X POST ^
-d "email@example.com%0ACc:firstname.lastname@example.com&subject=teste3&message=teste3" ^
https://seu-link.com

Observe exatamente o valor do email, ele é o importante:
email@example.com%0ACc:firstname.lastname@example.com

Isto irá fazer com que o campo de email seja igual ao email@example.com com o %0A que é o CR em HTML URL Encoding (ou %0D%0A) e por fim Cc:email@example.com.
Com isto uma outra pessoa também irá receber o e-mail, que inclusive pode mencionar mais de uma.

Mas porque o clean_string não funciona para remover o Cc que usou? Simples, ele é case-sensitive, somente o str_ireplace é case-insensitive. O Cc é diferente de cc. Em geral, blacklist não funcionam. É muito mais fácil dizer o que é permitido do que listar tudo que é proibido!
Veja que isto:
function clean_string($string) {
    $bad = array("content-type","bcc:","to:","cc:","href");
    return str_replace($bad,"",$string);
}

echo clean_string("BCC: email@example.com\r\n Cc: email@example.com");

Retorná:
BCC: firstname.lastname@example.com Cc: email@example.com

Isto é INÚTIL.

Como proteger:
Não utilize o último argumento, nem irei mencionar ele aqui porque sinceramente nem sei como protege-lo. Entretanto o quarto argumento tem salvação, mas antes vou listar todos os erros que possui o código:

Falta de CSRF.
Não tratando o CRLF.
O texto da mensagem não está sendo tratada.

1. CSRF:
Adicione o CSRF-Token, simplesmente utilize um bom CSPRNG e salve-o na sessão, por exemplo:
session_start();

if(!isset($_SESSION['CSRF'])){
    $_SESSION['CSRF'] = unpack('H*', random_bytes(64))[1];
}

Depois acrescente:
<input type="hidden" name="CSRF" value="<?= $_SESSION['CSRF'] ?>">

Depois compare ambos os valores, que foi enviado e que está armazenado na sessão:
if(hash_equals($_SESSION['CSRF'], $_POST['CSRF']){
// O CSRF é igual!
}

Não utilize ===, timing-attack. E obviamente não utilize o  ==,  principalmente se utilizar um json_decode/unserialize, porque "qualquer_coisa" == true é sempre true, que foi o que fazia o Laravel 4 (haha).
2. Remover CRLF:
$email_from = str_ireplace(["\r", "\n", ':', ','], '', $email_from);

Dessa forma o meu código iria cair por replace abaixo. :'( Porque neste caso iria se tornar:
firstname.lastname@example.com@outra-pessoa.com

Acrescentei o : e , para que na pior das hipóteses disto fracassar e ambos não são valores válidos para caracteres de e-mail, até onde eu saiba.
3. HTML:
A terceira questão é que seria ideal utilizar o htmlentities, dessa forma:
$email_message = htmlentities($email_message, ENT_QUOTES || ENT_HTML5, 'UTF-8');

Isto iria assegurar que nenhuma mensagem iria possuir HTML, principalmente <, > para prevenir que inserirem um


How do I theme a taxonomy term page?

Question: I am working on Drupal 8, trying to get a page template for each vocabulary. I have tried using hook_theme_suggestions_HOOK_alter() to achieve this, but I was not able to do it.
I tried using Devel with kint(), but no debugging information is shown on my screen.
How can I add a template suggestion for a vocabulary?
Answer: You can suggest a new template file with the following code.
Drupal 8
use Drupal\taxonomy\Entity\Term;

function THEME_NAME_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
  }
}

Drupal 9
use Drupal\taxonomy\Entity\Term;

function THEME_NAME_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->bundle();
  }
}

Then create the file: page--taxonomy--VOCABULARYNAME.html.twig and customise it as you wish.
Comment: @SaeedAfzal try using {{ name }}
Comment: Thanks for the help. Can you please also tell me how do I print the term name in this template?
Comment: ℹI've got the Taxonomy Term view that comes with Drupal core enabled, therefore   `Drupal::routeMatch()->getRouteName()` is returning `view.taxonomy_term.page_1`. HTH.
Answer: In Drupal 9, the getVocabularyId() method is deprecated so we use bundle() instead.
Use this hook in Drupal 9:
use Drupal\taxonomy\Entity\Term;

/*
 * Implements hook_theme_suggestions_HOOK_alter()
 */

function THEMENAME_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->bundle();
  }
}

How do I theme a taxonomy term page?


Python function returning first value twice

Question: I've written this function to calculate sin(x) using Taylor series to any specified degree of accuracy, 'N terms', my problem is the results aren't being returned as expected and I can't figure out why, any help would be appreciated.
What is am expecting is:
1  6.28318530718
2  -35.0585169332
3  46.5467323429
4  -30.1591274102
5  11.8995665347
6  -3.19507604213
7  0.624876542716
8  -0.0932457590621
9  0.0109834031461
What I am getting is:
1 None
2 6.28318530718
3 -35.0585169332
4 46.5467323429
5 -30.1591274102
6 11.8995665347
7 -3.19507604213
8 0.624876542716
9 -0.0932457590621
Thanks in advance.
def factorial(x):
    if x <= 1:
        return 1
    else:
        return x * factorial(x-1)

def sinNterms(x, N):
    x = float(x)

    while N >1:
        result = x
        for i in range(2, N):
            power = ((2 * i)-1)
            sign = 1
            if i % 2 == 0:
                sign = -1
            else:
                sign = 1
            result = result + (((x ** power)*sign) / factorial(power))
        return result

pi = 3.141592653589793
for i in range(1,10):
    print i, sinNterms(2*pi, i)

Comment: ii guess your indention is not correct for return result, you are returning result in a loop
Comment: Welcome to StackOverflow.  Please read and follow the posting guidelines in the help documentation.  [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here.  We cannot effectively help you until you post your code and accurately describe the problem.
Comment: What do you mean "not as expected" You should show a sample of what is
Comment: I've added examples of what I get and what I am expecting, thank you.
Answer: I see that you are putting the return under the for which will break it out of the while loop. You should explain if this is what you mean to do. However, given the for i in range(1,10): means that you will ignore the first entry and return None when the input argument i is 1.  Is this really what you wanted? Also, since you always exit after the calculation, you should not do a while N > 1 but use if N > 1 to avoid infinite recursion.
The reason why your results are off is because you are using range incorrectly. range(2, N) gives you a list of numbers from 2 to N-1. Thus range(2, 2) gives you an empty list.
You should calculate the range(2, N+1)
def sinNterms(x, N):
    x = float(x)

    while N >1:
        result = x
        for i in range(2, N):

Your comment explains that you have the lines of code in the wrong order. You should have
def sinNterms(x, N):
    x = float(x)

    result = x
    # replace the while with an if since you do not need a loop
    # Otherwise you would get an infinite recursion
    if N > 1:
        for i in range(2, N+1):
            power = ((2 * i)-1)
            sign = 1
            if i % 2 == 0:
                sign = -1
            # The else is not needed as this is the default
            # else:
            #     sign = 1
            # use += operator for the calculation
            result += (((x ** power)*sign) / factorial(power))
    # Now return the value with the indentation under the if N > 1
    return result

Note that in order to handle things set factorial to return a float not an int.
An alternative method that saves some calculations is
def sinNterms(x, N):
    x = float(x)
    lim = 1e-12
    result = 0
    sign = 1
    # This range gives the odd numbers, saves calculation.
    for i in range(1, 2*(N+1), 2):
        # use += operator for the calculation
        temp = ((x ** i)*sign) / factorial(i)
        if fabs(temp) < lim:
            break
        result += temp
        sign *= -1
    return result

Comment: When the input N is 1 I should return just the value of x (6.28318530718), when N is 2 I should return the value of x - (x^3)/3! (-35.0585169332). When it is 3 I should return x - (x^3)/3! + (x^5)/5! (46.5467323429). However I return none for N = 1, as you say, and then every other value occurs at the next value of N to what should be the case.
Comment: Thank you very much, I'm quite new to programming but I feel I've learned a lot from your response.
Comment: @JohnRichardson The changed code now fixes the error with None and also fixes the problem with the range.
Comment: Yes, I realised that the range should be up to N + 1 while implementing your first improvements, the function returns as expected now, thank you for being so helpful, sabbahillel.
Comment: @JohnRichardson I also fixed the range to set up the correct powers without having to calculate and started it from 1 to avoid the if.You could still use the if, but i think that this may be more readable.
Comment: @JohnRichardson Since it converges, one should allow for that case. See the change I put in


jQuery - Easiest way to pull multiple .(val) into one string

Question: Given an unknown number of dynamically produced  text inputs:
for (var i = 0; i < numInputs2Render; i++) {
    collectEmails = collectEmails + '<input type="text" id="Email' + i + '" name="Email' + i + '">';
}

I need to produce a comma delimited string of the combined input values. Does jQuery give me a one-step solution or will i need to iterate and manually construct the string? (if if manually...how's that look?)
thx
Answer: You can use .map(), like this:
var emails = $("input[name^=Email]").map(function() { return this.value; })
                                   .get().join(',');

This uses the attribute-starts-with selector to find the inputs, then .map() to get the values into an array you can .join() into a single string.
If they're in a container, say a
 you could slim the selector down to something like $("#Emails input"), I can't say for sure without seeing your markup, but anything with a container selector will make it more efficient.
Comment: @Felix - Agreed, or if we had a bit more context, they're probably all in a single container given how they're being generated.
Comment: Indeed - i pulled the 'class=emailInput' from the OP for sake of brevity. How would that change the answer? - very much appreciated!
Comment: @justSteve - Just use `$(".emailInput")` for your selector :)


Excluding Book children from a Custom view

Question: We have a News site that displays all news articles on the homepage and subpages that display only those items tagged with a certain Taxonomy term.  So for example we have a World News term so going to www.example.net/worldnews will only show those articles with that term.  That works great.
Now we have a request to also filter on Book Content type, so that instead of showing just Article Content nodes we want Article and Book.  For the Homepage we'd use the same sort of filter that we did for Article, and that works well.  However on the subpages, Book parents AND children are showing up.  Is there a way to make sure no children ever show up on the subpages ( but of course would still be accessible the usual way from the parent and siblings )?  I've played around with Contextual Filters but can't quite get it right.
We do have some module code written that uses this View so it may be that I need to go that route and write some code, but would love to see if a View-only solution is possible.
Comment: Are you going to give some specific taxonomy term to parent Book pages or Children Book pages or articles?
Comment: Parents will be a specific term AND have a --homepage-- term  Children can also have the first specific term but will not have the --homepage-- term
Comment: So, all Parent Book node will have *homepage* taxonomy term, right?
Comment: That is correct.
Answer: This can be done with Normal filter in views.
Following is the configuration of the filter UI, You need to separate the both content type in the filter with OR and in the Content Type: Book page you need to Book: Depth = 1.

Now in the following image you can see the Article and Book page titles, First one without Book: Depth =1, Second one with Book: Depth =1.

Hence, You can see the views fetches the all articles and only parents books page.
Comment: Oh, Just I realize that, you are using D8. Under D7 impression I did this in D7. But theoretically this is the way you can achieve. I am keeping this Answer, so you can refer this and can do for D8 also.
Comment: I don't have any of those Filter Options in D8.
Comment: Yes, that is right..:(.  After posting comment, I went to try in D8. But to my surprise, I did find nothing to Book in filters or contextual or field..:(. I am not getting why it is not there, even many things are not there in Views in D8. Tried to find but not getting anything. Hence, let this answer be there, so this will be the comparative example to make someone understand, so if someone knows D8 deep, can suggest by observing this answer. But, sure D7 solves your issue and can be as shown above. Hope, someone will put light abt D8.


Creating mulitple contact forms in drupal 7

Question: I have installed the contact and contact_forms modules.
I have created different categories in the contact settings page.
I want multiple contact forms as I have multiple domains. For each domain I should have a separate contact form.
But that categories displayed in the drop down of the contact form.
Is it possible with the contact module to create multiple contact us forms like contact/site1, contact/site2, contact/site3 etc?
Answer: Did you consider using Webform Module. I generally prefer this over contact forms on my websites.
Answer: Webforms is great but if you just need separate pages for the categories you can use https://www.drupal.org/project/contact_forms .
Comment: Is there any way to have multiple entity forms for multiple domains? So, basically I need a form to be re-used across all domains, but at the same time the form elements also should be different. Can this be achieved without adding a new form and then tagging it to the respective domains?


LazyLoad content from mysql/php Json encoded data and Jquery

Question: i'm creating a mobile app using Jquery mobile. i am getting the data from mysql DB to a PHP page and i encode the data as Json then i render it in my HTML page with a Jquery ajax request and append data to a  JQM 'listview' but since the amount of data is huge i want to load the list view gradually when user scrolls to the bottom of the page "Lazy Loading"
My PHP code sample:
$result = mysql_query("SELECT * FROM $tableName ORDER BY alpha");

$array = mysql_fetch_row($result);

    $data = array();
    while ($row = mysql_fetch_row($result))
    {
    $data[] = $row;

    }

    echo $_GET['callback'] . '('.json_encode($data).')';

My JS code :
 $.ajax({
  type: "POST",
  url: 'http://example.com/api.php',
  dataType: 'jsonp',
  contentType: "application/json",
  cache: false,
  success: function(data)
  {
  $("#loading").hide();
    for (var i in data)
    {
      var row = data[i];
      var id =  row[0];
      var alpha = row[1]
      var name =row[2];
      var url = row[3];

     $("#filelist").append('
<input name="name'+id+'" id="song'+id+'" type="checkbox" class="selectme">'+name+'
').trigger("create");
     $("#filelist").listview("refresh");

    }
      $("#filelist").listview("refresh");

});

this works fine but loads all my data from the DB
how i can load the data in chunks not one time i use the waypoint plugin to detect the scroll to bottom action all i need now is help with loading the data gradually from the DB
Note: i tried using the dcarrith.github.io/jquery.mobile.lazyloader/ but couldn't reach a solution.
your help is Greatly appreciated
UPDATE:
I managed to Load my Json data coming from DB in different pages so i can call the first 10 items from the url www.myDomain.com/api.php?page=2 and www.myDomain.com/api.php?page=1 and so on and when you call this in the jquery Ajax request you only load this amount of data.
The code is as follows to achieve paging :
<?php
  header('Content-type: text/html; charset=utf-8');
  $host = "xxxxxxxxxxx";
  $user = "xxxxxx";
  $pass = "xxxxxx";

  $databaseName = "xxxxxxx";
  $tableName = "xxxxxxxx";

  //--------------------------------------------------------------------------
  // 1) Connect to mysql database
  //--------------------------------------------------------------------------

  $con = mysql_connect($host,$user,$pass);
  $dbs = mysql_select_db($databaseName, $con);

    $tbl_name="xxxxxx";     //your table name
    // How many adjacent pages should be shown on each side?
    $adjacents = 3;

    /*
       First get total number of rows in data table.
       If you have a WHERE clause in your query, make sure you mirror it here.
    */
    $query = "SELECT COUNT(*) as num FROM $tbl_name";
    $total_pages = mysql_fetch_array(mysql_query($query));
    $total_pages = $total_pages[num];

    /* Setup vars for query. */
    $targetpage = "test.php";   //your file name  (the name of this file)
    $limit = 10;                                //how many items to show per page
    $page = $_GET['page'];
    if($page)
        $start = ($page - 2) * $limit;          //first item to display on this page
    else
    $start = 0;                             //if no page var is given, set start to 0

    /* Get data. */
    $sql = "SELECT * FROM $tbl_name ORDER BY alpha LIMIT $start, $limit";
    mysql_query("SET NAMES utf8;");
    $result = mysql_query($sql);

    /* Setup page vars for display. */
    if ($page == 0) $page = 1;                  //if no page var is given, default to 1.
    $prev = $page - 1;                          //previous page is page - 1
    $next = $page + 1;                          //next page is page + 1
    $lastpage = ceil($total_pages/$limit);      //lastpage is = total pages / items per page, rounded up.
    $lpm1 = $lastpage - 1;                      //last page minus 1

    /*
        Now we apply our rules and draw the pagination object.
        We're actually saving the code to a variable in case we want to draw it more than once.
    */
    $pagination = "";
    if($lastpage > 1)
    {}
?>

    <?php
    $data = array();
        while($row = mysql_fetch_array($result))
        {

        // Your while loop here
        $data[] = $row;

        }
        echo $_GET['callback'] . '('.json_encode($data).')';
    ?>

<?=$pagination?>

what is left now is :

HOW TO MAKE THE JQ AJAX REQUEST DYNAMIC TO CALL ?PAGE=2 THEN ?PAGE=3
  TILL THE END OF CONTENT !?

I CAN DETECT THE SCROLL TO BOTTOM ACTION WITH THE WAYPOINT PLUGIN - your help is greatly appreciated - Thanks
Answer: You are going to want to teach your PHP API as well as your jQuery Mobile App the notions of 'offset' and 'limit'.
Let's say you want to load the elements 10 at a time:
Your first request would be:
http://example.com/api.php?offset=0&limit=10

You second request (triggered on scroll) would be:
http://example.com/api.php?offset=10&limit=10

You would append this ajax result to the existing list...
On the PHP side you want:
mysql_query("SELECT * FROM $tableName ORDER BY alpha LIMIT $limit OFFSET $offset")

Comment: Thanks AllinOne for pointing me to this, i researched limit and offset and created a PHP page now that i can navigate to results with: ?page=1  and this is readable by my JS code when i make an Ajax request to it , now im researching how to implement this dynamically when i scroll to bottom and navigate to the page?2 dynamically until reaching the end of content coming for the DB (pages).
Answer: This is like two years already. but i think i have an idea. What if you put the ajax in a function and then whenever you detect end of page, you call the function. and dynamically changing the url.


Combine two Knockout Examples

Question: I am trying to get two examples from knockout.com working and I have yet to figure it out. Any help would be greatly appreciated!
http://jsfiddle.net/gZC5k/2863/
When running this project and using a debugger I get an error:
Uncaught ReferenceError: Unable to process binding "foreach: function (){return linesa }"
Message: linesa is not defined
From the original example I changed lines to linesa to see if anything else was screwing it up. It still did not like linesa
My main goal is to get these two samples working together. The Add a contact button works but the Add product does not work.
Thank you!

Contacts

                First name
                Last name
                Phone numbers

                        <input data-bind='value: firstName' />

Delete

                    <input data-bind='value: lastName' />

                                    <input data-bind='value: type' />
                                    <input data-bind='value: number' />
                                    Delete

                        Add number

        <button data-bind='click: addContact'>Add a contact</button>
        <button data-bind='click: save, enable: contactsa().length > 0'>Save to JSON</button>

    <textarea data-bind='value: lastSavedJson' rows='5' cols='60' disabled='disabled'> </textarea>

                Category
                Product
                Price
                Quantity
                Subtotal

                    <select data-bind='options: sampleProductCategories, optionsText: "name", optionsCaption: "Select...", value: category'> </select>

                    <select data-bind='options: products, optionsText: "name", optionsCaption: "Select...", value: $parent.product'> </select>

                    <input data-bind='visible: product, value: quantity, valueUpdate: "afterkeydown"' />

                    Remove

        Total value:

    <button data-bind='click: addLine'>Add product</button>
    <button data-bind='click: save'>Submit order</button>

    var initialData = [
    { firstName: "Danny", lastName: "LaRusso", phones: [
        { type: "Mobile", number: "(555) 121-2121" },
        { type: "Home", number: "(555) 123-4567"}]
    },
    { firstName: "Sensei", lastName: "Miyagi", phones: [
        { type: "Mobile", number: "(555) 444-2222" },
        { type: "Home", number: "(555) 999-1212"}]
    }
];

var ContactsModel = function(contactstest) {
    var self = this;
    self.contactsa = ko.observableArray(ko.utils.arrayMap(contactstest, function(contact) {
        return { firstName: contact.firstName, lastName: contact.lastName, phones: ko.observableArray(contact.phones) };
    }));

    self.addContact = function() {
        self.contactsa.push({
            firstName: "",
            lastName: "",
            phones: ko.observableArray()
        });
    };

    self.removeContact = function(contact) {
        self.contactsa.remove(contact);
    };

    self.addPhone = function(contact) {
        contact.phones.push({
            type: "",
            number: ""
        });
    };

    self.removePhone = function(phone) {
        $.each(self.contactsa(), function() { this.phones.remove(phone) })
    };

    self.save = function() {
        self.lastSavedJson(JSON.stringify(ko.toJS(self.contactsa), null, 2));
    };

    self.lastSavedJson = ko.observable("")
};

ko.applyBindings(new ContactsModel(initialData));

function formatCurrency(value) {
    return "$" + value.toFixed(2);
}

var CartLine = function() {
    var self = this;
    self.category = ko.observable();
    self.product = ko.observable();
    self.quantity = ko.observable(1);
    self.subtotal = ko.computed(function() {
        return self.product() ? self.product().price * parseInt("0" + self.quantity(), 10) : 0;
    });

    // Whenever the category changes, reset the product selection
    self.category.subscribe(function() {
        self.product(undefined);
    });
};

var Cart = function() {
    // Stores an array of lines, and from these, can work out the grandTotal
    var self = this;
    self.linesa = ko.observableArray([new CartLine()]); // Put one line in by default
    self.grandTotal = ko.computed(function() {
        var total = 0;
        $.each(self.linesa(), function() { total += this.subtotal() })
        return total;
    });

    // Operations
    self.addLine = function() { self.linesa.push(new CartLine()) };
    self.removeLine = function(line) { self.linesa.remove(line) };
    self.save = function() {
        var dataToSave = $.map(self.linesa(), function(line) {
            return line.product() ? {
                productName: line.product().name,
                quantity: line.quantity()
            } : undefined
        });
        alert("Could now send this to server: " + JSON.stringify(dataToSave));
    };
};

ko.applyBindings(new Cart());

Comment: If I split these two examples into different examples they both work fine.
Answer: ViewModel is a ContactsModel, since ContactsModel does not have a linesa property, it cannot render the contents of the table.

this is the offending line.
You are working with 2 ViewModels actually, the Cart ViewModel and the Contacts ViewModel.
you need to make a new ViewModel that implements both ViewModels and you can bind the views using  with binding.
Code:
function CombinedViewModel(){
  this.cart=new Cart();
  this.contact=new Contact();
}

ko.appyBindings(new CombinedViewModel());

and for the bindings

Comment: Thank you very much! That makes complete sense! Here is the completed solution in case anyone else finds it helpful.  http://jsfiddle.net/gZC5k/2881/
Comment: Here is an updated example with the numbers working. http://jsfiddle.net/gZC5k/2889/

Combine two Knockout Examples


Tychonoff and compactness (logic) and another small logic question

Question: It is claimed in some logic books that the compactness theorem of first-order logic can be proven using Tychnoff's theorem from topology.
Now, to me this feels very strange because I consider logic as something "lower" in the sense that the theorems of topology follow from the axioms and theorems in logic. How can we avoid circularities then?
Another small question I have is that if we have $A \iff B$ and we prove both directions with contraposition, does there exist a direct proof? You could say we could just follow the steps backwards, but is this always possible?
Comment: Jonas: You do not need compactness or completeness to prove Tychonoff's theorem, so there is no circularity. The use of topological arguments in logic is actually very fruitful.
Comment: You could define a topology on the sentences and have the theory as a product of compact spaces.
Answer: When we study mathematical logic, we use the same mathematical methods that would be used to study any other area (algebra, analysis, topology, etc.).  This includes the use of set-theoretical techniques.  Otherwise, we would be needlessly hamstringing ourselves.  In principle, the results that we obtain could be built up entirely from primitive axioms, just like the rest of mathematics; but just like the rest of mathematics complete formalization is not usually the goal.
However, even ignoring those practical considerations, it's not hard to see that none of the axioms of point set topology or set theory used in topology presuppose that the compactness theorem of logic holds. So there is no circularity if we use topological methods to prove the compactness theorem.
Answer: For the second question, suppose that in some proof system you can prove $p(x) \Leftrightarrow q(x)$ for some expressions $p,q$, and only $p(x)\Rightarrow q(x)$ requires proof by contradiction. Then to prove $p(x) \land q(y) \Leftrightarrow q(x) \land p(y)$ you probably need proof by contradiction on both sides.
If you only know that $p(x) \Rightarrow q(x)$ requires proof by contradiction ($p(x) \Leftarrow q(x)$ not necessarily being true), then $p(x) \Rightarrow p(x) \land q(x)$ also probably requires proof by contradiction, and this time both sides are equivalent.
Comment: Is there any difference if the proof is by _contraposition_ instead of contradiction? By the way, to summarize what you said, the answer to my question is: Not always?
Comment: If you want a real answer, you need to decide what a proof by contraposition/contradiction is. For example, you could side a statement uses these principles if it isn't true (can't be proven) in intuitionistic logic. For example, $\lnot \lnot A \Rightarrow A$ isn't true intuitionisticly. The rest probably works with this definition of "requires proof by contradiction/contrapositive".


Open the AJAX Login/Register popup when clicking on post titles

Question: The AJAX Login/Register module adds a block with a login button. Clicking on that button opens a nice popup login/register dialog.
But how to make the login dialog open when clicking on post titles?
I tried to add a block with this code:

     My Post Title

However it doesn't work. Anyone knows why?
Answer: You simply have a typographic error. Use "class=..." instead of "classes=..."
Comment: Yes, it works... :)


Why is JSON.parse changing the values in nested arrays?

Question: To learn Angular 2, I made a Connect Four game with Angular CLI when it used SystemJS.
I am replicating the effort from scratch with the new Webpack-based CLI and I am having a strange problem...
The following method receives a string with JSON-encoded data and initializes a new game instance with it. I added a few console.log to show the problem:
export class ConnectFourGameModel {
  static fromJSON(jsonString: any): ConnectFourGameModel {
    let jsonData = JSON.parse(jsonString);

    console.log('*** from JSON (compare the "columns" array between jsonString and jsonData below) ***');
    console.log('jsonString: ', jsonString);
    console.log('jsonData: ', jsonData);

    ...
    return result;
}

When this runs, the first console.log shows the JSON string correctly:
jsonString:
{... Several fields here ...
 "columns":[[0,0,0,0,0,1],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]]
}

But the second console.log, which is just the result of calling JSON.parse on this string, seemingly randomly changes the values:
jsonData:
> Object {... Several fields here ...
  > columns: Array[15]
    V 0: Array[6]
        0: 2     <-- Should be 0
        1: 2     <-- Should be 0
        2: -1    <-- Should be 0
        etc...

Why is this happening?
You can probably see it better if you load the app on Github Pages, open the JavaScript console on the browser, and click on any column to make a move.
The repository is on Github: https://github.com/cmermingas/connect-four-webpack
I looked for questions here regarding parsing nested arrays with JSON.parse but I couldn't relate this issue to the ones I found.
Thanks a lot in advance!
Comment: What @Phil said. If you set a breakpoint at the `console.log` line, you also get to inspect `jsonData`, where you can see that it is indeed a 1:1 decoding of `jsonString`.
Comment: You're changing the data. Objects shown via `console.log` are *live* so changes made to their properties will be shown, even after being logged
Answer: If you put your string example into a fiddle, it appears to parse just fine:
https://jsfiddle.net/z67Lgyrm/
What is likely happening is that you are changing the data after your console.log() call. When you click the expand arrow in the log, it is actually showing the value of the object now.
Also you seem to be using slice() on the columns array, but because it is multidimensional, it is only making a copy of the the references to the child arrays (i.e. not actually copying the values).
See here for a possible solution: Create copy of multi-dimensional array, not reference - JavaScript


jQuery Mobile changePage not working

Question: I'm trying to link to the following html page using
$.mobile.changePage( "myPage.html", { transition: "slide"} );

However, it's not working. The page will load however the alert box with the spinning cirlce and "loading" message never disappears and the page never fully loads in its css content. Can anybody see why based on the above call and the html below? Thanks
HTML Page
<!DOCTYPE html>

  <title>Sign up</title>

  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.css" />
  <link rel="stylesheet" href="./signup.css">

Classroom Tempo

Sign-In

Sign-Up

      <form id="form1">

        How Many Options?
        <input type="range" name="optionSlider" id="optionSlider" value="2" min="2" max="25" data-highlight="true" />

      <fieldset data-role="controlgroup">
      <legend>Numbers or Letters?:</legend>
          <input type="radio" name="numbersOrLetters" id="Numbers" value="Numbers" checked="checked" />
          Numbers

          <input type="radio" name="numbersOrLetters" id="Letters" value="Letters"  />
          Letters
    </fieldset>

Comment: Can you use the latest jQuery Mobile? I have a feeling that the old version doesn't support the option object.
Comment: you have saved me so much time. please add this as an answer so I can gladly upvote/mark as answer.
Answer: The $.mobile.changePage API has undergone some changes from version 1.0 alpha 4 and 1.0.1 of jQuery Mobile. The syntax you are using with option object is of the newer version of jQuery Mobile (at least from 1.0.1).

jQuery Mobile changePage not working


Missing value imputation using Amelia when variable count is greater than number of observations

Question: My dataset contains 5000+ variables measured over hourly for just over a week (201 observations).
These measurements are of the same metric, noise levels in a wireless network measured in dBm. These measurements were recorded at various locations across my country, some variables are measured at the same location and some could be hundreds of kilometers away. Please also note that the missingness is MCAR since either the wireless sites were off for maintenance or some sort of outage/physical upgrade.
Of the 5000 or so variables, only ~1% of variables are missing any values over time, please see the missingness map below for details. Time is represented on the Y axis and the 5000+ variables are on the X axis. These 1% of variables also have missingness for less than 5% of their total recordings e.g less than 10 samples over time of the total 201 samples for that variable are missing.

Rather than just cut these variables from the dataset I wish to impute these values using Amelia in R. When I tried to run the imputation I got the following error message:
<code>Amelia Error Code:  34
 The number of observations in too low to estimate the number of
 parameters.  You can either remove some variables, reduce
 the order of the time polynomial, or increase the empirical prior.
</code>
On the very bottom row you can see that there are a small number of missing values for a lot of variables. Rather than making the dataset smaller by deleting these values is there a smarter approach to imputing such values.
Comment: You may want to consider treating separate cases with missing data as individual time series that contain missing values to be imputed. Here is a [link](https://cran.r-project.org/web/packages/imputeTS/imputeTS.pdf) to an R package designed for time series imputation. You'll need to make sure it is a good fit for your data first. Alternatively, depending on what you want to do with the data in the end, you may want to consider modeling strategies that utilize full information maximum likelihood estimators.
Answer: The general idea of multiple imputation is to fit a quite general Bayesian model with very vague priors and to predict the missing data from that. The problem here is that you have not so many records relative to how much you measure. As a result, you need to put in more information in terms of the model structure (just using a subset of the variables would be an example, because then you would be saying that some of the variables don't matter for predicting the others) or in terms of more informative priors.
An alternative (as stated in the comment by Matt Barstead) is to use a model that is valid under a missing at random assumption. If you are willing to specify such a model, you should be willing to specify a more constrained model that would allow you to impute the data (there is to some extent no difference between the two approaches, except that you could impute with a more general model and analyze with a more restrictive model).


Problem in an example to Radon-Nikodym theorem.

Question: Let $X$ and $Y$ be two random variable with a joint distribution $P_{(X,Y)}$ absolute continuous with respect to the Lebesgue measure on $\mathbb R^2$. I want to show that  $P_{(X,Y)}$  has a density, that it, there exists a measurable function $f_{(X;Y)}$:$\mathbb{R}^2 \rightarrow \mathbb{R}_+$   such that $E\left ( g(X,Y) \right )=\int_{\mathbb{R}^2}g(x,y)f_{(X,Y)}(x,y)$ for every positive measurable function $g:\mathbb{R}^2\rightarrow[0,\infty[$.
Question: What is the relation between this example and Radon-Nikodym theorem?
Comment: That is the [Radon-Nikodym theorem](https://en.wikipedia.org/wiki/Radon%E2%80%93Nikodym_theorem). Do you want to do that yourself? It looks a bit like reïnventing the wheel.
Comment: I am not able to write it out more clearly than in the link in my former comment. A measurable function $f$ exists such that $P_{X,Y}(A)=\int_A fd\lambda$. This $f$ is the [density](https://en.wikipedia.org/wiki/Probability_density_function#Formal_definition) you are looking for. Is it your question how to prove that $\mathbb Eg(X,Y)=\int gfd\lambda$ for each suited $g$? If so then you asked the wrong question.
Comment: @ drhab Thank you for your comment. But I couldn't derive probability density from Radon-Nikodyn theorem. Please write it for me.
Comment: @drhab thank you so much for your comment.
Answer: To use the Radon-Nikodym theorem we need that:
(1) $P_{(X,Y)} \mbox{ is absolutely continuous w.r.t. the Lebesgue measure}$ $\lambda^2$ on $\mathbb{R}^2$
(2) $P_{(X,Y)}$ is $\sigma-$finite which is satisfied since it is even finite: $P_{(X,Y)}(\mathbb{R}^2) = 1 < \infty$.
(3) The Lebesgue measure $\lambda^2$ is $\sigma-$finite, for this we define for each $n \in \mathbb{N}$ the set $B_n := [-n,n] \times [-n,n]$ then we clearly have that $B_n \nearrow \mathbb{R}^2$ and for each $n: \lambda^2(B_n) = 4n^2 < \infty$. From this we conclude that $\lambda^2$ is indeed $\sigma-$finite.
Now the Radon-Nikodym theorem yields that there exists a measurable function $f_{(X,Y)}: X \rightarrow [0,\infty[$ which satisfies that what you need if you use Proposition 4.1 in the following:
https://www.math.ksu.edu/~nagy/real-an/4-04-rn.pdf
Comment: This is the complete answer, thank you. I ll add the complement for the last part.


Equivalence condition for vector addition and scalar multiplication is continuous

Question: My textbook says that vector addition and non-zero scalar multiplication is continuous are equivalent to the following things:
In Vector space $(\mathbb{E},\mathbb{K}),\mathbb{K}=\mathbb{R}\ or\ \mathbb{C}$ and topological space $(\mathbb{E},\tau)$

vector addition is continuous at $(0,0)$
scalar multiplication is continuous at $(0,0)$
$\forall x\in\mathbb{E}$, $\lambda x$ is continuous at $0\in\mathbb{K}$
$\forall \lambda\in \mathbb{K}$, $\lambda x$ is continuous at $0\in\mathbb{E}$

I'm not familar with point set topology, so I have difficulty to prove it is a TVS.
Answer: I have asked my TA, and he said one should select a particular $\tau$ such that it makes $\forall \alpha\in\mathbb{E},\ T_\alpha:\mathbb{E}\rightarrow\mathbb{E},\ x\mapsto \alpha+x$ and $\forall \lambda\in\mathbb{K}\setminus\{0\}, M_\lambda :\mathbb{E}\rightarrow\mathbb{E},\ x\mapsto\lambda x$ continuous with respect to $\tau$.
And under that condition we can prove the equivalence between i)-iv) and the continuity of $+:\mathbb{E}\times\mathbb{E}\rightarrow\mathbb{E}$ and $\cdot:\mathbb{K}\times\mathbb{E}\rightarrow\mathbb{E}$.