Discrete math induction proof

Question: I am trying to solve a induction proof and i got stuck at the end, some help would be great. This is the question and what i did so far:
Statement: For all integers $n \geq 5$ we have $2^n \geq n^2$.
Proof: Induction over $n$. Introduce the name $A(n)$ for the statement $2^n \geq n^2$. We shall prove, by mathematical induction that $\forall n \geq 5 : A(n)$.

$A(n)$ and test with $5$ so that $A(5): 2^5 ≥ 5^2 \implies 32 ≥ 25$ (true)
Assume $A(p)$ so that we have $A(p): 2^p \geq p^2$ and we want to prove $A(p+1): 2^{p+1} \geq (p+1)^2$.

$2^{p+1} \geq (p+1)^2 \iff 2 \cdot 2^p ≥ p^2 + 2p + 1$, with the assumption $2^p \geq p^2$ we get $2p^2 ≥ p^2 + 2p + 1$,         it is here where i dont know how to continue to prove the statement
Please help
Answer: Just don't try to do "if and only if":
$$
2^{p+1}=2\cdot 2^p\ge2p^2
$$
because of the induction hypothesis. Now, try proving that, for $p\ge5$, $2p^2\ge(p+1)^2$
Hint: this is equivalent to $p^2-2p-1\ge0$, which is true when $p\ge\dots$
Comment: i dont understand what u mean with this comment, it just looks like you repeated what i have already done? i dont know how to continue from here
Comment: @haha150 Can you say that $p^2-2p-1\ge0$ for $p\ge5$? Yes, because the inequality is satisfied when $p\ge 1+\sqrt{2}$ and $5>1+\sqrt{2}$. My initial comment is because you don't want to "solve an inequality", but just verifying it holds for certain values of $p$.
Comment: sorry i dont see the connection of this and what im trying to prove, i also dont know where u got p2−2p−1≥0 from, i cant figure out the answer
Comment: @haha150 You want to prove $2p^2\ge(p+1)^2$, don't you? Expand the right-hand side and transport.
Comment: Yes and I get 2p2≥p2+2p+1 but don't know what else to do
Comment: @haha150 Transport to the left-hand side; you get $p^2-2p-1\ge0$. Can you go on now?
Comment: Omg i see now what you meant, so that concludes the proof too I assume
Answer: $$2p^n \ge 2p^2 = p^2 + p^2$$
Here $p^2 = 2p + (p-2)p \ge 2p + 1 $ for (p > 4) since $(p-2)p > 1$ for p > 4
So $$2^{p + 1} = 2\,2^p > 2 p^2 = p^2 + p^2 \ge p^2 + 2p + 1 = (p + 1)^2$$

Discrete math induction proof


Limite timestamp 19 de janeiro de 2038

Question: Como é possivel resolver esse bug?
echo date('c', mktime(1, 2, 3, 4, 5, 2038));

Resultado
1970-01-01T00:00:00+00:00

Comment: Não é bug do php... Isso é a data limite do timestamp
Comment: Reporte para o PHP ;)
Comment: existe sim: http://stackoverflow.com/questions/6303972/format-date-whose-timestamp-exceeds-the-int-limit
Answer:
Esse bug é causado pelo uso de 4bytes signed integer utilizados para fazer  contas rápidas.
O problema:

Não existe nenhuma solução universal para o problema do ano 2038, qualquer
mudança na definição do time_t pode resultar em problemas de compatibilidade
em qualquer aplicação
Por exemplo, alterar time_t para um inteiro de 32 bits não assinado, o que estenderia o intervalo para o ano 2106, afetaria negativamente os programas que armazenam, recuperar ou manipular datas antes de 1970, uma vez que tais datas são representados por números negativos. O aumento do tamanho do tipo time_t de 64 bits em um sistema existente iria causar alterações incompatíveis para a disposição das estruturas de interface e o binário de funções.
Wikipedia - Solutions
Answer: Apenas para complementar a resposta, quero reletar que com a classe DateTime não tive esse problema.
Veja:
$date = new DateTime('+1000 years')

echo $date->format('c'); // 3015-11-25T09:20:54-02:00

Testado na linha de comando com psysh.
Atualização: No ideone.com, somente a forma destacada no meu exemplo funciona. A forma utilizando a função date falha.
http://ideone.com/VoYyOo
Observação: Tudo isso funcionará perfeitamente com DateTime, a não ser que você use DateTime::getTimestamp.
Testes
Uma boa maneira de testar essas limitações pode ser feita através da constantes PHP_INT_MAX, que provavelmente pode ser mudada em diferentes versões do PHP.
Teste 1 psysh, PHP 5.5.9 Ubuntu:
$date = new DateTime();
$date->setTimestamp(PHP_INT_MAX);
var_dump($date->format('c')); // 219250468-12-04T13:30:07-02:00
var_dump(PHP_INT_MAX); // int(9223372036854775807)

Teste 2 ideone.com:
$date = new DateTime();
$date->setTimestamp(PHP_INT_MAX);
var_dump($date->format('c')); // 2038-01-19T03:14:07+00:00

var_dump(PHP_INT_MAX); // int(2147483647)

Veja que nos dois casos, resultados diferentes foram retornados. Então também posso supor que, por conta do tamanho máximo do integer processado no PHP, isso possa afetar o comportamento das funções.
Comment: +1 Aqui funcionou legal também. essa DateTime  usa 64bits? não sei como ela faz essa magia.
Comment: Não sei @GabrielRodrigues. Mas dê uma olhada nisso que encontrei http://stackoverflow.com/questions/5319710/accessing-dates-in-php-beyond-2038
Comment: Atualizei a resposta @GabrielRodrigues. Veja a importante informação do `PHP_INT_MAX`
Comment: Nesse post fala que "O DateTime representa internamente os componentes de tempo de forma independente. Assim, não é suscetível à limitação de 2038." mas não tem nada na documentação do php e não achei nada em outros artigos, o.O
Answer: Use os métodos da classe \DateTime. Dessa forma, as datas geradas por sua aplicação não são limitadas pela arquitetura que o PHP está rodando (no caso, 32 bits).
Comment: Bom saber dessa informação, Rodrigo. Mais um motivo para usar o Objeto, ao invés da Função

Limite timestamp 19 de janeiro de 2038


Is counterpoint still used today?

Question: I was wondering if counterpoint is still used today or was it something that was just used by Bach? Does modern music like pop songs use it?
Comment: It's used a lot in popular music. Usually a line is sung by a lead vocalist then repeated by others with a varied melody. Here's some in the opening number of the musical Hamilton https://youtu.be/VhinPd5RRJw?t=166
Comment: A shame that some feel the need to bash any post that in any way questions common practice harmony. +1.
Comment: I've heard this club/dance song incorporates counterpoint. https://youtu.be/WP47nuuOU_I
(Reference: https://www.edmtunes.com/2014/05/look-mom-told-featuring-andrew-bayer/)
Comment: Check out the synth solo in the song **Doctor! Doctor!** by the 1980s band **Thompson Twins**: https://youtu.be/APyl6Cnbfzw?t=160
Answer: Counterpoint is simply the relationship between multiple musical lines. As such, any excerpt of music with more than one line is displaying some sense of counterpoint, whether intentional or not.
Note also that there are multiple eras and traditions of counterpoint, each with their own distinct styles (what many erroneously call "rules"). Palestrina is typically considered the master of Renaissance counterpoint, with Bach being the master of Baroque counterpoint. Mozart and Beethoven were among the many masters of counterpoint in the Classical era, and getting into the Romantic era you have composers like Brahms and Bruckner. And in the twentieth century you have composers like Shostakovich and Hindemith, both of whom wrote sets of piano fugues much like Bach did.
If you're asking whether or not something like fugues are still written today, of course they are! In fact, the fugue at the end of Young Person's Guide to the Orchestra (1945) is still to this day one of the most impressive feats of counterpoint I know:
Comment: The fugue in _Young Person's Guide_ is truly fantastic but 1945 is "today"?
Comment: I feel that your definition is rather ample. If we add this qualification from [Wikipedia](https://en.wikipedia.org/wiki/Counterpoint#General_principles) : _"Counterpoint focuses on melodic interaction—only secondarily on the harmonies produced by that interaction"_,  I'd say that counterpoint is practically absent in modern popular music. We compose (and hear) "vertically" (structure defined by sequences of chords ), the melodic line(s) lie on top of that.
Comment: If counterpoint is the relationship between multiple music lines then most music would have some form of counterpoint, even any kind of pop song? or does melody+chords not count?
Comment: @foreyez Yes; you could look at, for instance, the counterpoint between the bass and melody.
Comment: Indeed, composing a fugue is a key part of most (upper secondary) formal music education.
Comment: @leonbloy The problem with modern music and counterpoint is that you need two melodies for one to be the counterpoint to the other. A lot of the more recent pop genres (hip hop, trap, _reguetón_, etc.) tend to have only one voice melody, though, so counterpoint is provided by the guitar, the bass or some synthesizer — which makes it more difficult to identify. However, duets still make a clearer use of counterpoint. In this playlist of recent pop duets you might find some good examples of it (I say might because I didn't listen to it): https://open.spotify.com/playlist/2bAhfGTu4db4bXDM6i4Lms.
Answer: One practical use in pop, country, big band, (and probably jazz, maybe rock) is the counterpoint between melody and bass. One would like the melody and bass to be independent voices. Many bass players use chord inversions (playing the third usually) and walking basses to achieve this (and they do it on the fly.) If one isn't careful about parallels, the texture can suddenly seem "thin" like an instrument dropped out.
I like to think of songs as being a melody line (maybe several instruments), a bass line (using good two-part counterpoint), and a bunch of inner stuff that need not be so careful (because of doublings and texture, one doesn't usually hear multiple lines in these styles). Renaissance counterpoint sounds more like several independent voices but Baroque counterpoint (not counting fugues, canons, and inventions) can be a bass line supporting upper voices with some filler for chords.
I'd like to add an example. I'm suggesting that even popular music (since the Middle Ages anyway) has a skeleton consisting of a bass line and a melody line (or lines) with some chords thrown in between and a related but separate percussion part. Here's an example of a song with just a bass and melody exhibiting the point.
Answer: It is still used, but not the way Bach used it. Bach used to compose the different voices to be harmonically interdependent but rhythmically independent. After a certain point (later 19th-early 20th century) the composers took counterpoint in a different direction. They started composing for voices that were purely independent with each other; both harmonically and rhythmically.
A great example is Arnold Schoenberg and his use of 12-tone serialism.

Here is a more modern piece that uses contrapuntal techniques:

Also, here is an example from Radiohead's In a glass house:

Notice how the horns move independently from the voice and the rhythm section and how the clarinet moves in a different rhythm that the brass.
Answer: I get the feeling the question is more along the lines of: is there counterpoint in homophonic music, or is a homophonic bass part a contrapuntal line?
I think the answer is yes to both.
It's very common in pop/rock for the bass to move only by leaps to roots while the vocal melody moves in a more step-wise manner. By necessity those two lines are independent in terms of contour and relative motion. And, in pop/rock it would be very common for the bass and voice to be rhythmically independent.
Independent contours, independent rhythms: how is that not counterpoint?
The discussion on this post... Is there any name for two melodies that are being played at the same time? ...still sticks in my mind as making a muddle out of a simple idea: independence of contour and rhythm makes counterpoint.
Answer: Well, Scarborough Fair by Simon&Garfunkel qualifies as pop music I think and works with contrapuntal themes, even if they are slightly disentangled to accommodate reception.

Is counterpoint still used today?


Why can't I create an array with size determined by a global variable?

Question: Why does the array a not get initialized by global variable size?
#include<stdio.h>

int size = 5;

int main()
{
    int a[size] = {1, 2, 3, 4, 5};
    printf("%d", a[0]);

    return 0;
}

The compilation error is shown as

variable-sized object may not be initialized

According to me, the array should get initialized by size.
And what would be the answer if I insist on using global variable (if it is possible)?
Comment: They're already enabled - if he was in c89 mode, the error would be something like `ISO C90 forbids variable length array 'a'`.
Comment: Use `-std=c99` when compiling with GCC to enable variable size arrays.
Answer: In C99, 6.7.8/3:

The type of the entity to be
  initialized shall be an array of
  unknown size or an object type that is
  not a variable length array type.

6.6/2:

A constant expression can be evaluated
  during translation rather than runtime

6.6/6:

An integer constant expression
  shall have integer type and shall only
  have operands that are integer
  constants, enumeration constants,
  character constants, sizeof
  expressions whose results are integer
  constants, and floating constants that
  are the immediate operands of casts.

220.127.116.11/4:

If the size is an integer constant
  expression and the element type has a
  known constant size, the array type is
  not a variable length array type;
  otherwise, the array type is a
  variable length array type.

a has variable length array type, because size is not an integer constant expression. Thus, it cannot have an initializer list.
In C90, there are no VLAs, so the code is illegal for that reason.
In C++ there are also no VLAs, but you could make size a const int. That's because in C++ you can use const int variables in ICEs. In C you can't.
Presumably you didn't intend a to have variable length, so what you need is:
#define size 5

If you actually did intend a to have variable length, I suppose you could do something like this:
int a[size];
int initlen = size;
if (initlen > 5) initlen = 5;
memcpy(a, (int[]){1,2,3,4,5}, initlen*sizeof(int));

Or maybe:
int a[size];
for (int i = 0; i < size && i < 5; ++i) {
    a[i] = i+1;
}

It's difficult to say, though, what "should" happen here in the case where size != 5. It doesn't really make sense to specify a fixed-size initial value for a variable-length array.
Answer: You don't need to tell the compiler what size the array is if you're giving an initializer.  The compiler will figure out the size based on how many elements you're initializing it with.
int a[] = {1,2,3,4,5};

Then you can even let the compiler tell you the size by getting the total size of the array in bytes sizeof(a) and dividing it by the size of one element sizeof(a[0]):
int size = sizeof(a) / sizeof(a[0]);

Comment: What if I also wanted to initialize everything to zero, for example?

   `int myArray [numRows][numCols] = {{0}};`

Is there a way to skip the numRows and numCols variables on the LHS, but not have to write out all the zeroes on the RHS?
Comment: Wouldn't it be less ambiguous to refer to the number of actual elements in the array as *length* and the number of bytes comprising the array at the memory level as *size* ? This would have the benefit of being more compliant with the standard meaning used by the `sizeof` operator, which simply computes and returns the number of raw bytes of the array.
Answer: The compiler cannot assume that the value of size is still 5 by the time main() gets control. If you want a true constant in an old-style C project, use:
#define size 5

Comment: Good point. Solution can be also use of new fashioned `const int size = 5`
Answer: size is a variable, and C does not allow you to declare (edit: C99 allows you to declare them, just not initialize them like you are doing) arrays with variable size like that. If you want to create an array whose size is a variable, use malloc or make the size a constant.
Answer: It looks like that your compiler is not C99 Compliant...speaking of which, which compiler are you using? If it's gcc you need to pass the switch '-std=c99'.... if you are using a pre-C99 compiler, that statement is illegal, if that's the case, do this:

int main() {
   int a[5]={1,2,3,4,5};
   printf("%d",a[0]);
   return 0;
}

In pre-C99 standard compilers, use a constant instead of a variable.
Edit: You can find out more about the C99 standard here... and here....
Comment: In C99 you can declare a variable sized array, but you cannot then initialize it in this manner. The problem is exactly what the error message says.
Comment: In this case, the problem is not VLAs support or not,  it's providing an initializer to a vla - which is not allowed.
Comment: That's very interesting, I had no idea you could do that. The post is a little misleading though, as it doesn't mention the problem is the initialization and not the declaration. Anyway, +1 for teaching me something new.
Comment: The compiler is conforming (6.7.8/3).
Answer: The compiler needs to know the size of the array while declaring it.
Because the size of an array doesn't change after its declaration.
If you put the size of the array in a variable, you can imagine that the value of that variable will change when the program is executed.
In this case, the compiler will be forced to allocate extra memory to this array.
In this case, this is not possible because the array is a static data structure allocated on the stack.
I hope that this will help.
Answer: You cannot create arrays with globally variable size the same reason why you cannot create an array with size determined by a variable in general. The reason is because C++ enables manual memory management, which let's be honest is the reason why we learn this language, and when we allocate memory, we need to keep in mind the advantages and drawbacks of its two types and what we can do with it.
Stack memory literally implements the stack data structure. It has fixed size (a few megabytes as far as I know), and when you put any data on the stack, you push it to the top. Stack fits perfectly for scoped variables that are supposed to only live for a restricted amount of time, which means it will disappear as soon as they see }. Stacks use functions as a unit of grouping all variables, and whenever we call any function (including main), it pushes the total amount of memory this function uses, which is the sum of all variables it allocates. This total size is called stack frame, and it must be constant. Otherwise, if we allocate an array dynamically on the stack:
int size;
scanf("%d", %size);
int array[size];

We don't know how much space we need to reserve for the array and its stack frame responsively, which makes this a forbidden operations. You can, however, initialise it with a constant and constant expression:
constexprt int getSize(int n){
    return n * 2; //This can be anything, I just multiplied to get arbitrary value.
}

const int size = 45;
int constantArray[size]; //Works
int constantExpressionArray[getSize(2)]; //Also works

The reason why constant works is because they are always assured to have the same and known size, and furthermore they don't take up space in memory but compilers just substitute all constant calls with their respective values. Constant expresions also are functions that are executed in the compile-time, which means all values must be known, and then it just substitudes the result (that must always be the same) into its call, which assure the compiler in both cases the size of the arrays are going to be the same (45 for the first one and 4 for the second one).
If you want to have an array with size that veries each time you execute it, you should either allocate it dynamically:
int* dynamicArray = new int[variableSize];

or use std::vector:
std::vector<int> dynamicArray(variableSize);

In the latter case it sets variableSize to be the capacity,which is the length of the array it needs to exceed to resize. If you use it responsibly, you will end up simply using the array underneath it and will only suffer from the performance penalties imposed by dynamically allocating memory and jumping between the functions.
Answer: #include<stdio.h>

/* int size=5; */
#define size 5 /* use this instead*/
/*OR*/
int a[size]={1,2,3,4,5};  /* this*/

int main()
{
    int a[size]={1,2,3,4,5};
    printf("%d",a[0]);
    return 0;
}

int size means that size is a variable and C does not allow variablesize arrays.
I am using VS2008 where using
const int size=5;

allows
int a[size]={1,2,3,4,5};

Comment: @ashish: because global variables are still variables (the clue's in the name). Suppose somebody assigned the value `1` to `size` somewhere before your code to define `a`. Then you'd be trying to initialize an array of size 1 with an initializer list of size 5. Rather than trying to sort this mess out, the standard forbids it.
Comment: why can't i use global variables?
Comment: "size is a variable and C does not allow variable size arrays." we should add a point to your comment that: if we initialize the variable, C does allow defining an array using that variable. E.g. int size = 5; int a[size]; is totally fine.


Is there a way to statistically differentiate parametric and count data?

Question: I'm wondering whether there are any statistical properties that should differentiate count data and parametric data.  In other words, is there an aspect of my data that I can analyze, or a test I can run, that will allow me to determine whether the data is parametric or nonparametric?
My specific research involves peer nominations, in which a participant's score is based on the number of times the individual is nominated out of a list of peers as fitting a given criterion (e.g., "Circle the names of everyone in your class who is really popular").
Recently, I've been involved in an argument about the nature of peer nomination data-- specifically, whether it is count data or parametric data.  Although scoring is based on the count of nominations, it is also possible to see each nomination or non-nomination as a binary data point which, when combined, measure a continuously distributed latent variable.
If there's a general way to differentiate count vs. parametric data, it would provide me with a way of addressing this argument.
Comment: The things you're arguing about aren't contradictory terms. In fact, "parametric data" isn't even a defined term. I suspect you want to ask whether the data needs to be analyzed through non-parametric statistical methods.
Comment: 'parametric' and 'count' are not mutually exclusive categories. Many count models (indeed, most) are finite-parametric. Rather than trying to classify on what may be a non-existent distinction, the right thing to do is to try to write down your model (how the variables are related); it should be much clearer then
Comment: The question as you explain it in comments have little to do with original wording of Q! Can you please edit to update the question?
Comment: That's a fair assessment.  My issue really comes from whether the data can be subjected to analyses of internal reliability.  For some variables, researchers have argued that we "wouldn't expect" consistency for peer nominations, and that peer nominations should therefore not be subject to internal reliability measures.
Comment: Can you flesh out the two opposing models? It's not clear what you are actually trying to model.
Comment: I suppose I'm looking for a statistical solution to a conceptual problem.  I'm trying to show that internal reliability is meaningful when using peer nominations.  When conceptualized as binary items (nominated vs. non-nominated by each peer), internal reliability is the extent of agreement among nominators regarding which peers fit a criterion.  Other researchers have noted that we should not expect agreement for many questions (e.g., who nominators like or who their friends are).  I'm trying to say that these are latent variables and agreement necessarily indicates signal/noise in the data.
Answer: So first, just like the comments have been saying the opposite of parametric is non-parametric. As for whether we can tell if data is parametric or non-parametric, the answer is no. This is because being parametric or non-parametric is not a characteristic of the data. Parametric or non-parametric is a characteristic of the model we think generated said data. All that we can do is to compare models and say which one seems more likely to have generated said data.
In general, its good practice to make a simple parametric model first, see how well it fits the data, and if the fit is insufficient, consider moving to a non parametric model. (Ocham's razor after all). Or if you would like to be Bayesian, you can compute probabilities that model A generated the data over model B. But we can't really compute said probabilities over the space of all parametric and non-parametric models, such a space is much too big to say anything meaningful.


Unconstrained optimization: Derivative of FOC w.r.t parameter is 0?

Question: Suppose we have an unconstrained optimization problem
$$ \max f(x)$$
and suppose there is some constant (i.e. a parameter), $c$ in $f(x)$.
The FOC of the optimization problem is $$\frac{\partial f}{\partial x}=0$$
If we take the total derivative of the FOC with respect to the parameter,$c$ is this total derivative equal to 0?

let me try stating what I think is an equivalent (or more rigorous) statement of the question:

Let $x^*(c)$ denote the solution to the unconstrained optimization, where $x$ depends on some parameter in $f$
then by definition we have $$\tag{EQ1} \frac{\partial f}{\partial x}\vert_{x=x^*(c)}=0$$ for every $c$.
Is it then correct to say that the total derivative of the left hand side of (EQ1), with respect to $c$, is $=0$?

I believe my confusion is arising from the fact that, typically, if we say a function $g(y)=0$, we can't say that $g'(y)=0$, but with (EQ1) we know that the equation holds at every $x^*(c)$ (i think this might be called an identity)
Answer: There are obviously many regularity issues here. Let us take $f : (c,x) \mapsto f(c,x)$ is say $C^2$ on $\mathbb{R} \times \mathbb{R}^d$ and assume that, for every $c \in \mathbb{R}$, there exists a unique maximizer $x^*(c)$ of $f(c, \cdot)$. Assume moreover that $c \mapsto x^*(c)$ is $C^1$ on $\mathbb{R}$. Then, for every $c \in \mathbb{R}$, you indeed have
$$
\frac{\partial f}{\partial x} (c,x^*(c)) = 0
$$
which is an identity of which you can indeed take the total derivative with respect to $c$, yielding
$$
\frac{\partial^2 f}{\partial c \partial x} (c,x^*(c))
+ \frac{\partial^2 f}{\partial x^2} (c,x^*(c)) \frac{\partial x^*}{\partial c}(c) = 0.
$$
Here I assumed that everything was legitimate. The main difficulty is probably to check that, in your particular case, the minimizer is indeed unique, $f$ is indeed $C^2$, and $c \mapsto x^*(c)$ is also $C^1$.
Comment: Thank you. This answer is very clear and detailed. The continuity requirements I believe as so that the derivatives exist, but why does the maximizer need to be unique? Is it so the function is well defined?
Comment: Well, if you have multiple maximizers, say a set $\mathcal{X}(c)$, then you need to find a *selection* $x^*(c) \in \mathcal{X}(c)$ which has $C^1$ regularity. For this selected maximizer, the same reasoning applies. I stated it with a unique one for clarity. If you have multiple ones, constructing a selection is not always easy.


Which Winter Olympic sports gather the highest TV viewership?

Question: Which Winter Olympic sports gather the highest TV viewership?
This question is partly based on the assumption that Norway, which is where I'm from, overestimates cross-country skiing as a major sport.
Comment: Okay. I see where you are coming from. I'll attempt to revise your question. Also, here is a link regarding US TV viewership from the 2010 Winter Olympics: http://www.nielsen.com/us/en/newswire/2010/skiing-tops-olympic-tv-viewership-while-hockey-scores-online.html
Comment: In the Netherlands we consider speed skating as a major sport :) I think a good measure would be the historical diversity of countries with medalists.
Comment: Completely agree with your comments, I see now how this was a bad question. Regarding using "size", english is not my native language, I realize now it's a badly chosen word for this matter. And to narrow my question, it would be very interesting to see number of TV-viewvers for the different disciplines.
Answer: This a link which I came upon recently.
http://www.thisisinsider.com/most-watched-winter-olympic-sport-in-every-country-2018-2
Comment: You should write part of the link which answer the question here, as link may get broken.


.htaccess deny php files from all except index

Question: I have a .htaccess file with the following contents:
<IfModule mod_rewrite.c>
    RewriteEngine on
    SetEnv HTTP_MOD_REWRITE on
    RewriteBase /wsproject/

    Options All -Indexes
    DirectoryIndex index.php

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
</IfModule>

I want to hide everything from the users: the directory structure and private files, while enable public files: *.js, *.html, *.css, *.swf, *.jpg and other stuff. I want .php files to be accessible only from the file system, except only the index.php in the root dir.
I only want to serve request via HTTP which are written with an (abstract) MVC URL pattern like: www.domain.com/lang/controller_name/action_name/arg1/arg2/././argn, which are being rewritten by .htaccess, and public *.html, *.js ...etc files.
While Options All -Indexes hides file listing, it will not prevent an undesirable request e.g.: www.domain.com/library/Bootstrap.php from being served.
Whereas deleting/commenting out RewriteCond %{REQUEST_FILENAME} !-f would solve this, but in this case none of my public .html, .css, .js ...etc files would be served.
I tried to apply Deny from all for each php files except the index.php but I always get an 500-internal server error message. Im doing this on localhost, on windows.
Any ideas?
Answer: Instead of stating that all but existing files should be directed to index.php, you can say that everything except *.js, *.html, *.css, *.swf, *.jpg should be directed to index.php.
This isn't exactly the same as denying, since you don't give a Forbidden response. Though in this case you don't give out any information about which files exist or not, so I'd argue that it's a better solution.
<IfModule mod_rewrite.c>
    RewriteEngine on
    SetEnv HTTP_MOD_REWRITE on
    RewriteBase /wsproject/

    Options All -Indexes
    DirectoryIndex index.php

    RewriteRule \.(js|html|css|swf|jpg)(\?|$) - [QSA,L]
    RewriteRule ^index.php(\?|$) - [QSA,L]
    RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
</IfModule>

Note that rewriting to -, means no rewriting is done at all.
Comment: This worked well for me when the above solutions did not - slight modifications for those that try it:

Remove RewriteBase if you don't need it
Add some additional RewriteRule exceptions for Folders / Files if necessary, like so:

`RewriteRule ^administrator - [QSA,L]`
`RewriteRule \.(js|html|css|swf|jpg|ico|eot|woff|ttf|svg)(\?|$) - [QSA,L]`
Answer: Rather than (or maybe as well as...) editing your .htaccess file, I'd suggest using the chmod command to modify the read/write/executability values of your files.
A relatively succinct and sensible explanation of what chmod is/does can be found in the accepted answer here, but generally the simplest way is to chmod 644 your files and chmod 755 your folders.


Cells of CollectionView Not Displaying

Question: Im using storyboard to create a collectionview which displays incoming Instagram Pics. Can someone take a look at my project to find out why it is not working?
*Edit The main issue lies in either the storyboard or the class called StreamViewController.m
The project was cut down for the most essential parts so dont worry about digging through a project.**
https://docs.google.com/file/d/0B9J0YAIS_BJPcFhvdzJ3LVV2Znc/edit?usp=sharing
Comment: You need to be specific and identify where the issue is... I don't think anyone is going to look through your project to find the issue. People are more likely to look through a snippet or a class
Comment: @waf I just added it now.
Answer: I've looked through StreamViewController and you never set self as the delegate or datasource for "collectionView".

Cells of CollectionView Not Displaying


How long is the longest gap between gold medal wins by the same person in an individual event?

Question: At the 2016 Summer Olympics, Anthony Ervin won gold in the 50m freestyle, the same event he won gold in at the 2000 Summer Olympics. This marks 16 years between gold medal wins.
Has there been a longer gap between gold medal wins by the same person in an individual event? If so, how long is the longest gap in Olympic history?
Comment: Well, not a gold medal, but this [New Zealand horseman, Mark Todd](https://en.wikipedia.org/wiki/Mark_Todd_(equestrian)), went 28 years between medals (bronze in 2012, some other medal in 1984).
Comment: @NicholasV. That's incredible. However, he did win some medals in between those 28 years (1988 to 2012 for team eventing would still be an impressive 24 years, but that's not an individual event).
Answer: Sir Mark James Todd is a New Zealand horseman noted for his accomplishments in the discipline of eventing. Although he didnt win the gold medals, he holds the record for longest time between two medals and thats still really impresive
Aladár Gerevich (16 March 1910 in Jászberény – 14 May 1991 in Budapest) was a fencer from Hungary, regarded as "the greatest Olympic swordsman ever". He holds the record for the longest time between two gold medals. He won his first 1932 Los Angeles and last 1960 Rome. He does not fit your question 100% because he won multiple gold medals during that 28 year period
Birgit Fischer (born February 25, 1962) is a German kayaker, who has won eight gold medals over six different Olympic Games, first being in 1980 Moscow representing East Germany and the last one in 2004 Athens.
I believe Anthony Ervin is the only sportsman/woman who won two golds in such a long time span.


Finding period of a tangent graph

Question:
For example, $y= - \cot 4t$

I understand that period of function $f(t)$ is the smallest positive number $p$ such that $f(t+p)= f(t)$ for every value of $t$
How do I apply this fact to find the period? I am confused.
Answer: Applying angle-sum identities,
$$\cot(4(t+p)) = \frac{\cos(4(t+p))}{\sin(4(t+p))} = \frac{\cos(4t)\cos(4p)-\sin(4t)\sin(4p)}{\cos(4t)\sin(4p)+\sin(4t)\cos(4p)} \quad != \quad \frac{\cos(4t)}{\sin(4t)}.$$
To eliminate the terms multiplying $\sin(4p)$ in the numerator in the middle fraction, the smallest positive $p$ that will work is $p = \pi/4$.
Hence, the period is $\pi/4$.

Finding period of a tangent graph


Output both form and generated image (imagejpeg) onto same page

Question: This is my first newbie module (drupal 7). It's 'simple' but needs help x2.
Intention: To create an online image-name generator i.e, user types their name into a formfield and the browser outputs the text as a jpg image so they can right-click and save.
What I've done: 1. created one hook menu with two callback functions, one for the form and one for the image output.
2. A working form where user types in their name. 3. Able to output Image by setting name input manually through code, not by submitting the form!
What doesn't work: I created a $name variable within the form function, but using that same $name variable within the image-output function won't work. So I can't output  a text-image when users submit the form.  Also I don't know how to render both form and image output onto the same page.
I need help with: 1. How to render both form and image onto the same page?.
2: How to associate $name variable so inputted text will render upon submit button.
Frameyourname.module:
<?php

//Create simple image-generator.

//Implements hook_menu().

function frameyourname_menu() {
$items['frameyourname'] = array(
'title' => 'Frame Your Name form',
'page callback' => 'drupal_get_form',
'page arguments' => array('frameyourname_nameform'),
'access callback' => TRUE,
'type' => MENU_NORMAL_ITEM ,
);

//not entirely sure what to put here.

$items['image'] = array(
'title' => 'image',
'page callback' => 'drupal_get_form',
'page arguments' => array('create_textimage'),
'access callback' => TRUE,
'type' => MENU_NORMAL_ITEM ,
  );

return $items;

}

// Define a form.

function frameyourname_nameform() {
$form['user_name'] = array(
'#title' => t('Your Name'),
'#type' => 'textfield',
'#description' => t('Please enter your name.'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit')
);
return $form;
}

// Validate the form.
function frameyourname_nameform_validate($form, &$form_state) {
}

// Handle post-validation form submission.
function frameyourname_nameform_submit($form, &$form_state) {

//set name variable associated with user input and test if works.
$name = $form_state['values']['user_name'];
drupal_set_message(t('Thanks for adding your name,'.  $name));
}

// create image
function create_textimage() {

// Create a blank image and add text as per form input
$im = imagecreatetruecolor(400, 400);
$text_color = imagecolorallocate($im, 233, 14, 91);

//trying to reference $name variable not sure how.
imagestring($im, 1, 5, 5,  $name, $text_color);

// Set the content type header
drupal_add_http_header('Content-Type', 'image;jpeg');

// Output the image
imagejpeg($im);

// free from memory
imagejpeg($im);

}

Comment: Brilliant format, Question is well focused on the problem. You need to submit the form through the ajax then update image using same callback. For reference check on Drupal AJAX form submit examples.
Answer: If you put $form_state['rebuild'] = TRUE in your submit handler then the form's redisplayed and you have access to $form_state['values'] in the form constructor. This is typically how multi-step forms are done. So in this case something like:
if (empty($form_state['values']['user_name'])) {
  $form['user_name'] = array(
    '#title' => t('Your Name'),
    '#type' => 'textfield',
    '#description' => t('Please enter your name.'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  );
}
else {
  $form['image'] = array(
    '#theme' => 'image__nameform',
    '#path' => $path,
    '#width' => $width,
    '#height' => $height,
    '#alt' => $form_state['values']['user_name'],
  );
}

To pass the name to your image generation function you want to change its entry in hook_menu(): the path should be image/% (which says there's an argument), page callback create_textimage (because that's what generates the content) and page arguments array(1) (because the text is the second argument, and you start numbering at 0). There are more details in the documentation for hook_menu().
A few other points not directly related to the Q:

Currently the image generation function is a bit of a DOS vector (because it's a bit CPU intensive, isn't cached, doesn't require auth, and doesn't require a form submission).
You should use drupal_set_message(t('Thanks for adding your name, %name.', array('%name' => $name));. This is secure and translatable - see t() and format_string().
The function names are a bit all over the place. If your module's called frameyourname then all your functions should start with that (with a few exceptions). Also I'd suggest avoiding a path like image/% in favour of something more specific like frameyourname/%.
Comment: If you want the form open to anonymous users then a captcha makes sense to me - but adding it to the form alone won't make any difference because you can just use the image creation URL directly. The two methods I see are a) generate the image in the submit handler itself, or b) use a token to verify the link came from the site. For an example of the latter approach see `image_style_path_token()` and `image_style_deliver()`. Btw is the focus on learning how to do this yourself, or on creating a working product?
Comment: RE: Dos vector comment, if I apply Honeypot or Captcha module to the form, will that improve my module? (thanks, great help)
Comment: Good question--the focus for a working product (for my own personal blog though) where I just wanted to have some quirky interactivity for users, I thought something simple, yet fun would be the best approach to learning how to make a module too. great input thanks.


accessing xml property using php

Question: In an xml respone below
<response>
  <lst name="responseHeader">
    <int name="status">0</int>
    <int name="QTime">1</int>
  </lst>
  <lst name="initArgs">
    <lst name="defaults">
      <str name="config">../conf/dataconfig.xml</str>
    </lst>
  </lst>
  <str name="status">busy</str>
  <str name="importResponse">A command is still running...</str>
  <lst name="statusMessages">
    <str name="Time Elapsed">0:0:7.942</str>
    <str name="Total Requests made to DataSource">1</str>
    <str name="Total Rows Fetched">8831</str>
    <str name="Total Documents Processed">8830</str>
    <str name="Total Documents Skipped">0</str>
    <str name="Full Dump Started">2013-06-03 22:15:11</str>
  </lst>
  <str name="WARNING">
    This response format is experimental. It is likely to change in the future.
  </str>
</response>

I need to access two values:
<str name="status">busy</str>  --  busy
<str name="Total Rows Fetched">8831</str>  --  8831

Using code below:
$xml = simplexml_load_string($string);
echo $xml->str[0];

I am able to access value "busy" but I don't know how to access "8831".
Answer: Use var_dump($xml);  to understand xml object. Read Example #1 Interpret an XML string example http://php.net/manual/en/simplexmlelement.attributes.php
It will be something like,
foreach($xml->foo[0]->attributes() as $a => $b) {
      if($a=="Total Rows Fetched"){
         echo $b;
      }
  }

Comment: its giving A command is still running...[
Comment: not able to do it :-(
please help
Answer: use Xpath:
$xml = simplexml_load_string($x); // assuming XML in $x
echo $xml->xpath("//str[@name='status']")[0];

and do the same with the other value.
Comment: need solution using simplexml_load_string ?
Comment: yes, it's simplexml, see my edit.
Comment: Awesome solution .... heads off

accessing xml property using php


jPlayer - Use setMedia() to set the media URL

Question: I'm trying to use jPlayer under Firefox 3.6 (Ubuntu)
function loadmedia() {
  $('#jquery_jplayer_1').jPlayer('setMedia', {
    mp3: 'media/audio/04-Piste_4_1.mp3',
  });
}

$(document).ready(function () {
  $('#jquery_jplayer_1').jPlayer({
    ready: loadmedia,
    swfPath: 'static/jPlayer',
    errorAlerts: true,
    supplied: 'mp3',
  });
});

But it's telling me

jPlayer 2.1.0 : id='jquery_jplayer_1' : Error!
Attempt to issue media playback commands, while no media url is set.
Use setMedia() to set the media URL.
Context: play

And doesn't play the file
You check an online example here
Comment: I have tried hard, but I cannot get this, or any implementation to work in either Firefox 3.6.22 or Chromium 12. Results of debugging: Mp3 files are not supported in FF, the `ready` event is never being called. When I attempt to open files of another type, even from sources, errors are showing up: `Media URL could not be loaded.\nCheck media URL is valid.\n\nContext:http://example.com/file.mp3` (FF and Chrome).
Comment: I also tried to change the `solution` property to 'flash, html' to force jPlayer to use flash but same problem. It works when you lanch manually `loadmedia()` multiple times.
Answer: The main point of jPlayer is so that you can use html5 with flash fallback, so you should leverage the html5 of FF and chrome, not depending on it falling back to flash.
Firefox doesn't support mp3 on html5, they support ogg, which is better anyway. I always format each audio file I need to play for each browser, that way you can leverage html5 when its available, and you give your app a much better chance at loading the audio file, with 3 for each browser to choose from (not all get loaded, just the one it needs).
Use: .ogg for Chrome and Firefox, .m4a for Safari, and .mp3 for IE.
See here
Covert your audio files then try this:
function loadmedia(){
   $('#jquery_jplayer_1').jPlayer('setMedia', {
      oga: 'media/audio/04-Piste_4_1.ogg',
      m4a: 'media/audio/04-Piste_4_1.m4a',
      mp3: 'media/audio/04-Piste_4_1.mp3'
   });
}

$(document).ready(function () {
  $('#jquery_jplayer_1').jPlayer({
    ready: loadmedia,
    swfPath: 'static/jPlayer',
    errorAlerts: true,
    supplied: 'oga, m4a, mp3'//fyi, in your code you had a trailing comma here, that will break IE
  });
});

EDIT:
Saw this on the jPlayer site for the new audio demo: Link

Note that the {wmode:"window"} option is set to ensure playback in
  Firefox 3.6 with the Flash solution. However, the OGA format would be
  used in this case with the HTML solution.
Comment: Update on Firefox: mp3 is now supported since version 22 (2013)
Comment: Interesting. I thought that HTML5 would always ask for oga and m4a. I had no idea that browsers have already planned to support different formats :( And I didn't know that trailing commas don't work on IE, good to know Thanks.
Answer: You have an error in your code that is probably causing this behaviour:
You have:
mp3: 'media/audio/04-Piste_4_1.mp3',

It should be
mp3: 'media/audio/04-Piste_4_1.mp3'

So remove the comma.
Comment: that's not a syntax error, and I always include a comma after the last item in a javascript object in case I want to add another item and this way I don't forget about the comma


Como criar uma constraint de Primary Key nomeada no Postgres?

Question: Estou prosseguindo assim para criar uma tabela sem chave primária, inicialmente.  Depois eu adiciono um campo id do tipo serial e tento criar a constraint para a Primary Key (PK):
create table macaco(
  nome varchar(50),
  idade integer
);

--adicionando o id do tipo serial
ALTER TABLE "macaco" ADD COLUMN id SERIAL;

--criando a primary key
ALTER TABLE "macaco" ADD PRIMARY KEY (id);

Do modo como eu faço acima, ele cria a PK com o nome de macaco_pkey.
Até aí tudo bem. Mas e se eu quiser criar a constraint com o nome id_macaco_pk, o que devo fazer?
Answer: O que você quer é este comando:
ALTER TABLE macaco ADD CONSTRAINT id_macaco_pk PRIMARY KEY (id);

Veja aqui funcionando no SQLFiddle.
Comment: Obriagado cara, ajudou bastante!


Sites com autenticação - Web Scraping - JavaScript

Question: Estou tentando automatizar um processo de obtenção de dados via web usando JS. No meu caso, preciso puxar as informações da página https://sistema.justwebtelecom.com.br/adm.php. No entanto, antes de ir a essa página, precisa-se logar em https://sistema.justwebtelecom.com.br/login.php. Depois que eu já login, ou seja, estou na página .../adm.php .
const request = require('request-promise')
const cheerio = require('cheerio')

const URL2 = 'https://sistema.justwebtelecom.com.br/adm.php'

async function acesso(){
    const response = await request(URL2)

    let $ = cheerio.load(response)
    let title = $('title').text()
    console.log(title)

}
acesso()

No entanto, printando com console.log(title), eu obtenho o título da página https://sistema.justwebtelecom.com.br/login.php, ou seja, antes de logar. Sendo que eu peço o print da página depois de logar e eu tenho acesso ao painel .../adm.php .
Usando o puppeteer:
const puppeteer = require('puppeteer')

const getInfo = async() => {

        const browser = await puppeteer.launch()
        const page = await browser.newPage()
        await page.goto('https://sistema.justwebtelecom.com.br/adm.php')

        const info = await page.evaluate(() => {
            return {
                Tag: document.title
            }
        })
        console.log(info)
        await browser.close()

    }
    getInfo()

Gostaria de saber se tem como eu pegar essas informações da página .../adm.php, com esses pacotes, ou preciso de outros ?
Answer: Cara, algumas páginas tem redirecionamentos e recaptcha, que é ruim pra qualquer módulo que use, mas acredito que é melhor você fazer o seu webscraping com o módulo puppeteer do node js. Um exemplo de scraping com puppeteer:
const puppeteer = require('puppeteer')
let scrape = async () => {
 const browser = await
 puppeteer.launch()
 const page = await browser.newPage()
 await page.goto('http://books.toscrape.com/')

const result = await page.evaluate(() => {
const books = []
document.querySelectorAll('section > div > ol > li img')
        .forEach(book => books.push(book.getAttribute('alt')))
return books
})

browser.close()
return result
};
 scrape().then((value) => {
console.log(value)
    })

Comment: Olá DKNS,obrigado pela ajuda. Eu até tentei usar esse puppeteer tb, mas não tive sucesso. Saberia me informar como eu poderia pegar os dados usando ele ?
Comment: Os dados seria uma texto em uma pagina ou ... ??
Comment: Isso. Mas a principio eu só quero pegar o título, pq se eu conseguir pegar o título, ai eu consigo pegar o restante das informações da página.
Comment: Sugiro dar uma olhada na documentação, irá entender melhor e eles dão exemplo com o códico.


DNS - how does it resolve the name servers itself?

Question: Domain name: abc.com
Name Server: ns1.abc.com and ns2.abc.com
I am running a DNS server and hosting the zone (abc.com) on-premise.
When a client wants to resolve *.abc.com, it will query ns1.abc.com or ns2.abc.com, that is straight forward.
The question is how does it resolve ns1.abc.com before it can sends query to it?
Comment: Glue Records...
Comment: @joeqwerty thanks, this is exactly the answer to my questions.
Answer: To find the name server for abc.com a DNS server will query the DNS server for com.  This will return the nameserver information provided to your registrar.  You must provide the IP addresses to the registrar when the servers are within your domain.
To find the com DNS servers the DNS server will contact one of the root domain servers.  When the DNS server starts it will use a hints file to do an initial lookup of the root servers.
Comment: it's obvious with IP address, but not clear with domain name, e.g. how DNS resolve ns1.example.com, if it's under example.com which DNS is ns1.example.com
Comment: @AlexIvasyuv The server for `.com` will return the `NS` records for `example.com` which would be `ns1.example.com`, and include the `A` records for servers.  One of those servers would be queried for the `A` record for `example.com`.
Answer: you assign DNS servers on clients when configuring IP, so each client already have the ip addresses of DNS servers. and on your DNS servers there are NS records for your name servers.
Answer: You should never specify a name server by name, only by IP.  So you wouldn't tell the DNS client to talk to ns1.abc.com, you'd tell the client to talk to it's ns1.abc.com's IP.
For the top level DNS servers, a "hints" file is, or used to be, used to tell the client of the top level DNS servers.
Comment: Incorrect. The standard only allows `NS` records to refer to nameservers by name, not IP address, and [it was designed that way for a reason](http://serverfault.com/a/764957/152073).
Comment: if that's the case, google.com setup is wrong? since they are pointing to ns1.google.com etc etc...
Comment: Thanks for the correction guys, so the answer then is "A records are used to resolve the names in the NS records"?
Comment: It's a mixture. `NS` records point at `A` records. When defining the domain itself though, it is frequently necessary to use [glue records](http://serverfault.com/questions/309622/what-is-a-glue-record) as you otherwise end up with chicken and egg scenarios. (`example.com` defining nameservers inside of its own domain, ala `ns1.example.com`) They should be avoided unless absolutely necessary.


Write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months

Question: This question is for python 2.7. The question asks to write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months.By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month.
In this problem, we will not be dealing with a minimum monthly payment rate.
The following variables contain values as described below:
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
The program should print out one line: the lowest monthly payment that will pay off all debt in under 1 year.
Assume that the interest is compounded monthly according to the balance at the end of the month (after the payment for that month is made). The monthly payment must be a multiple of $10 and is the same for all months. Notice that it is possible for the balance to become negative using this payment scheme, which is okay. A summary of the required math is found below:
Monthly interest rate = (Annual interest rate) / 12
Updated balance each month = (Previous balance - Minimum monthly payment) x (1 + Monthly interest rate)
I came up with a code for the question; however, I repeatedly got an infinite loop.
    b = balance = 3329
    air = annualInterestRate = 0.2
    monthlyInterestRate = (air/12)
    mmp = minimumMonthlyPayment = (balance * monthlyInterestRate)
    month = 0
    while month <= 12:
        b = ((b - mmp) * (1 + (air/12)))
        month = 1 + month
        if b <= 0 and month == 12:
           break
        elif b > 0 and month == 12:
           b = balance
           month = 0
           mmp = minimumMonthlyPayment + 10.00
    print str('Lowest Payment: ' + str(round(mmp, 2)))

Can someone help me fix this code? For the given balance the lowest payment is 310...I'm not sure how to get this...
Answer: monthlyInterestRate = annualInterestRate/12
monthlyPayment = 0
newbalance = balance
while newbalance > 0:
    monthlyPayment += 10
    newbalance = balance
    month = 1

    while month <= 12 and newbalance > 0:
        newbalance -= monthlyPayment
        interest = monthlyInterestRate * newbalance
        newbalance += interest
        month += 1
    newbalance = round(newbalance,2)

Answer: monthlyPayment = 0
monthlyInterestRate = annualInterestRate /12
newbalance = balance
month = 0

while newbalance > 0:
    monthlyPayment += 10
    newbalance = balance

    for month in range(1,13):
        newbalance -= monthlyPayment
        newbalance += monthlyInterestRate * newbalance
        month += 1
print " Lowest Payment:", monthlyPayment

Answer: This code is a bit weird, namely lines like:
   mmp = minimumMonthlyPayment = (balance * monthlyInterestRate)

with the double equal signs.
This code doesn't get stuck:
balance = 5000
annualInterestRate = 0.2
monthlyInterestRate = (annualInterestRate/12)
minimumMonthlyPayment = (balance * monthlyInterestRate)
month = 0
while month <= 12:
    balance = ((balance - minimumMonthlyPayment) * (1 + monthlyInterestRate))
     month = 1 + month
    if balance <= 0 and month == 12:
        break
    elif balance > 0 and month == 12:
        month = 0
        minimumMonthlyPayment + 1.00

print str('Lowest Payment: ' + str(round(minimumMonthlyPayment, 2)))

But doesn't return the answer you're looking for.
Comment: well the teacher puts in a number of things in place of balance and annualInterestRate as long as it checks correctly I'm fine...but the guess and check program (as you can see) isn't really written so well...
Comment: This last code (from Dan Steingart) doesn't work either, for example: balance = 4773, annualInterestRate = 0.2.
The result gives the value 450, instead of 440!!
Answer: First of all you have to fix month <= 12
make it month < 12
secondly you are using a form which is not needed here
 balance = ((balance - minimumMonthlyPayment) * (1 + monthlyInterestRate))
because simply you don't have to use the minimum payment here
Your code is too bad
Try this:
    balance = 3329
    annualInterestRate = 0.2

    monthlyPayment = 10
    monthlyInterestRate = interestRate/12
    newbalance = balance - 10

    while newbalance > 0:
        monthlyPayment += 10
        newbalance = balance
        month = 0

        while month < 12 and newbalance > 0:

            month += 1
            interest = monthlyInterestRate * newbalance
            newbalance -= monthlyPayment
            newbalance += interest

    newbalance = round(newbalance,2)

    print " Lowest Payment:", monthlyPayment

Answer: This should give you the right answer in all of the cases:
monthlyPayment = 10
monthlyInterestRate = annualInterestRate /12
newbalance = balance - 10

while newbalance > 0:
    monthlyPayment += 10
    newbalance = balance
    month = 0

    while month < 12 and newbalance > 0:
        newbalance -= monthlyPayment
        interest = monthlyInterestRate * newbalance
        newbalance += interest
        month += 1
    newbalance = round(newbalance,2)
print " Lowest Payment:", monthlyPayment

Answer: balance = 3329
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate/12
monthlyPayment = 0
newbalance = balance
while newbalance > 0:
monthlyPayment += 10
newbalance = balance
month = 1
while month <= 12 and newbalance > 0:
    newbalance -= monthlyPayment
    newbalance += (monthlyInterestRate * newbalance)
    month += 1
print "Lowest Payment:",monthlyPayment

Think this will be the best solution to your doubt..and satisfies the answer
Answer: I think this is a fairly simple way of doing it:
x = 50
o = balance
a = [1,2,3,4,5,6,7,8,9,10,11,12]
monthly = annualInterestRate/12

while balance>0:
    for months in a:
        u = balance - x
        balance = u + (monthly * u)
    if balance > 0:
        x += 10
    else:
        break
print x

Answer: This is basically a slightly improved version of randomizertech's answer, which allows user to input different variables instead of only doing it for fixed values of Initial balance and Annual interest rate.
And in the end it prints some more variables that would be useful to a user.
InitialBalance = float(raw_input("Enter your current balance: "))
InterestRate = float(raw_input("Enter the yearly interest rate as a decimal: "))

monthlyPayment = 0
monthlyInterestRate = InterestRate/12
balance = InitialBalance

while balance > 0:
    monthlyPayment += 10
    balance = InitialBalance
    numMonths = 0

    while numMonths < 12 and balance > 0:

        numMonths += 1

        interest = monthlyInterestRate * balance

        balance -= monthlyPayment

        balance += interest

    balance = round(balance,2)

print "RESULT"
print "Monthly payment to pay off debt in 1 year: " , monthlyPayment
print "Number of months need to pay the debt: " , numMonths
print "Balance after debt is paid: " , balance

Comment: Could you please [edit] in an explanation of why this code answers the question? Code-only answers are [discouraged](http://meta.stackexchange.com/q/148272/274165), because they don't teach the solution.
Comment: Sorry, noob here. I was actually looking for a solution to a similar problem, where Monthly payment is obtained via bisection instead of being increased by 10. Then I ran into this so I just pasted what I had. Just realized very similar code was already posted too.
Answer: for i in range(12):
     balance = balance - (balance * monthlyPaymentRate) + ((balance - (balance * monthlyPaymentRate)) * (annualInterestRate/12))

print("Remaining balance:", round(balance, 2))

Correct 10/10


standard error for ratio of two poisson random variables

Question: I'm collecting data for two Poisson random variables, that are completely independent of each other. My current analysis method yields 95% (or 90% or other) confidence intervals for the two $\lambda_1$, $\lambda_2$ for the two Poissons.
My question: how can I come up with a confidence interval for the ratio of the two lambdas?
Answer: If $\lambda_1$ belongs to $[a_1,b_1]$ with probability at least $p_1$ and $\lambda_2$ belongs to $[a_2,b_2]$ with probability at least $p_2$ for some $0<a_1<b_1$ and $0<a_2<b_2$, then, by independence, $\lambda_1/\lambda_2$ belongs to $[a_1/b_2,b_1/a_1]$ with probability at least $p_1p_2$.
For example, $p_1=p_2=90\%$ yields $p_1p_2=81\%$.
Answer: You can calculate the CV for each of the two variables ($1/\sqrt{\lambda_1}$) and then add the squared CVs $CV=\sqrt{CV_1^2+CV_2^2}$.
But what you probably want to know is the confidence interval, and here the SE is not helpful as the ratio is not normally distributed. So unless the number are very large (say 1000 or so) I would rather do a parametric bootstrap.


Kronecker product and matrix multiplication property

Question: Given two symmetric matrices, $A \in \mathbb{R}^{n \times n}$ and $B \in \mathbb{R}^{m \times m}$, is there any property of the Kronecker product which relates to matrix multiplication?
More specifically, what is $(A \otimes B)C$?  And what should the dimensions of $C$ be?
Comment: $C$ must have dimension $nm\times r$ for some $r>0$. The way I like to think of tensor products of matrices is matrices of matrices (with some sort of multiplication at each element) which suggests that we will have an $n\times n$ matrix of $m\times m$ matrices so $A\otimes B$ has dimensions $nm\times nm$.
Comment: Thanks for the reply. What about the product $(A \otimes B) C$, is there any theorem related to it?
Answer: In general there is no nice formula for $(A\otimes B)C$. However, if you know $C=U\otimes V$, then
$$
(A\otimes B)(U\otimes V) = (AU)\otimes (BV).
$$
SeeKronecker product.


Compiler throws error; generated code missing a bracket

Question: Trying to populate a select list through a view model.
View Model:
public class CountryCity
{
    public IEnumerable<SelectListItem> Countries { get; set; }
    public SelectList Cities { get; set; }
}

Controller:
public class HomeController : Controller
{
    private CountriesContext context = new CountriesContext();
    public ActionResult Index()
    {
        CountryCity cc = new CountryCity();
        var countries = from c in context.Countries
                        orderby c.Name
                        select c;
        cc.Countries = new SelectList(countries,"CountryID", "Name");
        return View(cc);
    }
}

View:
@using CascadingDropdowns.Models.ViewModels
@model CountryCity

Index

    @using (Html.BeginForm())
    {
        @Html.DropDownList("CountryID", Model.Countries, "Please select country");
        @Html.DropDownList("City", new SelectList(string.Empty, "City", "<city>"), "Please select a city", new { @disabled = "disabled" }));
    }

This generates error:
C:\Users\Jakov\AppData\Local\Temp\Temporary ASP.NET Files\root\aad61407\c9799020\App_Web_index.cshtml.a8d08dba.lv9oabqd.0.cs(97,58): error CS1513: } expected

Everything looks fine to me.
Comment: Is here one ")"   redudant?      @Html.DropDownList("City", new SelectList(string.Empty, "City", ""), "Please select a city", new { @disabled = "disabled" }));
Comment: What line is the error on?
Answer: You need to remove one of the closing brackets on the below line:
@Html.DropDownList("City", new SelectList(string.Empty, "City", "<city>"), "Please select a city", new { @disabled = "disabled" }));

should be
@Html.DropDownList("City", new SelectList(string.Empty, "City", "<city>"), "Please select a city", new { @disabled = "disabled" });

Comment: Really sloppy of me. Thank you. Should I erase this question now since the error is a mistype?
Comment: @Jakov only if you start getting a lot of downvotes. The specific error you got is slightly counter-intuitive - I've gotten it a few times as well.


Android: Frame Layout - ImageView height won't fit

Question: I have a Frame Layout with an ImageView and a TextView inside it. I plan to make that text in the center of the picture.
The problem is that the image won't fit, the ImageView won't wrap the height of the content good. Look at the picture:

I need it to look like this:

I tried mixing the height and with (wrap content and match parent) but the picture still won't fit well.
This is the xml:
<FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            card_view:srcCompat="@drawable/tvrdjava"
            android:id="@+id/imageView3" />

        <TextView
            android:text="TextView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/textView6"
            android:textAlignment="center"
            android:textColor="@android:color/white"
            />

</FrameLayout>

The picture is in different drawable folders for different resolutions (hdpi, mdpi, xhdpi, xxhdpi, xxxhdpi).
Comment: Why not using a RelativeLayout for the ImageView and TextView?
Comment: U can use the android:background="@drawable/your_image ..
Comment: Because I cannot put the text on the picture. @MatPag
Comment: android:background= ... stretches the image for some reason. @RavindraKushwaha
Answer: You should try with something like this, using a RelativeLayout instead
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        app:srcCompat="@drawable/ok"/>

    <TextView
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="30sp"
        android:text="TextView"/>

</RelativeLayout>

Comment: This kind of worked. This frame layout is in a LinearLayout (vertical) and it worked for some reason. Thank you anyways Mat!
Answer: Thanks to @MatPag for the idea. Putting this frame layout in a LinearLayout (vertical) worked.
 <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/tvrdjava"
            android:id="@+id/imageView8"
            android:adjustViewBounds="true"
            android:cropToPadding="false" />

        <TextView
            android:text="TrTemp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/textView3"
            android:textColor="@android:color/holo_blue_dark"
            android:textAlignment="center"
            android:gravity="center"
            />

    </FrameLayout>

Answer: This works for me.
             <FrameLayout
              android:layout_width="match_parent"
              android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/homepage_background_imageView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_weight="1"
                    android:adjustViewBounds="true"
                    android:src="@drawable/background_homepage"/>

            </FrameLayout>


Byte Code vs Stream of bytes(Serialization)

Question: I have a question regarding byte code and serialization.
bytecode - every java class is converted to bytecode for compilation and stored on the memory (disk) as stream of bytes / bytecode.
Serialization - Serialization is the process of saving an object's state to a sequence of bytes.
can't this bytecode itself be used to send through network ?
So what is the exact difference between the two ??
Thanks in advance.
Comment: This has already been asked / answered : http://stackoverflow.com/questions/18025851/serialization-vs-byte-code-translation
Answer: The concepts are completely unrelated.

every java class is converted to bytecode for compilation

No, it isn't converted for compilation. Bytecode is the result of compilation. It is, well, code which is run by a virtual machine (JVM in Java's case) like machine code is run directly by the CPU. It is binary (a sequence of bytes instead of characters) simply because it's a more compact representation. It doesn't contain state of any objects (except for constants).
Serialization stores the state of an object (default Java serialization is binary, but other libraries/languages can use text). The serialized object doesn't contain bytecode: you can't run it or in JVM.
Answer:
Serialization - Serialization is the process of saving an object's
state to a sequence of bytes This bytecode can be sent through
network and after be deserialized it will be loaded into another jvm
as normal object
Compilation - Compilation is the process of creating bytecode from
class java, then be loaded into local jvm. If you want to use objects
in other jvm, then you have to implement Serializable interface
Answer: Yes, bytecode(java class file)can be used to send through network, but by sending a bytecode, you transferred a java class not a java object.
Serialization is used to save or transfer object.


How to align 16-bit ints for use with SSE intrinsics

Question: I am working with two-dimensional arrays of 16-bit integers defined as
int16_t e[MAX_SIZE*MAX_NODE][MAX_SIZE];
int16_t C[MAX_SIZE][MAX_SIZE];

Where Max_SIZE and MAX_NODE are constant values. I'm not a professional programmer, but somehow with the help of people in StackOverflow I managed to write a piece of code that deploys SSE instruction on my data and achieved a significant speed-up. Currently, I am using the intrinsics that do not require data alignment (mainly _mm_loadu_si128 and _mm_storeu_si128).
for (b=0; b<n; b+=8){
    v1 = _mm_loadu_si128((__m128i*)&C[level][b]); // level defined elsewhere.
    v2 = _mm_loadu_si128((__m128i*)&e1[node][b]); // node defined elsewhere.
    v3 = _mm_and_si128(v1,v2);
    _mm_storeu_si128((__m128i*)&C[level+1][b],v3);
}

When I change the intrinsics to their counterparts for aligned data (i.e. _mm_load_si128 and _mm_store_si128), I get run-time errors, which leads me to the assumption that my data is not aligned properly.
My question is now, if my data is not aligned properly, how can I align it to be able to use the corresponding intrinsics? I'd think since the integers are 16 bits, they're automatically aligned. But I seem to be wrong!
Any insight on this will be highly appreciated.
Thanks!
Answer: SSE needs data to be aligned on 16 bytes boundary, not 16 bits, that's your problem.
What you're looking for to align your static arrays is compiler dependent.
If you're using MSVC, you'll have to use __declspec(align(16)), or with GCC, this would be __attribute__((aligned (16))).
Comment: Note that allocating a `__declspec(align(16))` structure with `malloc` or `new` is not guaranteed to get you something aligned to 16 bytes, so you'll need to be very careful where you use those. It may be better to use `posix_memalign` (in POSIX) or `_aligned_malloc` (in VC++).
Comment: `__declspec(align(16))` worked fine for me. I'll look into `_aligned_malloc` also. Thanks for the help.
Comment: Is there a way to define a Macro which will be portable between MSVC and GCC? Thank You.


How can i load a table on changing a select option using AHAH callback

Question: I have drop down in a form as follows and i want to load a table of data using the drop down value , here is i have tried ,
function list_user_form(){
     $form['howmany'] = array(
    '#title' => t('List all the users in a group'),
    '#type' => 'select',
    '#options' => select_usergroup_dropdown_options(),
    '#default_value' => $default,
    '#ahah' => array(
      'path' => 'mailusers/listuserstable',
      'effect' => 'fade',
    ),

  );
   $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Click Me'),
  );
   return $form;
}

function listuserstable(){
//make html for the table and rendering it
}

But unfortunately it gives me 403 error , please help
Answer: Try to add some wrapper to your table:
function list_user_form(){
   $form['howmany'] = array(
      '#title' => t('List all the users in a group'),
      '#type' => 'select',
      '#options' => select_usergroup_dropdown_options(),
      '#default_value' => $default,
      '#ahah' => array(
         'path' => 'mailusers/listuserstable',
         'effect' => 'fade',
         'wrapper' => 'mytable'
      )
   );

   $form['mytable'] = array(
      '#title' => t("Generated table"),
      '#prefix' => '
',
      '#suffix' => '
',
      '#type' => 'fieldset',
      '#description' => t('This is where we get automatically generated table')
   );

   $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Click Me')
   );
   return $form;
}

function listuserstable(){
   // make html for the table and rendering it
}


Race condition makes nHibernate to create duplicate entry

Question: I have a race condition on nHibernate that's creating duplicate entries on my database. Unfortunately, I cannot create an UNIQUE index on database, thus I would like to solve this error using only nHibernate methods. It is a web application that might run on a web farm (hence I guess a system lock should not solve the problem neither). The simplified situation follows:
var current = UnitOfWorkManager.Instance.Current;
current.BeginTransaction(IsolationLevel.Serializable);
try {

    var myEntity = MyFactory.MyEntityRepository.GetBy(product, company);
    // race condition happens between the previous statement and Save() method.

    if (myEntity == null)
    {
      myEntity = new MyEntity();
      myEntity.Product     = product;
      myEntity.Company     = company;
      myEntity.Date        = date;
      myEntity.CurrentUser = currentUser;
      myEntity.IsManual    = true;
      myEntity.Save();
    }
    else
    {
      myEntity.IsManual    = false;
      myEntity.Save();
    }
    current.CommitTransaction();
}
catch {
    current.RollbackTransaction();
    throw;
}

I am new to nHibernate so maybe I am missing some basics here. I'd appreciate any feedback. :)
Comment: It's not really clear what the nature of your race condition is.
Comment: @GerardoLima: NHibernate is a part of your applications process. How is it supposed to help you if you can't adjust the database? NHibernate is not a cure for bad decision in the database design. That's how you solve this common problem: *Fix your database*. NHibernate basically is a library that generates SQL and interprets the results. Would you be able to achieve what you are trying to achieve with SQL alone?
Comment: myEntity.Save(); should be in a transaction.
Comment: The database concept you are looking for is a transaction. You need to create a transaction with lock for update starting at the GetBy and ending at the Save. I can'y tell you how to do that in Hibernate however.
Comment: @DarrenDavies, this code is contained into a transaction coordinated by a UnitOfWorkManager (code was updated to show). I even set the isolation level to Serializable hoping it would lock the entire table until commit, but it didn't solve the problem.
Comment: @BrianO''Byrne please check my previous comment -- cannot refer to more than one user in each comment ...
Comment: @DanielHilgarth, the race condition happens when two users test if the myEntity instance exists to decide whether to create a new instance or update the existing one; if both users test the existing condition at the "same time", both will create new instances and, since I cannot alter the database to create the UNIQUE constraint, both will succeed.
Comment: @GerardoLima: The database is the only instance that could provide the necessary synchronization. NHibernate can't help you here, especially when we are talking about a distributed system. In that case you have multiple processes that execute your code. If you don't have multiple processes, a simple solution would be to always allow only one thread access to that piece of code via `lock`.
Comment: @DanielHilgarth, I am sorry to ask, but are you 100% sure nHibernate can't help here? I'm new to this framework and I'd rather like to believe it's just my ignorance than such a well known framework should have ways to solve this common problem...
Comment: @DanielHilgarth, If I had access to the SQL server I could lock the table during the transaction (or even create my own lock table), it would provide me with the necessary synchronization. I'm trying to adjust my thoughts to the nHibernate way to solve this problem, though. Any suggestion left on how to do it?
Comment: @GerardoLima: What kind of access do you need to create a table lock? If that's the same kind of access that you need for a normal query you might have a chance. In that case you should ask that concrete question - after searching and not finding an answer: "How to make NHibernate issue a table lock for my transaction?".
Comment: BTW: There isn't really "the NHibernate way" to solve things. Conceptually, NHibernate is only a helper library that writes the SQL statements for you. But it's still a RDBMS underneath and it still uses SQL...
Comment: i guess you have confused myEntity.Save() with session.Save(myEntity), haven't you? Or is the entity accessing the session, and if so, how and which session?
The Save() @ else should be obsolete since NHibernate tracks changes and updates the entity automatically when committing.
Comment: @BatteryBackupUnit, I guess not ... from the feedback I got here I think nHibernate can't accommodate this pattern -- I don't like it, but we can't be very picky and re-implement a great deal of an application because of a maintenance task.
Answer: After reading the nHibernate Manual, I think your problem is maybe your second call to save if subProjectToSupplier isn't null. Because the nHibernate manual says "save" does an insert.
Try SaveOrUpdate
Comment: In this particular case, I need a new row to be inserted into database or fail.
Comment: The `SaveOrUpdate` should not solve the problem, though, because it's based on ID and a new different ID would've been created for each entity instance...
Comment: If your data is dupplicated, one of your calls to save must be your problem. If it's not the second then it must be the first. Your new entity gets the same product and company you searched before.
Comment: If your code is called twice, then your call to your function must be synchronized. nHibernates Sessions aren't thread safe! You have to synchronize access to them.
Comment: That's my problem, @user743414, my application runs on a web-farm to serve clients over Internet, so I don't really have an option to make it single-threaded or synchronize threads using dotNet regular locks. I need a pattern that uses nHibernate for persistence and implement some sort of lock (or alternative) to prevent race conditions.
Comment: nHibernate doesn't have such an option.
You have to build your own.

Create a new table [mylocks(nvarchar)] and a unique index on the nvarchar field. Just make a insert to that table, when you get an exception you know you are the second who tries to insert this data.
You could make the insert in your begin transaction or add this logic to your MyEntity class. Should run fast enough.
Comment: I already had considered this (to create a table to hold application locks), @user743414. Although it should solve my problem, I still think is to ... hackish. I really expected nHibernate to work in real world Internet applications, but it seems to lack this basic building block. (please see my comment on Jul 9 at 14:10)
Comment: Another question would be, why is this code called by two or more webservers "at the same"? I don't know your application nor your design. Maybe there is some other design issue.
Answer: You should wrap your Save() in a transaction, ideally you could implement a pattern such as IUnitOfWork or use the SessionFactory, for example:
using (var transaction = session.BeginTransaction()) {
  myEntity = new MyEntity();
  myEntity.Product = product;
  myEntity.Company = company;
  myEntity.Date = date;
  myEntity.CurrentUser = currentUser;
  myEntity.IsManual = true;
  myEntity.Save();
  transaction.Commit();
}

Comment: Thank you, @Darren Davies, but I'm already using a UnitOfWork implementation to create a transaction (I updated the question to show it). The point I got is that it seems there's nothing to lock because no record was fetched from repository, so both threads can create their instance ... any thoughts?
Comment: @GerardoLima - maybe have a boolean  indicating that it is creating a new type of `MyEntity` so the other transaction has to wait until it's complete.
Comment: @Daren Davies - This suggestion actually looks like creating a `lock`. Then I get the to problem: where should I put the lock on? As the system runs on a web-farm it is not feasible to create an application (or machine) wise lock and I don't know any way to tell nHibernate to put such lock on database...
Answer: OK, so you are asking for NHibernate solution here. I am not sure if this can solve in 100% your problem but try this one.

Use ReadCommitted isolation level.
Implement an interceptor for your needs http://nhibernate.info/doc/nh/en/#manipulatingdata-interceptors

Within the interceptor you can do:

Query the DB if there is a record on your unique column. Then you can apply some sort of a merge mechanism
Check the current session if there are other objects like yours pending to be persisted.

================
Other solution is to keep shared cache of between the farm (memcache) and track objects you do not want to be duplicated.
PS: I can talk more about each point. Just tell me if something sounds like a solution for you
Comment: Actually I'm not experienced on nHibernate -- and I don't know what an Interceptor is -- so I'd appreciate if you explained this suggestion in detail.


iOS:Draw Multiple Lines Using CGContextAddLineToPoint

Question: I am writing this code in drawrect
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 10);
CGContextSetStrokeColorWithColor(context, [UIColor yellowColor].CGColor);

CGContextMoveToPoint(context, 502,530);
CGContextAddLineToPoint(context, x2, y2);

CGContextMoveToPoint(context, 502, 530);
CGContextAddLineToPoint(context, x3, y3);

CGContextMoveToPoint(context, 502, 530);
CGContextAddLineToPoint(context, x4, y4);

NSLog(@"%d,%d--%d,%d--%d,%d",x2,y2,x3,y3,x4,y4);

CGContextStrokePath(context);

But this code always draw only two lines which are incorrect
It never draws the third line
When i give static values instead of x and y  code works fine with three lines
When I NSLOG x and y I get proper desired values
but lines are not drawn according to that
I want to draw 4-5 lines with continuesly changing coordinates
Please tell me where I am going wrong
Or any other alternative to solve this problem
Comment: Are x2, y2, etc CGFloat values?
Comment: they are int values Int will work or not
Comment: But making them CGfloat is also not working out
Comment: If you are drawing closer then decrease the line width and check
Answer:
The above code is working fine, they are making three individual lines (the starting point is same for all(502, 530)). I think you are giving ending position for two points (like x3,y3 or x4,y4) are same directions, that is why you are getting two lines only, if you want to differentiate those lines you can make the lines in different color like...
int x2, y2, x3, y3,x4, y4;
x2 = 100;
y2 = 100;
x3 = 200;
y3 = 200;
x4 = 200;
y4 = 50;

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 10);

// line 1
CGContextSetStrokeColorWithColor(context, [UIColor yellowColor].CGColor);
CGContextMoveToPoint(context, 502,530);
CGContextAddLineToPoint(context, x2, y2);
CGContextStrokePath(context);

// line 2
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextMoveToPoint(context, 502, 530);
CGContextAddLineToPoint(context, x3, y3);
CGContextStrokePath(context);

// line 3
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextMoveToPoint(context, 502, 530);
CGContextAddLineToPoint(context, x4, y4);
CGContextStrokePath(context);

NSLog(@"%d,%d--%d,%d--%d,%d",x2,y2,x3,y3,x4,y4);

Comment: This is the case with me also
when i am giving hardcoded static coordinates i am getting three lines drawn
But when I want line to be changed continuesly and value of x and y change continuesly I do not get desired result
I only get two lines drawn I have checked value of x and y are proper and not overlapping
Is there any other way to draw 3-4 lines


query condition comparing two fields

Question: i am having this query :
   $db = \Drupal::database();

  $exist_query= $db->select('user__roles', 'ur');
  $exist_query->fields('ur', ['entity_id']);
  $exist_query->condition('ur.entity_id','u.uid', '=');
  $exist_query->condition('ur.roles_target_id', $included_user_roles, 'IN');

  $not_exist_query= $db->select('user__roles', 'ur');
  $not_exist_query->fields('ur', ['entity_id']);
  $not_exist_query->condition('ur.entity_id','u.uid', '=');
  $not_exist_query->condition('ur.roles_target_id', $excluded_user_roles, 'IN');

  $query = $db->select('users_field_data', 'u');
  $query->fields('u', ['uid']);
  $query->condition('u.uid', 1, '>');
  if (!empty($param['login_value'])) {
    $query->condition('u.login', $logindate, '<');
    $query->condition('u.login', 0, '!=');
  }
  $query->exists($exist_query);
  $query->notExists($not_exist_query);
  dpq($query);

the problem i am having is here
  $exist_query->condition('ur.entity_id','u.uid', '=');

it generates :
WHERE (ur.entity_id = 'u.uid')

when it should
WHERE (ur.entity_id = u.uid)

How can i solve this ?
The working request i am trying to achieve
SELECT u.uid AS uid
FROM
users_field_data u
WHERE (u.uid > '1') AND (u.login < '1586705658') AND (u.login != '0') AND (EXISTS (SELECT ur.entity_id AS entity_id
FROM
user__roles ur
WHERE (ur.entity_id = u.uid) AND (ur.roles_target_id IN ('admin_site')))) AND (NOT EXISTS (SELECT ur.entity_id AS entity_id
FROM
user__roles ur
WHERE (ur.entity_id = u.uid) AND (ur.roles_target_id IN ('membre_du_site'))))

Answer: You can add such a clause manually:
$not_exist_query->where('ur.entity_id = u.uid');

query condition comparing two fields


Prove that $(\sum x^2)^3\ge9\sum x^4yz$

Question:
Prove that $\displaystyle\left(x^2+y^2+z^2\right)^3\ge9\left(x^4yz+y^4xz+z^4xy\right)$, for $x$, $y$, $z\in\Bbb R_+$.

The $pqr$ method doesn't seem possible because the power is too high.
$$\iff\left(p^2-2q\right)^2\ge9r\left(p^3-3pq+3r\right).$$
Then expand the expression to get
$$\sum x^6+3\sum\left(x^4y^2+x^2y^4\right)+6x^2y^2z^2\ge9\sum x^4yz.$$
I wanted to use SOS but cannot find the weight of three squares, my progress:
$$3\sum x^4(y-z)^2=3\sum\left(x^4y^2+x^2y^4\right)-6\sum x^4yz.$$
Whats left is $\displaystyle\sum x^6+6x^2y^2z^2-3\sum x^4yz$. I have trouble dealing with it.
Comment: I'm curious about the way of proving that stronger inequality you obtained by SOS , $\sum x^6+6x^2y^2z^2\geqslant3\sum x^4yz$ . I tried to divide both sides by $(xyz)^2$ and let $a=(x^2)/(yz),~\ldots$ , which yields $\sum a^2+6\geqslant3\sum a$ for $abc=1$ . That's the furthest I can go.
Answer: Update: A simpler pqr
It suffices to prove that
$$\left(p^2-2q\right)^3\ge9r\left(p^3-3pq+3r\right).$$
Using $q^2 \ge 3pr$ and $pq \ge 9r$, it suffices to prove that
$$\left(p^2-2q\right)^3\ge 9 \cdot \frac{q^2}{3p}\cdot\left(p^3-3pq+3 \cdot \frac{pq}{9}\right)$$
or
$$(p^2 - 2q)^3 \ge q^2(3p^2 - 8q)$$
or
$$(p^2 - 2q)^3 + (2q)^3 \ge 3p^2 q^2$$
or (using $x^3 + y^3 = (x + y)[(x + y)^2 - 3xy]$)
$$p^2[p^4 - 3(p^2 - 2q)\cdot 2q] \ge 3p^2 q^2$$
or
$$p^2 (p^2 - 3q)^2 \ge 0$$
which is true.
We are done.
Comment: Good. But what's the idea for transforming the inequality about $p$, $q$ and $r$? When I'm doing this, it's like trying my luck.
Comment: @youthdoo There are some most used relations among $p, q, r$. In experience, $q^2 \ge 3qr$, $p^2 \ge 3q$ and degree 3/4 Schur's inequalities etc. are often used. If all of them fail, you may used the ultimate $$0 \le (a - b)^2(b - c)^2(c - a)^2 = - 4p^3r + p^2q^2 + 18pqr - 4q^3 - 27r^2$$ which is quadratic in $r$ (gives you $\cdots \le r \le \cdots$).
Comment: Thanks, so is it that\\[0 \le (a - b)^2(b - c)^2(c - a)^2 = - 4p^3r + p^2q^2 + 18pqr - 4q^3 - 27r^2.\\]is the necessary sufficient condition right?
Comment: @youthdoo Yes, $a, b, c\ge 0$ is equivalent to $p, q, r \ge 0$ and $- 4p^3r + p^2q^2 + 18pqr - 4q^3 - 27r^2\ge 0$ (the cubic $u^3 - pu^2 + qu -r = 0$ has three real non-negative roots).
Comment: @youthdoo You may see my answer [pqr](https://math.stackexchange.com/questions/3459709/if-x-y-z0-prove-xyz-left-frac1x-frac1y-frac1z-right/3460737#3460737) for the book listing often used pqr relations.
Answer: This is a proof that continues your SOS attempt, which is to prove
$$
\sum x^6+6x^2y^2z^2\geqslant3\sum x^4yz
$$
By noticing the following identity, this inequality is obviously true by Schur's inequality
$$
\sum(x^6+6x^2y^2z^2-3x^4yz)=\sum x^4(x-y)(x-z)+4(x-y)^2(y-z)^2(z-x)^2+2\sum yz(x-y)^2(x-z)^2+2xyz\sum x(x-y)(x-z)
$$
This proof is by brute force using the Triangle of Coefficient Method. Though I've found a way to simplify this inequality, I didn't managed to solve it that way.
Namely, by dividing both sides with $(xyz)^2$ , we obtain
$$
\sum\left(\frac{x^2}{yz}\right)^2+6\geqslant3\sum\frac{x^2}{yz}
$$
Let $a=(x^2)/(yz),~b=(y^2)/(zx),~c=(z^2)/(xy)$ , we have to prove that
$$
a^2+b^2+c^2+6\geqslant 3(a+b+c)
$$
for positive real numbers $a,b,c$ such that $abc=1$ .
I hope someone would continue my attempt.
Edit. This edition contains a new proof of this inequality using SOS Method by LasterCircle
$$
\text{LHS}-\text{RHS}=\frac12\sum\left[\sum x^4+2xy(x^2+xy+y^2)-2xyz\sum x\right](x-y)^2
$$
It's apparent that $\sum x^4+2xy(x^2+xy+y^2)-2xyz\sum x>0$ , the inequality is true.
Edit2. River Li has given a nice proof in the comment.
And here's a simpler SOS
$$
\sum(x^6-3x^4yz)+6x^2y^2z^2=\frac1{18}\sum\left(x(x^2-yz)\right)^2+\frac12\sum x^2(x^2-y^2)(x^2+y^2)+\frac12\sum{x^2y^2(x-y)^2}\geqslant0
$$
Comment: @O-17 By the way, a proof for the above: WLOG, assume that $(b-1)(c-1)\ge 0$, we have$a^2+b^2+c^2+6-3(a+b+c) + (abc-1) $ $$= \frac12(a + b + c- 3)^2
 + \frac12(a - 1)^2 + a(b - 1)(c - 1) + \frac12 (b-c)^2 \ge 0.$$
Comment: @RiverLi Thanks for correcting, and your proof is very nice too.
Comment: Do you mean [Chinese Dumbass Notation](https://web.evanchen.cc/handouts/SOS_Dumbass/SOS_Dumbass.pdf)?
Comment: @youthdoo Right, that's its another name (probably more widely known)  , I have made some progress on this inequality and I'll show it in the next edition.
Comment: But isn't the last inequality obvious. Because $a^2-a\ge-\dfrac14$?
Comment: @youthdoo Please note that $\sum a^2\ne\left(\sum a\right)^2$ .
Comment: @O-17 Some typos? $a^2+b^2+c^2+6\ge 3(a+b+c)$?
Comment: Your method is called Schur splitting, which seldom works. But it miraculously solved this inequality...
Comment: @youthdoo I don't know if my method is Schur splitting, but I definitely wouldn't call this method 'seldom works'. I acknowledged from your homepage that you're also from China, welcome to 'the seminar of Triangle of Coefficient' (q gruop: 875413273)
Comment: @youthdoo By the way, your inequality may be refined to $\sum a^6+(24-9\sqrt{3})\sum a^2b^2c^2\geqslant(9-3\sqrt{3})\sum a^4bc$ by a theorem that is introduced in a book in that q group. It may be proved by its equivalence to $\sum\left((a^2+\sqrt{3}bc)\sum\left((a+b-\sqrt{3}c)(a-b)^2\right)\right)\geqslant0$ , which is obviously true.
Comment: The problem is, we need every single coefficient non-negative to conclude a polynomial $\ge0$, and very often one of them $<0$, and we need to do further work.
Comment: Which question? Proving $\sum x^6+6x^2y^2z^2\ge3\sum x^4yz$?
Answer: Since the expression is symmetric, WLOG, $ z \geq y \geq x$.
Let $ x = a, y = a + b, z = a+b+c$, where $a, b, c \geq 0$.
Then, expanding out $(x^2 + y^2 + z^2)^3 - 9 xyz(x^3+y^3+z^3)$ gives us, courtesy of Wolfram:
$9 a^4 b^2 + 9 a^4 b c + 9 a^4 c^2 + 28 a^3 b^3 + 42 a^3 b^2 c + 30 a^3 b c^2 + 8 a^3 c^3 + 42 a^2 b^4 + 84 a^2 b^3 c + 78 a^2 b^2 c^2 + 36 a^2 b c^3 + 12 a^2 c^4 + 30 a b^5 + 75 a b^4 c + 90 a b^3 c^2 + 60 a b^2 c^3 + 27 a b c^4 + 6 a c^5 + 8 b^6 + 24 b^5 c + 36 b^4 c^2 + 32 b^3 c^3 + 18 b^2 c^4 + 6 b c^5 + c^6.$
Since all the coefficients are non-negative, this is clearly non-zero, hence we are done.
Comment: Is this method called the Buffalos Way?
Comment: @youthdoo Yes. Often, the more common way BW appears is to set $ x = \min{x, y, z}, y = x+u, z = x+v$, and still requiring a bunch of SOS to resolve.  In this case, this approach immediately yields non-negative coefficients, so we are done.
Comment: A bit irrelevant but how do you copy the result from wolfram alpha to paste here? Use ocr?
Comment: Hover on the relevant line, click on the "Plain text" tab, then click the "Copyable Plain text" which will copy it to clipboard, then paste it.
Answer: This inequality is true for any real variables.
Indeed, let $x+y+z=3u$, $xy+xz+yz=3v^2$, where $v^2$ may be negative and $xyz=w^3$.
Thus, we need to prove that:
$$(9u^2-6v^2)^3\geq9w^3(27u^3-27uv^2+3w^3)$$ or $f(w^3)\geq0,$ where $f$ is a concave function.
But, a concave function gets a minimal value for an extremal value of $w^3$, which by uvw happens for equality case of two variables.
Since our inequality is symmetric,  even degree and homogeneous, it's enough to assume that $y=z=1$ (for $y=z=0$ the equality is obvious), which gives $$(x^2+2)^3-9x(x^3+2)\geq0$$ or
$$(x-1)^2(x^4+2x^3-2x+8)\geq0,$$ which is true because
$$x^4+2x^3-2x+8=(x^2+x-1)^2+x^2+7>0.$$
Answer: Another way.
By AM-GM we obtain: $$(x^2+y^2+z^2)^3-9xyz(x^3+y^3+z^3)=$$
$$=\sum_{cyc}(x^6+3x^4y^2+3x^4z^2+2x^2y^2z^2-9x^4yz)=$$
$$=\frac{1}{2}\sum_{cyc}(2x^6-x^4y^2-x^4z^2+7x^4y^2+7x^4z^2-14x^4yz-4x^4yz+4x^2y^2z^2)=$$
$$=\frac{1}{2}\sum_{cyc}(x-y)^2((x^2+y^2)(x+y)^2+7z^4-2xyz(x+y+z))=$$
$$=\frac{1}{2}\sum_{cyc}(x-y)^2((z^2-xy)^2+6z^4-2xy(x+y)z+(x^2+y^2)(x+y)^2-x^2y^2)\geq$$
$$\geq\frac{1}{2}\sum_{cyc}(x-y)^2\left(6z^4-\frac{1}{2}(x+y)^3z+\frac{7}{16}(x+y)^4\right)=$$
$$=\frac{1}{2}\sum_{cyc}(x-y)^2\left(6z^4+3\cdot\frac{7}{48}(x+y)^4-\frac{1}{2}(x+y)^3z\right)\geq$$
$$\geq\frac{1}{2}\sum_{cyc}(x-y)^2\left(4\sqrt[4]{6z^4\left(\frac{7}{48}(x+y)^4\right)^3}-\frac{1}{2}(x+y)^3z\right)=$$
$$=\frac{1}{2}\sum_{cyc}(x-y)^2(x+y)^3z\left(4\sqrt[4]{6\left(\frac{7}{48}\right)^3}-\frac{1}{2}\right)\geq0.$$
Answer: Hint :
Due to homogeneization we have :
$$\left(x^{2}+1^{2}+c^{2}\right)^{3}-9xc\left(x^{3}+1^{3}+c^{3}\right)$$
We need to show for $x\ge 1$ and WLOG $c\geq 1$
$$f(x)=\left(x^{2}+1^{2}+c^{2}\right)^{3}-9xc\left(x^{3}+1^{3}+c^{3}\right)\geq 0$$
The function is convex on $(0,\infty)$ because we have :
$$f''(x)=6(c^{6}+6c^{3}x^{2}+2c^{3}-18cx^{2}+5x^{4}+6x^{2}+1)>0$$
So we use the tangent line method we have :
$$f(x)\geq f(1)(x-1)+f(1)=(6 (c^3 + 2)^2 - 9 c (c^3 + 2) - 27 c)(x-1)+(c^3 + 2)^3 - 9 c (c^3 + 2)\geq 0$$
Because :
$$(6(c^{3}+2)^{2}-9c(c^{3}+2)-27c)\geq 0,(c^3 + 2)^3 - 9 c (c^3 + 2)=(c^3 + 2) (c - 1) (c^5 + c^4 + c^3 + 5 c^2 + 5 c - 4)\geq 0$$

Prove that $(\sum x^2)^3\ge9\sum x^4yz$


Como fazer uma imagem de Docker de um app de Node que usa repo privado que requere ssh

Question: Seguindo este guia do site do Node.js para criar uma imagem de Docker para um aplicativo de Node, tudo dá certo exceto quando se tem um repositório privado para um certo pacote de npm, como o seguinte snippet do package.json:
"dependencies": {
  (...)
  "um-certo-pacote": "git+ssh://firstname.lastname@example.com:/algum/diretorio/um-certo-pacote.git",
  (...)

O servidor que tem o repo armazena a chave ssh do computador que faz o pedido pra clonar o pacote. Localmente tudo funciona, mas na hora de fazer um build, não dá certo porque o Docker não tem acesso a chave ssh.
$ docker build -t nbkhope/meu-aplicativo --add-host=algumlugar.com:188.8.131.52 .

Ja pesquisei em vários locais e tentei copiar o arquivo com a chave pública de ssh, mas isso não é recomendado devido a motivos de segurança. Então qual é a maneira de fazer esse negócio funcionar de maneira segura, sem expor segredos?

Segue o Dockerfile:
FROM node:6
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 8080
CMD ["npm", "start"]

Answer: Ola, vejo duas opções,

Antes de fazer o build, fazer o download do pacote, que estará então disponivel para ser adcionado ao build

Adcionar uma chave em uma build multi-stage, em que um estágio adciona-se a chave e faz o download, e a outra copia-se o pacote sem adcionar a chave

FROM node:6 as base
WORKDIR /usr/src/app
COPY package*.json ./

FROM base as builder # esta imagem nao recebera tag, e ficara no sistema marcada como <none>
# Adcionar chave, seja por copia de arquivo ou variavel de ambiente
RUN npm install

FROM base as final #esta será a imagem final
COPY . .
COPY --from builder <diretório de pacotes> <diretório de pacotes>
EXPOSE 8080
CMD ["npm", "start"]


Pivots,column dependence & free/basic variables (General topic)

Question: Is it correct to say that pivots must be handled correctly,so that one can form the U matrix(like,making the correct row operations in order not to "destroy" the zeroes one has built,so then the system can be solved using recursive substitution)?
How are pivots connected to the idea of column dependence?
Lastly,why are pivot related columns considered as the basic variables,whereas the remaining columns are considered as the free variables?
(for example: if y is a basic variable,and w is a free variable suppose the equation : y=w+4 but <=> w=y-4.I know it's not correct,but why can't i say that y & w switched roles?)
Any help is appreciated!
Answer: Pivot should be handled correctly so that you have a systematic way to solve a linear system.
The columns of the original matrix corresponding to the pivot positions is a basis to its column space, they are linearly independent.
Let $N$ be the set of free variable.
The pivot variable can be set as linear combination of the other variable. $x_i = -\sum_{j>i, j \in N}\hat{A}_{ij}x_j$ where $\hat{A}_{ij}$ is the corresponding row echelon form.  Once we fix the value of those $x_j$, we totally determine $x_i$. Those $x_j$ can be chosen freely.  The standard procedure tell us that we can systematically fix the free variables to determine the pivot entries.
You can swith the role of $y$ and $w$. Choose the value of $y$ and determine $w$. However, after you do that, you then have to look at the other position that $w$ appears in the other rows. In contrast, for the standard procedure, you can directly fix all the other free variables and solve the pivot entries in parallel.