Menu block goes crazy after 4th level

Question: When I click on a 4th level link of a Menu block, the 3rd level disappear.
This is the menu:

Services

Accommodation

Building A

Apartment 1

Apartment 2

I have 3 blocks to show this menu:

1st level block (Starting level 1st, max depth 1): is ok
2nd level block (Starting level 2nd, max depth 1): is ok
3rd level+ block (Starting level 3rd, max depth 9): it's not ok

When I click on a third level link (Building A) the 3rd block shows:

Accommodation

Building A

Apartment 1

Apartment 2

but when I click on any 4th level links (i.e. Apartment 1), the 2nd level link disappears and it shows:

Building A

Apartment 1

Apartment 2

I need to see the third level links even if I click on the 4th+ levels. What I need is this:

Accommodation

Building A

Apartment 1

Apartment 2

Thank you.
Answer: Solved.
In the menu block configuration, Advanced Options, I checked Make the starting level follow the active menu item.

Menu block goes crazy after 4th level


Show that the intersection of $\overline{\text{span }\{e_{2n}\}}$ and $\overline{\text{span }\{e_{2n}+\frac{1}{n+1}e_{2n+1}\}}$ is zero.

Question: Let $(e_n)_{n\in\mathbb{N}}$ be a complete orthonormal system in a Hilbert space $H$. Let $x_n=e_{2n}$ and $y_n=x_n + \frac{1}{n+1}e_{2n+1}$. Let $F=\overline{\text{span }\{x_n, n\in\mathbb{N}\}}$ and $G=\overline{\text{span }\{y_n, n\in\mathbb{N}\}}$.
I need to show that any element in $F+G=\{z\in H \mid z=x+y,\quad x\in F, y\in G\}$ can be written as an element from $F$ and an element from $G$ in only one way.
When the intersection of $F$ and $G$ is the zero vector space, I can prove the statement above, but I do not know how to show $F\cap G=\{0\}$.
This means that no element in $F$ is in $G$ and vice versa.
What bothers me is that my intuition makes me feel like the intersection is not zero since $y_n = x_n + \frac{1}{n+1}e_{2n+1}$ converges to $x_n$ as $n$ becomes infinitely large, since the norm of $e_k$ is always 1. Therefore this would make it seem that $y_n=x_n\in G$ for $n\to\infty$, so $F\cap G\supset\{0,x_n\}\neq\{0\}$.
Any ideas? I know that if $z=(x+y)\in H$, then $(x+y)=\Sigma \langle (x+y)\mid e_k\rangle e_k$, since $(e_k)$ is a complete orthornormal system in $H$.
Comment: There are some misconceptions in your phrasing of the question that are probably hampering your progress. It doesn't make sense to ask if $F$ and $G$ are linearly independent; linearly independent is an adjective that applies internally to one set of vectors, not to a pair of vector sets. You want to prove that the intersection of $F$ and $G$ is the zero vector space, not the empty set. And "$y_n=x_n$ as $n\to\infty$" does not have meaning, at least for this algebraic question.
Comment: @GregMartin I edited the question. I do however still have the portion about convergence in it, but I explicitly told that I think this is a misconception since it results in the opposite of what I'm trying to prove.
Answer: The error in your intuition lies in the statement "$y_n = x_n + \frac{1}{n+1}e_{2n+1}$ converges to $x_n$ as $n$ becomes infinitely large". If you are letting $n$ tend to infinity, then any individual $x_n$ does not have meaning in that context.
Here's the same fallacy in a more elementary situation: "the function $y=x+1/x$ converges to $x$ as $x$ becomes infinitely large, so $y=x$ for $x\to\infty$".
Answer: It is demonstrated that $F$ and $G$ intersect trivially, as prompted in the title.
$F,G\subset H$ are closed subspaces, hence Hilbert spaces in their own.
An ONB in $F$ is $\{e_{2k}, k=0,1,2,\dots\}$, and in $G$ consider the ONB  $\big\{f_{2k}=\gamma_k\big(e_{2k}+\frac1{k+1}e_{2k+1}\big), k=0,1,\dots\big\}$ with normalisation factors $\,\gamma_k = \frac{k+1}{\sqrt{(k+1)^2+1}}$.
Let $z$ like "zero" be in $F\cap G$, and let
$$\sum_{k=0}^\infty\alpha_k e_{2k}\,=\; z \;=\,\sum_{k=0}^\infty\beta_k f_{2k}$$
be the Fourier expansions of $z$ in $F$ and $G$, respectively.
Denote the partial sums by $\,a_n=\sum_{k=0}^n\alpha_k e_{2k}\,$ and
$\,b_n=\sum_{k=0}^n\beta_k f_{2k}$, they converge in norm to $z$.
Fix $\varepsilon>0$. Then choose $N$ such that both
$\,\|b_n-z\|,\|z-a_n\|< \frac{1}{2}\sqrt\varepsilon\,$ for all $n\geqslant N$.
Then $\|b_n-a_n\|<\sqrt\varepsilon\,$ by the triangle inequality, and
$$\begin{align}\varepsilon \;>\;\|b_n-a_n\|^2 & \;=\;
\Big\|\sum\nolimits_{k=0}^n\big(\beta_k\gamma_k\, e_{2k}
 + \beta_k\frac{\gamma_k}{k+1}e_{2k+1} - \alpha_k e_{2k}\big)\Big\|^2 \\[1ex]
 & \;=\;\sum_{k=0}^n\Big(|\beta_k\gamma_k- \alpha_k|^2 + |\beta_k|^2\frac{\gamma_k^2}{(k+1)^2}\Big)\end{align}$$
as $\{e_0,e_1,\dots,e_{2k},e_{2k+1},\dots\}$ is an ONB in $H$.
Now in the last sum each summand $<\varepsilon$ by necessity, and $\varepsilon>0$ was at choice. Hence $\beta_k=0\,$ for all $k$, which means $z=0$ and $F\cap G=\{0\}\,.
\qquad\square$


Holomorphic functions on the product of open sets.

Question: Is it true that
$$
\mathcal H(\mathrm U \times \mathrm V) \simeq \mathcal H(\mathrm U) \widehat{\otimes} \mathcal H(\mathrm V)
$$
for open two open affine sets $\mathrm U$ and $\mathrm V$?
Edit: I am particulary interested in the case $\mathrm U = \mathrm V = \mathbb C^\times$.
Comment: What do you mean by "$\widehat{\otimes}$"?
Comment: Completed tensor product. As all the spaces are nuclear here, you can take the one you prefer.
Answer: This is true for arbitrary domains $U,V\subset \mathbb{C}^n$, see corollary 4.15 in The Homology of Banach and Topological Algebras by A. Ya. Helemskii.
Comment: Corollary 4.15 says that it is true, at least if $\mathrm U$ or $\mathrm V$ is simply connected. What happens when $\mathrm U = \mathrm V = \mathbb C^\ast$?
Comment: Below there is a note it is true for all domains


How to finish the bar with rests

Question: Can you help me check these two bars?

Did I finish these bars with rests correctly? Or haven't I handled these dotted eighth notes correctly?
Comment: Your rests are fine, but your written notes are a bit uncomfortable to read.  It would be easier to read if you put quaver, quaver tied to a semiquaver for the first example, and then dotted quaver, semiquaver tied to a semiquaver for the second example.
Comment: Is this for a rhythm quiz? Tying to only the first sixteenth of beat one seems kind of odd.
Comment: Nope. I've just learnt music theory. These rhythm were created randomly and I ask whether it's proper or not.
Answer: The first answer is on the money (BTW quaver = 8th note, semiquaver = 16th note). His or her advice is based on sight readers wanting to clearly see the beginning of every beat (in this case beat 2 of each bar) when 16th notes are involved. You can also substitute a single dotted 8th rest for the 16th and 8th note rests if you like.

How to finish the bar with rests


visualg escada quebra de linha

Question: Estou com problema no código para fazer a quebra de linha.
Preciso criar uma escada que fique como abaixo:
    #
   ##
  ###
 ####
#####

Se eu colocar escreval("#") ele quebra a linha, porem o resultado final fica assim:
     #
    #
#
   #
#
#
  #
#
#
#
 #
#
#
#
#

Alguém sabe qual ajuste devo realizar ?
com o código atual o resultado está ficando dessa maneira:
Quantidade de degraus: 5
     #    ##   ###  #### #####

Algoritmo "escada"
Var
p, x1, x, lin, col, degr: inteiro

Inicio
Escreva ("Quantidade de degraus: ")
Leia (degr)
x:=degr
x1:=1
Para lin de 1 ate degr passo 1 faca
Para col de 1 ate x passo 1 faca
escreva(" ")
Fimpara
x:=x-1
Para p de 1 ate x1 passo 1 faca
escreva("#")
Fimpara
x1:=x1+1
escreva( )
Fimpara
fimalgoritmo

desde já muito obrigado !!
Comment: Não entendi a variável x ai. Estou novo em Lógica de Programação.
Answer: Ficou assim:
Algoritmo "escada"
   Var
   p, x1, x, lin, col, degr: inteiro
   Inicio
   Escreva ("Quantidade de degraus: ")
   Leia (degr)
   degr:=degr + 1

   Para lin de degr ate 0 passo -1 faca
        Para col de 1 ate (degr - x) passo 1 faca
             escreva(" ")
        Fimpara
        Para col de 1 ate x passo 1 faca
             escreva("#")
        Fimpara
        x:=degr - lin
        escreval("")
   Fimpara
fimalgoritmo

Qualquer dúvida é só comentar aqui que eu respondo. :)
Comment: Muito obrigado !!!
Funcionou perfeitamente aqui!
Comment: a reposta está exata amigo , só queria entender como funciona as variaveis oque cada uma representa a quebra de linha ...
Comment: Leio a variável `degr`, acrescento 1 nela, pois minha estrutura de repetição dai de `degr` até 0, ao colocar +1 certifico que vai realmente até o número desejado. A variável `lin` é um contador, ela vai começar de `degr` e vai ate o 0, uso ela para imprimir cada linha. Na estrutura de repetição interna uso uma variável `col` que vai de 1 até `degr - x` onde `x` é `degr - lin` pois a cada linha vou exibir um espaço ( ) a menos.

visualg escada quebra de linha


Altering a data frame in R

Question: I have a data frame that has the first column go from 1 to 365 like this
c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2...

and the second column has times that repeat over and over again like this
c(0,30,130,200,230,300,330,400,430,500,0,30,130,200,230,300,330,400,430,500...

so for every 1 value in the first column I have a corresponding time in the second column then when I get to the 2's the times start over and each 2 has a corresponding time,
occasionally I will come across
c(3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4...

c(0,30,130,200,230,330,400,430,500,0,30,130,200,230,300,330,400,430,500...

Here one of the 3's is missing and the corresponding time of 300 is missing with it.
How can I go through my entire data frame and add these missing values?  I need a way for R to go through and identify any missing values then insert a row and put the appropriate value, 1 to 365, in column one and the appropriate time with it.  So for the given example R would add a row in between 230 and 330 and then place a 3 in the first column and 300 in the second.  There are parts of the column that are missing several consecutive values.  It is not just one here and there
Comment: I don't see any missing values in your example? Can you show your data.frame?
Comment: @agstudy - the data jumps from 230 to 330 without going through 300 in the second set, meaning there are only nine instances of 3 instead of the required ten.
Answer: EDIT: Solution with all 10 times clearly specified in advance and code tidy up/commenting
You need to create another data.frame containing every possible row and then merge it with your data.frame.  The key aspect is the all.x = TRUE in the final merge which forces the gaps in your data to be highlighted.  I simulated the gaps by sampling only 15 of the first 20 possible day/time combinations in your.dat
# create vectors for the days and times
the.days    = 1:365
the.times   = c(0,30,100,130,200,230,330,400,430,500)   # the 10 times to repeat

# create a master data.frame with all the times repeated for each day, taking only the first 20 observations
dat.all = data.frame(x1=rep(the.days, each=10), x2 = rep(the.times,times = 365))[1:20,]

# mimic your data.frame with some gaps in it (only 15 of 20 observations are present)
your.sample = sample(1:20, 15)
your.dat = data.frame(x1=rep(the.days, each=10), x2 = rep(the.times,times = 365), x3 = rnorm(365*10))[your.sample,]

# left outer join merge to include ALL of the master set and all of your matching subset, filling blanks with NA
merge(dat.all, your.dat, all.x = TRUE)

Here is the output from the merge, showing all 20 possible records with the gaps clearly visible as NA:
   x1  x2          x3
1   1   0          NA
2   1  30  1.23128294
3   1 100  0.95806838
4   1 130  2.27075361
5   1 200  0.45347199
6   1 230 -1.61945983
7   1 330          NA
8   1 400 -0.98702883
9   1 430          NA
10  1 500  0.09342522
11  2   0  0.44340164
12  2  30  0.61114408
13  2 100  0.94592127
14  2 130  0.48916825
15  2 200  0.48850478
16  2 230          NA
17  2 330  0.52789171
18  2 400 -0.16939587
19  2 430  0.20961745
20  2 500          NA

Comment: Note that my solution only has *9 times* in it.  The vector may need 100, 300 added to it before your run it, I missed them out!
Comment: This is really close to what I need.  In the X2 column I need a 300 that is associated with the NA between the 230 and the 330.  Would I be bale to use something from the plyr library?  I am playing around with rbind.fill right now but nothing yet
Comment: @user2113499: I don't think you need to play with any other packages.  The logic of the original solution is fine, I was just missing one of the times (300) as indicated in my comment.  Try running it a couple of times and inspect the variables to see what is happening, I've added comments for your understanding.
Comment: Thank you!  This did it.  When I first tried this I had my x and y missed up.  But this ended up working perfectly!
Answer: Here are a few NA handling functions that could help you getting started.
For the inserting task, you should provide your own data using dput or a reproducible example.
df <- data.frame(x = sample(c(1, 2, 3, 4), 100, replace = T),
                 y = sample(c(0,30,130,200,230,300,330,400,430,500), 100, replace = T))

nas <- sample(NA, 20, replace = T)
df[1:20, 1] <- nas
df$y <- ifelse(df$y == 0, NA, df$y)

# Columns x and y have NA's in diferent places.

# Logical test for NA
is.na(df)

# Keep not NA cases of one colum
df[!is.na(df$x),]
df[!is.na(df$y),]

# Returns complete cases on both rows
df[complete.cases(df),]

# Gives the cases that are incomplete.
df[!complete.cases(df),]

# Returns the cases without NAs
na.omit(df)

Altering a data frame in R


Reference to Statistical Control Quality

Question: This semester I'm taking a Green Belt course. I'm really enjoying it and I want to go more deeper in that, I already take this book to start to study
Introduction to Statistical Quality Control
does anyone know any more reference on the subject, or even online videos.
Thank you.
Comment: There is a supplement available: http://www.wiley.com/college/bcs/0471316482/add/s_index.html
Answer: May be you can get some useful things in the book Design and Analysis of Experiments, by the same author. It not only introduces some more advance techniques such as Factorial design, block and confounding, but also cover some materials in the level between, such as one-way anova and two-way anova.
There is a good thing in this book. A lot of examples using MINITAB are available in a companion book.
Comment: I already take a course in Design and Analysis of experiments with this textbook, but thank you anyway.


Why would you use GLM Proc to predict group membership based on a categorical predictor?

Question: Is there a "magic" number of meetings that a student needs to attend in a particular program that has a positive effect on 2nd year retention?
University students, who are at risk of not being retained into the second year, voluntarily participate in one-on-one meetings with a coach throughout their first semester.  The program coordinators want to know if there is a magic number of meetings that a student needs to attend in order to be successful (or retained).  I think it is really a dosage question.  What dose do the students need to get better?  So I actually created six groups for the number of meetings.
Group_1 : 2-4 meetings
Group_2: 5-7 meetings
….
IV: Categorical (Groups)
DV: Dichotomous - Not Retained (0)/Retained (1)
My colleague chose to use the GLM proc in SAS, which I do not know how to use, so I thought I would investigate this is SPSS using the Generalized Linear Model analysis.  But it is not clear to me why he used the Generalized Linear Model.  When he asked, he said it was a way to compare categorical data. Can someone explain this to me? And how would I do this in SPSS?
Comment: There is so much more information available from an analysis based on the count of the actual number of meetings as opposed to the categorical buckets. Hopefully, the buckets were created after the data was gathered. This would permit you to relax the groupings for your analysis.
Answer: If you want to know if there is some particular number of meetings that has a huge effect then I suggest using a regression with a restricted cubic spline of the number of meetings as the independent variable.
If the dependent variable is retained/not retained then this should be a logistic regression which is not in PROC GLM in SAS.
I don't use SPSS though and, in any case, questions about how to do something in particular software packages is off topic here. But look for logistic regression with splines of the IV.
Answer: In addition to Peter's advice sometimes for count variables a quadratic fit is good, mainly because it is difficult to choose knot locations in a spline function when there are many tied values.
As said by @DJohnson it is not appropriate to pre-group an ordinal variable as this is making pre-judgements about the dose-response relationship and making the peculiar assumption of piecewise flatness.  But I have reservations related to her comment of hoping the buckets were created post hoc.  This would create a bias that inflates type I error and hurts confidence interval coverage.


Finding two primes $p,q$ such that $(p^2 + 1)(q^2 + 1) = n^2 + 1$

Question: Find all the positive integers p,q,n such that p,q are primes and also $$(p^2 + 1)(q^2 + 1) = n^2 + 1$$.
We know that pair squares are all divisible by 4 (because they have two or more times 2 as factor), so I squared the possible residues of 4.
$$(4k)^2 = 16k^2 = 4k$$
$$(4k+1)^2 = 16k^2 + 8k + 1 = 4k+1$$
$$(4k+2)^2 = 16k^2 + 16k + 4 = 4k$$
$$(4k+3)^2 = 16k^2 + 24k + 9 = 4k+1$$
So, every squared odd number has residue 1 when it's divided by 4.
We can notice that $n^2 + 1$ has residue 1 or 2.
Let's suposse $p$ and $q$ are both odd numbers, then
$ (p^2 + 1)(q^2 + 1) $
Has to be divisible by 4 (because both factors let residue 2), and that doesn't make sense.
So, $p$ or $q$ (it doesn't matter) has to be pair, an the only pair prime is 2. Then we have
$$5(q^2 +1) = n^2 + 1$$
I found $$5(3^2 + 1) = 7^2 + 1$$
but i don't know if they're the only 3 numbers. So i'm wondering to know how to prove that they're, and if they aren't wich are the others (and again, how to prove that they're the only) using the method i did or another (but not that complicated)
Thanks.
Answer: We have to solve $p^2+p^2 q^2+q^2 = n^2$. If both $p$ and $q$ are odd, the LHS is $\equiv 3\pmod{4}$, hence it cannot be a square. It follows that the only solutions are given by $p=2$ and
$$ 5q^2+4=n^2 $$
whose solutions depend on Fibonacci numbers of the form $F_{2m}$. The only Fibonacci number of the form $F_{2m}$ that is also a prime is $F_4=3$ (due to $F_{2n}=F_n L_n$), hence the only solutions are
$$ (p,q,n)\in\{(2,3,7),(3,2,7)\}.$$
Comment: How do you know the solutions are the Fibbonacci numbers? (i opened the pdf but i didn't get it, i'm not that good at  number theory, can you please try to explain a little?
Comment: @Pulie: that is a well-known topic. The solution of Pell's equations $5n^2\pm 4=m^2$ are given by Fibonacci numers. That also follows from the general theory of Pell's equations.
Comment: See also https://en.wikipedia.org/wiki/Fibonacci_number#Identification


MVVM - IsEnabled not working properly with bound boolean

Question: I have a simple button:
<Button Content="Login" Command="{Binding StartAction}" IsEnabled="{Binding Path=Loading, Converter={StaticResource InverseBooleanConverter}}"/>

As you can see, IsEnabled is bound to a boolean property. When StartAction is executed, the boolean is set on true so the button gets disabled (note that I'm using a InverseBooleanConverter). This works fine.
After changing the boolean, the StartAction-method creates a new thread which calls a callback on the ViewModel (where the thread was created, so where the StartAction-method can be found) when it's finished. This callback is very simple:
private void DisplayResult()
{
    Loading = false;
}

This should enable the button again, however, this doesn't happen.
If I set loading on false somewhere else, the button DOES get enabled. Together with the button, some other elements (also bound to this boolean) should get invisible/visible when the boolean changes and that DOES work fine too, even when the Loading property is changed by the callback method.
I'm a bit confused here. Why doesn't it work? I think it may have something to do with the thread, but I don't see any reason why this shouldn't work, especially since it works with other elements on the UI.
Just to be clear, this is the Loading property:
public bool Loading
{
    get { return loading; }
    set
    {
        if (loading != value)
        {
            loading = value;
            RaisePropertyChanged("Loading");
        }
    }
}

Any idea what might be wrong here?
Thanks
Comment: Maybe there is a problem with the `StartAction` command `CanExecute`? Can you post the code of `StartAction`?
Comment: have you traced it through the converter?
Comment: Yes, nothing seems to be wrong with the converter.
Comment: And you must have an IPropertyChange* whatever it's called that you're inheriting from. Seems right otherwise. Threads?
Comment: Have you tried changing Loading to a dependency property and see if it solves your problem?
Comment: You do know, that IsEnabled is modified indirectly through the command? If its canExecute is false, the button appears to be disabled, but the IsEnabled is not changed(my guess is to stop changing it with tools like snoop and breaking an application).
Answer: On your callback you may need to instruct the UI to check that property again and update accordingly. This is performed with the CommandManager. I've added a bit to your callback code:
private void DisplayResult()
{
    Loading = false;
    CommandManager.InvalidateRequerySuggested();
}

The CommandManager.InvalidateRequerySuggested instructs WPF to update any bound controls as necessary right away.


How to catch username or password using hook_form_alter

Question: I need to catch username/password using the hook_form_alter(). I'm using this code:
function sds_form_alter(&$form, FormStateInterface $form_state, $form_id ) {

  if (in_array($form_id, ['user_login_block_form', 'user_login_form'])) {
    $username= $form_state->getValue('name');
    echo "Username Value".$username;
  }

}

but it returns null. What am I missing here?
Comment: Please provide what you want to achieve by catching the username and password so we can provide better solution for your requirement. hook_form_alter is called before form is rendered. So you'll always get the username and password empty, because user has not yet entered that info in form.
Comment: @Yogesh . thanks for the response i want to get the username and password after the form was submitted because i want to query the username and password from other platform specifically in salesforce.
Now according to you , i think im in a wrong track can you help me out of this.. thanks a lot.!
Answer: You can use in VALIDATE function like
$form['#validate'][] = 'mymodule_user_validate';

In this you can all values even if there is no successful values in it.
But remember to call your function first before default validate function.
Answer: When hook_form_alter() is invoked, the form has not been submitted yet, so you cannot get any value from $form_state. You need to add a form submission handler, and from that get the username.
$form['#submit'][] = 'mymodule_user_submit';

If you are, instead, trying to get the default value set in the form, then you should use the following code, in your hook_form_alter() implementation.
$default_name = $form['name']['#default_value'];

It would still return an empty value, since Drupal doesn't set a default value for the username, but that is the correct code to get the default value of a form element from hook_form_alter().
Comment: hi @kiamlaluno , its good and working but

$form['#submit'][] = 'mymodule_user_submit' bu works only if the form was successful (ie if username and pass is valid or true) but i want to catch the username and password even if it's not a authenticated user!
can we do that though?
Comment: I did these:
 * add $form['#submit'][] = 'mymodule_user_submit'; in my hook_form_alter.
*in my mymodule_user_submit I get the $form_state->getvalue('name or pass').
these code are working but now the problem it's only triggered and executed when the form was successful , now i'm wodering if i can get those user inputs right before the it was submitted or trigger the function mymodule_upload_enabled_types_submit even though the login is failed .!


Linear maps on vectors in general position

Question: Let $V$ be a finite dimensional vector space over an infinite field $\mathbb{F}$, and let $v_1,\dots, v_n \in V$ be a collection of non-zero vectors for which $\dim \text{span}\{v_i, v_j\} =2$ for all $i\neq j \in \{1,\dots, n\}$ (i.e. they are in 2-general position) and $\dim \text{span} \{v_1,\dots, v_n\} \geq 3$. Does there always exist an index $i \in \{1,\dots, n\}$ and a linear map $\Pi \in L(V)$ with $\ker(\Pi)=\text{span}(v_i)$ such that $\dim \text{span} \{\Pi v_j, \Pi v_k\} =2$ for all $j \neq k \in \{1,\dots, n\} \setminus \{i\}$?
Answer: No. The vectors
\begin{align}
\begin{bmatrix}
1\\0\\0
\end{bmatrix}
,
\begin{bmatrix}
0\\1\\0
\end{bmatrix}
,
\begin{bmatrix}
\frac{1}{\sqrt{2}}\\\frac{1}{\sqrt{2}}\\0
\end{bmatrix}
,
\begin{bmatrix}
0\\0\\1
\end{bmatrix}
,
\begin{bmatrix}
0\\\frac{1}{\sqrt{2}}\\\frac{1}{\sqrt{2}}
\end{bmatrix}
\end{align}
in $\mathbb{R}^3$ do not satisfy this property.


SQLAlchemy: Do I need 2 classes for this?

Question: I've been following the SQLAlchemy Object Relational Tutorial (http://docs.sqlalchemy.org/en/latest/orm/tutorial.html) and I've created table_def.py, a file that specifies a table containing Player objects (in my case):
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class Player(Base):
    """"""
    __tablename__ = "players"
    id = Column(Integer, primary_key=True)
    firstName = Column(String)
    lastName = Column(String)
    college = Column(String)
    ranking = Column(Integer)
    rating = Column(Float)

def __init__(self, rating, college, firstName=None, lastName=None, ranking=None):
    """"""
    self.rating = rating
    self.college = college
    self.firstName = firstName
    self.lastName = lastName
    self.ranking = ranking

This seems to specify everything SQLAlchemy would need to know about player objects.  However, I also have a classes.py file which contains:
class Player:
    def __init__(self,  rating, college, ranking = None, firstName = None, lastName = None):
        self.rating = rating
        self.college = college
        self.ranking = ranking
        self.firstName = firstName
        self.lastName = lastName

    def to_string(self):
        if self == None:
            return "None Object"
        rep = "firstName is " + self.firstName + " lastName is " + self.lastName + " rating is " + str(self.rating) + " college is " + self.college
        if self.ranking is not None:
            rep = " ranking is " + str(self.ranking) + " " + rep
        return rep

I'm actually able to call to_string() on normal Player objects (before I even use the DB).  But it also seems duplicative to have these two definitions of the Player class.
What am I doing wrong / what should I be doing to avoid this?
Thanks,
bclayman
Answer: No, you don't need two classes. You can add the to_string() method to the one that's used by SQLAlchemy, and you need to fix the order of the arguments of the __init__ in the code.
Comment: Hmm, when I comment out the contents of my classes.py file (the Player class described above), I'm no longer able to create a bunch of Player objects in my Python code (before any database functions are called).  How would you recommend getting around this duplication?
Comment: You can create the Player objects but you don't have to add them to session.


which hypothesis for boundedness of this function

Question: Let $v:[0,\infty)\rightarrow \mathbb{R}_+$ be a positive function such that $$\exists T,q>0\,\,s.t.\,\, \forall t\in[0,\infty),\,\,\int_t^{t+T} v(\tau) d\tau \le q$$
I'm looking for the "less restrictive" possible condition which together with the equation above ensures that $v(\tau)$ is bounded in $[0,\infty)$. Any guess?
Answer: Regarding boundedness on $[0,T)$, the condition on $v$ translates to $v\in L^1([0,T))$ (let $t=0$). What you are asking is what extra condition you can put on an integrable function for it to be bounded.
Comment: Yes, exactly. I'm looking for some "lightweight" condition to be sure that $v$ is bounded. Sorry, I corrected the question since I'm actually interested in boundedness on the whole $[0,\infty)$ no more just in $[0,T)$. My doubt is: ok that integral is finite, but actually I don't know whether $v$ assumes or not unbounded values for some null-measure subsets of $[t,t+T]$, therefore I'm looking for some extra condition. Do you think Locally Lipschitz condition to work?
Comment: Locally Lipschitz implies continuous. If $v$ is continuous on $[0,\infty)$ then it is bounded on any bounded interval.
Comment: yes sure... What other hypothesis may I use?
Comment: Other than asking directly for $v$ to be bounded, you could impose that $v$ has weak derivatives in $L^p$, $p>1$,  of any bounded interval.
Comment: Ok, thank you a lot Sir.


Generate a random number with pre-defined length

Question: with specific sequence like first 8 digits are current date 20160518{year-mm-dd] which always change and last 4 digits are random digit in php. I know how to generate random number using mt-rand() but how to manage sequence.
 I can generate random number using this code.
$randnum = rand(1111111111,9999999999);
but i want to restict first 8 digit like if someone place order on site then its format should be [yyyyddmm]and remaining number are random digits.
Output should be 201703158877.
Comment: _...how to manage sequence?..._ What do you mean by that? Show us your code and the expected output and tell us what does not work.
Comment: ___Read your question back to yourself!___ But now pretend you dont know what you are talking about.. like us. Now ask yourself, could I answer this question with the information provided?
Comment: as per the edit: question's too broad.
Comment: sidenote: is this db-related also?
Comment: um.... combine them? no idea what you're really asking here; include an example output. (as already asked)
Comment: Let me have a guess what you want... your 12-digit sequence consists of the current date in the format yyyymmdd and 4 random numbers. You want to put those together and e.g. echo this or return them to work further with them. Am I right?
Comment: and what does this have to do with javascript?
Comment: yes thats what i am asking
Comment: You can do this with like every language you want to. Just use google, it's one of the most basic things you could do.
Comment: @T.D Numbers like placing an order generate a table id. That ID is appended to a date string. Nothing "random" about that.
Comment: but i dont know how to implement it
Comment: @T.D use google!
Comment: okay so i get a idea how to do this.So thanks for helping me
Comment: Please review this post [How to create a Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve)
Answer: If you want only 4 digits then give rand() a min and max that are only 4 digits long like this
$randnum = rand(1000,9999);

Then you will only get a 4 digit number back from the randomiser
Comment: *"then give mt_rand()"* - You meant *then give rand()...*, *n'est-ce pas true?*
Comment: Oui bien sur mon ami
Comment: @Fred-ii- Ah my get out of Jail Free card `7.1.0 rand() has been made an alias of mt_rand()`.
Answer:
mt_rand() function is used to generate random numbers in php.
mt_rand() function is much faster then rand() function.
syntax: mt_rand() or mt_rand($min , $max);
example of generate 4 digit random number in php:

check Generate 4 Digit Unique Random Numbers


Why creating the front page doesn't work?

Question: I created the file named page--front.tpl.php, which is empty, in the Garland theme and set the front end to it. I still can access the front page: why?
Answer: Have you cleared the cache after you added the new template file in the theme directory? You should always clear the cache, once you change a template file for a theme already installed, or you add a new file that was not used before.
Comment: no, got it.when i clear the cache,it's ok. thank you.


Solaris doesn't know which MAC address to use to send an UDP multicast message

Question: I have a pair of Solaris 10 boxes which are supposed to send multicast UDP packets to a group of hosts. One of them works just fine, whereas the other one does not.
The problem with the second machine is that it doesn't know what MAC address to use to wrap this piece of UDP/IP in an ethernet frame. When I run arp -an I see that it has this multicast address as U for unresolved for a couple seconds, then it gives up.
Nobody answers ARP requests for this multicast IP address, which is totally expected.
In theory (and in practice on the other machine) this MAC address should be well known. You take the lower 23 bits of the IP address, OR it with 01:00:5e:00:00:00 and you get the MAC address of the multicast group. No ARPs should be sent at all.
When I manually inject this MAC address into the ARP table of that machine (using arp -s), it works OK.
PS. The software runs within a non-global Solaris zone. Maybe it does make some difference.
Answer: Do you have multiple interfaces? The first one listed in /etc/zones/myzone.xml will be used for multicast. You should be able to see this with "netstat -rn".
Here is a blog entry that covers this: http://www.lecentre.net/blog/archives/142
Comment: Routing table is fine. I checked that. It's not that the packets get sent via wrong interface and don't reach the destination. They don't get sent at all, which I verified with snoop.
Answer: What type of networking does the zone running the app use?  Shared or exclusive?  It is possible to specify the mac address of the vnic for the zone using the anet property.  Checkout the relevant doc section.
Comment: What has it to do with determination of MAC addresses for UDP multicast groups?


Exporting displayed columns in dataGridView to Excel

Question: I may be blind, but this is a little different than the normal export-to-excel.  I've created a solution and would like to know if this is the best way.  Or even if there is another way to do it.
Background: WinForms, VisualBasic, VS2012, N-Tier (backend is DB2).  My DTOs are set up in order of the DB2 tables.  My users want to see the fields in a certain order within the DGV AND be able to export the fields in the same order.  Users can also rearrange and hide columns.  Hidden columns should not be exported.
My solution does do the normal copy from dgv field by field to excel.  The difference is that I had to use DataGridViewColumnCollection so that I could utilize DataGridViewElementStates.Visible in order to make sure I'm only exporting visible columns.
Here is the code.
<code>Private Sub ExportToExcelToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExportToExcelToolStripMenuItem.Click
  If((dgv.Columns.Count = 0) Or (dgv.Rows.Count = 0)) Then Exit Sub
  Dim XlApp = New Excel.Application With {.Visible = True}
  xlApp.Workbooks.Add(Excel.XlSheetType.xlWorksheet)
  Dim xlWS = xlApp.ActiveSheet
  xlWS.Name = "Exported Data"

  'Copy visible data from DGV to Excel
  Dim columnCollection As DataGridViewColumnCollection = dgv.Columns
  Dim currentVisibleColumn AS DataGridViewColumn = columnCollection.GetFirstColumn(DataGridViewElementStates.Visible)
  Dim lastColumnExported As DataGridViewColumn = currentVisibleColumn
  Dim visibleColumntCount As Integer = columnCollection.GetColumnCount(DataGridViewElementStates.Visible)

  'Finally export the data
  For c = 1 to VisibleColumnCount
     xlWS.Cells(1,c) = currentVisibleColumn.HeaderText
     currentVisibleColumn = columnCollection.GetNextColumn(lastColumnExported, DataGridViewElementStates.Visible, DataGridViewElementStates.None)
     lastColumnExported = currentVisibleColumn
  Next

  'Only export visible cells
  For r = 0 To dgv.Rows.Count - 1
     'Reset values
     currentVisibleColumn = columnCollection.GetFirstColumn(DataGridViewElementStates.Visible)
     lastColumnExported = currentVisibleColumn
     For c = 1 to visibleColumnCount
         Dim value = dgv.Rows(r).Cells(currentVisibleColumn.Index).Value
         If value <> vbNullString Then
            xlWS.Cells(r + 2, c) = value.ToString()
         End If
         currentVisibleColumn = columnCollection.GetNextColumn(lastColumnExported, DataGridViewElementStates.Visible, DataGridViewElementStates.None)
         lastColumnExported = currentVisibleColumn
     Next
  Next

  'Autosize columns in excel
  Dim columns = xlWS.UsedRange.Columns
  columns.AutoFit()
End Sub
</code>
Thank you for your feedback.
Brian.
Comment: What exactly is your question? Is it just "was this code written well"?
Comment: The question is, "Is there another way to do this that works better?  Or is this the way to do it?"  My first time encountering this situation, so I want to make sure I'm doing it right.
Answer: Theres is more simple way to do that and it is to perform the if statmente at each iteration of the cells copy process. You ask if that column at that index is visible, if it is visible you copy else you skeep that column and take next.


Explanation of a function that gets letter from word

Question: I'm making a hangman game in javascript, and I'm having trouble understanding the code in this one function.
Here is the function:
function getLetter(word,letter,display){
    // This method is called by the Hangman program when your isLetterInWord function
    // above returns true.
    // The parameters passed in are the guessed letter, the secret word,
    // and the current display state of the secret word.
    // This method will return a new display state of the secret word based on the matching letter.
    // REPLACE THIS CODE WITH YOUR getLetter() METHOD
    while (word.search(letter) != -1) {
        var index=word.search(letter)
        display = display.substr(0, index) + letter + display.substr(index + 1);
        word = word.substr(0, index) + '-' + word.substr(index + 1);
    }
        return display;
}

The part I don't really understand:
display = display.substr(0, index) + letter + display.substr(index + 1);
word = word.substr(0, index) + '-' + word.substr(index + 1);

Basically this program takes a word, find the number of letters and replaces them with hyphens.
For example the word 'boat' would be turned to '----'
The the job of the function above is to replace the letter guess (correctly) with the corresponding hyphen.
Here is the background code for the whole project.
// Hangman Project
//RETURN A 'HIDDEN' VERSION OF THE SUPPLIED SECRET WORD
function getDisplay(word)
{
    // Given a string, "word", return a hidden version of it consisting
    // of dashes for the display.
    // REPLACE THIS CODE WITH YOUR getDisplay() METHOD

    var disp="";
    for (var i=0; i < word.length; i++ ){
        disp = disp +'-';
    }
    return disp;
}

//FIND IF THE LETTER IS IN THE WORD
function isLetterInWord(word,letter){
    // Given the word "word", check if it contains the letter "letter".
    // REPLACE THIS CODE WITH YOUR isLetterInWord() METHOD

    if(word.search(letter) != -1) {
        return true;
    } else {
        return false;
    }

}

Any help explaining those two lanes would be appreciated. Thanks.
Comment: @dandavis obviously its not his, probably some hangman library he found on the net.
Comment: Look at what `display.substr(0, index)` and `display.substr(index+1)` return. In particular, count how many characters there are in them, compared to the number of characters in the word.
Comment: MDN might be helpful, understanding [`search`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search) and [`substr`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr) will help you to understand the whole code.
Comment: how can you have trouble understanding code you are making?
Comment: @Teemu I understand both of them. What I don't understand is at what point the hyphen is taken away. I see how the display adds the letter into the hyphens, but  I don't see when the extra hyphen is taken away.
Answer: Suppose the word is animal, and the player has already guessed a and l correctly. The input will be:
word = "animal"
letter = "i"
display = "a---al"

Follow the code:
var index = word.search(letter);

Now index = 2 (counting is 0-based).
word = word.substr(0, index) + letter + word.substr(index+1);

word.substr(0, 2) is "a-". word.substr(3) is "-al". So when everything is concatenated word = "a-i-al".
It's the index+1 that skips over the character being replaced.
The next line
word = word.substr(0, index) + '-' + word.substr(index + 1);

is similar, replacing the found letter with -. This is needed in case the letter appears multiple times in the word (like a does in animal), so that the while loop won't keep trying to replace the same position.


EmbeddedRecordsMixin hasMany causing TypeError on embedded records

Question: I'm getting the following error while using DS.EmbeddedRecordsMixin when my records have embedded data:
TypeError: Cannot read property 'typeKey' of undefined

I'm using Ember CLI 0.1.2 with Ember 1.7.0 and Ember Data 1.0.0#beta11
My adapters:
Application Adapter - /app/adapters/application.js (RestAdapter):
import DS from 'ember-data';
import config from '../config/environment';

export default DS.RESTAdapter.extend({
    namespace: config.APP.RestAdapterNamespace,
    host: config.APP.SERVER_LOCATION
});

Adapter in question - /app/adapters/screen.js (screenSlideGroups should be embedded):
import ApplicationAdapter from './application';
import DS from 'ember-data';

export default ApplicationAdapter.extend(DS.EmbeddedRecordsMixin, {
    attrs: {
        screenSlideGroups: { embedded: 'always' }
    }
});

Model: /app/models/screen.js
import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  path: DS.attr('string'),
  screenSlideGroups: DS.hasMany('screen-slide-group')
});

Example of data returned from the API:
{
  "screen":[
     {
        "id":1,
        "name":"Weather",
        "path":"weather",
        "screenSlideGroups":[
           {
              "id":1,
              "screen":1,
              "slideGroup":1,
              "order":1
           }
        ],
        "lastUpdated":"2014-09-18T18:26:25.69"
     },
     {
        "id":2,
        "name":"Front Lobby",
        "path":"frontlobby",
        "screenSlideGroups":[

        ],
        "lastUpdated":"0001-01-01T00:00:00"
     }
  ]
}

I also tried removing screen from the embedded record, incase the backwards reference could screw it up, but it didn't make a difference. As far as I can tell, the EmbeddedRecordsMixin adapter I created may not be getting used at all.
Any ideas on what may have gone wrong here?
Answer: Turns out I misread the documentation, and DS.EmbeddedRecordsMixin should be on the Serializer, NOT the Adapter.
The correct implementation was as follows:
/app/serializers/screen.js:
import DS from 'ember-data';

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
    attrs: {
        screenSlideGroups: { embedded: 'always' }
    }
});


Why are 3/4 size guitars not more common?

Question: I find a 3/4 size guitar with a scale length of 21 inches is easier to play (at least when stretching on the low frets) than a bigger guitar.
I've read that 3/4 scale guitars go out of tune easily because their string tension is low, and this is a reason why longer scale lengths are conventional. However, this can be offset simply by using higher gauge strings. A side benefit of this is that the treble strings would be less prone to snapping because they're thicker.
What are the disadvantages then of shorter-scale guitars?
Answer: Two thing come to mind immediately:

Tone: Thicker strings cannot make up for the tonal differences of shorter scale lengths and especially smaller bodies on acoustic guitars.
The highest frets on full scale guitars can be hard to play because they can be too close together for comfort. This problem will come up at lower fret positions on short scale guitars.

Besides those large issues, some guesses on other reasons include smaller guitars not looking as cool, smaller guitars not being built to as high a standard and not marketed as well (lower profit margin), and finally many guitarists have no reason or few reasons to want a smaller guitar.
Answer: I can answer for a similar instrument, the five-string banjo, but I think this will apply equally well to a non-amplified acoustic guitar.
I play short-scale banjos, because my hands are very small and full-scale instruments give me hand injuries.  Short-scale instruments work for me, but I've noticed these disadvantages:

I could stretch my fingers to play a full sized banjo, but since I don't regularly, I can't.  I'm too used to the short scale.  This means I cannot enjoy trying out a friend's banjo at a jam, for example.  It's my instrument or nothing.

Similarly, the choice of instruments available to me in the marketplace is far less.  Almost no used instruments, and darned few new ones, unless custom (and then they are expensive).

For a non-amplified instrument, you get less volume.  This matters at an acoustic jam, where my short-scale banjos are more likely to get buried by the dreadnought guitar in the circle.

String bends are harder.  I could make them easier by using lighter strings, but I've already got problems with low volume compared to "normal" acoustic instruments.

I think these issues will apply to non-amplified acoustic guitar as well.  For me, the ease of playing and the reduction in hand injuries makes the disadvantages worth it, but they are disadvantages.
Answer: Honestly I think that a big factor in that is a sense of shame about playing a "child's" instrument. I know a grown man who'd take a 3/4 guitar to all his hiking trips (hey, nothing beats singing around a fire), as it makes for a less unwieldy luggage than a full-size guitar to carry around, but it takes a kind of self-confidence to do that where people can see and mock you.
And then there's just a sort of... inertia. Full-size guitars are way more prevalent, which means you're much more likely to inherit one, come across them for sale second-hand, or see a selection of in a shop. So unless you go and buy your first guitar with a pronounced preference for 3/4, chances are you'll end up with full-size.
"Easier to play" is subjective, but the most part of what type of guitar is easier to play than another is what you're used to. Unfamiliar dimensions throw you off; once you play that guitar regularly, it becomes the easy one.
Answer: I won't say this is a reason people don't buy 3/4 guitars, but note that when you use thicker strings on a shorter guitar, the high frets won't be in tune with the low frets.
This is the reason why the bridge is adjustable or shaped, but the problem is more pronounced with shorter thicker strings, and is one of the reasons why concert grand pianos are bigger/longer than compact upright pianos.
Answer: I don't sense any disadvantage when moving between 3/4 and full scale guitars. As with any instrument it takes a little work to get the best sound through technique (style).
Martin and Taylor makes nice little guitars that are very common.
Answer: What mainly contributes to a guitar being a 3/4 size version is body size.  Tone quality and volume are lessened as acoustic body sizes decrease.  Travel and 3/4 size guitars tend to have very shallow small bodies that produce a thinner tone of  less volume than regular guitar sizes.  Their shorter scale length does not cause tuning issues.  While the fretboard is usually shorter than many others, the nut width and tuning machines are similar to larger guitars.
Comment: End effects, the effect of the bend at the fixed end when the string vibrates, are an effect of the stiffness of the string, which is associated with the thickness. End effects are the reason why the bridge is not parallel to the frets. This is why short-neck instruments are normally tuned higher.  "Setting up" a guitar includes adjusting the bridge so that the part of the fretboard with the best "intonation" is the part where you play most. The thinner the strings, the longer the neck, the less important end effects are, and the better the "in tone ation" is.


Density of square root of sum of squared independent uniform random variables

Question: Let $X \sim U(-1, 1)$ and $X \sim U(-1,1)$. We want to find density function of $W = \sqrt{X^2 + Y^2}$.
I got stuck and I have no idea, where I am making a mistake. This is my approach.
Let $F$ be a cumulative distribution function of $W = \sqrt{X^2 + Y^2}$
\begin{align*}
F(w) = P(W \le w ) &= P(\sqrt{X^2 + Y^2} \le w) \\
&= P(X^2 + Y^2 \le w^2) \\
&= \iint \limits_{x^2 + y^2 \le w^2} \frac{1}{4} dxdy \\
&=
\int \limits_{0}^{w^2} \int \limits_{0}^{2 \pi} \frac{1}{4} d\theta dr \\
&= \pi \frac{w^4}{4}
\end{align*}
So, the density:
$$
f(w) = F'(w) = \pi w^3
$$
But if I run a simulation:
<code>X <- runif(100000, -1, 1)
Y <- runif(100000, -1, 1)
R2 <- X^2 + Y^2
R <- sqrt(R2)

hist(R,  prob=TRUE)
</code>

Where am I making a mistake?
Comment: Closely related questions include https://stats.stackexchange.com/questions/28658 and https://stats.stackexchange.com/questions/52909.
Comment: This looks exactly like https://stats.stackexchange.com/q/323617/119261.
Answer: Some observations:

The radius is $w$, but you're taking it as $w^2$
Don't forget the $|J|$ term (i.e. $rdrd\theta$) in the integral (or you can simply use area of the circle as well)
The density will take two different functional forms for $[0,1]$ and $[1,\sqrt{2}]$. Visualise a growing circle inside the square $[-1,1]\times[-1,1]$.
Comment: Thanks! for $[0,1]$ calculations are easy and I was able to receive the good result. Will it be correct if for $[1, \sqrt{2}]$ I would consider one quater and write $\int_0^1    \int_0^{\sqrt{w^2 -1}} \frac{1}{4} dx  dy   +   \int_{\sqrt{w^2 -1}}^1 \int_0^{\sqrt{w^2 - x^2}} \frac{1}{4} dydx$ and then multiply the result by 4?
Comment: I might be mistaken but the integral didn't seem correct. Why don't you calculate using just the formulas for area and then try to verify your integrals?


Boost Multi-Index : Composite key of vector and int for hashed indices

Question: as I've just learned in in my other question, I could use a composite_key for a struct, which has a std::vector and an integer. Now my question is: Can I use this somehow to work with hashed_indecies?
Here an example similar to THIS:
struct unique_property
{
  //the pair of int and std::vector<int> shall be unique
  int my_int;
  std::vector<int>  my_vec;
};

typedef multi_index_container<
  unique_property,
  indexed_by<
    hashed_unique< // indexed by my_int and every entry of my_vec
      composite_key<
        street_entry,
        member<unique_property,int,&unique_property::my_int>,
        member<unique_property,std::vector<int>,&unique_property::my_vec>
      >
    >,
    random_access< >
  >
> property_locator;

The problem is (of course) that a std::vector<int> is no suitable hash-key. Can I put this code in an elegant wrapper (or something like that), to produce a hash-key from every entry of my_vec as well?
Answer: Use code snippet from your suggestion here. It should work. I've added my comments there.
Answer: If you want vector to be hashable, you can just write a hash<vector<int> > function in namespace std, making it hash however you please (hint: you might be able to get away with hashing only the first few elements in some applications).  This should make std::hash_set<vector<int> > work, and I think your more complex container as well.


Given a Adjacency Matrix Table, complete an adjacency List

Question: I'm given the table:
(An Adjacency matrix of a graph)
$$\begin{array}{c|c|c|c|c|c|c|c|}
 & \text{a} & \text{b} & \text{c}& \text{d}& \text{e}& \text{f} & \text{g}\\ \hline
\text{a} & x & 7& &5\\ \hline
\text{b} & 7& x &8 &9&7 \\ \hline
\text{c} & &8&x&&5 \\ \hline
\text{d} &5&9&&x&15&6\\ \hline
\text{e} &&7&5&15&x&8&9 \\ \hline
\text{f} &&&&6&8&x&11\\ \hline
\text{g} &&&&&9&11&x\\ \hline
\end{array}$$
And I'm told to complete the adjacenty list below
Where all the blank spaces in the table are filled with infinity.
a.      b, 7      d, 5
I'm not sure how to go about approaching this, since I'm not given the graph, but only the adjacency table. Any ideas?
Comment: What do the numbers in the table correspond to?
Comment: I'm not told, all I'm told is to consider the table and all the blank spaces are  filled with infinity. And the table is an adjacency matrix of a graph.
Answer: This would be an example of an adjacency matrix $A$ of a graph that is not simple. Each entry $A_{ij}$ in the matrix corresponds to the number of edges between vertices $i$ and $j$. For example, there are 5 edges between $a$ and $d$, since $A_{a,d}=5$. If $A_{ij}$ is a blank entry, then there are no edges between vertices $i$ and $j$. From this, it should not be too difficult to determine what the graph looks like.
The adjacency list of a graph is the list of vertices of the graph along with all of their neighbors. Vertices $i$ and $j$ are considered neighbors if $A_{ij}\neq0$. The first entry in the adjacency list would be
$$
a:b,d
$$
since $a$ is adjacent to $b$ and $d$. Can you fill in the rest?
Comment: Okay, but how do i go about completing the adjacency list, assuming I can now draw out the graph? (I'm not sure what is meant by the adjacency list).
Comment: See the addition to my answer :)


Getting image path for API post request - Swift, iOS

Question: I am using an API post request in order to get a modified image.
curl \
    -F 'image=@/path/to/your/file.jpg' \
    -H 'api-key:[myKey]' \
    [api url]

It worked fine directly on my Mac's terminal using:
curl \
    -F 'image=@/Users/user/image.jpg' \
    -H 'api-key:[myKey]' \
    [api url]

Trying to use it in an iOS app, I'm struggling to get an image path.
The api works with Alamofire using another parameter that uses an image url. So I thought to upload the image to a server and use that url, but it would be much better if I could use directly the path parameter.
This is what I tried, but it doesn't work.
func imagePath(_ image: UIImage, handler: @escaping (String?) -> Void ) {

    let path = NSTemporaryDirectory()
        .appending(UUID().uuidString)
        .appending("png")

    let url = URL(fileURLWithPath: path)

    let data = image.pngData()

    let urlForApi = "@" + path

    do {

        try data?.write(to: url)

        //  Just to check if write above works, it always works fine
        let postData = try UIImage(data: Data(contentsOf: url))

        handler (urlForApi)

    } catch {

        handler (nil)

    }

}

It returns handler(urlForApi), but the request gets an error. I'm not getting the correct path to use for the request.
Comment: First of all `let urlForApi = "@" + path` <-- this is not needed, the "@" notation is CURL-specific syntax. Second: `/Users/user/` absolute path is quite different from `NSTemporaryDirectory()`
Answer: I could solve it using the Alamofire upload request.

func getPostURL(`fromImage` preImage: UIImage?, postImageURL: @escaping (_ outputImageURL: String) -> (), error: @escaping (_ error: Error?) -> ()) {

        if let safeImage = preImage {

            let data = safeImage.pngData()!

            AF.upload(multipartFormData: { (form) in
                form.append(data, withName: "image", fileName: "image.png", mimeType: "image/png")
            }, to: apiURL!, headers: headers).validate(statusCode: okStatusCodes).responseDecodable(of: ImageResponse.self) {

                response in

                if let url = response.value?.output_url {
                    postImageURL(url)
                } else {
                    error(response.error)
                }

            }

        } else {
            error(ImageDataError.gettingPostURL)
        }

    }

However, it would be interesting to know how to get temporary paths to files.


Want to show $\sum\limits_{k=1}^\infty \frac{1}{k^p}$ converges by cauchy condensation for $p>1$

Question: Anyone know of a series I can bound the other one by? This one:
$$\sum\limits_{k=1}^\infty 2^k \frac{1}{k^{2p}}$$
Comment: @Shaun I dont have much ,  just trying to use the compariso ntest, i wrote out some terms of that series thats really all. i want to find a series to bound it above by.
Comment: Please show your working so far :)
Comment: So the goal here is to use a more advanced theorem (without proof), to prove a much simpler statement? Why not use the integral test? I'm sorry, but I find it incredulous that one would use more technical theorems to prove much simpler statements.
Answer: Actually in the case of $$\sum_{k=1}^{\infty} \frac{1}{k^p}$$ you have that $f(k)=k^{-p}$ (using the notation of Wikipedia). So according to the Cauchy condensation test the above series converges iff the sum $$\sum_{k=1}^{\infty}2^kf(2^k)=\sum_{k=1}^{\infty}2^k(2^k)^{-p}=\sum_{k=1}^{\infty}(2^k)^{1-p}=\sum_{k=1}^{\infty}(2^{1-p})^k \tag1$$ converges. But, since $1-p<0$ we have that $$2^{1-p}<1$$ hence the RHS in $(1)$ is a geometric series of a term which is less than $1$ and therefore converges.
Comment: thank you!! that helps a lot.
Comment: @terribleatmath You are welcome!
Answer: Well, note that if $a_k=k^{-p}$ then $2^ka_{2^k}=2^k 2^{-pk}=2^{(1-p)k}$.


What is it called when the first/last note of a three-/four-note chord is moved one half-step up/down?

Question: Is there a term for the chord or the act of moving the note?
There are a few songs I know of that do this, e.g., the last chord of The Platters' Only You and Stranger Things' theme.
Comment: I've listened to both of your examples and I'm not certain what you're referring to. Could you give us a video and timestamp by any chance?
Comment: Of course, @Richard. The examples I listed were terrible. Take, for example, a chord composed of E, G, B, and Eb — or a chord composed of A, Db, E, and Ab.
Comment: @Crys.... instead use `E G B` and `D#` or `A C# E` and `G#`...but we know what you mean.
Answer: This may not apply to the cases of interest to the original questioner but things like an A-minor chord moving to an F6 chord (A-C-E to A-C-F) is referred to the 5-6 technique. The technique also applies to whole tone movement. The procedure is reversible. One can do similar things with the lower note like (C-F-A to D-F-A). I don't really know a name for the procedure.
I think (but I'm not sure and I'm not familiar with the relevant literature) that some neo-Riemannian procedures follow this. There are placements of notes (or chords) on a hexagonal lattice (Tonnetz) which encompass these techniques.
Answer: For the last chord of The Platters' Only You I think you need to provide some music, because I don't see the half-step movement you mention.
In the Stranger Things theme I think you mean...

...where the circled notes are the half-step movement you mention.
I think the theme exploits a harmonic ambiguity and creates its effect from a few musical elements rather than one single device with a tidy name. So bear with my long-ish answer...
If we simply list out the notes used in the beginning and arrange them in thirds we get C E G B which at face value is C major-seventh chord. The bass note is E instead of C and so we say the chord is in first inversion...

...*if we labeled the chord as such it would be I6/3.
If we use that chord label, the half-step movement would be called simply a broken chord, because the movement is using only the notes of the chord.
The problem with that analysis is the music really sounds like it's in a minor mode. A C major-seventh chord does not seem a good chord to represent the sound of a minor mode tonic chord. So I want another way to analyze this music.
Instead I can consider the E of the bass the chord root and the circled E G B are the chord tones for an Em chord.
This leaves out the C tones indicated by arrows.
We call these non-chord tones (NCT), because they don't "belong" to the Em chord. NCTs add tension to music. This "not fitting" the chord and tension can also be called dissonance. If a NCT moves to a chord tone, it is called resolving. So, the dissonance and tension of a NCT is resolved by moving the tone to a chord tone.

A few observations can be made from this view.

Em certainly better matches the minor mode feel of the music.
the upper C tone is part of a neighboring motion with the B or the Em chord. This is an example of a dissonant NCT resolving into a chord tone.
the lower C does not involve a step-wise resolution to a chord tone. This tone is implied to be sustained through the whole measure. That is an implied, sustained, unresolved dissonance. This adds a lot of tension to the music. I think this constant tension creates an angst which expresses the mood of the t.v. show.
it's reasonable to return to the first idea and call this a C major-seventh chord. That possibility makes the theme a bit ambiguous. In some settings a major-seventh chord sounds very mellow and pretty. I think this ambiguity tempers the strong dissonance of a minor second - which could be found in many horror movie soundtracks - to something less harsh, more eerie than terrifying.

On a purely technical note. The score samples above are from a YouTube video, they aren't a real score of the recorded theme. As recorded the E in the left-hand bass clef is a synth bass which is clearly lower than the C in the right-hand bass clef.
I threw out a bunch of music theory terms in this answer only to give you the details to understand my conclusion. I think the essential effect of the music is created by an unresolved dissonant non-chord tone and the half step movement from B to C would be called a neighbor tone.


Coordinates of a meetpoint of two tangent (fun)

Question: A line is a tangent to the circle $C_1:x^2+y^2+4x-16y+23=0$, at the point$(-5,14)$. This line cuts another Circle $C_2:x^2+y^2+56x+10y+744=0$, at points $A$ and $B$. The tangents to $C_2$ at $A$ and $B$ meet at point $C$. Find the coordinates of $C$.
Answer: I think that explicit computations is the way in this question.
Rewrite $C_1$ as
$$C_1: (x+2)^2 + (y-8)^2 = 45$$
The line from the center of $C_1$, which is $(-2,8)$, to the point $(-5,14)$ is given by
$$L_1: y=-2x+4$$
So the tangent to $C_1$ at $(-5,14)$ is perpendicular to $L_1$ (so it has gradient $1/2$), and since it must pass through $(-5,14)$, it is given by
$$L_2: y = \frac 12 x+\frac {33}{2}$$
Rewrite circle $C_2$ as
$$C_2: (x+28)^2+(y+5)^2 = 65$$
Solve the two equations $L_2$ and $C_2$ simultaneously to obtain the intersection points
$$A = (-27,3) \qquad B = (-35, -1)$$
The center of $C_2$ is $O_2 = (-28,-5)$, and the lines from $O_2$ to each of $A$ and $B$ are respectively given by
$$O_2A : y=8x+219 \qquad O_2B: y = -\frac 47 x-21$$
So the tangents to $O_2$ at $A$ and $B$ have respective gradients $- 1/8$ and $7/4$, and are hence given, respectively, by
$$L_3: y = -\frac 18 x -\frac 38 \qquad L_4: y = \frac 74 x+ \frac{241}{4}$$
Finally, solve $L_3$ and $L_4$ simultaneously to obtain the intersection point being $$\biggl(-\frac {97}{3}, \frac {11}{3}\biggl)$$
Answer: This is easily solved without explicitly computing $A$, $B$ or the tangents at those points to $C_2$ by exploiting pole-polar relationships. The tangent to $C_1$ at $(-5,14)$ is the polar line of this point. The intersection of the tangents to $C_2$ at the points at which this line intersects $C_2$ is its pole. Thus, in homogeneous coordinates, $$C = \begin{bmatrix}1&0&28\\0&1&5\\28&5&744\end{bmatrix}^{-1} \begin{bmatrix}1&0&2\\0&1&-8\\2&-8&23\end{bmatrix} \begin{bmatrix}-5\\14\\1\end{bmatrix} = \frac1{13}\begin{bmatrix}-291\\33\\9\end{bmatrix}.$$ Dehomogenizing yields $\left(-\frac{97}3,\frac{11}3\right)$.
Comment: Could you explain a bit more how you established these matrices? Seems like a really nice trick!
Comment: @GuusPalmer See https://en.wikipedia.org/wiki/Matrix_representation_of_conic_sections#Poles_and_polars and https://en.wikipedia.org/wiki/Pole_and_polar for brief glosses.


How can we access a one class object in another class?

Question: I still have not been able to figure this out. How can we access a one class object in another class?
I am using the below code but I am getting and error:
class ListofRecord{
        var $db;
    function __construct(){
            $db = global $db;

    }
    function record(){
       $record = $this->db->SelectQuery("SELECT * FROM user order by UID ASC");
       return $record;
    }

}

Answer: You need to refer to the global $db variable first and then use it in a statement. You also have a minor syntax error in your constructor. You forgot to use the $this keyword when referring your your $db property.
function __construct(){
    global $db
    $this->db = $db;
}

It also is a better practice not to use global variables and instead pass any variables that you need as parameters to your method call. In this case it is your constructor:
function __construct($db){
    $this->db = $db;
}

$list_of_record = ListofRecord($db);


Token for Total Flag Count

Question: I have created a flag for my comments named HELPFUL. If users find a comment helpful they vote it as such.
The challenge that I have is how do I show the total votes for the flag next to the button? If a comment was voted as helpful 5 times for example, show that next to the helpful button.
If there are no helpful votes for a particular comment show nothing (do not display 0) but only the HELPFUL rate button (flag)
I have tried to add [flag-action:count] and [flag-helpful-count] as the token under the flag setting (/admin/structure/flags/manage/helpful >>edit>> Flag link text) but it does not work.
Looked at COMMENT tokes and I see this available: [comment:flag-helpful-count]
It still won't work. It shows this text [comment:flag-helpful-count] instead of a total number.
Any help would be greatly appreciated.
Answer: You try code:
<code>/**
 * Implements hook_tokens().
 */
function mymodule_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();
  if($type == 'comment' && !empty($data['comment'])) {

    foreach($tokens as $name => $original) {
      switch($name) {
        case 'flag-helpful-count':
          //$comment = \Drupal\comment\Entity\Comment::load($data['comment']->get('cid')->value);
          //$count_flag = \Drupal::service('flag.count')->getEntityFlagCounts($comment);
          $replacements[$original] = 10;
          break;
      }
    }
  }
  return $replacements;
}

function mymodule_preprocess_comment(&$variables) {
  $token_service = \Drupal::token();
  $token_count_flag = $token_service->replace('[comment:flag-helpful-count]', array('comment' =>
    $variables['elements']['#entity']));

}
</code>
Comment: Thank you for the reply. Which file is this supposed to go in?
Comment: I think you will need it
Comment: I have a custom theme. I am not sure which file to paste the code you provided. Thanks.
Comment: Any other suggestions?
Comment: It executes in the custom module

Token for Total Flag Count


Would " -5 + Par" instead of "5 under Par" be understood/accepted?

Question: I'm currently writing a program involving Golf and my code's structure makes outputting "-5 + par" way easier (& shorter, in terms of code length required) than "5 under par". Now, is the former likely to be understood by the general golf player or is it so odd that I ought not to use it at all?
Answer: It would probably be understood... but I'd seriously question whether you've got your cost:benefit analysis right here - it would make your program look like it's written by someone who doesn't understand golf, and (as a professional programmer) it's two lines of code to output "5 under par" instead of "-5 + par".
Comment: I'd agree with you about the ratio if this were for a client, but it isn't. :)


Intersection of inverse images

Question: Given $A$ and $B$ is the subset of $C$ and $f:C\mapsto D$,
$$f(A\cap B)\subseteq f(A) \cap f(B)$$ and the equality holds if the function is injective.
But why for the inverse, suppose that $E$ and $F$ is the subset of $D$,
$$f^{-1}(E \cap F) = f^{-1}(E) \cap f^{-1}(F)$$
without saying that the inverse function is injective. So if
$$x\in f^{-1}(E) \cap f^{-1}(F)$$
$$x\in f^{-1}(E) \text{ and } x\in f^{-1}(F)$$
This means that there exists elements $y_1 \in E$ and $y_2 \in F$.
So here how do we know that these two elements are equal.
I am independent learner so I hope I can get an explaination in more details.
Answer: proof: $$x\in f^{-1}(E \cap F)\Leftrightarrow f(x)\in E\cap F\\\Leftrightarrow f(x)\in E \  and \ f(x)\in F\\\Leftrightarrow x\in f^{-1}(E) \ and \ x\in f^{-1}(F) \\
\Leftrightarrow x\in f^{-1}(E)\cap f^{-1}(F)\\$$
so the equality holds.
Answer: They don't mean the inverse by $f^{-1}$ but the pre-image under f. Maybe once you have studied that definition, it will become more evident!
Comment: ya i know here pre-image is not inverse. But how we know the two images are the same?
Answer: The sentence "This means there exists elements $y_1\in E$ and $y_2\in F$" is incomplete. The mere fact that $y_1,y_2$ exist is not very useful. Say what property those elements have, and you will see why they are equal.
Comment: Do you mean that $y$ must be inside intersection of $E$ and $F$ in order for the previous statement exists?
Comment: I mean that opening the sentence with "This means" indicates a relation with the previous statement, which is "$x\in f^{-1}(E)$ and $x\in f^{-1}(F)$". So there should be some relation between $y_1,y_2$ and the $x$ of that statement. Write down that relation and you're almost done.

Intersection of inverse images


Maximizing area of the triangle in a quarter circle

Question:
The radius of the quarter circle is $6\sqrt 5$ and we assume that $OA= 5$ and $OC=10$. What is the maximum area of the blue triangle?

Interpreting the problem statement, I believe that points $A$ and $C$ are fixed and point $B$ can move on the arc. To solve this problem, I assumed that the coordinate of $O$ is $(0,0)$ and then assigned coordinates for each vertex of the triangle: $A(5,0), C(0,10), B(x,\sqrt{180-x^2})$ where $x \in [0, 6\sqrt5]$. Then I applied the formula for the area of the triangle given its vertices, and the problem is reduced to maximizing
$$A(x)= \left|25-(\frac52\sqrt{180-x^2}+5x)\right|\quad \text{for}\quad x \in [0, 6\sqrt5]$$
Which is easy to continue and I got $50$ as the answer.
I'm looking for other approaches to solve this problem. I'm particularly interested in geometric approaches.
Comment: Hint: Max area=>max height of B from base AC. So think of the tangent to the quarter arc which is parallel to AC
Comment: @SohamSaha Oh true, I wrongly thought $AC$ has the slope of $1$. Obviously the parallel line intersect the upper endpoint first!
Comment: @SohamSaha Nice and intuitive approach! It explains the idea that the height from $B$  to $AC$  should passes through $O$ to maximize the area. One can expand this idea to notice that the minimum area occurs when $B$ is on each endpoint of the arc.
Comment: umm… not exactly, the upper endpoint would be better for minimizing area in this case. Can you see why?
Comment: Would it be acceptable to fix at least 1 of A,B or C; perhaps 2 of them? Failing that much, what point could there be?
Answer: The area of the triangle ABC is equal to its side AC multiplied by the height, divided by $2$. The height will be maximal if we draw a radius OB such that OB is perpendicular to AC. Let H be the intersection of AC and OB.
Then $$AC=\sqrt{OC^2+OA^2}=\sqrt{25+100}=5\sqrt5.$$
It is known that $$OH=\frac{OA\cdot OC}{AC}=\frac{5\cdot 10}{5\sqrt5}=2\sqrt5.$$
Then $$HB=OB-OH=6\sqrt5-2\sqrt5=4\sqrt5.$$
Then the area of the triangle ABC is $$\frac{BH\cdot AC}2=\frac{4\sqrt5\cdot 5\sqrt5}2=50.$$
Answer: Just extend the circle, call $A'$ and $C'$ the intersection of the line AC with the circle. The middle $B$ of the arc $A'C'$ is the solution.
Answer: Applying Heron's formula for the area of a triangle as a function of the value of the length of its sides and finding the value of x for which this value has a maximum, we obtain that:
$AC=5\sqrt{5};AB=\sqrt{85};CB=4\sqrt{10}$
being the coordinates of the point B :
$x=12, y=6$.


Differential Equation problem

Question:
Find $y$, when $xy'-x=1$ and $y(1)=2$.

I get that $y=x+\ln{ x}+C$
But then $y(1)=2$ isn't true. Did I do something wrong?
Comment: we get $1+C=2$ can you solve this
Comment: You are supposed to sub in $x=1$ and $y=2$ to find the constant $C$.
Comment: Of course, I knew that..... Just misunderstood my teacher then, but thank you :-)
Answer: In this case, $\ \ y(x) = x + \ln(x) + C\ \ $ is called the 'general' solution, because no matter what value of $C$ is used, this function satisfies your differential equation.
You have a more specific problem however, they want you to solve for a function which satisfies two conditions! The differential equation as well as the condition that $y(1) = 2$. Having this condition allows you to find a $C$ which gives you a 'particular' solution for the problem as a whole.

Differential Equation problem


Imagem na URL do Image.network do flutter não funciona no dispositivo físico

Question: Fiz um app básico, pois até então, eu só usava Image.asset() para colocar imagem, agora eu fui colocar Image.network() e a URL e funcionou no AVD que criei, mas quando eu faço o APK e instalo no meu celular, não funciona as imagens do Image.network().
Agora mesmo eu coloquei para rodar o meu app no meu celular físico por fio e as imagens carrega, mas quando eu realmente instalo(APK) não funciona.
Isso pode ser um erro do meu celular?
E tabém, quando eu fiz um app com uma API, só funcionou no AVD, quando eu instalei no meu celular não rodou também.
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    title: "asdas",
    home: Home(),
  ));
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: AppBar(
          bottom: TabBar(tabs: <Widget>[
            Tab(
              icon: Icon(Icons.home),
              text: "Home",
            ),
            Tab(
              icon: Icon(Icons.file_download),
              text: "Download",
            ),
          ]),
        ),
        body: SingleChildScrollView(
          child: Container(
            child: Column(
              children: <Widget>[
                Text("lorem ipsum dolor"),
                Image.asset(
                  "images/judeu.jpg",
                  fit: BoxFit.fill,
                ),
                Image.network(
                  'https://picsum.photos/250?image=9',
                  fit: BoxFit.fill,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Comment: Adicionou as permissões de acesso a internet no `Android Manifest`?
Comment: Olá, não, não coloquei.
Comment: Onde que eu coloco isso?
Comment: No arquivo `AndroidManifest.xml` localizado em `android/app/src/main` adicione esta linha dentro da tag ``
Comment: Funcionou, eu não sabia disso.
Comment: Muito obrigado.
Comment: Sem problemas. Para ajudar outras pessoas eu vou postar como resposta e vc poderá sinalizar como solução válida ajudando outros membros da comunidade caso tenham a mesma dúvida que você.
Answer: O Problema ocorre por não ter a permissão de acesso a internet configurada. Em modo Debug o framework já tem tratamentos para bloquear este acesso. Já no modo release é necessário informar. Para fazer isso adicionar a linha abaixo dentro da tag <manifest do arquivo AndroidManifest.xml que fica localizado em android/app/src/main.
<uses-permission android:name="android.permission.INTERNET"/>

Exemplo
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.exemplo.flutter">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label="Exemplo"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">

            <meta-data
                android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
                android:value="true" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>


Does $P(B|A) \neq P(B| A^c)$ prove dependence?

Question: Does P(B|A)!=P(B|!A) prove dependence?
!= means 'is not equal to'
!A means 'not A' or 'the complement of A'
Thanks.
Edit:  I believe I may have proved that inequality shows dependence.
Proof:
1)  Assume independence.
<code>            P(AB)=P(A)P(B)

            P(B)=P(AB)/P(A)

            P(B)=P(B|A)

    2)  Repeat with !A

            P(A!B)=P(A)P(!B)

            P(B)=P(!AB)/P(!A)

            P(B)=P(B|!A)

    3)  Therefore

            P(B|A)=P(B|!A)
</code>
By contradiction, the events are dependent.
Comment: Are A and B the only two events that are possible?
Comment: @user1357015 Yes.
Comment: Your solution doesn't work. If in fact A & B are independent, then $Pr(B) = Pr(B|A^c)$ and $Pr(B) = Pr(B|A)$? Why? Because,under independence, it doesn't matter what A is when calculating the probability of B conditioned on A (By the fact of independence!). Take a look at mine.
Answer: I think one may proceed as follows:
Suppose A & B ARE independent. That means $P(A \& B) = P(A)P(B) \Rightarrow Pr(B|A) = Pr(B) $
Now from your equation, that would mean that $Pr(B|A) \neq Pr(B|A^c)$ which by independence of A and B would imply that:
$Pr(B) \neq Pr(B)$
since $Pr(B|A) = Pr(B)$ and $Pr(B|A^c) = Pr(B)$ (using th indepdence property).
Clearly that is false. That means A & B are dependent.
Comment: From A and B being independent, how can you say that $A^c$ and B are also independent?
Comment: @user1357015 thank you. our proofs are similar.
Comment: @Anoldmaninthesea. I asked if A & B are the only two possible so it seems to me you're either in A or in B? No?
Comment: @Guest: Not quite, your proof doesn't work because under independence I think that's what you expect? Don't forget to mark as answered if you agree :-).
Comment: I maybe wrong, but, if A and B are the only two possible sets, then B=$A^c$. Or is there another meaning that I don't understand?
Comment: @Anoldmaninthesea. Here's a proof of "If A & B are indepedent, then $A \& B^c$ are independent". https://answers.yahoo.com/question/index?qid=20100328144146AAKNKoS


Fourier transform wrt spatial variable of a distribution

Question: Let $T\in\mathcal{S}'(\mathbb{R}^{n+1})$ be a tempered distribution, i think that:
$$ \mathbb{R}^{n+1}=\{(x,y):x\in\mathbb{R}^n,y\in\mathbb{R}\}.$$
How i can define the Fourier transform of $T$ wrt $x$? There is way to make this definition rigours? Any help is appreciated:
Answer: You can define the Fourier transform for only one variable as following:
If $T$ is a tempered distribution, $\mathbb{F}_yT$ is the only distribution such that for any $\psi \in \mathcal{S}(\mathbb{R}^{n+1})$ we have:
$$\langle\mathbb{F}_yT,\psi\rangle = \langle T,\mathbb{F}_y\psi\rangle$$
Where on the right hand side $\mathbb{F}_y\psi$ is the usual fourier tranform in only $y$ of $\psi$.


Generating files by programming in Jekyll

Question: Suppose I have some data in the _data folder from which I want to automatically generate pages. That is: imagine _data/structure.md is something as follows
chapters:
  -
    chapter1
    chapter2
    chapter3
    ...

and I need static files chapter1.md, chapter2.md ... and so on which are quite similar in structure (for instance, chapter1.md is
---
title:chapter1
layout: default
---

This is chapter1!!

). Is there a way to create these files automatically, without doing them by hand, just changing or adding items in the _data file?
Comment: Is content (like "This is chapter1!!") needs to be different for all files ?
Comment: @DavidJacquel Different but depending only on the parameter `chapter1`, that is, there is no more info needed than what `_data` contains
Answer: You can use a generator (documentation).
This can be something like this :
module Jekyll

  class DataPage < Page
    def initialize(site, base, dir, name)
      @site = site
      @base = base
      @dir = dir
      @name = name
      self.process(@name)
      self.data ||= {}
      self.data['layout'] = 'default'
      self.data['title'] = data
    end
  end

  class CategoryPageGenerator < Generator
    def generate(site)
      datas = site.data['structure']
      datas.each do |data|
        name = "#{data}.md"
        page = Jekyll::DataPage.new(site, site.source, @dir, name)
        page.data['title'] = data
        page.data['layout'] = 'default'
        page.content = "This is #{data}"
        site.pages << page
      end
    end
  end

end

Comment: in `initialize` : `@dir = 'chapters'`
Comment: Works fine!! What about doing exactly the same, but saving the generated files in a specific folder? (that is, `_site/chapters` instead of `_site`) I guess some extra piece of code is needed


Como implementar spinner loanding em AngularJS?

Question: Estou tentando implementar spinner loanding no meu projeto em angularjs, já faz um tempo! o spinner deve rodar sempre que uma requisição for executada.
Que biblioteca uso?
Answer: Você pode usar dessa forma, ele só vai aparecer enquanto $scope.loading for true.

app.controller('myCtrl', function ($scope, $http) {
  // Show loading spinner.
  $scope.loading = true;
  $http.get('/some/awesome/content')
    .success(function (data) {
      // Do stuff with data.
    })
    .catch(function (err) {
      // Log error somehow.
    })
    .finally(function () {
      // Hide loading spinner whether our call succeeded or failed.
      $scope.loading = false;
    });
});

Ou para ficar melhor ainda, você pode criar uma diretiva, assim:
.directive('loading', function () {
      return {
        restrict: 'E',
        replace:true,
        template: '
LOADING...
',
        link: function (scope, element, attr) {
              scope.$watch('loading', function (val) {
                  if (val)
                      $(element).show();
                  else
                      $(element).hide();
              });
        }
      }
  })

Toda vez que você setar $scope.login = true; em algum lugar, vai aparecer o loader.
Answer: Você pode estar utilizando esse módulo angular-loading-bar ele é muito fácil de implementar e modificar. Com certeza atende a sua necessidade.
Ele funciona da seguinte forma, toda requisição do serviço $http ele irá "capturar" e irá injetar em seu código uma barra de progresso e também no canto inferior direito um loading.
No próprio github do projeto existe uma documentação de como implementar.
Primeiro passo para utiliza-lo é colocar a sua dependência
angular.module('myApp', ['angular-loading-bar'])

E também não esqueça de colocar seus arquivos no projeto
<link rel='stylesheet' href='build/loading-bar.min.css' type='text/css' media='all' />

Feito isso qualquer requisição ele será ativado.
JSFiddle Demo
Answer: Existem algumas maneiras. Caso você queira mostrar o spinner sempre que o Angular fizer uma requisição, implemente uma Interceptor Factory, como na resposta aceita a esta pergunta no SO em Inglês:
https://stackoverflow.com/questions/17838708/implementing-loading-spinner-using-httpinterceptor-and-angularjs-1-1-5
Este interceptor será executado sempre que uma requisição ao serviço $http for feita. A chave é esta linha aqui:
$httpProvider.interceptors.push('httpInterceptor');

Que injeta o Interceptor no provider.


Calculate distance using Geolocation module

Question: I'm using the drupal/Geolocation module to assign a location field to a specific content-type.
I have created a View (REST Export display) to return all the content-type entries with all the fields and it's working fine.
I'd like to calculate the distance between a sent lat/lng point and the location of each entry and sort them by distance (and also include it in the resulting JSON).
I'm already applying some changes to the JSON output using the views_post_render hook (and changing the $output variable), but I don't think in that hook I can access a query string (sent via Ajax request).
What would be the best way to pass the user's location from the website frontend to the view? Right now my bet would be sending the query parameter via an Ajax request, adding something like ?location=-17.000,19.000 to the URL.
And where could I access that data (the user's lat/lng location) and calculate the distance to pass it again to the frontend?
Answer: I've found a solution.
Getting the user location
I'm using the Browser API to get the user location in the frontend and then pass those parameters as query strings to my view, like ?latitude=xxxx&longitude=xxxx.
if (navigator.geolocation) {
    var options = {
        enableHighAccuracy: true,
        maximumAge: 0
    };

    function success(pos) {
        var crd = pos.coords;
        // Send ajax request with crd.latitude and crd.longitude in query strings
    };

    function error(err) {
        console.warn(`ERROR(${err.code}): ${err.message}`);
    };

    navigator.geolocation.getCurrentPosition(success, error, options);
} else {
    console.warn('Geolocation not available.')
}

Using the location to calculate distances with Drupal hook
Then, using the THEME_views_post_render(\Drupal\views\ViewExecutable $view, &$output) hook I check that $view->id() is the view in which I want to make the calculations and I get the data from the URL using the Drupal function \Drupal::request()->query->get('latitude'); (and longitude).
From that point, I decode the JSON variable $output['#markup'] and change the JSON objects the way I need to fulfill my requirements.
if ($view->id() == 'farmacias_perto') {
        $user_latitude = \Drupal::request()->query->get('latitude');
        $user_longitude = \Drupal::request()->query->get('longitude');
        $json_result = json_decode($output['#markup']->jsonSerialize());

        foreach ($json_result as $pharmacy) {
            $latlong = explode(',', $pharmacy->field_geolocation);
            $pharmacy_latitude = $latlong[0];
            $pharmacy_longitude = $latlong[1];
            $distance = distance($pharmacy_latitude, $pharmacy_longitude, $user_latitude, $user_longitude);
            $pharmacy->distance = round($distance);
        }

        $output['#markup'] = json_encode($json_result);
}

I used the distance function explained here.


Prove that for any sets $A$, $B$, and $C$, $A×(B\setminus C) = (A×B)\setminus (A×C)$.

Question: This is Velleman's exercise 4.1.8 ("$×$" means the Cartesian product):
Prove that for any sets $A$, $B$, and $C$, $A×(B\setminus C) = (A×B)\setminus (A×C)$.
Cartesian product of $A$ and $B$, denoted $A × B$ is equal to $\{(a, b) | a ∈ A and b ∈ B\}$ ("$(a, b)$" is an ordered pair).
And here's my proof of it:
Proof.
($\rightarrow$) Let $(x, y)$ be an arbitrary element of $A×(B\setminus C)$, then $x ∈ A$ and $y ∈ (B\setminus C)$ which means that $y ∈ B$ and $y ∉ C$. From $x ∈ A$ and $y ∈ B$, we get $(x, y) ∈ (A×B)$. From $x ∈ A$ and $y ∉ C$, we get $(x, y) ∉ (A×C)$. Thus $(x, y) ∈ (A×B)\setminus (A×C)$. Therefore $A×(B\setminus C) ⊆ (A×B)\setminus (A×C)$.
($\leftarrow$) Let $(x, y)$ be an arbitrary element of $(A×B)\setminus (A×C)$, then $(x, y) ∈ (A×B)$ which means that $x ∈ A$ and $y ∈ B$ and $(x, y) ∉ (A×C)$ which means that either $x$ is not an element of $A$ or $y$ is not an element of $C$ or both. But since we saw that $x ∈ A$, therefore $y ∉ C$. From $y ∈ B$ and $y ∉ C$, we get $y ∈ (B\setminus C)$. From $x ∈ A$ and $y ∈ (B\setminus C)$, we get $(x, y) ∈ A×(B\setminus C)$. Therefore $(A×B)\setminus (A×C) ⊆ A×(B\setminus C)$.
From ($\rightarrow$) and ($\leftarrow$), we get $A×(B\setminus C) = (A×B)\setminus (A×C)$.
Is my proof correct (particularly "From $x ∈ A$ and $y ∉ C$, we get $(x, y) ∉ (A×C)$" in the forward direction)?
Comment: Yes, it's correct.
Comment: I would call it $\subseteq,\supseteq$ instead of $\rightarrow,\leftarrow$, since $=$ is about sets that contain one another, not logical statements that imply one another, but it's not terribly important. If you make the simple rewrite $A×(B\setminus C) = (A×B)\setminus (A×C)$ into $x\in A×(B\setminus C) \iff x\in (A×B)\setminus (A×C)$, then arrows is more correct again. And it doesn't affect the actual proof.
Comment: Re the "particularly" part: you don't need x member of A for that statement. If y not member of C than (x, y) not member of S x C for any set S and any value x member S.
Answer:
($\rightarrow$) Let $(x, y)$ be an arbitrary element of $A×(B\setminus C)$, then $x ∈ A$ and $y ∈ (B\setminus C)$ which means that $y ∈ B$ and $y ∉ C$. From $x ∈ A$ and $y ∈ B$, we get $(x, y) ∈ (A×B)$ $(x,y)\in A\times B$. From $x ∈ A$ and $y ∉ C$, we get $(x, y) ∉ (A×C)$. (Enough to say "From y ∉ C, ...") Thus $(x, y) ∈ (A×B)\setminus (A×C)$. Therefore $A×(B\setminus C) ⊆ (A×B)\setminus (A×C)$.
($\leftarrow$) Let $(x, y)$ be an arbitrary element of $(A×B)\setminus (A×C)$, then $(x, y) ∈ (A×B)$ (Redundant parentheses) which means that $x ∈ A$ and $y ∈ B$ and $(x, y) ∉ (A×C)$ (Redundant parentheses) which means that either $x$ is not an element of $A$ or $y$ is not an element of $C$ or both. But since we saw that $x ∈ A$, therefore $y ∉ C$. From $y ∈ B$ and $y ∉ C$, we get $y ∈ (B\setminus C)$ (Redundant parentheses). From $x ∈ A$ and $y ∈ (B\setminus C)$, we get $(x, y) ∈ A×(B\setminus C)$. Therefore $(A×B)\setminus (A×C) ⊆ A×(B\setminus C)$.
From ($\rightarrow$) and ($\leftarrow$), we get $A×(B\setminus C) = (A×B)\setminus (A×C)$.

(Just several redundant parentheses for sets. Your proof is correct.)


Showing $e^{\alpha N_t}W_t$ is a mixed process

Question: On the probability space ($\Omega, \mathcal{F}, (\mathcal{F}_t), \mathbb{P})$, let $(N_t)$ be a Poisson process with intensity $\lambda$ and $(W_t)$ be a Brownian motion (the two processes being independent from each other.

Applying Itô's lemma, show that the process $Y_t=e^{\alpha N_t}W_t$, $t\ge0$ is a mixed process.

A mixed process $(X_t)$ is defined as having a representation of the form: $X_t=X_0+\int^t_oh_sds+\int^t_0f_sdW_s+\int^t_0g_sdM_s$, where $M_0$ is a constant, $W$ Brownian motion and $M$ is the compensated martingale associated with a Poisson process $N$ with constant intensity $\lambda$ (i.e. $M_t=N_t-\lambda t)$. $h,f,g$ are adapted processes.
To be honest I don't know how to choose a function directly for $Y$ in order to apply Itô formula, since $Y_t$ should admit the representation $Y_t=Y_0+\int^t_0K_sds+\int^t_0H_sdW_s$, for $K_s,H_s$ adapted stochastic processes (I think it doesn't).
My idea was to divide the process in continuous and pure jump (discontinuous) process as follows:
$W_t$ is the continuous process and $V_t:={\alpha N_t}$ is the pure jump process.
In my notes I have the following variant of Itô formula for a pure jump process $V_t$: $f(V_t)-f(V_0)=\sum_{s\le t}\Delta f(V_s)$, where $\Delta f(V_s)=f(V_s)-f(V_{s-}), V_{s-}=\lim_{h\downarrow0}V(t-h)$.
Then, following the resolution as in this paper (page 48):
For $f(x)=e^x$, $f(V_t)-f(V_0)=e^{\alpha N_t}-1=\sum^t_{s=0}e^{V_s}-e^{V_{s-}}$. As $\Delta N_s=N_s-N_{s-}=1$, we have $e^{V_s}-e^{V_{s-}}=e^{\alpha N_{s-}}(e^{\alpha}-1)=e^{\alpha N_{s-}}(e^{\alpha}-1)\Delta N_s$
So $e^{\alpha N_{t}}-1=\sum_{s\le t}e^{\alpha N_{s-}}(e^{\alpha}-1)\Delta N_s=(e^{\alpha}-1)\int^t_0e^{\alpha N_{s-}}dN_s$
Regarding the Brownian motion, I have this alternative Itô formula for $f\in C^2$: $f(W_t)-f(W_0)=\int^t_0f'(W_s)dW_s+\frac12\int^t_0f''(W_s)ds$
So take $f\equiv Id$, then I just get $W_t=W_t$
In the end I would just multiply the result I got for both processes, but doesn't sound that right to me.
Comment: If $f\equiv Id$, then $f'\equiv 1$ and $f''\equiv 0$, so Itô's formula yields $W_t = W_t$ instead of what you wrote.
Comment: So apparently you found an SDE for $e^{\alpha N_t}$ and $W_t$ is a standard Brownian motion. Since $Y_t$ is the product of those two, I guess you should be able to finish by applying Ito's product rule
Comment: @Stratossupportsthestrike thank yuo fo your remark, I edited it in my question, but that doesn't take my concern away, does the rest makes sense to you?
Answer: Since $e^{aN_t}$ and $W_t$ are both semi martingales we have
\begin{align}
e^{aN_t}W_t&=\int_0^te^{aN_{s-}}\,dW_s+\int_0^tW_s\,d(e^{aN_s})+\big[e^{aN},W\big]_t\,.
\end{align}
Since $e^{aN_t}$ changes only by jumps of size
$$
e^{aN_t}-e^{aN_{t-}}=e^{aN_{t-}+a\Delta N_t}-e^{aN_{t-}}=e^{aN_{t-}}(e^{a\Delta N_t}-1)=e^{aN_{t-}}(e^a-1)\Delta N_t
$$ the second integral is
$$
\int_0^tW_s\,d(e^{aN_s})=\sum_{s\le t}W_s\,e^{aN_{s-}}(e^a-1)\,\Delta N_s=\int_0^tW_s\,e^{aN_{s-}}(e^a-1)\,dN_s\,.
$$
The quadratic variation term is zero because $W$ is continuous and $e^{aN}$ changes only by jumps.
Writing $M_t=N_t-\lambda t$ obviously brings
\begin{align}
e^{aN_t}W_t&=\int_0^te^{aN_{s-}}\,dW_s+\int_0^tW_s\,e^{aN_{s-}}(e^a-1)\,dN_s\,.
\end{align}
into the desired form
\begin{align}
e^{aN_t}W_t&=\int_0^te^{aN_{s-}}\,dW_s+\int_0^tW_s\,e^{aN_{s-}}(e^a-1)\,dM_s+\lambda\int_0^tW_s\,e^{aN_{s-}}(e^a-1)\,ds\,.
\end{align}


jQuery load() whole html file but only show single divs

Question: I want to load the whole html content of an extern html file from the server into my website - just like a php inculde would do more or less.
So far I can load the whole file and show in a div while using the id and all.
But how can I only show one part of the div?
This is my HTML with the jQuery Script:

    <meta title="TITLE">
    <link rel="stylesheet" href="css/style.css" type="text/css" />

This is the content of the HTML file i want to load from:

CITY1

CITY1

CITY1

CITY1

CITY1

CITY1

CITY1

CITY1

CITY1

CITY2

CITY2

CITY2

CITY2

CITY2

CITY2

CITY2

CITY2

CITY2

What I want to do now is, to only load the file once and then place the content into the specific divs I placed on my Website. For Example, I want to place the div subnavione from file.html into the div PlaceSubNaviOne and the same for the subnavitwo and PlaceSubnaviTwo.
Is this possible with jQuery load() or do i have to use a different way to get this done?
Comment: "Is this possible with jQuery load()?" Did you try it to find out?
Comment: i already managed to do it with load() in first place. But the problem is that i have to store the html i got from the load() into a div from which i can then place the specific html in single divs. my question was to load the html file once and just hold it in the back. then place the specific html into the single divs. thats why i asked if THIS is possible with load() or if i have to use a totaly different way
Answer: Try this : you can make use of .get() here as shown below
$(document).ready(function(){
  $.get( "file.html", function( data ) {
      $( "#PlaceSubNaviOne" ).html( $($.parseHTML(data)).filter("#subnavione") );
      $( "#PlaceSubNaviTwo" ).html( $($.parseHTML(data)).filter('#subnavitwo') );
  });
});

For more information on jquery get()
Answer: Try this :
$( "#main" ).load( "file.html", function() {
  $("#PlaceSubNaviOne").html($("#subnavione").html());
});

Refer : http://api.jquery.com/load/
Comment: when i use this the .load() places the whole html file code into the #main div and the  $("#PlaceSubNaviOne").html($("#subnavione").html()); places the code of the subnavione div into the PlaceSubNaviOne. now i have everything double on my website