Stuck in Induction Inequality: $2^n>3n^2$

Question: I am doing an inequality induction question that looks like this:
Prove that $2^n>3n^2$ for $n\geq 8$
So I have done Step $1,2$ but I can't finish step $3$
Step $1$: RTP: $n=8$
LHS=$2^8=256$
RHS=$3(8)^2=192$
Therefore  true for $n=8$
Step $2$: Ass $n=k$
$2^k>3k^2$
Step 3: RTP: $n=k+1$
$2^{k+1}>3(k+1)^2$
LHS=$2^k \cdot 2$
$>2 \cdot (3k^2)$
$=6k^2$
New aim-RTP: $6k^2>3 \cdot (k+1)^2$
$6k^2>3k^2+6k+3$
I am stuck here, how do I continue beyond this step?
Comment: why are you writing the product as . instead of $\cdot$?
Comment: "\cdot" is the symbol that accomplishes this, BTW
Comment: You should take a look [here](http://www.math.harvard.edu/texman/) to learn how to properly format math in LaTeX.
Answer: Notice that $6k^2\ge3(k+1)^2\iff 2k^2\ge(k+1)^2\iff 2k^2\ge k^2+2k+1\iff k^2\ge2k+1$.
Now use your assumption that $k\ge8$, so $k^2\ge 8k$.
Comment: is there a way to prove $k^2>2k+1$ without using the assumption?
Comment: @user117196 For $k = 0$ or $k = 1$, this is not true. Hence, you need some assumption on $k$.
Answer: Hint: write your statement as
$$2^n - 3n^2 > 0.$$
That way, you can work with the both parts at once (as they are on the same side of the inequality).
So, your final step transforms to
$$6k^2 - 3k^2 -6k - 3 = 3k^2 -6k - 3 = 3 (k^2 - 2k - 1) > 3 (k^2 - 2k - 3) = 3(k-3)(k+1).$$
Since we have assumed that $k \ge 8$...
Answer: Why don't you consider the real function $f(x) = 3x^2 -6x - 3$ ?
Comment: I doubt the OP is still stuck there after 18 months.
Comment: What do you mean by "OP"? Sorry, I'm not so familiar with English and this site.
Comment: On math.SE, "[Original Poster](http://www.urbandictionary.com/define.php?term=op)".


$\sigma$-algebras with a finite number of atoms

Question: Suppose that a $\sigma$-algebra on $\mathcal{X}$ has a finite number of atoms. Is it true that this set of atoms partitions the space $\mathcal{X}$?
Answer: If you consider a sigma algbra without atoms and enlarge the space by adding a 'point at $\infty$' you get a sigma algebra with  a single atom. The atoms do not form a  partition in this case.
 Ref: https://mathoverflow.net/questions/22477/sigma-algebra-without-atoms
The answer is YES, if the sigma algebra is countably generated. In this case there are enough atoms and every set in the sigma algebra is a union of atoms.   Atoms are pair-wise disjoint. Since $\mathcal X$ belongs to the sigma algebra you can express it as  a union of atoms. Hence atoms form a  partition.
Answer: No, not in general. There exist sigma algebras without atoms.
Hence, the atoms cannot partition the space in general.


PHP / JavaScript custom progress bar animate on changing of input value

Question: I'm looking for an HTML5/PHP/JavaScript based progress bar that can work/animate on the changing of input values, the emotions (shown below and in link) are selectable actually they  are checkbox (See this page http://hashtaginc.us/Projects/Relax/self_assessment.php). I want when user select/deselect any emotion the progress bar animates (increase/decrease) respectively..
So any one can help me to find a way to create a custom progress bar according to my requirement.
(custom progress bar as shown in the image below)
Answer: You can try and use Jquery UI Progressbar
And just adjust the value depending on how many checkboxes are selected. If you would like to use a custom progressbar you can try to make css classes 0% 25% 50% 100% and just call them with jquery.


Nuevo estudio de plantilla CommandBar

Question: How can I put the CommandBar on top of the Desktop and at the bottom on the mobile device?.enter code here
enter code here
    <Grid.RowDefinitions>
        <RowDefinition x:Name="TitleRow" Height="48"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

 `enter code here`   <TextBlock
        x:Name="TitlePage"
        x:Uid="Main_Title"
         FontSize="{StaticResource FontSizeMedium}" Foreground="{StaticResource RedBrush}" FontWeight="SemiLight" TextTrimming="CharacterEllipsis" TextWrapping="NoWrap" VerticalAlignment="Center"
        Margin="0,0,12,7"/>

 `enter code here`   <CommandBar x:Name="Topbar" Margin="0,0,12,7"  HorizontalAlignment="Right"  Background="White" Visibility="Collapsed"  >
        <CommandBar.PrimaryCommands>
            <AppBarButton  x:Name="AddButton" Icon="Accept" x:Uid="Aceptar"  Foreground="{StaticResource RedBrush}" Click="AddButton_Click"/>
        </CommandBar.PrimaryCommands>
    </CommandBar>

Comment: Could you please clarify what you are asking? With current writing, it's hard to understand what your problem is.
Comment: On desktop I have the CommandBar at the top when I throw the emulator the CommandBar is still up, I want it with the visualstate, when this in DESKOTP this in the top, when this a smartphone is at the bottom
Answer: Since you're already using VisualStates, you can have three rows in your Grid and just change the CommandBar's Grid.Row value with an AdaptiveTrigger using the Width of the app.
Here is a video of the example code below at run-time.
UPDATE
To re-iterate what I stated in my last comment, you no longer need to use "Page.AppBar" property. In fact, you don't want to use it because your Grid's VisualStateManager can't alter page level properties.
Instead you can do what I show below (it's a complete, working, example):
<Grid x:Name="ContentArea"
          Margin="{StaticResource MediumLeftRightMargin}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <CommandBar x:Name="MyAppBar"
                    Grid.Row="0" />

        <Grid Grid.Row="1" Background="DarkGray">
            <TextBlock Text="This is where your page content would go"
                       VerticalAlignment="Center"
                       HorizontalAlignment="Center"/>
        </Grid>

        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="WindowStates">
                <VisualState x:Name="WideState">
                    <VisualState.StateTriggers>
                        <AdaptiveTrigger MinWindowWidth="640" />
                    </VisualState.StateTriggers>
                    <VisualState.Setters>
                        <Setter Target="MyAppBar.(Grid.Row)"
                                Value="0" />
                    </VisualState.Setters>
                </VisualState>
                <VisualState x:Name="NarrowState">
                    <VisualState.StateTriggers>
                        <AdaptiveTrigger MinWindowWidth="0" />
                    </VisualState.StateTriggers>
                    <VisualState.Setters>
                        <Setter Target="MyAppBar.(Grid.Row)"
                                Value="2" />
                    </VisualState.Setters>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    </Grid>

When the app is on mobile, the screen will be less than 640epx wide and the CommandBar will at the bottom. Otherwise, it will be on the top.
Comment: Problem is that I stay up in the Samrtphone part, will not have to use   and also  . After with the Visualsate
Comment: I'm using template studio
Comment: Template Studio just generates XAML. You can customize it after the fact. In the case where you have two commandBar properties (Top & Bottom), then just create both of them and toggle each the CommandBar.Visibility property depending on the VisualState
Comment: As I can place the lower command in the XAML, sgun the code that is put up
Comment: For what you're trying to do, you wouldn't want to use Page.TopAppBar and Page.BottomAppBar because the VisualStateManager can't set the properties. Instead, you can go with the approach I mentioned so you have more flexibility. I've updated my answer to provide all the code from a working demo I just tested.
Comment: Thank you very much

Nuevo estudio de plantilla CommandBar


How can I prove the finite axiom of choice? (Actually, theorem)

Question: Let $\displaystyle \{X_i\}_{i\in I_m}$ a collection of nonempty sets, $I_m=\{i\in \mathbb N | 0<i\leq m\}$. Then show that there is a $x:I_m\rightarrow \displaystyle \bigcup_{i\in I_m} X_i$ such that $x(i)\in X_i$ (without axiom of choice).
I think I have to show that by induction.
For $n=1$,  I have to show that there is a $x:\{1\}\rightarrow \bigcup X_1$ such taht $x(1)\in X_1$.
Since $X_1$ is non-empty. Then it has at least one element. I will "select" one of them and call it $x$, this allows me to form the ordered pair $(1,x)$. So there is a function of $ x:\{1\}\rightarrow \bigcup X_1$ such that $x(1)\in X_1$, and the function $x$ is $(1,x)$.
Now, let's assume that it holds for $n$. That is, if $\{X_i\}_{i\in I_n}$ is any collection of non-empty sets, then there exists a function $x':I_n\rightarrow \bigcup _{i\in I_n} X_i $ such that $x'(i)\in X_i$
Let $A$ be a non-empty set which we will call $X_{n+1}$, this allows us to form a family of non-empty sets of $n+1$ elements $\{X_i\}_{i\in I_n+1 }$. Since $X_{n+1}$ is a non-empty, then it must have some element, say $y$, this allows us to form the ordered pair $(n+1,y)$ which if we join the set $x' $, we will obtain the following function $x^*:I_n\cup \{n+1\}\rightarrow \displaystyle \bigcup _{i\in I_n} X_i \cup X_{n+1}$ such that for all $i\in I_{n +1}$ it is true that $x^*(i)\in X_i$. Since $A$ was arbitrary, then we have found a required function for a collection of non-empty sets with $n+1$ elements.
This completes the proof, that is, that for all $n\in \mathbb N$ there exists a choice function for a finite collection of $n$ non-empty sets.
I am not sure if my attempted demonstration is correct, in any case it seems somewhat cumbersome to me, I would appreciate it if you could tell me if it is correct, and if so, how I could make it more understandable.
Answer: Your solution seems correct and very understandable, but maybe you find the approach below more amusing.
If you can accept that a function $\displaystyle x:I_m\to\bigcup_{i\in I_m} X_i$ is the same as an element $\displaystyle x\in\prod_{i\in I_m} X_i$, then all you have to do is to show that if $X_i\neq\varnothing~\forall i\in I_m$, then $\displaystyle\prod_{i\in I_m} X_i\neq\varnothing$, which can be done by induction!
Base case:
The claim is trivially true for $m=0$ and $m=1$. Also, given $A, B\neq\varnothing$, we have $a\in A$ and $b\in B$, so $(a, b)\in A\times B\neq\varnothing$ and the claim is true for $m=2$.
Induction hypothesis: Suppose the claim is true for $m$.
Inductive step:
Let $\{X_i\}_{i\in I_{m+1}}$ be a collection of non-empty sets. Then by our hypothesis $\displaystyle\prod_{i\in I_m} X_i\neq\varnothing$ and $X_{m+1}\neq\varnothing$, so, by our base case, $\displaystyle\prod_{i\in I_{m+1}} X_i=\left(\prod_{i\in I_m}X_i\right)\times X_{m+1}\neq\varnothing$, as we wanted.


Creating a New Predictor Variable From a "Lagged Response Variable"?

Question: Our TA in our stats class told us that when working with regression models, it is generally unadvisable to create a new predictor variable from a "lagged regression variable" (unless you are ready to consider very complicated regression models like "dynamic regression models").
As an example, suppose there are some students - you have repeated measurements on these students (e.g. age, weight, height) and the results (e.g. pass/fail) from fitness test taken by these student. As an example - suppose here are the test results for the same student over a period of years:
<code>  student_id age weight height fitness
1          1  20    186   1.76    PASS
2          1  21    187   1.76    FAIL
3          1  22    191   1.77    FAIL
4          1  23    188   1.78    PASS
</code>
Suppose I wanted to add some new variables to this dataset (pass = 1, fail = 0):
<code>  student_id age weight height fitness total_tests_taken result_previous_test cumulative_average
1          1  20    186   1.76       1                 0                   NA                 NA
2          1  21    187   1.76       0                 1                    1               1.00
3          1  22    191   1.77       0                 2                    0               0.50
4          1  23    188   1.78       1                 3                    0               0.33
</code>
Let's say that the goal is to build a model that models the relationship between passing the fitness test and historical results from students. Supposedly, these new variables that I have created are not to be inserted into a regression model due to assumption violations.
However, I have the following question - suppose instead of a regression model, I decide to use a model like a "Decision Tree" (e.g. CART, C4.5, CHAID) which in theory has fewer assumption restrictions compared to a regression model. Using models such as Decision Trees, is it now "more permissible" to create new predictor variables based on "lagged values of the covariates" as compared to regression models?
Answer: First, use of lagged regressors in linear regression is a fairly standard practice. You will find it in most econometrics textbooks, even on an introductory level. Time series models are a bit more complicated than cross sectional ones due to an additional dimension of dependence (time dependence). This shows up when deriving properties of estimators such as consistency and asymptotic normality of OLS. The TA probably does not want you to deal with this at an early stage in the course but they should not be against that in general.
Second, while trees and linear regression are different models, I do not think one can accommodate time dependence and lagged regressors more or less easily than the other. The model formulations are equally straightforward. The facts that (1) we study properties of OLS but not tree estimators in introductory statistics or econometrics courses and that (2) proofs for OLS get a bit harder when considering the time dimension do not imply that the properties of tree estimators are unaffected.
Comment: This is not an answer from a reputable source, but I think it will not hurt to share it nevertheless.
Comment: @ Richard Hardy: Thank you for your answer! I thought that if you use a regression model like Logistic Regression, creating predictors from lagged responses will violate assumptions?
Comment: In this example, is it unreasonable to create a logistic regression model that estimates the probability of passing the next exam based on the results of previous exams?
Comment: @stats_noob, I do not think logistic regression and trees used as predictive models have inherent differences regarding incorporation of lagged regressors. There may be some nuance about properties of the estimators, but again I do not think trees are inherently better in this regard. But this is just my general intuition, not an answer from a reputable source.
Answer: While in a regression setting using a lagged value or its transformation would lead you to something similar to an Autoregressive Model with covariates (which then trains and behaves differently from a normal linear regression), it would be perfectly acceptable when using decision trees and derivate algorithms.
However, if you plan on using a training-testing split (or CV) on your data to optimize the choice of some hyperparameters, it is important that you do so respecting the "direction" of the time component - i.e. do not train on "future" data to test on "past" data.
Comment: @ Davide ND: Thank you so much for your reply! Can you recommend any sources that confirm that "lagged variables would be perfectly acceptable when using decision trees"? Thank you!


Ornaments in J. S. Bach's 4th prelude

Question: Inverted mordents and turns are frequently used in the prelude No.4 of J.S. Bach in C-sharp minor. In what follows I assume the key of the piece is known.

My first question is related to the normal mordent that is placed on top of the E-G chord in the second bar (see image below). Does the mordent here only concern the upper note, namely the G? If yes, how is it played together with the E?

If there was just the G note, then the mordented G is equivalent to: G-A-G.
But given the additional E note that has to be played, my current take is that it should be played as: E-G chord played, followed by A-G while keeping the E held down. Is this correct?

Similarly in the 11th bar, (with the difference of having inverted mordents), we have two chords mordented, but the sign being underneath the chords.

The sign being placed underneath instead of on top, does it mean that the lower note is mordented? For example the A-sharp in the first chord (see image below), in which case we'd play A#-C chord followed by G-A#.

Finally, as a general rule, when a chord of arbitrary number of notes (2, 3, ...) is coupled with an ornament sign, how do we know which note it concerns? (does the sign being on top mean the most upper note is concerned, and the converse for when the sign is underneath?)

Music sheet reference: Taken from here: http://www.allpianoscores.com/free_scores.php?id=36
Answer: Here is a transcription of Bach's own Table of Ornaments from the Klavierbüchlein vor Wilhelm Friedemann Bach. A PDF of the Klavierbüchlein ms is available on IMSLP here. (This Prelude is in the Klavierbüchlein, but completely devoid of ornamentation.) You may find the discussion here useful (a condensation of the subject as presented in Willard Palmer's edition).

Your first example has two parts: an appoggiatura and a trill.
An appoggiatura is not a grace note. In Baroque music, it is shorthand for a nonharmonic tone resolving by step into a tone of the harmony. All the commentators of the time (C. P. E. Bach, Marpurg, etc.) agree that an appoggiatura of a regular note value is played on the beat and takes a duration of half the written value. Most agree that an appoggiatura played against a dotted note takes 2/3 of the written duration, although there is a certain freedom allowable. In this particular case, anything from a crochet to a dotted minim should work pretty well.
There is no such thing as a Baroque upper mordent, however: that's a later (19th century) ornament. C. P. E. Bach was vehement that trills always started on the upper auxiliary, and J.S. Bach's table certainly shows that kind of trill for this symbol. In a case like this, where the upper auxiliary repeats the appoggiatura, starting on the auxiliary would help keep the trill from sounding like a kind of Nachschlag of the appoggiatura. Note that the number of alternations in the trill is variable.
Having said that, I have heard an effective rendition on harpsichord that used a crochet-length appoggiatura and started the trill on the main note, so you have some leeway in ornamenting the Prelude. The Prelude does exist in a number of manuscripts and underwent some changes along the way. Prelude 4 in the fair autograph of WTC I (P415, which Bach signed off with "SDG", Soli Deo gloria, at the end) is like the version in the Klavierbüchlein in being devoid of ornamentation. You can see it here at the Staatsbibliothek-Berlin (bottom half of the page). Ornamentation would have been added according to the conventions of the time.
My understanding is that the written ornamentation was added at a later stage (not necessarily by Bach, but possibly definitive copies by students). The WTC went through a number of stages of revision after the autograph. The question can be vexed: here is some discussion of it, and the Preface to the Henle Urtext edition gives an idea of the development. I haven't got the Henle edition, so I can't say what they would show as definitive (and what in small notes and symbols) as a result of Heinemann's research. I'm not a Bach scholar, so I don't know where to track down all the sources, nor do I know their relative merits. For this, you can pick up your own Urtext or critical edition (usually a good idea), and work out for yourself what ornamentation is correct and/or effective.
So... The takeaway here is that the appoggiatura is an emphasised non-harmonic tone played on the beat with a fairly substantial duration, and that the symbol over the main note is for a trill, not an upper mordent - Baroque mordents only used the lower auxiliary. Last, these ornaments were added in later copies of the WTC I manuscript that the editors of the Bach-Gesellschaft (whose edition you've got) considered authoritative.

In your second example, yes, the mordents would apply to the alto voice. If both voices were affected, there would be mordent symbols both above and below the stave. You would thus play the first instance as something like demisemiquavers A♯-G♯-dotted quaver A♯ (the rhythm in Bach's table) under the held C♯.
Answer: Your ideas are basically correct, but the first example is a bit more complicated because of the appoggiatura A before the chord.
In Bach's time the A would be played on the beat, not before it. Part of the reason for writing as an ornament is because the previous note in the treble is also an A, and repeated notes are a bit unusual, especially in a slow tempo. If Bach had written the appoggiatura-A as a normal note, his contemporaries would probably have put another ornament on it to "hide" the repetition, but Bach's notation is saying "don't do that". (It's a bit paradoxical that sometimes written ornaments really mean "play it as if it wasn't ornamented"!)
So, the initial chord is E-A, and the question then is how long the A should be, before playing the mordent.
Playing the A short seems like throwing it away rather than making it something significant. But you play it at its written length of an 8th-note, you get consecutive seconds G#/A - F#/G# with the left hand voice which doesn't sound good (and worse on a harpsichord than a piano, where you can partially hide the discords by adjusting the dynamics.)
I usually play the A as at least a quarter note long, so you get an anticipation in the left hand (C#/G#/A - C#/F#/A) and then a 6-4 5-3 progression (C#/F#/A - C#/E/G#) plus the mordent on the G# of the C#minor chord.
Or, since these ornaments were meant to be a matter of taste rather than following strict rules, I might extend the appoggiatura A to be a dotted half note, and play the mordent as the end of arpeggio ornament on the next beat, i.e. make the arpeggio into 6-notes, E-G#-C#(LH)-G#-A#-G#(RH), or even 7 notes playing the tied E again, E-G#-C#-E-G#-A#-G#, or even really make a meal of the arpeggio and play E-G#-C#-D#-E-F#-G#-A#-G#. "It all depends on the mood I'm in...."
Of course if you play the second bar of the piece like that, you are giving notice that you are going to play a lot of unwritten ornaments all the way through - and an examiner might not approve of such things (but I took my last exam decades ago, so I don't care about that!)
Answer: As I remember things from years ago, the mordent over a chord applies to the top note and under a chord to the bottom note (inverted mordent). Of course these names are reversed by some authors.
In the cases you showed, I think your first idea is correct. You play a sustained (relatively) E and while holding the E, play G-A-G. Similarly for other cases.
A quick check of Dolmetsch's book and Dart's book didn't discuss mordents over chords.
I don't remember any multiple trills before Beethoven. Multiple trills are a succession of the same harmony and don't seem to fit Baroque sensibilities.
Comment: An inverted mordent uses the upper neighbor rather than the lower; it has nothing to do with which member of the chord it is applied to.

Ornaments in J. S. Bach's 4th prelude


Medidas adicionais para evitar ataques de injeção de SQL são realmente necessárias?

Question: Estava dando uma olhada em alguns projetos na internet que envolvem segurança e me deparei com o seguinte código.
Todas as requisições ao site eram redirecionadas ao index.php pelo mod_rewrite, a conexão com o banco de dados era feita com PDO, utilizando prepared statements, tudo estava no padrão, porém fui dar uma olhada no index e me deparo com esse código
    /** O projeto permite somente slugs com 250 caracteres **/
    if (isset($_GET['params']) && (strlen($_GET['params'])  > 250))
    {
        header('HTTP/1.0 403 Forbidden');
        die('O endereço atual excede os limites de segurança');
    }

Achei bem estranho e resolvi baixar pra conferir.
Utilizei o sqlmap pra fazer alguns testes e o mesmo não obteve resultado. Tirei essa linha que postei acima e fiz os testes novamente, basicamente não mudou em nada, exceto nos logs do Apache que pude ver que as strings do sqlmap estavam "passando", ao invés de serem "barradas" pelo script e gerando erros 403.

Para assegurar o aplicativo e poupar recursos do servidor, o código
  acima é uma medida preventiva ou desnecessária?
Comment: Eu acho que a palavra "segurança" nesse caso está sendo usada num sentido figurativo (i.e. um slug muito grande poderia causar bugs em outras partes da aplicação por razões quaisquer)., e não no sentido literal. Mas é só um palpite...
Comment: Não há nada no que postou que reforce a segurança no que se refere a SQL injection. O script apenas impede que a aplicação prossiga caso o slug tenha mais que 250 caracteres e ainda dispara um aviso de segurança caso ocorra. Conforme já comentado, é um exagero pois não tem a ver com segurança, mas sim, com regras de negócio e também pelo fato de que o método GET é limitado a 255 caracteres. Resumindo, é uma gambiarra muito grosseira. Aplicada de forma confusa por disparar um 403 forbidden com mensagem sobre segurança.
Comment: é confuso dar uma resposta. Se puder modificar a questão para algo mais relevante, pelo menos relevante ao título ou modificar o título conforme o conrtexto, acho que pode tornar-se viável
Answer: Não entendi bem a questão, me parece que você dizer que $_GET['params'] é passado para o mysql, ele não parece pra evitar sqlinjection, acredito que podem ser dois motivos:
URL amigáveis (slug)
Lendo sobre o termo "slug" ele significa que as urls devem ser mais fáceis para leitura humana, ou seja estamos falando de urls reescritas (mod_rewrite), um exemplo seria:

Titulo da página/artigo: Como criar urls amigáveis!
slug do titulo para url: como-criar-urls-amigaveis
No código usado este slug tem um limite de 250 caracteres, pois a ideia é que se for maior ele provavelmente será difícil de ser "lembrado" pelo usuário. Não que a solução proposta vá resolver, mas é um caminho para tentar evitar o problema.

Evitar conexões ao mysql sem necessidade
Pense assim, se os parâmetros são inválidos não existe necessidade de conectar no mysql, isto pouparia um pouco o servidor, pois aparentemente não existe urls com mais de 250 caracteres, por que todas vez que você faz uma requisição valida ele conecta no servidor mysql, sei que seria difícil haver múltiplas conexões com querys invalidas.
Sobre o código que você citou eu notei uma coisa estranha pois ele parece tentar evitar strings maiores que 250 (strlen($_GET['params'])  > 250), mas como o @rray disse, strlen retorna bytes e não caracteres, então talvez o código não funcione bem como o esperado.
Comment: Acho que o código da pergunta está preocupado em tratar o undefined index, lembre que o `strlen()` retorna o número de bytes e não de caracteres.
Comment: @RenanCavalieri não diria errada, mas sim da interpretação dele, ele talvez acredite que seja a segurança do usuário lembrar :) - Mas realmente é melhor evitar o uso da palavra neste contexto.
Comment: Pelo que eu entendi desse código ele conta o número de caracteres que eu coloco na URL, pois se eu coloco mais que 250 ele dá aquela mensagem que está dentro do die(); Achei bem estranho esse código, a ideia parece ser boa de poupar o servidor, mas não compreendi o código em sí.
Comment: A menos que se queira enviar uma hash como parâmetro, ou que os parâmetros sejam _"desconhecidos"_, essa verificação é um desperdício de linha, e nada tem haver com protecção. Eu pessoalmente não entendi a razão, existem formas bem melhores de lidar com problemas como este como já mencionaram.
Comment: Fazendo uns testes parece que a única coisa que ele fez foi poupar o BD de consultas inválidas, nada mais, acho que realmente a palavra segurança foi empregada de forma errada ali.
Comment: Estou pesquisando essas coisas pois irei fazer um TCC com o tema de segurança no ano que vem, não vou invadir ninguém não hehe, valeu pelas respostas.


php AND, OR operators in If statements

Question: I am new to programming so please don't judge me. This question is simple concept knowledge that I have somehow missed. My question is, do brackets make difference when you are using AND and OR operators? For example,
if ( x == 1 && ( y == 1 || y == 2 ) ){
  // do something
}

Basically, what I want to do is that x has to take value 1 at all times and y can vary between 1 and 2. Does the above code make sense for this purpose? And is it different from:
if ( x == 1 && y == 1 || y == 2 ){
  // do something
}

Comment: Like in arithmetics, `AND` behaves like `*` and `OR` like `+`.
Comment: it's good habit to always put your conditions in "blocks" using brackets, so instead of `if ( x == 1 && ( y == 1 || y == 2 ) )` you type `if ( (x == 1) && ( (y == 1) || (y == 2) ) )`. Pays off when you start using languages supporting macros or using preprocessor
Answer: Yes,
in the first code, x == 1 will be checked first and the result will be checked against the result of  y == 1 || y == 2 .
and in the second one , x == 1 && y == 1 will be checked at first and the result of it will be checked against || y == 2
Comment: so you mean in the second one `|| y == 2` has no use?
Comment: no, in second one, the result of `x == 1 && y == 1` will be checked, and the result will be check against `|| y == 2`
Comment: in the first code I think if x!=1 it wouldn't even go into bracket, so you answer is not correct.
Comment: yes, I didn't made my point right, and now I updated my answer
Answer: Yes, they do. What you're really asking is what is the operator precedence for && and ||?
&& has higher precedence than ||, which means it will be evaluated first if the order isn't specified explicitly using brackets (as you do in your first example).
You can think of precedence as the order in which PHP adds brackets to the expression if you haven't already put them in. In your second example, the operator with the highest precedence is ==, so all instances of these are grouped with brackets:
(x == 1) && (y == 1) || (y == 2)

The next highest is &&, so now we add brackets around these:
((x == 1) && (y == 1)) || (y == 2)

The expression is now unambiguous, so we needn't add any more brackets.
Hopefully it's clear from this argument that the first expression in your post is not the same as the second. For example, if x==0 and y==2, the first expression (correctly) evaluates to false, while the second evaluates to true.
See here for a list of operator precedences in PHP.
Comment: +1 for taking time to create a well described answer
Answer: && has higher precedence than ||, so it'll be evaluated first. The use of parentheses helps you make sure the order of execution is same as what you expect.
From the PHP manual:

Use of parentheses, even when not strictly necessary, can often increase readability of the code by making grouping explicit rather than relying on the implicit operator precedence and associativity.
Answer: The && (logical AND) operator indicates whether both operands are true.
The || (logical OR) operator indicates at least one of the operands are true. And...what an operand is?
when you use a simple expression, like x == 1, that is considered an operand.
if you use brackets, everything inside the brackets is consider one operand, no matter how complex it is inside. So you can group conditions.
so   x == 1 && ( y == 1 || y == 2 )  will evaluate if the first operand x == 1 is true,  and the second operand, the whole ( y == 1 || y == 2 ) is true.
To know if something inside brackets is true or false, whatever it has inside is evaluated as an independent expression.
so, we have to operands. First, it will check if x == 1 is true. If it is false, it wont check what is inside the brackets, it doesnt matter since anyways the first condition is not fulfilled. if x==1, we can check the second operand:
so it will check the expresions inside the brackets, this is, y == 1 || y == 2, and if some is true, then  ( y == 1 || y == 2 ) is true operand, and the whole expression will be x == 1 && true, so basicaly it now depends on x,  and if none inside the brackets is true, then ( y == 1 || y == 2 ) is a false operand, and the whole operation will be x == 1 && false so everything is false
If you dont use brackets, you can achieve the same results, but you will have to check the precedence rules, that will be harder to keep in mind at the begining
I recommend that before you learn a programing language, you read a few tutorials about  boolean algebra and logic. Everything will be easier after that.
Answer: Brackets don't make a difference. If you want to read more about it, look at the wikipedia page of Boolean logic:
http://en.wikipedia.org/wiki/Boolean_algebra
Answer: in first example
the left side is evaluated first. if that is true it looks to the right side which is the bracket so it goes to the bracket and evaluates it and than checks against left side.
the second example will not work as you want because if x!=1 it will still go to right side to look for y==1 and you can end up with true.

php AND, OR operators in If statements


Survival Curve vs Cox PH hazard levels discrepancy

Question: This is a very high level question, hope it's not too general for this forum:
Is it possible to have a greater risk (hazard) for a factor variable in a COXPH regression for one level against another one, while at the same time when plotting a survival (Kaplan Meier) curve, we have the opposite (i.e. the same factor level with the higher risk also having a better survival probability on the curve than the other level).
Note1: proportionnal assumption is met and p-value are significant.
Note2: the 2 variable are very similar, either be the survival curve or the risk levels (small differences in both case).
Thank you.
Comment: I think your situation is impossible,a better "survival" probability means lower risk of "event".There might be something wrong with your code or you need to understand the meaning of "event" and "censor",.
Comment: Hello, thanks for your reply. Yes I understand it's "impossible", hence my question. I'll keep digging, wish I could share my data. If I find a solution I'll post it here.
Answer: To everyone it may help, I solved my issue.
My mistake was a bad understanding of how to check for a violation of the proportionnal assumption. I hastily concluded it was good by looking at q-plots of my continuous and categorical variable (the p-value of the proportionnal test didn't apply in my case since my sample is very large), but since these plots were very cluttered, it couldn't help me on that matter.
However I learned, thanks to the below link that one can check for proportionnal hazard violation in a different way by also checking Kaplan Meier curves, and some of them in my case are crossing each other, making invalid the cox regression results.
http://statistics.ats.ucla.edu/stat/examples/asa/test_proportionality.htm
Thank you.


Why is the gradient of this determinant, $\det(I - AA^\dagger)$, off by factor of $2$?

Question: I have banged my head on this for a couple of hours and I can't find what's wrong:
$$
\begin{align}
\frac{\partial}{\partial A_{pq}}\det(\mathbb{1} - AA^\dagger) &= \det(\mathbb{1} - AA^\dagger)\mathrm{tr}\left[(\mathbb{1} - AA^\dagger)^{-1}\frac{\partial(\mathbb{1} - AA^\dagger)}{\partial A_{pq}}\right]\\
&=\det(\mathbb{1} - AA^\dagger)\sum_{mnk}(\mathbb{1} - AA^\dagger)^{-1}_{mn}\frac{\partial(\mathbb{1}_{nm} - A_{nk}A^\dagger_{km})}{\partial A_{pq}}\\
&= \det(\mathbb{1} - AA^\dagger)\sum_{mnk}(\mathbb{1} - AA^\dagger)^{-1}_{mn}\delta_{np}\delta_{kq}(-A^\dagger_{km})\\
&=\det(\mathbb{1} - AA^\dagger)\sum_{m}(\mathbb{1} - AA^\dagger)^{-1}_{mp}(-A^\dagger_{qm})\\
&=-\det(\mathbb{1} - AA^\dagger)(\mathbb{1} - AA^\dagger)^{-T}A^*
\end{align}
$$
When I try it out numerically though, it's off by a factor 2:
<code>def det(A):
    return np.linalg.det(np.identity(A.shape[0]) - A @ np.conj(A.T))

def ddet(A):
    return - det(A) * np.linalg.inv(np.identity(A.shape[0]) - firstname.lastname@example.com(A.T)).T @ np.conj(A)

A1 = np.array([[0.1, 0.2],[0.2, 0.3]])
A2 = np.array([[0.1, 0.2],[0.2, 0.3+delta]])
delta = 1e-6

np.isclose((det(A2) - det(A1))/delta, 2*ddet(A1)[1,1])
>>> True
</code>
When the entries of $A$ are complex it's even more wrong, but let's solve the 2x issue first.
Comment: Does $\dagger$ denote the Hermitian transpose? Is $\mathbb{1}$ the identity matrix or a matrix of $1$s?
Comment: [Related](https://math.stackexchange.com/a/1797287/339790)
Comment: Are you sure you're not forgetting to multiply by 2 from differentiating the quadratic $A_{pq}^2$ for the chain rule?
Comment: I thought about that, but I'm computing $\frac{\partial}{\partial A}$ independently from $\frac{\partial}{\partial A^*}$ (as per Wirtinger calculus), so the expression in the determinant is linear in $A$.
Answer: For typing convenience define the variables
$$\eqalign{
P &= \Big(I-AA^H\Big) = P^H \quad\implies\quad P^T=P^*\\
\phi &= \det(P)\\
}$$
and denote the trace as a colon product
$$A:B = {\rm Tr}(A^TB)$$
Then calculate the Wirtinger differential via Jacobi's formula
$$\eqalign{
d\phi &= \phi\;P^{-T}:dP \\
  &= -\phi\;P^{-T}:\big(dA\,A^H+A\,dA^H\big) \\
  &= -\phi\;P^{-T}A^*:dA -\phi\;A^TP^{-T}:dA^H \\
  &= -\phi\;\big(P^{-1}A\big)^*:dA -\phi\;\big(P^{-1}A\big):dA^* \\\\
}$$
When $A$ is real, $\,A^*=A,\,$ $P^*=P\,$ and
$$\eqalign{
d\phi &= -2\phi\;\big(P^{-1}A\big):dA \\
\frac{\partial \phi}{\partial A} &= -2\phi\;P^{-1}A \\
}$$
In the general case
$$\eqalign{
\frac{\partial \phi}{\partial A} &= -\phi\;\big(P^{-1}A\big)^* \\
\frac{\partial \phi}{\partial A^*} &= -\phi\;P^{-1}A \\\\
}$$
NB:   In order to test the complex case, your Python code should estimate the total differential instead of the gradient, i.e. by validating expressions such as the following
$$\eqalign{
A &= A_1 \quad\qquad&\implies\quad dA = A_2-A_1 \\
P &= I - AA^H \quad\qquad&\implies\quad dP = -dA\,A^H-A\,dA^H \\
}$$
$$\eqalign{
\frac{-d\phi}{\phi}
=
\frac{\det(P)-\det(P+dP)}{\det(P)}
  \quad \overset{?}{=} \quad
{\rm Tr}\Big(\big(P^{-1}A\big)^HdA
 +
\big(P^{-1}A\big)^T\,dA^*\Big) \\
}$$
If you insist on using the gradient, then you must use multivariate Wirtinger derivatives in order to code the correct expression.


Compiler diverge on overload resolution using argument-dependent lookup and constraint expression

Question: In the following program template function f calls overloaded template function p and one of the overloads is declared after f, but as far as I understand it must be found at the point of instantiation using argument-dependent lookup:
struct A{};

constexpr bool p(auto) { return false; }
constexpr bool f(auto v) { return p(v); }
constexpr bool g() { return f(A()); }
constexpr bool p(auto) requires true { return true; }

static_assert( f(A{}) );

The static_assert passes in MSVC and in GCC only with -O0 option, and it fails in Clang and in GCC with -O1 and higher optimization options. Online demo: https://godbolt.org/z/crvE5azWe
Is there any undefined behavior in the program, and if not, which compiler is correct here?
Comment: You are all right, I wasn't paying attention. I think these are not solutions: https://godbolt.org/z/Gqa1z319P and behavior is still inconsistent. I deleted my answer.
Comment: I heard a rumor that `requires true` is ill formed, no diagnostics required. If you replace `true` by something that depends on the argument type, such as `sizeof(&arg)`, then the behavior is consistent. https://godbolt.org/z/f1GxP3Y3a
Comment: @alfC, thanks, but in your modification all compilers complain about invalid program syntax: `error: expression must be enclosed in parentheses`
Comment: Sorry for the confusion, that was not the point I wanted to make. https://godbolt.org/z/snG5nTdjc
Comment: @alfC, now GCC complains `error: constraint expression does not have type 'bool'`
Answer: The declarations of the p templates are IFNDR (ill-formed, no diagnostic required) per https://eel.is/c++draft/temp#over.link-7.sentence-2:
The two declarations have corresponding signatures (which doesn't consider trailing requires-clauses), but they do not correspond because that does require equivalent trailing requires-clauses. If they did correspond however, then the declarations would (re-)declare the same function template.
Also, the two function templates accept and satisfy the same template argument lists. requires true does not constrain the template in any form.
Two function template declaration can't be "functionally equivalent" but not "equivalent" (in which case they would declare the same function template). If the templates have the exact same signature and accept/satisfy the same template arguments, then they should be the same template and to make sure that they can be recognized as same template, their declarations should have the exact same form (except for template parameter names).

Even if you resolve that issue by making the second overload not functionally equivalent, you still have the following problem:
g is not a template, so the use of f(A()) in its definition already causes instantiation of the specialization f. Since this is earlier than the instantiation of the same specialization that would be required from static_assert( f(A{}) ); the latter doesn't matter.
There are two points of instantiation for a function template specialization: Either directly after the declaration from which the instantiation is required, or at the end of the translation unit.
At the first point of instantiation the second p overload hasn't been declared yet. Therefore it can't be found by name lookup. At the second point of instantiation the second p has been declared and, as you are correctly arguing, should be found by ADL and used for the call.
So, the overload resolution gives different results depending on the point of instantiation. If two points of instantiation of a template specialization cause the meaning of the program to change, then the program is IFNDR as well.
In other words, you are not allowed to add an overload that would have been chosen by overload resolution via ADL after the point where the overload resolution is first required. All functions that should be connected to the class via ADL should be declared before any use of the class (typically in a header for the class).
Comment: @Fedor See edit for the second problem.
Comment: @Fedor The second problem mentioned in my answer doesn't apply there because the argument type is `int`, so that ADL isn't done and the second overload can't be considered at either point of instantiation. The first problem still applies and makes it in my opinion IFNDR. The relevant wording in the standard changed a lot though and the sentence I quote was added only with [CWG 2603](https://cplusplus.github.io/CWG/issues/2603.html). I think it was IFNDR in the C++20 wording as well though.
Comment: Thanks. I changed the second overload to `constexpr bool p(A) { return true; }` so the referenced item does not apply any more, but the result is the same: https://godbolt.org/z/nzYYehGon
Comment: There is a similar issue fixed recently in Clang: https://github.com/llvm/llvm-project/issues/50644#issuecomment-1915791545 Does the example from there also IFNDR (so the fix was not necessary)?


Type '{ uri: string | null | undefined; }' is not assignable to type 'ImageSourcePropType | undefined'

Question: I am new to typescript and getting the error described the title on the react-native-elements component.
Here is my component:
export type Props = {
  navigation: any;
  chats: Array<string>;
};

export interface ChatProps {
  id: string;
  chatName: string;
}

export interface AvatarSource {
  uri?: string | undefined;
}

const HomeScreen: React.FC<Props> = ({ navigation }) => {
  const signOutUser = () => {
    auth.signOut().then(() => {
      navigation.replace("Login");
    });
  };

  useLayoutEffect(() => {
    navigation.setOptions({
      headerLeft: () => (
        <View style={{ marginLeft: 20 }}>
          <TouchableOpacity onPress={signOutUser} activeOpacity={0.5}>
            <Avatar
              rounded
              source={{
                uri: auth?.currentUser?.photoURL,
              }}
            />
          </TouchableOpacity>
        </View>
      ),
      headerRight: () => (
        <View>
          <TouchableOpacity>
            <AntDesign name="camerao" size={24} color="black" />
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => navigation.navigate("AddChat")}
            activeOpacity={0.5}
          >
            <SimpleLineIcons name="pencil" size={24} color="black" />
          </TouchableOpacity>
        </View>
      ),
    });
  }, []);

  const enterChat = ({ id, chatName }: ChatProps) => {
    navigation.navigate("Chat", {
      id,
      chatName,
    });
  };

  return (
    <SafeAreaView>
      <ScrollView style={styles.container}>
        {chats.map(({ id, data: { chatName } }) => {
          return (
            <CustomListItem
              key={id}
              id={id}
              chatName={chatName}
              enterChat={enterChat}
            />
          );
        })}
      </ScrollView>
    </SafeAreaView>
  );
};

The typescript error is on:
source={{ uri:auth?.currentUser?.photoURL}}
I am still unsure on how to define the type here, I have tried above as you can see but don't know what is the next step for it to work.
Any idea on how to define this / correct it in Typescript?
Comment: Please provide a [mre] suitable for demonstrating your issue when pasted as-is into a standalone IDE.  Undeclared/unimported types/values should be fixed.  Ideally, unless you want to tag this with react or react-native-elements, you should remove dependencies on these third party packages.
Answer: I not know if understand correctly your question, im needed more details.
But, I understand that you have typescript problem in source property in Avatar component, so maybe you can create a variable with concatenated value of uri, because the value of uri expected is of type string and add on Props type with the following:
export type Props {
  navigation: any;
  chats: Array<string>;
  url: string;
}

const url = auth?.currentUser?.photoURL;

But I would need to understand what exactly this Avatar component is about. Assuming the Avatar component maybe use ImageBackground with ImageSourcePropType  type, like this:
// Avatar Component Example
import { ImageBackground, ImageSourcePropType } from 'react-native';

export function Avatar({ ...rest }: ImageSourcePropType) {
  <ImageBackground {...rest}>
   { /** Some code here **/}
  </ImageBackground>
}

This is just an idea, hope it helps.
Comment: This might be better suited as a [comment](https://stackoverflow.com/help/privileges/comment). Typically answers to incomplete questions are incomplete themselves.


Cannot let go of an object when in another object's collider

Question: I have some fairly simple code that allows me to grab, move, and let go of objects (in this case, the "LoopCubes" are the only things I want to be able to pick up:
public void grab(object sender, ClickedEventArgs e)
{
    if ((objectTouching != null) && objectTouching.CompareTag("LoopCube") == true)
    {
        objectTouching.gameObject.transform.SetParent(gameObject.transform);
    }
}

//Letting go of grip
public void releaseGrab(object sender, ClickedEventArgs e)
{
    if (objectTouching != null)
    {
        objectTouching.gameObject.transform.parent = null;
    }
}

This works as intended. However, a problem arises when I want to let go of the cube when the controller/cube are within a box collider (marked as a trigger). I can't let go and the cube becomes 'stuck' to the controller. What am I doing wrong?
Comment: What does that "stuck" mean ? You assign `null` but you still can reference one, or you expect immediate release of memory once `null` is assigned ?
Comment: By 'stuck' I mean I cannot let go of the cube, even by pressing and releasing the grip. I'm afraid I don't understand your second question.
Comment: Well, it's hard to deduct from the code provided what's happening there. You may have temp variables that are still pointing to the cube, and resetting to `null` parent has not any effect on them, hence you continue using them like before. Just an example of what may happen.
Comment: Ah, I understand. @Fredrik mentioned something similar below, and I think that sounds like what's happening.
Answer: Since I can't see your code I'm going to make some assumptions.
This is what I'm guessing is happening:

Enter a trigger and set it to objectTouching
Grab objectTouching & move around
Enter another trigger, which sets objectTouching to something else, still having the previous objectTouching grabbed
Release, which tries to release the current objectTouching, which is the last trigger you entered - not the grabbed object.
Comment: In terms of grabbing itself, that's all there is. The other code I have is for entering/exiting the trigger on the controller. I'll edit my question to include that code.
Comment: Oh sorry, I now see that you ARE showing the grabbing code. After your `SetParent(transform)` you should save _that_ object, `currentHeldObject = objectTouching` where currentHeldObject is a class GameObject variable
Comment: Thanks! I'll give that a shot and mark your answer as successful if it works out.
Comment: That seems very plausible! Can you think of a way around this?
Comment: Show me the grabbing code! What i'd do is to simply reference the grabbed object instead of the last touched object when releasing.
Comment: Yes, sorry - I wrote too hasty :)
Comment: ...and it worked! Much appreciated. That's saved me a lot of headache :)


Why is my Multi-Step form going back to the first page instead of moving to the third?

Question: I've buit a multi-step (3 steps) form in form api, and going from step one to two works fine, but going from 2 to three just brings me back to step one.
function multi_step_menu() {
  $items = array();

  $items['multi-steps'] = array(
    'title' => 'Multi Steps',
    'description' => 'Multi Steps',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('step_one_form'),
    'access callback' => TRUE,
  );

  return $items;
}

function step_one_form($form, &$form_state) {

  // Display page 2 if $form_state['page_num'] == 2
  if (!empty($form_state['page_num']) && $form_state['page_num'] == 2) {
    return step_two_form($form, $form_state);
  }

  // Otherwise we build page 1.
  $form_state['page_num'] = 1;

  $subschoices = array(1 => t('Day'), 2 => t('Month'), 3=> t('Year'));
 $form['subscription_choice'] = array(
   '#type' => 'radios',
   '#title' => t('Subscriptions'),
   '#options' => $subschoices,
  '#description' => t('Choose your subscription type.'),
  '#required' => TRUE,
 );

  $form['next'] = array(
    '#type' => 'submit',
    '#value' => 'Purchase >>',
    '#submit' => array('step_one_next_submit'),
    '#validate' => array('step_one_next_validate'),
  );

  //  syslog(1, print_r($form, true));

  return $form;
}

function step_two_form($form, &$form_state) {

  // Display page 3 if $form_state['page_num'] == 3
  if (!empty($form_state['page_num']) && $form_state['page_num'] == 3) {
    return step_three_form($form, $form_state);
  }

  $form['description'] = array(
    '#type' => 'item',
    '#title' => t('Purchase Subscription'),
  );

  $form['clientReference'] = array(
    '#name' => 'clientReference',
    '#type' => 'hidden',
    '#value' => $account->uid,
  );

  $form['clientType'] = array(
    '#name' => 'clientType',
    '#type' => 'hidden',
    '#value' => 'individual',
  );

  $form['recurrentDebitExecutionDate'] = array(
    '#name' => 'recurrentDebitExecutionDate',
    '#type' => 'hidden',
    '#value' => date('m/d/Y'),
    '#attributes' => array(
      'id' => array('recurrentDebitExecutionDate'),
    ),
  );

  $form['recurrentDebitAmount'] = array(
    '#name' => 'recurrentDebitAmount',
    '#type' => 'hidden',
    '#value' => $recurrentDebitAmount,
    '#attributes' => array(
      'id' => array('recurrentDebitAmount'),
    ),
  );

  $form['recurrentDebitLabel'] = array(
    '#name' => 'recurrentDebitLabel',
    '#type' => 'hidden',
    '#value' => $recurrentDebitLabel,
    '#attributes' => array(
      'id' => array('recurrentDebitLabel'),
    ),
  );

  $form['name']['firstName'] = array(
    '#name' => 'firstName',
    '#type' => 'textfield',
    '#title' => t('First Name'),
    '#maxlength' => 20,
    '#size' => 21,
    '#required' => TRUE,
  );

  $form['name']['lastName'] = array(
    '#name' => 'lastName',
    '#type' => 'textfield',
    '#title' => t('Last Name'),
    '#maxlength' => 20,
    '#size' => 21,
    '#required' => TRUE,
  );

  $form['phoneNumber'] = array(
    '#name' => 'phoneNumber',
    '#type' => 'textfield',
    '#title' => t('Phone Number'),
    '#maxlength' => 13,
    '#size' => 13,
    '#required' => TRUE,
  );

  $form['address']['line1'] = array(
    '#name' => 'line1Inv',
    '#type' => 'textfield',
    '#title' => t('Address'),
    '#required' => TRUE,
  );

  $form['address']['line2'] = array(
    '#name' => 'line2Inv',
    '#type' => 'textfield',
  );

  $form['city'] = array(
    '#name' => 'cityInv',
    '#type' => 'textfield',
    '#title' => t('City'),
    '#required' => TRUE,
  );

  $form['postalCode'] = array(
    '#name' => 'postalCodeInv',
    '#type' => 'textfield',
    '#title' => t('Postal Code'),
    '#required' => TRUE,
  );

$form['countryCode'] = array(
    '#name' => 'countryCode',
    '#type' => 'textfield',
    '#title' => t('Country Code'),
    '#required' => TRUE,
  );

  $form['displayedCost'] = array(
    '#title' => t('Cost'),
    '#markup' => $recurrentDebitAmount . "
",
  );

  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('<< Back'),
    '#submit' => array('step_two_back'),
    '#limit_validation_errors' => array(),
  );

  $form['next'] = array(
    '#type' => 'submit',
    '#limit_validation_errors' => array(

    ),
    '#value' => 'Checkout >>',
    '#submit' => array('step_two_next'),
    '#validate' => array('step_two_validate'),
  );

  return $form;
}

function step_three_form($form, &$form_state){

  $form['slimpay'] = array(
    '#type' => 'submit',
    '#value' => t('Slimpay'),
    '#submit' => array('step_three_one_submit'),
  );

  $form['ogone'] = array(
    '#type' => 'submit',
    '#value' => t('Ogone'),
    '#submit' => array('step_three_two_submit'),
  );

  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('<< Back'),
    '#submit' => array('step_three_back'),
    '#limit_validation_errors' => array(),
  );

  return $form;
}

function step_one_validate($form, &$form_state) {

}

function step_two_validate($form, &$form_state) {

}

function step_one_next_submit($form, &$form_state{
  $form_state['page_values'][1] = $form_state['values'];

  if (!empty($form_state['page_values'][2])) {
    $form_state['values'] = $form_state['page_values'][2];
  }

  // When form rebuilds, it will look at this to figure which page to build.
  $form_state['page_num'] = 2;
  $form_state['rebuild'] = TRUE;
}

function step_two_next_submit($form, &$form_state) {
  syslog(1, $form_state['values']);
  $form_state['page_values'][2] = $form_state['values'];
syslog(1, "page_values" . print_r($form_state['page_values']));
  if (!empty($form_state['page_values'][3])) {
    $form_state['values'] = $form_state['page_values'][3];
  }

  $form_state['page_num'] = 3;
  $form_state['rebuild'] = TRUE;
}

function step_two_back($form, &$form_state) {
  $form_state['values'] = $form_state['page_values'][1];
  $form_state['page_num'] = 1;
  $form_state['rebuild'] = TRUE;
}

function step_three_back($form, &$form_state) {
  $form_state['values'] = $form_state['page_values'][2];
  $form_state['page_num'] = 2;
  $form_state['rebuild'] = TRUE;
}

function step_three_one_submit($form, &$form_state) {

  $page_one_values = $form_state['page_values'][1];
  $page_two_values = $form_state['page_values'][2];

  $form_state['redirect'] = 'node';
}

function step_three_two_submit($form, &$form_state) {

  $page_one_values = $form_state['page_values'][1];
  $page_two_values = $form_state['page_values'][2];

  $form_sate['redirect'] = 'node';//ogone
}

Comment: where is the step_two_next function?
Comment: @SibirajPR It's step_two_next_submit
Answer: Once you correct a few of the obvious submit handler names in that code and run it, the issue eventually boils down to checking if your $form_state['page_num'] is 2 in step_one_form(). When you attempt to go to step 3, the condition in step_one_form() fails (because page_num is 3), so step_two_form() never gets called (to eventually call step_three_form).
A few other comments about your code:

You should be prefixing all functions in your module with the module name. This is to avoid namespace collisions, which can sometimes be obvious to fix and other times, be very frustrating.
With a multistep form, it may be easier to read by having one function that calls the function of each step. See this blog post for an example of a multistep form.
instead of using the syslog PHP functions, install the devel module and use dpr(). It's more drupaly, and easier to read the output of arrays and objects with that function.
Comment: Thank you, I didn't realize I had to do this in step one.

As for the naming conventions, I edited them because the function names I have are very long due to the module name so I made them smaller to post here.

I will look to the dpr() function, thanks.
Comment: @CR47 It's popular here to replace long module names with "mymodule", like `function mymodule_step_two_form($form, &$form_state)` - it shows you know about prefixing, you care, and you don't want to post module name here ;)
Answer: In your code you can make a fix with step_one_form function.
function step_one_form($form, &$form_state) {

 // Display page 2 if $form_state['page_num'] == 2
 if (!empty($form_state['page_num']) && $form_state['page_num'] == 2) {
   return step_two_form($form, $form_state);
 }
 if (!empty($form_state['page_num']) && $form_state['page_num'] == 3) {
   return step_three_form($form, $form_state);
 }


Meaning of $\{1,2,4\}^5$ in linear algebra

Question: I encountered the expression $\{1,2,4\}^5$ in the context of linear algebra. Could someone please explain what this means.
Comment: Set of all 5-tuples, each co-ordinate is from this set ?
Answer: It is the fifth Cartesian power of the set.
As you know (now) the Cartesian square of a set is the Cartesian product of the set with itself.   The set of all pairs whose members are elements of the set $\{1,2,4\}$.
$\{1,2,4\}^2 = \{1,2,4\}{\times}\{1,2,4\} = \{(1,1), (1,2), (1,4), (2,1), (2,2), (2,4), (4,1), (4,2), (4,4)\}$
The Cartesian power to the fifth exponent is defined in the same way.   The set of all quintuples whose members are elements of the set  $\{1,2,4\}$.   There are $3^5$ quintuples and I'm not going to list all $243$ of them.   You grok the idea.
$\{1,2,4\}^5 = \{1,2,4\}{\times}\{1,2,4\}{\times}\{1,2,4\}{\times}\{1,2,4\}{\times}\{1,2,4\} \\ \qquad\qquad = \{(1,1,1,1,1), (1,1,1,1,2), \ldots, (4,4,4,4,4)\}$


How to force authentication in Camunda Java api?

Question: We have a Spring based application deployed in Camunda BPM. We have exposed some REST services here using Camunda JAVA api. We did this for some specific requirements where we did not have a Camunda REST api available. These custom REST services are running without authentication & authorization. I am able to create/complete/delete processes & tasks through these services without authenticating a valid user. I want to know how to force the Camunda Java apis to look for an authenticated user before executing. I am using Camunda BPM 7.3.
Answer: I found the answer. The authentication in this case is in our hands. We have to authenticate user any way we want and then set the authenticated userId in identityService. If the authenticated user is null then authroization check is also skipped. Hence my code was working without authentication.
Check the following code in AuthorizationManager class -
<code>    public void checkAuthorization(List<PermissionCheck> permissionChecks) {
        Authentication currentAuthentication = getCurrentAuthentication();
        CommandContext commandContext = getCommandContext();

      if(isAuthorizationEnabled() && currentAuthentication != null && commandContext.isAuthorizationCheckEnabled()) {

      String userId = currentAuthentication.getUserId();
      boolean isAuthorized = isAuthorized(userId, currentAuthentication.getGroupIds(), permissionChecks);

        ...........
        .......
</code>
As is evident from the IF condition, if the currentAuthentication is null the isAuthroized() method won't be called.
Another thing to remember is in bpm-platform.xml where we have defined the ProcessEngineConfiguration we need to set authorizationEnabled property as true.


How to move significant level on plot to the top?

Question: I have this barplot using ggpubr with the code
visualiseplot <- visualisepwc %>% add_xy_position(x = "Condition")
visualiseplot3 <- ggbarplot(data_sum, x = "Condition", y = "Q70.7", fill = "Condition") +
  stat_pvalue_manual(visualiseplot, hide.ns = TRUE)
visualiseplot3

My graph I got from it looks like this:

I got a message saying I can only have a link to the picture so I hope you can see the image, but if you can't basically the significance levels are at the bottom of the graph and overlap, and I would like it to be above the graph at the top.
this is an example of how it should look but using a boxplot - it seems to work with boxplot but not barplot :

Any recommendations for what I should do? -
Answer: Without your data and the visualisepwc output, it is difficult to replicate the issue. However, you could avoid the issue altogether by using the ggsignif package. I've tried to replicate the aesthetics of the ggpubr plot as much as possible.
library(ggplot2)
library(ggsignif)

## Fictional Data (your data_sum)
data_sum <- data.frame("Condition"=c("Fictional","Socratic","Textbook"),"Q70.7"=c(52,45,20))

ggplot(data_sum,aes(x=Condition,y=Q70.7,fill=Condition))+ # map data
  geom_bar(stat="identity",color="black")+ # plot bars
  geom_signif(comparisons =
    list(c("Fictional","Textbook"),c("Socratic","Textbook")), # indicate which pairs to connect with significance bars
          map_signif_level = TRUE,
          y_position = c(60,50), # indicate where to put the bar for each pairing
          tip_length = 0.1, # set vertical size of bars
          color="black",
          annotations = c("**","**"))+ # indicate signif level for each pairing
  theme_classic()+
  theme(legend.position = "top")

Comment: Thank you so much! For my data I just had to use the y_position = c(60,50) that you suggested and it worked perfectly!!!


Div taking all horizontal space

Question: Why?
i dint speficy the width, so it should be as big as content inside it.
#swfbox {
 padding: 10px 10px 10px 10px;
 margin: 50px auto 0px;
 background: #310600;
 border: 3px solid #4b0900;
}

i have it centered and load swf files in it, so for it to work i have to set its width to the width of the swf file, which is bad since i every file has different width.
Answer:
 elements are block-displayed elements, which means they default to 100% width unless otherwise specified.
If you want the element to expand based on its content, you might want to try setting the display property on the
 to inline (or just use a span since it's essentially an inline-div).
Edit:
I guess inline didn't work quite the way I expected, so I learned something today. What you're going to want to do instead is to set display: inline-block, but that comes with it's own set of problems.
First, according to the Quirks Mode page for the display property, IE6 and IE7 only support inline-block on elements with a natural display: inline which means you need to use  elements rather than
 elements.
Second, inline-block has its own set of quirks which you should read up on before using it, to prevent being surprised by further "gotchas". This page has a pretty good write-up on inline-block.
Comment: so how to change it to be as width as content inside it ?
Comment: @AgentConundrum yes, but not there is some padding issue.
inside swfbox i have another div, so swfbox is just to look nice, but now the top padding is non existing.
Comment: @Plaski: What padding issue are you seeing?
Comment: | |     | |
| | img | |
| |_____| |
|_________| it looks like this.
Comment: @Plaski: What image are you referring to? I'm clearly not getting the whole story here. Could you update your question with the *complete* HTML+CSS you're using? You can use jsfiddle.net if you'd like.
Comment: @Plaski: You're going to want to use `inline-block` for this, unless someone comes up with a better answer. I edited my answer to explain.
Answer: check this out for a solution: http://www.tightcss.com/centering/center_variable_width.htm
float the div that the swfs reside in (floats shrink to fit content)

Relatively position the outer float
  left:50%, so that the left edge is at
  the middle of the page. Then
  relatively position the inner float
  left:-50% to shift it exactly
  1/2 of the outer div's width to the
  left, so that it is centered.

the link gives a full explanation and example.

Div taking all horizontal space


How do I get the Unix timestamp?

Question: I want to use format_date(), but it requires a Unix timestamp and my dates are ISO.
Is there a drupal way to convert ISO date to Unix timestamp? If I use strtotime, I lose my timezone offset.
Answer: You shouldn't use format_date() anymore.  You should create a DrupalDateTime object, and then use the format() method.
$date = \Drupal\Core\Datetime\DrupalDateTime::createFromFormat('c', $my_iso_8601_date);
$my_rfc2822_string = $date->format('r');

Comment: @Greg My bad, 'c' is not an accepted format for http://php.net/manual/en/datetime.createfromformat.php; it will work if you build the format string from the parts listed there.
Comment: I can't get it to work. This is what I'm passing: 2016-06-07T14:00:00, and I'd like to get this in return (except have it go through any timezone conversions): 1465308000
Comment: @Greg Per spec, ISO 8601 dates have to include the time zone portion, so that doesn't comply with that format.  Try either adding the timezone to what you are passing in, or use the PHP date format placeholders to build up a format string that matches what you are passing in. `DrupalDateTime::createFromFormat` works; it's how the field storage parses data from the database, but you do have to make sure your format string works (it's also wrapper to \DateTime::createFromFormat, but takes into account Drupal TZ handling).
Comment: Thank you MPD, I went with a straight PHP solution for the time being.  I will look into the DrupalDateTime in the future though.
Comment: @mpdonadio, can you edit your answer with the updated comment ? Iso8601 should be Y-m-d\TH:i:sT (even though I still haven't got it to work)
Answer: format_date deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
It's better to do it with Drupal way, using Drupal time service:
$time_value = \Drupal::time()->getCurrentTime();
print \Drupal::service('date.formatter')->format($time_value, 'long');

Comment: Here are the available built in format other than 'long': https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Datetime%21DateFormatter.php/function/DateFormatter%3A%3Aformat/8.2.x
Answer:
I can't get it to work. This is what I'm passing: 2016-06-07T14:00:00,
  and I'd like to get this in return (except have it go through any
  timezone conversions): 1465308000

It's simple - you can use standard getTimestamp() function within the DrupalDateTime object:
$date = '2016-06-07T14:00:00';
$dateTime = new DrupalDateTime($date, 'UTC');
$timestamp = $dateTime->getTimestamp();

Comment: This should be the right answer, thx!!
Answer: In Drupal 9 you can get the current timestamp using the following
use Drupal\Core\Datetime\DrupalDateTime;
$current_timestamp = (new DrupalDateTime())->getTimestamp();

DrupalDateTime is a wrapper over PHP DateTime object.
Answer: This is what I ended up using.  I would like to experiment with MPD's solution more and will up date this question if I do.
$start_date = new DateTime($my_IOS_date, new DateTimeZone('UTC'));
$start_date->setTimezone(new DateTimeZone('America/New_York'));

$my_timestamp = $start_date->getTimestamp();

How do I get the Unix timestamp?


preg_replace problem

Question: I'd like to match and extract variables from: {{variable:int}}

variable would be anything a-z
: is a separator
int would be an integer 0-9

Curretly i have: preg_replace('!\{\{(\S+)\}\}!', "$1", $string)
which does only half the job, i still have to split by :.
Thank you!
Answer: You need a non-greedy match (.*?): preg_replace('!\{\{(.*?):(\d)\}\}!')
Answer: Use
{{([a-zA-Z]+):(\d+)}}

$1 will contain the captured variable, $2 will contain the captured integer
Explanation
{{([a-zA-Z])+:(\d+)}}

[a-zA-Z]+ means atleast one more alphabets (small or caps)
followed by a ":"
followed by atleast one or more digits (0-9)
Answer: If you want to extract the name/value, I think you want to use preg_match.
preg_match('!\{\{(.*?):(\d)\}\}!', $string, $matches);
$varname = $matches[1];
$val = $matches[2];

Comment: Suited my needs best. Thank you all for replying!

preg_replace problem


Select ID in table

Question: I have this code
<% foreach (var item in Model.List) { %>

        <%: item.LastName %>
        <%: item.FirstName %>
        <%: item.IsEnable %>
        Edit
        Detail
        Delete

<% } %>

It's not in the code but I have an "Item.Id", it's not place anywhere because I don't know where place it ;-). I'd like when I click on the "Edit" hyperlink get the id (item.Id) of the current line.
Any idea ?
Thanks,
Answer: <a href="#" class="CustomerEdit" id="edit_<%: item.Id %>">Edit

and then read the id:
$(function() {
    $(".CustomerEdit").click(function() {
        var id = this.id.replace(/edit_/, '');
        alert(id);
        return false;
    });
});

Answer: You could just add a Javascript function at that point
For instance
<a href="#" class="CustomerEdit" onclick="getdata(<%: item.Id%>); return false;">Edit

If Id=11 This will call getdata(11) when you click on Edit. What you do in getdata then, it's up to you!
EDIT: actually, you should probably just use a
 instead of  if those link don't actually link to anything.
Answer: <% foreach (var item in Model.List) { %>
  <tr id="<%: item.Id %>">
    <%: item.LastName %>
    <%: item.FirstName %>
    <%: item.IsEnable %>
    Edit
    Detail
    Delete

<% } %>

NOTE: Untested, but I think that should work.

Select ID in table


Passar lista de objetos entre arquivos

Question: Como passar uma lista de objetos através de dois arquivos JavaScript?
Tenho uma lista:
var elementsList = [];

E esta lista é populada com N objetos:
var oElement = {
    elem: "",
    emin: 0.0000,
    emax: 0.0000
}

Eu preciso passar isto tudo para uma janela modal:
var oElem = {
            "id": "FCADELEM",
            "data-height": "558",
            "data-width": "320",
            "data-name": "Elementos Químicos",
            "data-url": "FCADELEM.aspx?returnToForm=ifr_FCADQUAL",
            "data-module": "Elementos Químicos",
            "attr": function (param) {
                return this[param];
            }
        }
        parent.createDialog(oElem);

Como posso passar esta lista de objetos para a outra janela sem usar o C#?
INFORMAÇÕES COMPLEMENTARES

As duas janelas em questão são iframes Modal, da biblioteca jQuery.
Não é possível armazenar os dados no js da página 'mãe'.
As duas janelas são do mesmo domínio.
Comment: O seu modal é uma iFrame? se não, então está tudo disponível. Pode ter de ajustar o escopo, mas parece-me simples de resolver. Mais uma duvida. Qual é a relação entre os dois? Por exemplo o 1o el da array tem a ver com que parte do objeto?
Comment: William, com os detalhes que faltavam à pergunta vai ser possível responder com a solução. Pode acrescentar esta informação na pergunta também para ficar mais completa.
Comment: Não percebo o seu problema. Pode explicar melhor? A array e o objeto estão em ficheiros/páginas diferentes? em diferentes momentos?
Comment: E basicamente, eu abro uma janela modal ao clicar em um botão, parent.createDialog(oElem); cria o modal, e eu preciso desta lista dentro do JS do modal, que devo abrir.
Comment: A janela de onde vem os dados também é um iframe, não é possível armazenar na pagina pai. Então, teoricamente, é como se fosse de uma página para outra.
Comment: Ok, e a iFrame está no mesmo domínio? e já agora, usa alguma biblioteca como jQuery ou MooTools?
Comment: Sim, no mesmo domínio, uso jQuery.
Comment: William, coloquei uma resposta. Não sei qual é o modal que usa, se não fôr o do jQuery UI diga qual é que eu posso ajustar a resposta.
Answer: Para aceder por exemplo a uma função dentro de uma iFrame no mesmo dominio pode fazer assim:
var iFrame = $('#myIframe')[0].contentWindow;
iFrame.receberDadosExternos('Olá!!');

Isto implica que haja uma função dentro do iFrame com esse nome e que esteja no escopo global.
Exemplo:
function receberDadosExternos(dados) {
    alert(dados);
}

Exemplo ao vivo
No exemplo no jsFiddle que coloquei em cima uso este código que corre só quando o dialog abre:
$("#dialog").dialog({
    autoOpen: false,
    modal: true,
    height: 600,
    open: function (ev, ui) {
        var iFrame = $('#myIframe')[0].contentWindow;
        iFrame.receberDadosExternos('Olá!!');
    }
});

Mas pode chamar a função quando quiser e passar o que quiser para dentro dela.
No caso de querer o contrário, ie chamar uma função de dentro da iFrame para a janela "mãe" pode usar javascript simples, ou seja:
window.parent.nomeDaFuncao();

Answer: Obrigado pela colaboração Sérgio, ajudou bastante para o desenrolar da questão, mas tive que fazer algumas adaptações, pois a lista de objetos é um pouco mais complexa do que uma string, por exemplo..
A resolução, se deu da seguinte forma:
Pensei em usar PostMessage, mas para isso precisaria que o iframe modal estivesse aberto, primeiro passo então, criar o modal.
No modal recém criado, volta ao iframe anterior, e recolhe o objeto. Chamamos a função getItem() no onload.
function getItem() {
    try {
        var returnToUrl = "FCADQUAL.aspx";
        var msgAddr = window.location.protocol + "//" + window.location.host + returnToUrl;
        var o = parent.document.getElementById("ifr_FCADQUAL");
        o.contentWindow.postMessage("100;0", msgAddr);
    } catch (e) {
        Save Exception();
    }
}

No iframe anterior então, recebe a mesagem post, e adiciona o objeto ao parametro, e o manda de volta:
window.addEventListener("message", receiveMessage, false);

function receiveMessage(e) {
    try {
        //url que verifica se post message é valido
        var url = window.location.protocol + "//" + window.location.host
        //testa se origem do post é do mesmo dominio
        if (e.origin !== url)
            return;
            var sData = e.data.split(";")

            //Solicita informações do item para a tela de informações diversas
            sendInfoDiver();

    } catch (e) {
        Save Exception();
    }
}

function sendInfoDiver() {
    try {
        var returnToUrl = "FCADELEM.aspx";
        var msgAddr = window.location.protocol + "//" + window.location.host + returnToUrl;
        var o = parent.document.getElementById("ifr_FCADELEM");
        o.contentWindow.postMessage(elementsList, msgAddr);
    } catch (e) {
        Save Exception();
    }
}

Depois, já na tela modal que recem foi aberta, recebe o objeto e inicia o tratamento.
window.addEventListener("message", receiveMessage, false);

function receiveMessage(e) {
    try {
        //url que verifica se post message é valido
        var url = window.location.protocol + "//" + window.location.host
        //testa se origem do post é do mesmo dominio
        if (e.origin !== url)
            return;

        if (typeof e.data == "object") {
            //Recebe o objeto item e popula campos do formulário
            setData(e.data);
        }

        //Oculta a mensagem de loading
        parent.hideLoading();

    } catch (e) {
       Save Exception();
    }
}

function setData(PlReturn) {
...
}

E para mandar os dados atualizados de volta, basta fazer o caminho inverso.
Agradeço a colaboração, e fica a fonte de pesquisa para futuras dúvidas da comunidade.
Abraço
Comment: William, bom você ter respondido com detalhe. Dá para editar a pergunta coma informação que lhe faltava? assim fica mais claro para quem procurar solução para o mesmo problema.

Passar lista de objetos entre arquivos


how to print an array as a matrix in C

Question: so I´m trying to print this 2d array as a matrix and it´s not working. any hints? no matter what i change i cant get to print an all 0 3x3 matrix
    int main()
        {
        int i, j, m, n, primeira;
        int matrix[10][20];

        printf("Enter number of rows : ");
        scanf("%d", &m);
        printf("Enter number of columns : ");
        scanf("%d", &n);

        /* first input */
        printf("1 ou 0");
            scanf("%d", &primeira);
        if (primeira = 0) {
        matrix [0][0]=0;
matrix [0][1]=0;
matrix [1][0]=0;
matrix [1][1]=0;}

    /* Display the matrix */
    {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");

    return 0;
}

Comment: You obviously need some sort of loop. Have you actually attempted to code in a loop? Also, please format your code properly and provide code that has your best attempt and at least compiles.
Comment: Remember the difference between assignment with`=` and comparison for equality with `==`
Comment: so i cant just print an array?
Comment: And you also only initialize four of the 200 elements of `matrix`. Even if you change it to a 3 by 3 matrix, that will leave five elements uninitialized. Or rather, with the current assignment instead of comparison, you don't initialize *any* elements.
Answer: You would need to create a nested loop to display the matrix. If you want to display a 3x3 matrix you can run something like this.
  int matrix[3][3] = { 0 };

  /* Display the matrix */
  for (int i = 0; i < 3; i++) {
     for (int j = 0; j < 3; j++) {
        printf ("%d\t", matrix[i][j]);
     }
     printf ("\n");
  }

Answer: regarding:
printf("%d\t", matrix[i][j]);

The variables: i and j are not initialized!
Suggest:
for( int i =0; i<10; i++ )
{
    for( int j=0; j<20; j++ )
    {
        printf( "%d ", matrix[i][j] );
    }
    puts( "" );
}

as that will print all the elements of the matrix and move to a new line after printing each row of the matrix.

how to print an array as a matrix in C


How can I execute only one tab of content in Android studio?

Question: When I press tab 3, it will toast the message of tab 0, tab1, tab2, tab3.
However, it displays the correct content of tab 3.
How can I only execute the content of tab 3?  And why it will execute others pages?
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainscreen);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount()));
    mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;
    public SectionsPagerAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    } @Override
    public Fragment getItem(int position) {
        position = mViewPager.getCurrentItem();
        System.out.println("This is the currnet position : " + position);
        if (position == 0) {
            Tab0Index tab0 = new Tab0Index();
            Toast.makeText(getApplicationContext(), "tab1 active " + position, Toast.LENGTH_SHORT).show();
            return tab0;
        } else if (position == 1) {
            Tab2Top10 tab2 = new Tab2Top10();
            Toast.makeText(getApplicationContext(), "tab2 active " + position, Toast.LENGTH_SHORT).show();
            return tab2;
        } else if (position == 2) {
            Tab3UserRanking tab3 = new Tab3UserRanking();
            Toast.makeText(getApplicationContext(), "tab3 active " + position, Toast.LENGTH_SHORT).show();
            return tab3;
        } else if (position == 3) {
            Tab4Profile tab4 = new Tab4Profile();
            Toast.makeText(getApplicationContext(), "tab4 active " + position, Toast.LENGTH_SHORT).show();
            return tab4;
        } else if (position == 4) {
            Tab5Setting tab5 = new Tab5Setting();
            Toast.makeText(getApplicationContext(), "tab5 active " + position, Toast.LENGTH_SHORT).show();
            return tab5;
        }else{
           return null;
        }
    @Override
    public int getCount() {
        // Show 5 total pages.
        return mNumOfTabs;
    } }}

Answer: Don't use Toast.makeText(getApplicationContext(), "tab1 active " + position, Toast.LENGTH_SHORT).show(); in SectionsPagerAdapter . The view page already loads previous and next page when you select a page. So change toast to onResume of each fragment(Pages). for example. for Tab 1 fragment's onResume(), use below code
     @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()) {
              Toast.makeText(getApplicationContext(), "tab1 active " + position, Toast.LENGTH_SHORT).show();
           }
        }

Comment: However, I don't want the view page loads previous and next page when I select a page, is there any ways to do that?
Comment: For example, I just want to force one of the tab pages to start an intent(other activity), but not three of tabs are forced to do that.
Comment: Using ViewPager you can't do that. but you can check if your tab page is active or not by using getUserVisibleHint()


haproxy missing fetch method in ACL expression

Question: i am using these conditions in ha proxy
use_backend test if { path_beg -i /test/ } { { ssl_fc_has_crt } || { src 10.0.0.25 }  || { src 10.1.0.152 }  || { src 10.0.2.41 }  || { src 10.0.0.158}  || { src 184.108.40.206 }  || { src 18.104.22.168 } || { src 18.104.22.168 } || { src 188.8.131.52 } }

But i am seeing this error:
error detected while parsing switching rule : missing fetch method in ACL expression '{'.

Answer: Docs show { } like it could group ACLs, but doesn't elaborate on it:
A condition is formed as a disjunctive form:

   [!]acl1 [!]acl2 ... [!]acln  { or [!]acl1 [!]acl2 ... [!]acln } ...

So maybe it isn't grouping at all. All examples with {} i can see are for anonymous ACLs.
You want to combine AND with OR in one condition and haproxy isn't very helpful, but here is something that should work:
acl allowed_to_test_site src 10.0.0.25 10.0.0.24 10.1.0.152 10.0.2.41 10.0.0.158 126.96.36.199 126.96.36.199 188.8.131.52 184.108.40.206
acl allowed_to_test_site ssl_fc_has_crt
use_backend backend-sonar if { path_beg -i /test/ } allowed_to_test_site

Few points to explain here:

src IP1 || src IP2 can be declared as acl ip src IP1 IP2 and so on. such list works as multiple OR
declaring ACL multiple times works again as multiple OR
Docs say:

acl <aclname> <criterion> [flags] [operator] <value> ...
Declare or complete an access list.

which could use some more explicit explaination
3. AND is implicit
This way we get the logic of (path_beg -i /test/) AND ( ssl_fc_has_crt OR src matches one of the IPs)
Maybe one day haproxy will have better syntax for that.


Expressing each column vector of a matrix as a linear combination of Eigen vectors of that matrix

Question: Let's say we have a full rank square matrix $A$ of size $n$ and we have found the eigenvectors of the matrix through eigen-decomposition/SVD.
Here, $A = [ V_1 , V_2 , V_3 , \ldots, V_n ]$ , where $V_i$ is a vector of size $n\times 1$.
How can I express $V_i$ as a linear combination of eigenvectors of
$A$?
Answer: If $A$ ist normal then by the spectral theorem $A=UDU^T$ where $D$ is a diagonal matrix containing the eigenvalues and $U$ is orthonormal matrix whose columns are the eigenvectors.
Then all you have to do is solve the linear system $UX=A$ since then then the first column if $A$ equals a linear combination of the columns of $U$ whose coefficients are given by the first column of $X$, etc.
Since $U$ is orthonormal, the system is trivial to solve: $X= U^T A=DU^T$. So the Eigendecomposition already encodes this information.


Cox & Snell $R^2$ rule of thumb threshold

Question:
Like p value is usually compared to 0.05,
What is the magic number that is considered a good fit for a logistic regression Cox & Snell pseudo $R^2$ result?
>0.1? >0.5? something else?
Answer: The analogy suggested in this question--between a p-value statistical significance threshold and a Cox-Snell logistic regression pseudo-$R^2$ that represents a "good fit"--isn't apt.
Think about ordinary least squares multiple linear regression. That produces both a p-value for the model as a whole and an $R^2$ value that is the fraction of variance in the outcome variable that is explained by the model. Those represent two different things.
The p-value tells you how likely it is that your study has led you astray. If there really was no relationship between the outcome and the predictors and you did the study multiple times, a p-value of 0.05 says that you would have only found a relationship at least that strong by chance in fewer than 5 out of 100 cases. Without more information (e.g., about how many data points you have) it says nothing directly about the fraction of variance in the outcome that the predictors explain.
The linear multiple regression $R^2$ provides that information about the fraction of variance explained by the model. But there is no single $R^2$ value that represents a "good fit"; that depends on the underlying subject matter. What's considered a "good fit" $R^2$ in a biomedical study might be considered woefully inadequate for a "good fit" in a physical-science study, even if a large number of observations provided a "statistically significant" p-value of p < 0.05 in the latter study.
It's similar in logistic regression: the p-value tells you how likely you are to have found an apparent relationship even if there isn't really one. The value of a Cox-Snell pseudo-$R^2$ that represents a "good fit" will depend on what is being studied.
Finally, a good argument can be made that pseudo-$R^2$ values shouldn't even be reported for logistic regression. Other measures more closely related to the purpose of the study are much more important.


jquery smooth-div scroll doesn't work

Question: for some reason the autoScollingMode is not working on my site: http://tinyurl.com/6ux32fe
that's my code:
<code><script type="text/javascript">
$(document).ready(function () {
// Initialize the scroller
$("#makeMeScrollable").smoothDivScroll({
       mousewheelScrolling: true,
       manualContinuousScrolling: true,
       visibleHotSpotBackgrounds: "false",
       autoScrollingMode: "always"
   });
}); // End query document ready
</code>
i can't find the error ...
thx for any advise.
Answer: When I checked your site now it worked fine so I guess you solved the problem on your own?
If you want to you could also upgrade to Smooth Div Scroll version 1.3. You might have to alter some of the options to make the upgrade work though depending on which features you use.
Speaking of features - Smooth Div Scroll 1.3 has support for touch which is nice since many people use iPhones, iPads etc.

jquery smooth-div scroll doesn't work


Help me with hook_views_data

Question: I create a simple module to test hook_views_data but may I get some errors
this is my code
in tungcan.module file
function test_views_api() {
  return array(
    'api' => '3'
  );
}

and in tungcan.views.inc file
function tungcan_views_data() {
  $data = array();
  $data['tungcan']['table']['group'] = t('TungCan');
  $data['tungcan']['table']['basic'] = array(
    'field' => 'tungid',
    'title' => t('Tungcan'),
    'weight' => -100,
    'defaults' => array(
      'field' => 'tungname',
    ),
  );

  $data['tungcan']['tungname'] = array(
    'title' => t('Tung Name'),
    'help' => t('Display name of Tung')
  );

  return $data;
}

but when I clear cache, in my Views (add new views or add new Field) doesn't change anything.
Can somebody point out what is wrong in my code?
Answer: If the module is tungcan.module, then the implementation of hook_views_api() (necessary to load the include files used from the module to integrate with the Views module) should be tungcan_views_api(), not test_views_api().
If, vice versa, the module is test.module, then tungcan_views_data() should be renamed to test_views_data().

Help me with hook_views_data


How to replace template with my own content, xml Odoo 14

Question: I need to replace the template variants of the sale module using my own content.
My code-xml:
<template id="my_variants" inherit_id="sale.variants">
  <xpath expr="." position="replace">

  </xpath>
</template>

using the previous code my new template does not work, what am I doing wrong? how do I solve it?
Note: use <t t-call = "web.layout"> with all content after the xpath; my template works but shows a JS error
Code with error JS:
   <template id="my_variants" inherit_id="sale.variants">
      <xpath expr="." position="replace">
        <t t-call="web.layout" >

        </t>
      </xpath>
    </template>

JS error:

web.assets_common_lazy.js:4497 Uncaught (in promise) TypeError: Cannot
read property 'user_context' of undefined
Answer: Using the following code:
<template id="my_variants" inherit_id="sale.variants">
    <xpath expr="." position="replace">

My codee, this is not shown

    </xpath>
</template>

The paragraph will be shown to the left of the item price in the Available Options
Do not use <t t-call="web.layout" > inside variants template, the product template already did that.
web.layout is usually used when we add a new layout.


Why are parentheses optional when using print in Python 2.7?

Question: In Python 2.7 both the following will do the same
print("Hello, World!") # Prints "Hello, World!"

print "Hello, World!" # Prints "Hello, World!"

However the following will not
print("Hello,", "World!") # Prints the tuple: ("Hello,", "World!")

print "Hello,", "World!" # Prints the words "Hello, World!"

In Python 3.x parenthesis on print is mandatory, essentially making it a function, but in 2.7 both will work with differing results. What else should I know about print in Python 2.7?

See also: Getting SyntaxError for print with keyword argument end=' ' for another consequence in Python 2.x of the difference in print handling.
Comment: p.s., To enable the print function in 2.7 (and not have the print statement behavior), you have to do a future import: `from __future__ import print_function`
Comment: In Python 2.x `print` is actually a special statement, not a function. This is also why it can't be used like: `lambda x: print x` Note that `(expr)` does not create a Tuple (it results in `expr`), but `,` does.
Comment: I'm assuming the support for print as a function and print as a statement is to maintain backwards compatibility with older versions of python while encouraging people to use the new syntax to migrate towards python 3.
Comment: Will the second example will in fact print "Hello,World!" (without the space) or will it print "Hello, World!" (with the space) as in the example.
Answer: In Python 2.x print is actually a special statement and not a function*.
This is also why it can't be used like: lambda x: print x
Note that (expr) does not create a Tuple (it results in expr), but , does. This likely results in the confusion between print (x) and print (x, y) in Python 2.7
(1)   # 1 -- no tuple Mister!
(1,)  # (1,)
(1,2) # (1, 2)
1,2   # 1 2 -- no tuple and no parenthesis :) [See below for print caveat.]

However, since print is a special syntax statement/grammar construct in Python 2.x then, without the parenthesis, it treats the ,'s in a special manner - and does not create a Tuple. This special treatment of the print statement enables it to act differently if there is a trailing , or not.
Happy coding.

*This print behavior in Python 2 can be changed to that of Python 3:
from __future__ import print_function

Comment: Thanks for the `(expr) != tuple` explanation :-)
Answer: It's all very simple and has nothing to do with forward or backward compatibility.
The general form for the print statement in all Python versions before version 3 is:
print expr1, expr2, ... exprn

(Each expression in turn is evaluated, converted to a string and displayed with a space between them.)
But remember that putting parentheses around an expression is still the same expression.
So you can also write this as:
print (expr1), (expr2), ... (expr3)

This has nothing to do with calling a function.
Comment: This is a perfectly correct answer, I'm not sure why it was downvoted so much either.
Comment: It's not about ``print (expr1), (expr2), ... (expr3)``, it is about why ``print (expr1, expr2, ... , expr3)`` is legal in python 2.x while it shouldn't be according to 2.x standards.
Answer: Here we have interesting side effect when it comes to UTF-8.
>> greek = dict( dog="σκύλος", cat="γάτα" )
>> print greek['dog'], greek['cat']
σκύλος γάτα
>> print (greek['dog'], greek['cat'])
('\xcf\x83\xce\xba\xcf\x8d\xce\xbb\xce\xbf\xcf\x82', '\xce\xb3\xce\xac\xcf\x84\xce\xb1')

The last print is tuple with hexadecimal byte values.
Comment: I assume that's because print prints UTF-8 correctly, but when it receives a tuple, like your last print, it runs `repr` on it, at which point it probably encodes all strings in the dict to ASCII.
Comment: @Codemonkey, you are right about __repr__. You are wrong about ASCII. ASCII is default encoding for Python. But I have at the beginning of Python script `#encoding=utf-8`, linux env `LANG=en_US.UTF-8`. So __repr__ encodes not using default ASCII, but utf-8 encoding.
Comment: Repr encodes `str` with the special `string_escape` encoding. The string was already unicode encoded as UTF-8.
Comment: @KarloSmid: What I meant to say was that `repr` probably takes steps to ensure that the text *can* be represented by ASCII (by means of escaping non-ASCII symbols), not necessarily that the string *is* encoded as ASCII. I still don't know if that's completely accurate though.
Comment: *All* Python containers (list, dict, tuple, set) include their contents as `repr()` output when converted to a string (they don't implement `__str__`, only `__repr__`). What you see is not special to UTF-8; the `repr()` of a string gives you valid Python string literals that are ASCII-safe.
Comment: Does this depend on whether it is [UTF-8](http://en.wikipedia.org/wiki/UTF-8), [UTF-16](https://en.wikipedia.org/wiki/UTF-16), or [UTF-32](https://en.wikipedia.org/wiki/UTF-32)?
Answer: Basically in Python before Python 3, print was a special statement that printed all the strings if got as arguments.  So print "foo","bar" simply meant "print 'foo' followed by 'bar'".  The problem with that was it was tempting to act as if print were a function, and the Python grammar is ambiguous on that, since (a,b) is a tuple containing a and b but foo(a,b) is a call to a function of two arguments.
So they made the incompatible change for 3 to make programs less ambiguous and more regular.
(Actually, I think 2.7 behaves as 2.6 did on this, but I'm not certain.)
Comment: No it wasn't "tempting" to use it as a function. :) However, it was impossible to use it as a function, so you can't do [print x for x in alist] for example.


Search and Replace Scanner not publishing nodes after search?

Question: I'm using the handy Search and Replace Scanner module to do a basic sitewide search. It's working well... except that it's not publishing the nodes after the it does the replace. It's making new unpublished revisions. This is quite annoying because then I have to go to all 50+ nodes that were changed and publish them all.
Is there any way around this? Ideally, I'd like the nodes to just be published after the replace.
Answer: It's a node setup thing. Adjusted Workflow/Revision settings to auto-publish, and we're all good.


Preciso editar esse codigo javascript para gerar letras e numeros

Question: O Codigo é esse abaixo eu preciso que nele gere letras e numeros em vez so de numeros como faço?

<title>Gerador de CPF e CNPJ Válidos</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<

<form name="form1" method="post" action="">

      Gerador
        de CPF e CNPJ Válidos

      <input name="numero" type="text" id="numero" size="20">

        <input name="tipo" type="radio" value="cpf" checked>
        CPF
        <input type="radio" name="tipo" value="cnpj">
        CNPJ

      <input type="button" name="Button" value="Gerar" onClick="faz()">

</form>

     © 2010 - 2011 por: Marcos Guiga

Answer: Eu criaria um array com todas as letras do alfabeto minúsculas e maiúsculas.
var alfabeto = ['a','b','c','d','e','f',...,'X','Y','Z'];

E seguiria utilizando seu código só que com os números correspondendo nesse vetor.
Por exemplo, seu código gerou os números 10,33,13,5.
Fazendo uma equivalência naquele vetor seriam jJme.
Por outro lado se o que deseja são os dois juntos, faria da mesma maneira, porém adicionando os números ao vetor também.
Assim:
var num_e_letra = ['0','1','2','3','4','5','6','7',...,'X','Y','Z']

Para isso o random é feito utilizando o length máximo do vetor.
Edit
Acabei de fazer o código abaixo, nele criei uma função que gera uma sequência de números e letras aleatórios, a outra gera uma letra aleatória.
random.html

KKK

    <button onclick="seqNumLetra()">Clique Aqui!</button>

    <button onclick="seqLetra()">Clique Aqui Depois!</button>

Teste:

Resultado

Teste2:

Resultado

Comment: Voce poderia montar isso no codigo pra mim ? pois ele so gera numero, gostaria que gerasse letras e numeros maiúsculas, agradeço!
Comment: Mas você precisa de algo que seja totalmente aleatório? Parecido com algum hash, tipo a1H2jb3Y, ou algo mais específico, que você consiga decidir quando gerar números e letras, como uma função só para gerar letras.
Comment: Pronto fiz das duas maneiras, se tiver alguma dúvida só falar.