Calculate a correlation matrix for all factor levels of a column

Question: How can I calculate a correlation matrix for each level of the categorical variable, where the correlations are among all variables in the remaining columns?
For the example below, this means the correlation between q2 to q10 in each level of q1?.
A<-data.frame(q1=c("A","A","A","D","D","D","F","F","F","G","G","G","G","A","D"),
      q2=sample(1:70, 15, rep=1),
      q3=sample(1:60, 15, rep=1),
      q4=sample(1:60, 15, rep=1),
      q5=sample(1:103, 15, rep=1),
      q6=sample(1:50, 15, rep=1),
      q7=sample(1:101, 15, rep=1),
      q8=sample(1:40, 15, rep=1),
      q9=sample(1:100, 15, rep=1),
      q10=sample(1:200, 15, rep=1))

Also, how can I show these correlations on a plot?
Comment: "all variables for each levels of the categorical variable(q1)" is unclear. In the sample data `q1` is not categorical. Do you mean all other rows for each level of q1?
Answer: If I understand you correctly, you need n correlation matrices, one for each level of q1.
If that's the case, you can use a simple for loop to get them:
c <- list()
for(q in unique(data$q1)) {
  c[[q]] <- cor(data[data$q1 == q,2:10])
}

The c list will have an entry for each level of q1
Answer: correlations <- lapply(split(A, A$q1), function(x) cor(x[,-1]))

> correlations
$A
            q2          q3          q4          q5         q6         q7          q8          q9         q10
q2   1.0000000 -0.44803503  0.50600715  0.93230347  0.4369729 -0.1247089  0.83257155  0.47128720 -0.40309437
q3  -0.4480350  1.00000000  0.53166771 -0.20412996 -0.9404926 -0.7119750  0.06469342 -0.36555367  0.95642170
q4   0.5060071  0.53166771  1.00000000  0.71679818 -0.5384897 -0.7141115  0.87705638 -0.04306433  0.57753545
q5   0.9323035 -0.20412996  0.71679818  1.00000000  0.1162383 -0.1865482  0.96352065  0.16325848 -0.08958274
q6   0.4369729 -0.94049256 -0.53848969  0.11623826  1.0000000  0.4923609 -0.13194449  0.64332166 -0.99763177
q7  -0.1247089 -0.71197500 -0.71411145 -0.18654820  0.4923609  1.0000000 -0.39564648 -0.34010040 -0.55069571
q8   0.8325715  0.06469342  0.87705638  0.96352065 -0.1319445 -0.3956465  1.00000000  0.08376171  0.16455409
q9   0.4712872 -0.36555367 -0.04306433  0.16325848  0.6433217 -0.3401004  0.08376171  1.00000000 -0.59118795
q10 -0.4030944  0.95642170  0.57753545 -0.08958274 -0.9976318 -0.5506957  0.16455409 -0.59118795  1.00000000

$D
             q2         q3          q4         q5          q6         q7          q8         q9         q10
q2   1.00000000 -0.6763867  0.95671018  0.9704899 -0.04887372  0.3729085  0.83267631 -0.2684279 -0.38379940
q3  -0.67638669  1.0000000 -0.58384573 -0.6513078 -0.60950525 -0.3943479 -0.62258512  0.8898461  0.69153886
q4   0.95671018 -0.5838457  1.00000000  0.8620453  0.01355672  0.5925750  0.63735667 -0.1899837 -0.51516909
q5   0.97048986 -0.6513078  0.86204530  1.0000000 -0.17072346  0.1417973  0.93960117 -0.2401559 -0.19646514
q6  -0.04887372 -0.6095053  0.01355672 -0.1707235  1.00000000  0.5915035 -0.23682009 -0.8533831 -0.83975896
q7   0.37290854 -0.3943479  0.59257503  0.1417973  0.59150349  1.0000000 -0.17116412 -0.3371096 -0.90364809
q8   0.83267631 -0.6225851  0.63735667  0.9396012 -0.23682009 -0.1711641  1.00000000 -0.2699661  0.02392984
q9  -0.26842790  0.8898461 -0.18998368 -0.2401559 -0.85338309 -0.3371096 -0.26996613  1.0000000  0.70740850
q10 -0.38379940  0.6915389 -0.51516909 -0.1964651 -0.83975896 -0.9036481  0.02392984  0.7074085  1.00000000

$F
            q2         q3          q4         q5         q6         q7         q8         q9         q10
q2   1.0000000  0.1439251 -0.36801650 -0.7892030 -0.4045654 -0.9979487  0.8095933  0.9463303  0.96088598
q3   0.1439251  1.0000000  0.86717169  0.4941522  0.8467606 -0.2069818 -0.4643589 -0.1836355  0.41235657
q4  -0.3680165  0.8671717  1.00000000  0.8614718  0.9992149  0.3077360 -0.8437394 -0.6487839 -0.09611375
q5  -0.7892030  0.4941522  0.86147184  1.0000000  0.8809138  0.7482684 -0.9994238 -0.9453351 -0.58825368
q6  -0.4045654  0.8467606  0.99921489  0.8809138  1.0000000  0.3451900 -0.8643422 -0.6784229 -0.13547310
q7  -0.9979487 -0.2069818  0.30773601  0.7482684  0.3451900  1.0000000 -0.7703543 -0.9236982 -0.97664447
q8   0.8095933 -0.4643589 -0.84373942 -0.9994238 -0.8643422 -0.7703543  1.0000000  0.9558589  0.61536300
q9   0.9463303 -0.1836355 -0.64878390 -0.9453351 -0.6784229 -0.9236982  0.9558589  1.0000000  0.81980673
q10  0.9608860  0.4123566 -0.09611375 -0.5882537 -0.1354731 -0.9766445  0.6153630  0.8198067  1.00000000

$G
             q2         q3         q4         q5         q6         q7          q8         q9        q10
q2   1.00000000 -0.5672060  0.9137473  0.9221046  0.4872684 -0.4363765  0.06508126  0.4942240 -0.4619742
q3  -0.56720597  1.0000000 -0.6033027 -0.2675167  0.1195274  0.7432619 -0.85226036 -0.0813887  0.9611281
q4   0.91374727 -0.6033027  1.0000000  0.9014109  0.6820842 -0.7236664  0.21082792  0.7548119 -0.4087825
q5   0.92210460 -0.2675167  0.9014109  1.0000000  0.7670341 -0.3702843 -0.21819900  0.7237786 -0.1032187
q6   0.48726838  0.1195274  0.6820842  0.7670341  1.0000000 -0.4108090 -0.35300010  0.9657497  0.3702882
q7  -0.43637648  0.7432619 -0.7236664 -0.3702843 -0.4108090  1.0000000 -0.70799246 -0.6287476  0.5407077
q8   0.06508126 -0.8522604  0.2108279 -0.2181990 -0.3530001 -0.7079925  1.00000000 -0.1025016 -0.8382874
q9   0.49422403 -0.0813887  0.7548119  0.7237786  0.9657497 -0.6287476 -0.10250163  1.0000000  0.1913168
q10 -0.46197421  0.9611281 -0.4087825 -0.1032187  0.3702882  0.5407077 -0.83828741  0.1913168  1.0000000

To display, you can use image,
par(mfrow=c(1, length(levels(A$q1))))
for(c in correlations) image(c)

although for interpretation, you may want a legend. For that, try the ggplot2 code in Lapointe's answer
Comment: that means there are too many missing observations to calculate a correlation. see Details in the help for `cor` for other options (to view help type `?cor` in the R console
Comment: Thanks so much for your help. In my real data, I have lots of missing values. When I run this code the correlation would be NA. How can I modify this code to fix this issue. For example, How can I have use="complete.obs"?
Comment: No problem. To deal with missing obs, you could change ` cor(x[,-1]))` in the first line to ` cor(x[,-1], use="complete.obs"))` (or any of the other possible arguments to `use`)
Comment: When I use it , i got this error                                                                     Error in cor(x[, -1], use = "complete.obs") : no complete element pairs
Answer: Simply use cor(data) and here's how to put it in a chart.
data_cor <- cor(data)
library(ggplot2)
library(reshape2)
melted_data <- melt(data_cor)

library(ggplot2)
d <-ggplot(data = melted_data, aes(x=Var1, y=Var2, fill=value))
d +geom_tile()

Comment: Thanks for your help. But I need the correlation matrix for each levels of q1 separately.


Memory leak node js

Question: I have a memory leak on my nodejs application. In order to resume the purpose of the application, it's an api called by an iOS application and a backoffice to administrate some content.
The application is in production and we experience some memory leak due to utilisation.
The memory on the server is always going up and never going down.
I try to analyze the problem using node-heapdump.
First of all, i see a big difference between the heap size of the snapshot given by node-heapdump and the size taken by the app in the memory (heap size ~ 30Mb and RAM size ~ 100Mb), where that difference came from ?
Then i see an increment of the heap size just by refreshing a home page who does not return anything.
Is anyone has an idea of where my problem could be ?
For information i use nodejs version 0.10.x and expressjs 4.0.0
Thanks in advance guys.
EDIT
I install memwatch-next and the leak event is raised.
The error i have is this one :

warning: possible EventEmitter memory leak detected. 11 leak listeners
  added. Use emitter.setMaxListeners() to increase limit.

I try to set the defaultMaxListeners but when i stress the application the leak event is raised after sometime.
Does anyone knows what that error means ?
Comment: A home page that does not return anything?
Comment: For anything i mean not a json result or thing like that. So it's not because of a new memory allocation for an object that the memory went up.
Answer: have a look at memwatch-next
I had similar issues with the memwatch package and switched to memwatch-next and it installed without the node-gyp error and produced worked. As for the difference between the RSS and the heapdump , I am in the same boat as you are.
Comment: Thanks, the memwatch-next module actually work. I'll edit my post to put the result i have.
Comment: i use memwatch-next with heapdump to take the memory snapshot whenever the leak event occurs so that i can load those snapshot file in chrome and look for objects thats are consuming more memory but i am not able to diagnose exactly where those objects are been used in my code as it shows the strings object with highest count. Any luck with diagnosing the snapshot .
Answer: Try to find memory leakage leak and stat from https://www.npmjs.com/package/memwatch.
Hope it would help.
Comment: I try to install memwatch through npm but it fails.
Failed at the firstname.lastname@example.com install script 'node-gyp rebuild'.
npm ERR! This is most likely a problem with the memwatch package,
npm ERR! not with npm itself.

Did you have the same problem ?
Comment: you have to install python to order to use mematch as its uses some os apis to get data..make sure you seted up environment variable so python command can run from anywhere..
Comment: This still isn't working. Anyways memwatch will not give me more information that i already have with node-heapdump as the both show the heap size and repartition. Anyway thanks for your reply
Comment: @MartinStievenart install node-gyp package globally and it will fix the issue of installation.
Answer: I think you need this tool: easy-monitor
Answer: Might I recommend you try running the application with the --inspect argument, this will then allow you to attach Chrome dev tools and take memory snapshots. From here take one at startup one during testing and then one after you have finished testing the application (no more requests to the application but must still be running.) This will allow you to see what exactly is causing the growth in memory.
From here you will be able to see what is causing the growth and hopefully an indication as to where the leak is.

Memory leak node js


Em que tag colocar o formulário?

Question: Eu criei uma página e dentro desta página tem um formulário. Até aí, tudo ok. Mas eu coloco o formulário dentro de que tag? Semanticamente falando, dentro de um section, de um article, de um section e um article, ou de uma div? Ainda estou um pouco confuso com a semântica quando sai do usual. Pesquisei no Google, mas não obtive respostas satisfatórias.
section
form
form
/section

ou
article
form
/form
/article

ou
section
article
form
/form
/article
/section

ou
div
form
/form
/div

Comment: Resposta rápida: não existe resposta. O elemento pai dependerá da [outline](https://pt.stackoverflow.com/q/247160/5878) da sua página. Se o formulário faz parte do conteúdo principal, estará dentro da `article`, mas poderá estar dentro da `article > section`  se a outline exigir isso, ou ainda em `article > section > div`. Se o formulário é secundário na página, estará fora da `article`, em qualquer combinação de elementos novamente. Em relação ao formulário, não faz diferença, o que muda é a outline.
Answer: Na documentação da W3C aparentemente não existe referencia a estrutura semântica de onde o form deve vir na página. Já na documentação da Mozilla eles colocam na verdade a section dentro do form!
Mas o ponto mais importante, e que tanto a W3C quando a Mozilla abordam é a estrutura semântica do form em si.
Veja o modelo proposto pela Mozilla abaixo:

Here you'll see that we are wrapping the contact information fields
  inside a distinct
 element.

OBS: Tente contar quantas
 existem nesse modelo!

h1 {
    margin-top: 0;
}

ul {
    margin: 0;
    padding: 0;
    list-style: none;
}

form {
    margin: 0 auto;
    width: 400px;
    padding: 1em;
    border: 1px solid #CCC;
    border-radius: 1em;
}

div+div {
    margin-top: 1em;
}

label span {
    display: inline-block;
    width: 120px;
    text-align: right;
}

input, textarea {
    font: 1em sans-serif;
    width: 250px;
    box-sizing: border-box;
    border: 1px solid #999;
}

input[type=checkbox], input[type=radio] {
    width: auto;
    border: none;
}

input:focus, textarea:focus {
    border-color: #000;
}

textarea {
    vertical-align: top;
    height: 5em;
    resize: vertical;
}

fieldset {
    width: 250px;
    box-sizing: border-box;
    margin-left: 136px;
    border: 1px solid #999;
}

button {
    margin: 20px 0 0 124px;
}

label {
  position: relative;
}

label em {
  position: absolute;
  right: 5px;
  top: 20px;
}
<form method="post">

Payment form

Required fields are followed by *.

Contact information

            <fieldset>
              <legend>Title</legend>

                      <input type="radio" id="title_1" name="title" value="M." >
                      Mister

                      <input type="radio" id="title_2" name="title" value="Ms.">
                      Miss

            </fieldset>

                Name:
                *

              <input type="text" id="name" name="username">

                E-mail:
                *

              <input type="email" id="mail" name="usermail">

                Password:
                *

              <input type="password" id="pwd" name="password">

Payment information

                Card type:

              <select id="card" name="usercard">
                <option value="visa">Visa</option>
                <option value="mc">Mastercard</option>
                <option value="amex">American Express</option>
              </select>

                Card number:
                *

                <input type="text" id="number" name="cardnumber">

                Expiration date:
                *
                formatted as mm/yy

              <input type="text" id="date" name="expiration">

 <button type="submit">Validate the payment</button>

    </form>

Contou quantas
 tinham? Isso mesmo ZERO! Reparou como o form é montado de maneira minuciosa e 100% semântico. Essa tem que ser a preocupação principal.
Palavras finais:
Então onde o form está na estrutura não importa muito. Se seu form é o assunto principal da página coloque o
 nele e coloque ele posicionado mais para cima na página, pois os leitores de tela começam de cima para baixo. Se puder faça um teste básico, tente navegar em sua tela apertando o TAB para ver como o foco vai mudando. Se precisar faça correções usando o tabindex (leia mais sobre tabindex aqui)

Documentação W3C: https://www.w3.org/TR/html401/interact/forms.html
Documentação Mozilla: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/How_to_structure_an_HTML_form

Informações adicionais sobre acessibilidade
Segundo ai W3C WAI e a WebAim vc pode e deve usar os aria-labelledby na construção do formulário para ajudar os leitores de tela. Vc pode se informar mais aqui https://www.w3.org/WAI/tutorials/forms/instructions/#using-aria-labelledby
EX: <input type="password" name="password" id="password" aria-describedby="password">
Além disso, vc também pode usar os role para interagir melhor com os leitores de tela. Basic form hints da Mozilla Nessa documentação vc pode se informar melhor.
EX: Repare no role na section e no aria-required no input
<form>

      * Name:
      <input type="text" value="name" id="name" aria-required="true"/>

</form>

Importante: Se vc tem uma div que semanticamente não é um buttom, mas faz o papel de buttom, pois pode ser clicado etc, é imprescindível que vc use esses atributos de role e aria para os leitores de tela identificarem esse "componente" como algo clicável e aria ativa! Documentação completa W3C ARIA, lá tem tudo sobre os roles e os arias https://www.w3.org/TR/aria-in-html/ (2017)
EX: Mais uma vez repare no role na section e no aria-checked

    Escolher esse

Vc ainda pode trabalhar melhor seu forme usando os microdatas do Schema por exemple e colocando itemscope itemtype itemprop nos elementos. Aqui tem um modelo para LocalBusiness http://schema.org/LocalBusiness

Em que tag colocar o formulário?


What happens in the fully connected layer of a Deep-Q-Network?

Question: I am currently reading Deepminds "Playing Atari with Deep Reinforcement Learning"-Paper (2013) and since I don't quite understand it, I would like to ask here.
What exactly happens in each fully connected layer? I understand what the convolutional layers do. How do the fully connected layers decide on which action to take?
From my understanding, we train, using the shown algorithm in the paper and when we finally got it trained, we just simply combine the information we get from the input with the weights and it's done.
Please help me :)
Comment: I am not sure what you mean by "where the Q-function specifically is used in that fully connected layer". The fully connected layer does not "use" Q-function. But the loss function does involve Q-function. Perhaps that's what you are asking?
Comment: The whole neural network provides an estimate of the Q-function ( state action value function) from input images. Its last layer would give estimated utility of taking different actions. Based on the utilities, the agent decides to take the optimal action, or with a small probability take a random action (exploration).
Comment: That I already know. I would like to know where the Q-function specifically is used in that fully connected layer only. I understand the basic conecpt if that wasn't clear.
Answer: The network in the referenced DQN paper estimates state-action values for a single state and all possible actions at once. It returns a vector $[\hat{q}(S,a_1), \hat{q}(S,a_2), \hat{q}(S,a_3)...]$ given an input state $S$ - the action space is the same for all states, and is just associated with each possible controller input (plus I assume a "no input" choice).
The action choice is then made using $\text{argmax}_a$ over this vector.

What exactly happens in each fully connected layer? I understand what the convolutional layers do. How do the fully connected layers decide on which action to take?

They don't "decide" what action to take, but calculate the action value for each $a$ - the fully connected layers are just a normal multi-layer neural network used for regression, taking the feature maps extracted from the pixels as input. The actual decision is left to the agent, but the predictions of the network guide the agent to the best estimate of the optimal action given any input state.
An alternative, and equally valid, approach is to have the network predict value given an (S, A) pair. Then in order to select an action, the network needs to predict a minibatch of the state plus all possible actions in order to construct the same vector, and select the maximum.
Depending on the nature of the environment and possible actions, you may choose either architecture (predict values of all actions at once from state representation or predict one action at at time from state & action representation), they are roughly equivalent theoretically.


Show the functional $ x(t) \mapsto \int_0^1 \left[ \frac{1}{2} \left( \frac{dx}{dt} \right)^2 - a x \right] \, dt$ is minimized at a parabola

Question: Consider functions $x(t): [0,1] \to \mathbb{R}$ with $x(0) = x(1) = 0$.  I would like to find a prove that the functional
$$ x(t) \mapsto \int_0^1 \left[ \frac{1}{2} \left( \frac{dx}{dt} \right)^2 - a x \right] \, dt$$
is minimized along the curve $x_0(t) = a t (1 - t)$.  Perhaps I could argue that $x(t) = x_0(t) + \epsilon \, x_1(t)$ and differentiate with respect to $\epsilon$ ?
This is not unlike the isoperimetric problem.
Comment: Have you written down the Eulier-Lagrange equation for the problem?
Comment: I should also say, "Yes, you could write $L(x) = $ your integral, and then ask what is $L(x + \epsilon y)$, arguing that if $x_0$ is a minimum for $L$, then $\epsilon \mapsto L(x + \epsilon y)$ must have a minimum at $\epsilon = 0$ for every $y$, and see what this tells you (using integration by parts, and your boundary conditions)." This amounts to deriving the E-L equation by hand. I'm surprised you've got no boundary conditions on $x'(0), y'(0)$, but maybe those aren't needed for some reason.
Comment: finally I did recibe  an upvote, which positively validates me… if you closed the OP, I will thank you.
Answer: For the functional $\int_0^1\left(\frac{x'^2}{2}-ax\right)dt$ and the Euler-Lagrange equation you need to calculate
$$\frac{\partial{\cal L} }{\partial x}=-a,$$
and
$$\frac{\partial{\cal L} }{\partial x'}=x'.$$
Then the equation is
$$x''+a=0$$
which upon integration you will get
$$x(t)=-\frac{at^2}{2}+Bt+C$$
for some other constants $B,C$.


What is the real meaning of Hilbert's axiom of completeness

Question: According to Greenberg's book of geometry it is sufficient to consider the axiom of Dedekind along with Hilbert's axioms (except of course for the Archimedian Principle and his Axiom of Completeness) in order for Euclidian Geometry to be categorical (in this case the only model is that of order pairs of numbers used in Analytic Geometry).
From this I can say that, because Dedekind's axiom of continuity is equivalent to Cantor's axiom (Nested Intervals Principle) and because any of them implies the Archimedian Principle but not the other way around then I guess Hilbert's Axiom of completeness is necessary in order to fix that "something" missing if the Archimedian property is assumed as an axiom instead of the others.
So, my problem is basically that Hilbert's axiom of completeness is pretty weird and I cannot imagine in what sense it can be used along with Archimedes' Axiom to obtain Dedekind's Axiom.
Now, this is what Hilbert says in his book:
This axiom gives us nothing directly concerning the existence of limiting points, or of
the idea of convergence. Nevertheless, it enables us to demonstrate Bolzano's theorem by
virtue of which, for all sets of points situated upon a straight line between two definite
points of the same line, there exists necessarily a point of condensation, that is to say,
a limiting point. From a theoretical point of view, the value of this axiom is that it
leads indirectly to the introduction of limiting points, and, hence, renders it possible to
establish a one-to-one correspondence between the points of a segment and the system
of real numbers.
These are the definitions I'm talking about:

Hilbert's Axiom of completeness: To a system of points, straight lines, and planes, it is impossible to add other elements in such a manner that the system thus generalized shall form a new geometry obeying all of the five groups of axioms. In other words, the elements of geometry form a system which is not susceptible of extension, if we regard the five groups of axioms as valid.
Dedekind's Axiom: Suppose that the set ${l}$ of all points on a line $l$ is the disjoint union $\Sigma_1\cup \Sigma_2$ of two nonempty subsets such that no point of either subset is between two points of the other.Then there exists a unique point $o$ on $l$ such that one of the subsets is equal to a ray of $l$ with vertex $o$ and the other subset is equal to the complement.
Cantor's Axiom: Let $\{\overline{A_nB_n}\}_{n\in N}$ be a sequence of segments on
    some straight line such that $\overline{A_{n+1}B_{n+1}}\subset \overline{A_{n}B_{n}}$ for all $n\in \mathbb{N}$. Then the intersection of such segments is not empty and there is
    a point $o$ that belongs to all of them.
Archimedes' Axiom: For any two segments $\overline{AB}$ and $\overline{OE}$ there is
    a positive integer $n\in \mathbb{N}$ such that $\overline{AB}<n\cdot\overline{OE}$.
Comment: `According to Greenberg's book of geometry it is sufficient to consider the axiom of Dedekind along with Hilbert's axioms (except of course for the Archimedian Principle and his Axiom of Completeness) in order for Euclidian Geometry to be categorical`, on which page?
Answer: Hilbert's completeness axiom is not a standard axiom because it is about the other axioms, it is rather a meta-axiom about the models of the other axioms.
Giovanni argues that Hilbert's was aware of Dedekind completeness axiom and chose this completeness property V.2 rather than second order Dedekind cuts because V.2 does not imply Archimedes axiom:
http://dx.doi.org/10.1387/theoria.4544
See also the review of the above paper by Pambuccian which links to interesting related papers:
https://zbmath.org/?q=an:06179688
Answer: Roughly speaking, with the Archimedean axiom, one restricts to the line to subfields of the reals.  Maximality says all the reals are there.


Prove: If $\sum a_n$ converges conditionally, then $\sum a_nz^n$ has radius of convergence is $1$.

Question:
Prove: If $\sum a_n$ converges conditionally, then $\sum a_nz^n$ has radius of convergence  is $1$.

How should I approach this? I tried looking at $\sum |a_n z^n|$ to conclude about $|z|$.
Comment: $\sum a_n$ converges implies $a_n \to 0$ implies $\limsup_{n\to \infty} \sqrt[n]{|a_n|} \le 1$.  $\sum |a_n|$ diverges implies $\limsup_{n\to \infty} \sqrt[n]{|a_n|} \ge 1$ by the contrapositive of the root test.
Answer: If $r$ is the radius of converge of a power series, then that series converges absolutely for all $z$ with $|z| < r$, and diverges for  $|z| > r$.  So conditional convergence tells you exactly what the radius is.
Comment: $\sum a_n$ converges so $\sum a_n z^n\rightarrow |z|\geq 1$

$\sum |a_n|$ diverges so $\sum|a_n|| z|^n\rightarrow |z|\leq 1$

so $|z|=1$?
Comment: What you wrote didn't make sense
Answer: This follows from Abel's lemma:

If $f(z) = \sum a_n z^n$ is a power series and if the sequence $(|a_n|s^n)$ is bounded then $f$ converges absolutely in $B(0,s)$.

Indeed,
if $0<t<s$ then $q=t/s <1$ and $|a_n|t^n \leqslant M q^n$ where $M$ is the bound we're assuming exists, so
$$\sum |a_n|t^n \leqslant M \frac{1}{1-q}<\infty$$
On to your problem, the sequence $(|a_n|)$ is certainly bounded since it converges to $0$ by virtue of the conditional convergence, so Abel's lemma guarantees $f(z) = \sum a_n z^n$ converges absolutely in $B(0,1)$. This means the radius is at least $1$.
It cannot have radius of convergence larger than $1$, because by Abel's lemma, again, it would force absolute convergence on $B(0,r)$ with $r>1$, contrary to your hypothesis.


Indices - factorising

Question: Simplify: $$\frac {x^5y^2x^3 + x^4y^5 - y^5x^7y^4}{x^4y^3}$$
I know this is probably low level stuff but I need to be able to do this specific type of question and I have no way of checking my work. If anyone could offer a step by step working I'd be appreciative
Comment: Well, if you want us to check your work you should provide it.  What answer do you get?
Comment: Note:  an excellent way of checking supposed simplifications is to plug in values.  If an algebraic identity is intended to hold for all $x,y$ then it must hold for particular $x,y$.  Try $(x,y)=(1,1), (2,1),(1,2)$ for example.
Answer: You have
\begin{align*}
\frac {x^5y^2x^3 + x^4y^5 - y^5x^7y^4}{x^4y^3}
&=\frac {x^8y^2 + x^4y^5 - x^7y^9}{x^4y^3} \\
&=\frac {x^4y^2\big(x^4 + y^3 - x^3y^7\big)}{x^4y^3} \\
&=\frac {x^4 + y^3 - x^3y^7}{y},\quad x\not=0.
\end{align*}
That's about as far as you can go.
Comment: I sit corrected, then.
Comment: you should edit to show y is not zero (as it is what is in the denominator.
Comment: Don't need to. $y$ is still in the denominator. It's when a factor *disappears* from the denominator that you need to specify such a thing.
Answer: The highest common factor of the terms in the numerator is $x^4y^2.$ This is also a factor of the denominator, hence you can cancel it off to get $$\frac{x^4+y^3-x^3y^7}{y}.$$
Answer: An alternate way is to break the problem down into simple workable parts:
$$\frac{x^5y^2x^3+x^4y^5−y^5x^7y^4}{x^4y^3}$$
$$=\frac{x^5y^2x^3}{x^4y^3}+\frac{x^4y^5}{x^4y^3}-\frac{y^5x^7y^4}{x^4y^3}$$
$$=\frac{x^8y^2}{x^4y^3}+\frac{x^4y^5}{x^4y^3}-\frac{x^7y^9}{x^4y^3}$$
$$=\frac{x^4}{y}+y^2-x^3y^6,\quad x\not=0.$$
This is equivalent to the answers given above.
Comment: Done -- thanks.
Comment: Technically, you'd need to add provisos like $x\not=0$ and maybe $y\not=0$ to be equivalent to my answer. When factors disappear from the denominator, it aids in clarity to display such a proviso.

Indices - factorising


Prove that a non-zero, non-unit element $a \in R$ is irreducible

Question: Prove that a non-zero, non-unit element $a \in R$ is irreducible iff its only divisors are units of $R$ and elements of $R$ which are associates of $a$
I have a proof below but i'm not sure if it is correct. I think I need to use $c$ in the second part but I'm not sure how.
Here is my proof
$\Rightarrow$
Assume $a\ne 0$, $a$ is not a unit $\in R$ is irreducible
Then $a=bc$ where at least one of $b$ or $c$ is a unit
Therefore if $b$ is a unit then $c$ is an associate of a and if $c$ is a unit then $b$ is an associate of a
As $a=bc$ then $b|a$ and $c|a$
$b$ and $c$ are either units or associates of $a$ therefore the only divisors of $a$ are units of $R$ or associates of $a\in R$
$\Leftarrow$ Assume $a\in R$ can only be divided by units or associates
Let $b,c\in R$ divide $a$, by assumption $b$ must either be a unit or an associate
If $b$ is a unit then $a$ is irreducible
else $b$ is an associate
This means there exists a unit $u\in R$ where $a=ub$
Therefore $u|a$ so once again a is divided by a unit and is therefor irreducible
Comment: What does it mean for a "non-reducible" element to be irreducible?
Comment: How do you define "non-reducible" vs. "irreducible". I've never seen them used to mean different things.
Comment: @ErickWong That was meant to say non-unit my bad
Comment: @CameronBuie Was meant to say non-unit
Comment: @MartinBrandenburg This is not a duplicate as I was trying to see if my own proof was correct which I have been told to put in the question which I shall now do
Answer: $\Rightarrow$
Assume $a\ne 0$, $a$ is not a unit $\in R$ is irreducible
Then $a=bc$ where at least one of $b$ or $c$ is a unit
Therefore if $b$ is a unit then $c$ is an associate of a and if $c$ is a unit then $b$ is an associate of a
As $a=bc$ then $b|a$ and $c|a$
$b$ and $c$ are either units or associates of $a$ therefore the only divisors of $a$ are units of $R$ or associates of $a\in R$
$\Leftarrow$ Assume $a\in R$ can only be divided by units or associates
Let $b,c\in R$ divide $a$, by assumption $b$ must either be a unit or an associate
If $b$ is a unit then $a$ is irreducible
else $b$ is an associate
This means there exists a unit $u\in R$ where $a=ub$
Therefore $u|a$ so once again a is divided by a unit and is therefor irreducible
Comment: Since this proof is part of your question (this is, you ask if it is correct), it should be included in your question, not presented as answer.
Comment: How did you that in a second
Comment: @robjohn Oh ok, I thought as I was trying to answer it it would be an answer, what if I find out it does work would I then move it to the answers section?
Comment: Since your question is about the correctness of the proof, not about what the proof is saying, I would not think the proof would actually answer the question. If you or someone else shows that your proof is correct, then *that* should be in the answers.
Comment: @robjohn The main question is to find a proof which I have done and I think it is correct I'm just note sure if I need to add something extra into it to make it a more complete proof


Issue with deferred location updates ios

Question: I have been trying to implement deferred location updates in an app for the past two days.
The problem I am facing is that
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

method is being called each second even after I call the
 [self.locMgr allowDeferredLocationUpdatesUntilTraveled:(CLLocationDistance)200 timeout:(NSTimeInterval)25];

method.
ALthough I have to say that
 - (void)locationManager:(CLLocationManager *)manager didFinishDeferredUpdatesWithError:(NSError *)error

is called exactly after 25 seconds as specified by me allowDeferredLocationUpdatesUntilTraveled method with error code = null.
It is my understanding from the docs that didUpdateLocations should be called after 25 seconds only.
Any help would be much appreciated.
Comment: I checked almost all the forums present on deferring in ios and found this. It has almost the same issue that i am facing.
 https://devforums.apple.com/message/903992#903992
Comment: I dont think I will get a correct answer.The following link seemed helpful,

https://devforums.apple.com/message/766429#766429

Posting it cause it may be helpful to others.
Answer: I have been struggling with the same issue, and I may have found an answer that solves this problem for many - at least it solves my problem and gets deferred updates working consistently for me. I followed all of the steps in the list above and no matter what I did, location updates would not defer. It occurred to me that I might have other apps running that were not allowing the system to sleep, so I killed all other apps in the multitasking tray. I ran my sample app again and ... it worked! But the story doesn't end there. I tried again a little later, and even though there were no other apps running in the multitasking tray I couldn't get location services to defer. Then it occurred to me that I have an app on my phone called "Moves" which manages to keep itself alive even after you manually kill it. I'm not entirely sure how Moves comes magically back to life when you kill it, but it does (perhaps using bluetooth and the app preservation / restoration service). Even though it is alive and tracking your location it doesn't appear in the multitasking tray. I think that only apps that are manually launched appear in the tray - if the OS launches an app it doesn't appear in the tray. But I digress ... I was able to get deferred location services to work consistently in my app by disallowing Moves to use location services. When I did, Moves complained even though it wasn't in multitasking tray. It seems that if another app is using location services (and not deferring) your app won't defer either.
Answer: According to the Apple Developer Forums for the iOS 6.0 SDK, deferred location updates are only available:

on iPhone 5 hardware
running iOS 6.0 or higher
desired accuracy set to kCLLocationAccuracyBest
call the "startUpdatingLocation" method
wait for location updates to come in at approximately 1 per second
then begin deferring updates

See: https://devforums.apple.com/message/751974#751974
So sounds like you need iPhone 5 hardware, and to wait for location updates to come in at 1Hz.
Comment: And yes I forgot to mention, I am using an actual iphone 5 , tested with both ios 6 and 7 versions, had a clear view of the sky and also have taken care of all the points mentioned by @viruss mca
I beleive u took this answer from

 http://stackoverflow.com/questions/12992380/how-to-work-with-deferred-location-ios-6
Comment: @giddyboy: of course it is from it.can you show initialisation of location manager?
Comment: - (id)init {
 self = [super init];

 if(self != nil) {
        if([CLLocationManager locationServicesEnabled])
        {

            self.locMgr = [[CLLocationManager alloc] init];
            self.locMgr.delegate = self;

            self.locMgr.desiredAccuracy = kCLLocationAccuracyBest;
            [self.locMgr setDistanceFilter: kCLDistanceFilterNone];
        }
        else
        {
            self.locMgr = nil;
        }

 }

 return self;
}
Is this it?
Comment: try removing after `[self.locMgr setDistanceFilter: kCLDistanceFilterNone];`.
Comment: I tried with that. The location manager reports an error with error code 12( a kCLErrorDeferredDistanceFiltered error). Also it is written in the docs that we have to set it to kCLDistanceFilterNone.


$\dim V=\dim W+\dim U$ and the dimension of $\mathbb{R}^3$ proof ex

Question: For each of the following pairs $E_1,E_2$ of a subspace of $\mathbb{R}^3$, determine $E_1+E_2$ and prove if $E_1\oplus E_2=\mathbb{R}^3$:
$E_1=\{(x,y,z)\in\mathbb{R}^3:x+y+z=0\};E_2=\{(x,y,0):(x,y)\in\mathbb{R}^2\}$
The intersection is zero. However the dimension of $E_2$ is 2 and the dimension of $E_1$ is 2,since a possible basis for $E_2$ is $e_1=(1,00)$ and $e_2=(0,1,0)$
According to the theorem.
$\dim V=\dim W+\dim U$ when W and U are subspaces of V.
However the dimension of $\mathbb{R}^3$ is not 4.
Questions:
What is going wrong?
Thanks in advance!
Comment: Are you sure the intersection is 0? What about $(1,-1,0)$?
Comment: According to what theorem? $\mathrm{span}(e_1), \mathrm{span}(e_2)$ are subspaces of $\mathbf{R}^4$, but $\dim\mathrm{span}(e_1)+\dim\mathrm{span}(e_2)=2\neq4$. $\dim V=\dim W+\dim U$ holds iff $V=W\oplus U$.
Answer: The intersection is $ \ne \{0\}$ !
We have $\{(x,-x,0): x \in \mathbb R \}= E_1 \cap E_2$, thus $E_1+E_2=\mathbb{R}^3$, but $E_1\oplus E_2=\mathbb{R}^3$ is not valid.
Comment: How did you compute the intersection?
Comment: $(x,y,-x-y)=(x,y,0)$, however if $-x-y=0$ then $x=0$, right?
Comment: It should be clear that $\{(x,-x,0): x \in \mathbb R \} \subseteq E_1 \cap E_2$. Now let $(x,y,z) \in E_1 \cap E_2$. Then $x+y+z=0$ and $z=0$. Hence $y=-x$, therefore $(x,y,z)=(x,-x,0)$
Comment: what am I doing wrong with my method?
Comment: What do you mean with "my method" ?
Comment: Thanks for the replies. I have just discovered what I was doing wrong. Mistaken x by y.


Partial derivatives with Einstein summation

Question: Can someone help me to prove this statement? Or provide argumentation why it holds.
$$\frac{\partial x^a}{\partial x^{b'}}\frac{\partial x^{b'}}{\partial x^c}=\delta^{a}_{b}$$
It uses the Einstein summation convention - if an index is repeated, we assume the quantity is summed over. The superscripts denote indices, not exponents. The $x'$ are a different coordinate system from the $x$.
Answer: If $x^a = x^a(x')$ then using the chain-rule
$$
\delta_b^a = \frac{\partial x^a}{\partial x^b}
= \frac{\partial x^a}{\partial x'^c}\frac{\partial x'^c}{\partial x^b}
$$


How to create a view to display event registrants?

Question: I'm having troubles setting up a View that displays a list of registrants (not registrations!) for a particular event. I don't know how to setup RELATIONSHIPS correctly?
(I have already created a view that displays all registrations for a particular event, but since the user can register more than once for a particular event, I'm getting a list with multiple users enteries (if user registered multiple times) which is not what I want.)
Any suggestions?
Answer: For displaying user entries only one, open the  Query settings: Settings located at bottom of the Advance section.
There u can check the Distinct checkbox which will make the view display only distinct items.
Hope this help you...
Comment: Distinct cannot solve this since registration ID is always unique per event, but user ID is not and I would need to apply distinct on that column.
Answer: I do not see a difference between registrations and registrants,this can be handled with what fields you are showing in the views.While the problem of having repetitive results can be handled by showing the distinct results but I would have preferred doing it at the time user is registering multiple times for the same event user has already registered, as the problem you are having user will face the same problem, they will never know if they are already registered for the event, instead a validation should be there on email address(or any unique field to catch user presence) and event to tell user about being already registered.
Comment: There is a difference between registrations and registrants: User can have more than one registration per event (in my case that is desirable). That means if I list all registrations for particular event, I could possibly get multiple enteries of one user. Distinct cannot solve this since registration ID is always unique.
Answer: I believe you can expose user fields and add a relationship on the user entity referenced by registration field "user". This may not solve your duplicate problems.
You may be able to list users instead, and add a relationship to the registration referencing the user, and you may need to go one level deeper and add a relationship to your event content referencing the registration. Then filter on the registration existing and on the event content ID.
If anonymous users can register, both of these will have slight issues with that.
Answer: Dealing with duplicates like this is often an issue with Views. I have two suggestions to try:

Assuming this is a field-based View, try using "group by" on a user field, and don't display any of the registration distinct information, if possible. You may want/need to play with display tricks, whether specifying tags or custom CSS to get the display nice.
If that doesn't do the trick, you may have to resort to a hook_views_prerender function, and combine/eliminate results there. It's not fun, but I have had to do that kind of thing on more than one occasion.


Why margins and mfx yield different results in R?

Question: When I run a simple logit regression between a binary variable $y$ over another binary variable $x$, the average marginal effects obtained by the function logitmfx (from mfx package) are different from those obtained by the function margins (from the eponymous package).
Because there is only one covariate ($x$), this discrepancy cannot be linked to a difference in concepts between average marginal effects (AME) and marginal effects at mean (MEM), as both coincide in this case.
Hence, what explains the gap?
Answer: The reason lies in the types of the variables: mfx is insensitive to type, and treats a binary variable as a boolean, even if it is numeric; whereas margins treats differently factors or boolean from numerical variables. In particular, the marginal effect computed for binary numerical variables is the predicted output $y$ when the variable $x$ equals 1 minus the predicted $y$ when $x$ equals its average, instead of subtracting the predicted output at $x=0$, as in mfx or when $x$ is a factor or a boolean. Hence, if you change the types of $x$ and $y$ to logical (or factor), you should retrieve the results of mfx.
To conclude, the most intuitive and consistent definition is probably the one of mfx.


I dont understand this probability question.

Question:

Bill, George, and Ross, in order, roll a die. The first one to roll an even
  number wins and the game is ended. What is the probability that Bill will
  win the game?

My Answer: Since Bill is the one to first roll the die, and the probability of him gettin an even number in the die is $\frac{3}{6} = \frac{1}{2}$ . Doesn't that mean that regardless of how George or Ross will have their turn, doesn't that mean that Bill will have a $\frac{1}{2}$ chance of winning this game?
Book's Answer: $\frac{4}{7}$ . (What?)

The Mathematics Department of the University of Louisville consists of
  8 professors, 6 associate professors, 13 assistant professors. In how many of
  all possible samples of size 4, chosen without replacement, will every type of professor be represented?

My Answer: Isn't this just a matter of combination? Let $S$ be the event in which every type of professor be represented then
$N(S)=  \binom {8} {4} + \binom {6} {4} +  \binom {13} {4} = 800$
Book's Answer: $7884$ (What?)
Comment: For the first part:  You are correct in that Bill has at least a $\frac 12$ chance of winning, but the game might not end on the first round!  You have to add the chance that he wins on round 2 (or round 3, or 4, ...).  For the second:  your calculation  considers the groups which only have one type, but the problem wants the groups with at least one prof, one assoc., one asst.
Comment: The book's answer to the second question should be $7488$.  These two questions are not related.  They should have been posed separately.
Comment: Sorry, but I can't understand on how will I set up of the chances that he wins on the 2nd or 3,4... round. Suppose 1 Round is where all three will roll the die. If B(ill) didn't win in this round, then he has 2/3 chance? of losing, thus making it 1/2 * 2/3 = 1/3. Does this mean, if neither one gets an even in the 1st round, then will we have another round where Bill has 1/3 chance of winning?
Comment: Let $p_k$ be the probability that Bill wins on Round $k$.  You have already shown that $p_1=\frac 12$.  What's $p_2$?  Well, the only path is $OOOE$, what's the probability of that?  Likewise he can only win on round $3$ if the path is $O^6E$, and so on.
Comment: Correct me if I'm wrong, $p_2$ = 1/8 right? If so, then I can create this summation $p_k = \sum_{k=1}^b \frac{p_{k-1}}{2^k}$ where $p_0 = 1$. Am I in the right track?
Comment: No....$OOOE$ is a path of length $4$ so $p_2=\frac 1{2^4}$.
Comment: Oh, sorry about that, but then going through it, I will then have this $\frac{1}{2}+\sum_{p=2}^k p_{k-1}\cdot \frac{1}{2^3}$. Does this even converge to something?
Comment: You need to get a closed formula for $p_k$.  You have $p_1=\frac 1{2^1}$, $p_2=\frac 1{2^4}$. You need the pattern.  What's $p_3$?  $p_4$?
Answer: Bill will ultimately win if he rolls an even number before the other two do so.

If he immediately rolls an even number he wins.
If he immediately rolls an odd number and both his opponents also do, then he's back in the same situation.
If any other result, he looses.
So by partitioning on these three cases, the probability of ultimately winning $p$ is defined recursively by the Law of Total Probability.

$$\begin{align}p ~=~& \mathsf P(\textsf{E}.^+) + \mathsf P(\textsf{OOO}.^+) p + 0
\\[1ex] ~=~& \tfrac 1 2 + \tfrac 1 8 p
\\[2ex] \therefore ~ p = 4/7
\end{align}$$

$N(S)=  \binom {8} {4} + \binom {6} {4} +  \binom {13} {4} = 800$

You have counted ways to select four professors, or four associate professors, or four assistant professors.   That is not the ways to select a group of four with at least one of each type.   This is:

 $$N(S_{\text{true}})=  \binom{8}{2}\binom{6}{1}\binom{13}{1} + \binom{8}{1}\binom{6}{2}\binom{13}{1}+\binom{8}{1}\binom{6}{1}\binom{13}{2}$$
Comment: An elegant solution.
Comment: @Maasumi The second bullet point.  After three consecutive odd results the first player is back in the original situation.
Comment: Thanks I got it now. Just started probability
Answer: For the second question. The 3 groups will have at the least one of their members being chosen to fill in a spot and once one has been chosen, then he/she cannot be chosen once again. This leaves us with a combination: $\binom {8} {2} \binom {13} {1} \binom {6} {1} + \binom {8} {1} \binom {13} {2} \binom {6} {1} + \binom {8} {1} \binom {13} {1} \binom {6} {2} = 7488$. This is because one group cannot be left out when choosing the professors. (The solution 7884 is not correct)
Answer: 1) No. Bill can win by rolling an even number, but he can also win by rolling an odd number: for instance, if George and Ross also roll odd numbers and then Bill rolls an even number.
2) No. A sample of size 4 contains at least one of each kind of professor if and only if it contains a professor, an associate professor, an assistant professor, and any one of the remaining 7+5+12 people. (You will have to make sure you don't overcount if you do it like this: if we have Professor 1, Associate Professor 4, Assistant Professor 5, and Professor 2, we need to make sure we don't count the duplicate Professor 2, Associate Professor 4, Assistant Professor 5, and Professor 1.)
Comment: You certainly did not say anything false.  What prompted my comment was answering [this question](http://math.stackexchange.com/questions/1707395/the-number-of-possible-options-to-get-colored-balls) and reading [this similar question](http://math.stackexchange.com/questions/1707781/combinations-of-6-students-among-20-at-least-one-male) yesterday.
Comment: does that mean(for part 2) I have to add 24C4 in my calculations?
Comment: Your calculations for Part 2 are simply irrelevant. You've found the number of ways you can have four Professors or four Associate Professors or four Assistant Professors. It will not help to add the number of ways you can have four people given that a Professor, an Associate Professor and an Assistant Professor are ill.
Comment: Thank you sir, I get it now :)
Comment: While you have correctly identified the errors made by the OP, the way you described the second question could lead to counting each of the valid solutions twice.
Comment: @N.F.Taussig My description of the set is correct, isn't it? I considered it OP's job to count the set correctly.
Comment: Fair enough. I'll add another line to clarify.
Answer:
Bill, George, and Ross, in order, roll a die. The first one to roll an even number wins and the game is ended. What is the probability that Bill will win the game?

The probability that Bill wins on the first throw is $1/2$.  If Bill does not win on the first throw, he can still win if George and Ross both toss odd numbers until Bill tosses an even number.  You did not take into account the possibility that Bill could win after the first round.
Since the probability of rolling an odd number is $1/2$, the probability that nobody wins during the first round is $(1/2)^3 = 1/8$.  Bill can then win in the second round by rolling an even number with probability $(1/8)(1/2)$, where $1/8$ is the probability that nobody won during the first round and $1/2$ is the probability that Bill wins on his throw during the second round.
If nobody wins during the second round, Bill can win in the third round with probability $(1/8)^2(1/2)$, where $(1/8)^2$ represents the probability that all three men toss odd numbers during the first two rounds and $1/2$ represents the probability that Bill tosses an even number in the third round.
More generally, Bill can win in the $k$th round if everybody tosses odd numbers for the first $k - 1$ rounds and Bill tosses an even number in the $k$th round.  Thus, the probability that Bill wins in the $k$th round is $$\left(\frac{1}{8}\right)^{k - 1}\left(\frac{1}{2}\right)$$
The probability that Bill wins is the sum over all $k$ of his winning in the $k$th round.
$$P(\text{Bill wins}) = \sum_{k = 1}^{\infty} \left(\frac{1}{8}\right)^{k - 1}\left(\frac{1}{2}\right) = \frac{1}{2}\sum_{k = 1}^{\infty} \left(\frac{1}{8}\right)^{k - 1}$$
You can calculate the probability by finding the sum of the geometric series.

The Mathematics Department of the University of Louisville consists of $8$ professors, $6$ associate professors, $13$ assistant professors. In how many of all possible samples of size $4$, chosen without replacement, will every type of professor be represented?

You added up the number of ways of selecting four professors, four associate professors, and four assistant professors.  In each case, you only considered samples with one type of professor.  Instead, you were supposed to consider samples with at least one representative of each type of professor.  Since the four selected people must contain at least one professor of each type, one type of professor must be represented by two people while each of the other types is represented by one person.

  The number of ways this can be done is $$\binom{8}{2}\binom{6}{1}\binom{13}{1} + \binom{8}{1}\binom{6}{2}\binom{13}{1} + \binom{8}{1}\binom{6}{1}\binom{13}{2}$$


Which site is better for questions about protracted visitor visas?

Question: In some countries it's possible to extend visitor visas to much longer than a tourist would usually stay; you could be on such a visa paying rent, getting dental cleanings, etc., though you're not taking local work.  I know someone even with kids in school under such visas.
Questions about such extensions and the like seem to lie somewhere between Travel.SE and Expatriates.SE.
I suspect these might be considered on-topic at either site, but I am more so wondering at which site such questions would be more likely to attract better answers.
On one hand, Travel has on the order of 10x more answers than Expatriates.  In fact, for some countries there are only a few questions here in total, but hundreds on Travel.
OTOH, on Travel, much of the Q/A, though not all, pertains to more touristic concerns, so "more Q/A" doesn't necessarily translate to "more likely to answer on intermediate topics."
Which community is better for these sorts of questions?
Answer: These questions would likely be on-topic here - you don't need to work somewhere to be an expatriate, and usually after 3-6 months of staying somewhere (which is the usual limit of most tourist visas) you will have different problems than someone who only spends a couple weeks in the country.
Whether these questions are on-topic on Travel.SE, I have no idea, but they might not be - I remember a couple questions that have been migrated from there over here that fall into the category you seek. You can definitely ask this question over there on the Meta as well. If they do allow - I would say because of the bigger community you will find more answers over there. A lot of the people who frequent this site also have an account on Travel as well, so it's likely you'll still receive answers from members who have more experience with long(er)-term living.


Hibernate criteria return more than one class

Question: I am newbie to Hibernate criteria and I got problem with simple obtain class.
Assume we have classes:
    Class A{
    int id;
    List aList;
    }

and:
  Class B{
    A a;
    (...)

}

and :
Class C{
int id;
String name;
B b;
}

I want to get List< C > if 'name' like 'abc'. Here is my criteria code:
    Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
    Criteria crit = session.createCriteria(C.class);
    crit.add(Restrictions.like("nazwa", "%"+string+"%").ignoreCase());
    return crit.list();

I got exception:

org.postgresql.util.PSQLException: ERROR: operator does not exist:
  character varying = integer

In my SQL query generated by criteria I can see "left outer join" on my A and B classes that are contained in my C class. Probably that's why I cannot load
Answer: There will be left outer joins if the associations are @OneToOne or @ManyToOne, just because they are eager in the ToOne owning side by default.
If you want to use such a LIKE clause, use MatchMode.ANYWHERE  and ilike instead:
add(Restrictions.ilike("nazwa", string, MatchMode.ANYWHERE))

Also, make sure the property you want to query in class C is named nazwa (it is typed as name in the code example), and it has a proper getter/setter.
Comment: yes, there are @ManyToOne annotations. How to drop left outer join in this criteria? I must select only my C class...
Comment: You can find the answer to that question in this site easily: [How to stop Hibernate from eagerly fetching many-to-one associated object](http://stackoverflow.com/q/222453/851811). Have you tried `@ManyToOne(fetch=FetchType.LAZY)` ?


perfect match graph theory

Question: The question:

Prove that if $G$ is a graph with $2n$ vertices and degree of each
  one is at least $n$, then  there is perfect match in G.

hint???
Comment: What is perfect match?
Comment: @hyprfrco [Definition](https://en.wikipedia.org/wiki/Matching_(graph_theory)#Definition)
Comment: Hint: You can use Hall's theorem to prove there is a perfect matching.
Answer: Prove each step in sequence or use previous results from your book/lecture notes
Step 1:

A graph with $2n$ vertices where every degree is at least $n$ must be connected

Step 2:

A graph with $2n$ vertices where every degree is at least $n$ must have a Hamiltonian cycle.

Step 3: (hidden with spoiler tag)

 - A graph with a Hamiltonian cycle and an even number of vertices must have a perfect matching.

perfect match graph theory


Strip NSString of special characters in setter method in implementation file in Objective-C

Question: I have a property
@property (strong,nonatomic) NSString *myString;

where I store an NSString and this property is called in many places in the implementation file as self.myString.
I have run into a problem where the string sometimes contains an angled apostrophe as opposed to the kind on the QWERTY keyboard and this special character is throwing off string comparisons.
With a managed object, you can use the setter method to do things to a property.  Is there a way that I can use a setter method to convert the angled apostrophe into a regular apostrophe in an implementation file.
Something like:
-(NSString*) myString {
    NSString * myString = [self stringByReplacingOccurrencesOfString:@"'" withString:@"'"];
}

This is a mixed Objc-Swift project, so I guess I could also add an extension to NSString in Swift if that is a better way to do it.
Thanks for any suggestions.
Answer: As setter:
- (void)setMyString:(NSString *)aString {

    _myString=[aString stringByReplacingOccurrencesOfString:@"'" withString:@"'"];
}

However you could also leave it a regular property, storing it exactly as received, but providing a derived property that would sanitize the string. Example:
- (NSString *)myStringSanitized {

    return [self.myString stringByReplacingOccurrencesOfString:@"'" withString:@"'"];
}

Optionally if your code uses Key-Value observation (for example with Cocoa Bindings), you could also add this to make sure a change notification for your sanitized string is fired whenever the underlying original changes:
+ (NSSet *)keyPathsForValuesAffectingMyStringSanitized {

    return [NSSet setWithObjects:@"myString",nil];
}

Now you can use self.myStringSanitized anywhere you need the sanitized version of your string, but you still have the unmodified version available as self.myString.


Extrair parte de URL com PHP

Question: Preciso pegar uma parte de determinada URL e guardar em uma variável mas não sei como fazer com PHP, é a parte que está o nome da loja, existem várias lojas cadastradas, ai preciso pegar o nome depois do desconto/ e antes da última /.
https://www.localhost.com/desconto/nome-da-loja/
Comment: Leia sobre a função `parse_url`.
Comment: Por que tu não passa via `get`? cria o link pra o endereço " `https://www.localhost.com/desconto.php?nome_loja=nome-da-loja` " e depois recupera usando $_GET['nome_loja']. Sei que não é a melhor alternativa, mas pode ser interessante
Comment: Resolvi com o `.explode`, guardei numa variável e deu certo. Obrigado, galera.
Answer: Pode usar simplesmente regex, desde que a URL do site seja "fixa", fazendo algo como:
<?php
$url = 'https://www.localhost.com/desconto/nome-da-loja/';

if (preg_match('#^https?:\/\/www\.localhost\.com\/desconto\/([^\/]+)\/#', $url, $matches)) {
    $loja = $matches[1];

    var_dump($loja);
} else {
    echo 'URL invalida';
}

Ressaltando, desde que a URL "seja fixa" e só o nome da loja mude.
A regex é simples, cada ponto é necessário escapar porque o . é usado como um tipo de curinga
O ([^\/]+) é um grupo, esse grupo pega qualquer coisa que não contenha /, o sinal ^ indica que tem que ser diferente do que esta dentro de [...] e o sinal de + no final do grupo indica que tem que pegar tudo até o próximo match da regex (a parte seguinte da regex é o \/, antes do #)
O # em php é usado para delimitar apenas, não tem haver com a regex usada em si.
Se esta usando com .htaccess pode pegar através do REQUEST_URI, fazendo algo como (mais simples):
<?php
$url = $_SERVER['REQUEST_URI'];

if (preg_match('#^/desconto\/([^\/]+)\/#', $url, $matches)) {
    $loja = $matches[1];

    var_dump($loja);
} else {
    echo 'URL invalida';
}

Extrair parte de URL com PHP


Why is a topology easily described by its subbasis, but a $\sigma$-algebra cannot be expressed by its generating set?

Question: Let $X$ be a set and $ \mathscr{A} \subseteq 2^X $ a collection of subsets. Describing the topology $\tau(\mathscr{A})$ generated by $\mathscr{A}$ is easy: any open set in $\tau(\mathscr{A})$ is just an arbitrary union of finite intersections of elements in $\mathscr{A}$.
However, the $\sigma$-algebra $\sigma(\mathscr{A})$ generated by $\mathscr{A}$ is a completely different story. One can never hope to express $\sigma(\mathscr{A})$ explicitly in terms of $\mathscr{A}$, even if $\mathscr{A}$ is an algebra of sets. In fact, let's say $\mathscr{A}$ is an algebra of sets. Let $\kappa(\mathscr{A})$ be the collection of sets obtained from taking complements, countable unions and countable intersections of members of $\mathscr{A}$ countably many times. Then $\kappa(\mathscr{A})$ is still a very small subcollection compared to $\sigma(\mathscr{A})$, nowhere approaching all of $\sigma(\mathscr{A})$. The collection $\sigma(\mathscr{A})$ is simply too huge to have any explicit expression.
Why is it so much harder to describe a $\sigma$-algebra than a topology, even though the definitions of both look simple and similar?
Comment: Definition of a topology does not involve  cardinalities. Arbitrary union of open sets are open. Defintion of a sigma algebra involves countability in a crucial way.
Comment: See [this question](https://math.stackexchange.com/questions/1327870/a-construction-of-sigma-algebras-surely-not-new-right) and [this question](https://math.stackexchange.com/questions/509326/borel-hierarchy-doesnt-collapse-before-omega-1).
Comment: See also this detailed [answer](https://math.stackexchange.com/q/1902261).
Comment: The sigma algebra (or topology) generated by a collection K of subsets, is the intersection of all sigma algebra (topologies) that contain the subset K.
Answer: There is an "explicit" description (depending on what you call explicit), by something resembling the Borel hierarchy :
Rename your generating set $\Sigma_0$, and the set of complements of those $\Pi_0$.
Then define by transfinite induction $\Sigma_{\alpha+1} = $ the set of countable unions of elements of $\Pi_\alpha$ and $\Pi_{\alpha+1}= $ the set of countable intersections of elements of $\Sigma_\alpha$ (equivalently : the set of complements of elements of $\Sigma_{\alpha+1}$), and at limit stages define both $\Sigma_\alpha = \bigcup_{\beta < \alpha}\Sigma_\beta$ and $\Pi_\beta = \bigcup_{\beta < \alpha}\Pi_\beta$
Then one may check that for each element in the generated $\sigma$-algebra, there is an ordinal $\alpha$ such that it belongs to $\Sigma_\alpha$. This sounds awful because ordinals go very far up, but in fact one may do better than that : it actually stops at $\omega_1$, that is : every element of the generated $\sigma$-algebra belongs to $\Sigma_\alpha$ for some countable ordinal $\alpha$; or in other words, the generated $\sigma$-algebra is precisely $\Sigma_{\omega_1}$ (this follows from the fact that $\omega_1$ is regular, i.e. -here- it is not a countable union of countable subsets)
In general, one cannot hope to do better than that : for instance if you start with the open subsets of $\mathbb R$ as $\Sigma_0$, there is no lower stage where you have all the generated $\sigma$-algebra (the Borelian $\sigma$-algebra)
Now this is "explicit", but of course more complex than the situation for topology. So what's happening ?
Well  you're adding various new complex phenomena : first you're adding complements (that's not too big a deal, because they behave nicely with respect to intersections and unions : just swap them), but most importantly you're allowing for infinite intersections, with some constraints. To my mind, that's what it all comes down to.
Indeed although $(\bigcup_{i\in I}U_i)\cap (\bigcup_{j\in J}V_j)$ is easily described : $\bigcup_{(i,j)\in I\times J}U_i\cap V_j$ (which is a countable union, if both $I,J$ are), so that finite intersections of families of unions are easy to understand;  $\bigcap_{\alpha\in A} \bigcup_{i\in I_\alpha}U_i$ is not so easily described : it's (assuming the axiom of choice) $\bigcup_{f: A\to \bigcup_{\alpha} I_\alpha \mid \forall \alpha, f(\alpha) \in I_\alpha} \bigcap_{\alpha \in A} U_{f(\alpha)}$, where the first union is not necessarily countable anymore, even if $A$ and all $I_\alpha$'s were : you're getting away from the constraint you had imposed.
So in the case of topology, all problems of non-distributivity (you can't write a union of intersections as an intersection of unions) were taken care of in one step : "oh just take finite intersections, then just all unions of that", here you have a second issue which comes from the mixing of infinite intersections with the requirement for countability. So you can't reduce to something simpler in the same way : the operations you would want to do get you far from countability


R fuzzy sets - Cannot plot tuple of fuzzy multisets

Question: I'm trying to implement this example using R's fuzzy set capabilities.  Code:
<code>sets_options("universe", seq(from = -200, to = 200, by = 1))
#------------------------------------------------------------------------------------------
# Fuzzy Variables
variables <-
  set (
    temp = fuzzy_variable(cold   = fuzzy_trapezoid(corners=c(-101, -100, 40, 70)),
                          ok     = fuzzy_triangular(corners=c(40,70,100)),
                          hot    = fuzzy_trapezoid(corners=c(70, 100, 200, 201))),
    ctrl = fuzzy_variable(small  = fuzzy_triangular(corners=c(-50,0,50)),
                          med    = fuzzy_triangular(corners=c(0, 50, 100)),
                          large  = fuzzy_triangular(corners=c(50, 100, 150)))
  )

#------------------------------------------------------------------------------------------
# Fuzzy Rules
rules <-
  set(
    fuzzy_rule(temp %is% cold, ctrl %is% large),
    fuzzy_rule(temp %is% ok,   ctrl %is% med),
    fuzzy_rule(temp %is% hot,  ctrl %is% small)
  )

#------------------------------------------------------------------------------------------
# Set up Fuzzy System
system <- fuzzy_system(variables, rules)
print(system)
plot(system)

#------------------------------------------------------------------------------------------
# Example
# If the measured temperature is 80 degrees, what's the control effort?
fi <- fuzzy_inference(system, list(temp=80))
## plot resulting fuzzy set
plot(fi)
## defuzzify
gset_defuzzify(fi, "centroid")

## reset universe
sets_options("universe", NULL)
</code>
When I run it however, I get two errors:
<code>> plot(system)
Error in lines.tuple(as.tuple(x), ...) :
  Cannot plot tuple of fuzzy multisets.
> fi <- fuzzy_inference(system, list(temp=80))
Error in rep.int(0, len - length(ret)) : invalid 'times' value
</code>
I'm a bit stumped.  Did find this which looks like a similar problem but I can't see typos in above.
Any help appreciated. Thanks.  Using R v3.2.4 on windows in case that matters.
Answer: This was an environment problem.  Reset the RStudio environment & it worked.  Leaving Q&A here in case anyone sees the same thing.
Comment: No need. You can delete.


How can compiler optimizations affect on a cache-unfriendly algorithm?

Question: I've noticed an interesting behavior in the code of this question which is also comes from Agner Fog in Optimizing software in C++ and it reduces to how data is accessed and stored in the cache (cache associativity). The explanations is clear for me, but then someone pings about volatile...
That is if we add volatile qualifier to the matrix declaration: volatile int mat[MATSIZE][MATSIZE]; the running time for value 512 dramatically decreases: 2144 → 1562 μs.
As we know volatile prevents compilers from caching the value (in a CPU register) and from optimizing away accesses to that value when they seem unnecessary from the POV of a program.
One possible version assumes that the computation process happens only in RAM and no cpu caches is used in the case of volatile. But on the other hand the run-time for value 513 again is less than for 512: 1490 μs...
Comment: Sounds like testing error/noise.  Depending on your architecture and OS, different virtual memory can have different caching characteristics.  Most particularly for tests like this.  It's important that a good benchmark test the operations at a variety of virtual addresses to make sure it's not grossly distorted by a knotty patch of VM.  That is to say; you allocate a lot of memory and then run your test at different offsets within that allocation.
Comment: Pure speculation: the introduction of volatile could be generating more memory accesses influencing the cache replacement behavior (i.e., a cache line might be more recently accessed and so not evicted before its next use).
Answer: Unfortunately I cannot confirm that the volatile version is running faster. I did a test run of both the volatile and the non-volatile version, and the time comparison of both can be seen in the chart below. When measuring performance in order for optimizing code it is always important to take several steps (not just one or two, but in the range of thousands) and take the mode (https://en.wikipedia.org/wiki/Mode_(statistics)) of the gathered data as per Alexandrescu's Fastware.

There are various peaks, and deep valleys, but looking at the chart you cannot conclude that the volatile is faster.
Indeed, the code generated by the compilers is different, but not to such an extent, you can check it out on https://godbolt.org/g/ILw3tg


Setting field value in try{} and calling base class in finally{}

Question: I was browsing .NET Framework source code trying to understand another issue and I saw this code (in PeerNearMe.cs from System.Net.PeerToPeer.Collaboration):
private bool m_Disposed;

protected override void Dispose(bool disposing)
{
    if (!m_Disposed){
        try{
            m_Disposed = true;
        }
        finally{
            base.Dispose(disposing);
        }
    }
}

Is there any reason to put variable assignment in try block? May it fail in any way with an exception?! At first I thought it's because finally will be executed even if thread is aborted with Thread.Abort():

Unexecuted finally blocks are executed before the thread is aborted.

In this case I'd expect try block to include all method body:
try {
    if (!m_disposed)
        m_disposed = true;
}
finally {
    base.Dispose(disposing)
}

However they also says:

The thread that calls Abort might block if the thread that is being aborted is in a protected region of code, such as a catch block, finally block, or constrained execution region. If the thread that calls Abort holds a lock that the aborted thread requires, a deadlock can occur.

IMO calling a base class virtual method is little bit a jump in the dark in this case.
In short: what's this point of that code? What it really tries to implement? If it's because of Thread.Abort() then isn't it just wrong?
EDIT: if it's really just because of Thread.Abort() then it doesn't do its job if abort happens after if (!m_Disposed) { but before try {. Note that Dispose() must be resilient to multiple calls and simply do nothing (regardless when it's called).
Comment: Irony - msdn suggests avoiding _ and Hungarian notation for fields and they have done it internally.
Comment: @dotnetkid, conversion is just conversion. As long as whole organization follow it, it works.
Comment: It could also be the case, that previous versions of this code had more statements before the `m_disposed = true;` statement. And that the try/finally block is merely a left-over.
Answer: The only thing that can happen is an asynchronous exception - Thread.Abort is one example, but there's also the likes of Thread.Interrupt or OutOfMemoryException.
Your suggestion actually breaks the code, because you call base.Dispose regardless of whether the instance was already disposed or not - that's not the intention.
Now, Thread.Abort should only be used when terminating an application domain - so you don't care whether the m_disposed = true succeeds or not, the domain is going to be torn down soon anyway. However, you still care about releasing any native resources, because those are usually tied to the process, not the application domain (and sometimes, they even transcend processes or whole machines).
Code in finally gets a chance to run even in the middle of a Thread.Abort - there's no other way to ensure code runs during an asynchronous exception. By calling base.Dispose in a finally clause, you ensure that it at least gets a chance to execute, and that it will not be terminated in the middle of operation (though note that there's a fixed time limit for all the finally clauses that execute - you don't want to do anything complex in a finally).
Now, in this particular case, there isn't a real reason to do this - the base class doesn't do anything either. So it's probably just a common Dispose pattern the team uses :) Since Dispose is designed for deterministic release of native resources, it's perfectly safe to call it in a finally clause - it's not supposed to do any work, just release native resources. Of course, Dispose is frequently abused - but then you just reap what you've sown.
Finally, don't forget that this is also exactly what a using clause does, so if you're using using, you're already running the Dispose method in a finally clause!
using (var bmp = new Bitmap())
{
  ...
}

Is translated to the equivalent of
Bitmap bmp = null;
try
{
  bmp = new Bitmap();

  ...
}
finally
{
  if (bmp != null) bmp.Dispose();
}

All in all, there's nothing suspicious about that implementation, really :)
Comment: I'd agree with you about everything but _"...breaks the code, because...that's not the intention". I mean: Dispose() must be resilient to multiple calls. If aborting happens after if (...) but before try { then base class will not be called.
Comment: @AdrianoRepetti The thing is, it really doesn't matter much. You should really *always* call `Dispose` in a `finally` block at some level - that's its whole purpose. This way of writing the `Dispose` method itself ensures that the base classes' `Dispose` method is called within a `finally` - which is not a bad idea, since you shouldn't depend on implementation details of your base classes.
Answer: I'm not sure about why its in a try as it's only assigning a variable, maybe someone else can tell us this.
I would say that your expectation would act differently though. Putting the whole try finally inside the if(!m_disposed) means that the object won't call Dispose if that m_disposed is true whereas your expectation would call dispose regardless of m_disposed value.
Comment: It's true but you should be able to call Dispose() multiple times without any side effect and it will call base.Dispose() also if thread is aborted after if (!m_disposed) { but before m_disposed = true.
Comment: @AdrianoRepetti A lot of those guarantees no longer apply when you're unloading an application domain - and that's the only place where `Thread.Abort` should be used.
Comment: @Luaan I don't think so otherwise it's not a guarantee! If this is the purpose of this code (protect against asynchronous exceptions) then it _may_ simply fail.
Comment: @AdrianoRepetti There's no 100% guarantees in C# - or any other language, really. You *must* understand the boundaries of any guarantees, otherwise you'll end up in trouble. `Thread.Abort` is one of those massive disruptors (and it didn't even allow `finally` to continue originally - that was a breaking change), as is appdomain unload, or a process kill, or a power plug being yanked from the socket. And your code doesn't help anyway - the try-finally *still* doesn't cover the whole method. That's why `Dispose` is called from a `finally` clause in most cases.
Comment: Dispose() may release per AppDomain resources. Per process resources. Per **machine** resources. Also on **another machine**. There isn't (there shouldn't be) a corner-case where it works _more or less_. If you're running on a server and your process is softly killed because (let's say) consuming too much resources then you want to release them all. Both on your machine and (especially!) on other machines. If that's the case and that pattern is used to protect against this kind of exceptions then (IMO, of course!) is just done wrong.


Low power, quiet and semi affordable domain controller for distributed environment use

Question: I work in a distibuted environment, and I would like to setup a domain controller. I don't really want a full blown desktop running full time, just to handle requests from 1 client pc in my home office.
I was wondering do you get any specialized boxes which are specifically used as windows based domain controllers, something like those small modern NAS servers?
I need real domain functionality for testing, so it can't be light weight or watered down.
Might sound a bit off the wall, but I would like to just have a device like a router, I could rdc in when required, but it would only be a Windows 2008 r2 domain controller. And support upgrading to future versions.
Does such a solution exists. I don't want my study to be turned into a server room. Thanks
Answer: You seem like a good candidate for an HP ProLiant Microserver....
See:
http://h10010.www1.hp.com/wwpc/us/en/sm/WF31a/15351-15351-4237916-4237918-4237917-4248009.html
and
http://h30423.www3.hp.com/?fr_story=c080b0e57b3504e624b5e1e2dbc8122de745469c&rf=sitemap
It's pretty tiny, has four hot-swap bays and is more than robust enough for your application. A good number of people have used them as Solaris ZFS NAS appliances. There's also a thread for owners of the device detailing their experiences here.
Comment: That server literally dropped out of the sky from God :)
Comment: Do you think these specs can keep up with advanced testing AD - Report smallest size savings for office work and for basic home use, D510 CPU Intel Atom 1.66GHz dual-core, 320GB SATA HDD, 2GB DDR2, VGA int. GMA 3150
Comment: That server is more powerful than the DC machines that I had in my first Win2k domain. You'll be fine.


Returning Array with-in a foreach loop

Question: I want to ask - How can I return/make array with-in a foreach loop?
Here is my code
function getAllUsers() {
   $dir = "users/";
   $fl = scandir($dir);
   $cnt = 0;
   foreach (scandir($dir) as $fl) {
       if ($fl !== '.') {
           if ($fl !== '..') {
                if ($fl !== 'index.php') {
                    $pr = $fl;
                    $fl1 = scandir($dir . '/' . $fl);
                    $cnt++;
                    return $fl1[3]; //Here I want a array for file inside 'users\'.
                }
           }
       }
   }
}

Thanks for giving answer.
Answer: Basically: you can not.
upon using return, the current function returns the value and stops execution.
return is by definition the end of the function.
but you can save the data you want to return in an array and then return the whole thing:
function getAllUsers() {
   $dir = "users/";
   $fl = scandir($dir);
   $cnt = 0;
   $result = []; //initiating the array
   foreach (scandir($dir) as $fl) {
       if ($fl !== '.') {
           if ($fl !== '..') {
                if ($fl !== 'index.php') {
                    $pr = $fl;
                    $fl1 = scandir($dir . '/' . $fl);
                    $cnt++;
                    $result[] = $fl1[3]; //adding your value to the array
                }
           }
       }
   }
   return $result;
}

Edit: If your PHP-Version mucks about the $result = []; you can use the "old" style $result = array(); instead
Comment: no we don't, we want to add the variable in an array, not append it to a string.
Answer: Generators: Solution for PHP >= 5.5.
If you want the function to return a value for each element in the loop back from the function use a generator:
/**
 * @return Generator|Iterator
 */
function getAllUsers() {
    $dir = "users/";
    $fl = scandir($dir);
    $cnt = 0;
    foreach (scandir($dir) as $fl) {
        if ($fl !== '.') {
            if ($fl !== '..') {
                if ($fl !== 'index.php') {
                    $pr = $fl;
                    $fl1 = scandir($dir . '/' . $fl);
                    $cnt++;
                    yield $fl1[3]; //Here I want a array for file inside 'users\'.
                }
            }
        }
    }
}

// Loop over
foreach (getAllUsers() as $file) {

}

// Or one at a time
$generator = getAllUsers();
$file1 = $generator->current();

The other solutions here are more feasible however, this solution is mostly useful for implementing the IteratorAggregate interface, or creating co-routines.
Comment: That must really suck mate.
Comment: My PHP version is `5.3.5`
Answer: You can achieve this by using an array. like below..
function getAllUsers() {
   $dir = "users/";
   $fl = scandir($dir);
   $cnt = 0;
   $array = array();
   foreach (scandir($dir) as $fl) {
       if ($fl !== '.') {
           if ($fl !== '..') {
                if ($fl !== 'index.php') {
                    $pr = $fl;
                    $fl1 = scandir($dir . '/' . $fl);
                    $cnt++;
                    $array[$fl] = $fl1[3]; //Push values in array for each user.
                }
           }
       }
   }
  return $array;
}

Hope this will help
Comment: replace this $arr = []; with $arr = array();
Comment: This not worked for me. It showing up error `Parse error: syntax error, unexpected '[' in C:\Apache2.2\htdocs\user_controll.php on line 27`
Comment: `$arr = [];` is line 27

Returning Array with-in a foreach loop


Product View does not show for Anonymous user

Question: I would like to use a view to display products in front page. So, in the view 'Products (Commerce Product)' i created separate block view 'My Products Block'. This view is added to the region in Block section and then rendered in the front page:
print render($page['region_containing_product_view']);

This displays products fine if logged in as admin but not for anonymous users. For anonymous users it shows:
No products have been created yet. Add a product.

I have updated the permissions for my custom view to 'Access:Role | anonymous user' but it still doesn't show the products. How come? what am i doing wrong?
Thank You
p.s. Drupal 7, Commerce module
Answer: It turns out for every product type created there is permissions that need to be enabled for every user roles including anonymous users
'people-permissions-roles'
Comment: That's bummer because Drupal says it has security implications and should only be displayed to trusted users.
Comment: bum...couple months later again wasted time on this. So, if you create view from entity of type products, make sure to enable permission 'View any product of any type' for anonymous user other wise the view will not display the products for site visitors


using an aws lambda as a node webserver

Question: I have heard of people using AWS lambdas as a place to run node express webservers which to my mind is an awful idea for the following reasons:

it is hard to run them in a similar state locally
This is not their intended use
Cold starts are a problem
Annoying to release code to
You can't do file uploads
you can't put nginx or a reverse proxy in front of it
all webserver code configuration is done through code

I am open to the idea of me being wrong on this :).
I am talking about a mission critical website and not a blog or something.
Am I right or are aws lamdas a credible place to put a  node server.
Comment: It's entirely possible. That's what https://vapor.laravel.com/ does with PHP.
Answer: What you appear to have overlooked is that this arrangement doesn't actually run the web server in Lambda -- that is not even possible because Lambda functions do not have a daemon mode.
A Lambda container that is not currently handling a function invocation is in suspended animation, being denied access to the underlying CPU.  It can't listen on a socket.
The web server is AWS API Gateway or Application Load Balancer, both of which accept viewer requests and use their payload to invoke a Lambda function.  There's no need for Nginx but, technically, you could still use it, it would just be quite pointless... but CloudFront is a nice serverless reverse proxy that can, say, send requests for <code>/assets/*</code> to an S3 bucket while sending everything else to the application behind API Gateway.
So the argument that this isn't the intended purpose seems premised on a misunderstanding of what's involved.
Also, AWS has an official library for exactly this purpose.

Run serverless applications and REST APIs using your existing Node.js application framework, on top of AWS Lambda and Amazon API Gateway
https://github.com/awslabs/aws-serverless-express

...so it's a perfectly valid use case for existing applications, at the very least.
For new applications, including the framework is more debatable since it's a layer of overhead that isn't strictly necessary, but the rest of the architecture is unchanged if you omit the framework -- you can build a complete web site on Lambda functions, in Node.js, without Express, and it's largely the same setup.  The web server is API Gateway or ALB, or can simply be CloudFront if you are using Lambda@Edge for your JS or Python code.
Comment: I am talking about rendering react server side, not serving static files from an s3 bucket.  I should have mentioned that in the post.
Comment: Server side rendering is what this answer is about.  I mentioned CloudFront and S3 for completeness because all sites also have some static content, and that plus API Gateway and Lambda are the serverless equivalent of Nginx passing through the dynamic requests to the framework and serving static content from local files.
Comment: the aws-serverless-express does look fairly abandoned with the last commit over 11 months ago.

using an aws lambda as a node webserver


How to disable subwords embedding training when using fasttext?

Question: Here is a snippet of the corpus I try to use for training word embedding.
news_subent_12402 news_dlsub_00322 news_dlsub_00001 news_sub_00035 news_subent_07737 news_sub_00038 news_dlsub_00925 news_subent_07934 news_sub_00057 news_dlsub_01826 news_dlsub_00437 news_sub_00037 news_sub_00050 news_dlsub_00205 news_sub_00270 news_subent_05735 news_dlsub_00143 news_subent_12439 news_sub_00051 news_subent_08446 news_dlsub_00091 news_sub_00222 news_dlsub_00009 news_dlsub_00126 news_subent_15202 news_dlsub_00019 news_sub_00076 news_dlsub_00059 news_subent_11158 news_subent_10981 news_dlsub_00634 news_dlsub_00018 news_subent_03496 news_subent_16059 news_subent_08005 news_dlsub_00020 news_subent_15460 news_dlsub_00908 news_subent_12712 news_sub_00258 news_sub_00048 news_dlsub_00022 news_dlsub_00206 news_dlsub_00106 news_sub_00248 news_sub_00047 news_subent_02476 news_subent_14554 news_dlsub_00134 news_sub_00070 news_subent_06676 news_dlsub_00306 news_subent_11635 news_dlsub_01137 news_sub_00081 news_dlsub_00024 news_dlsub_00242 news_dlsub_00920 news_dlsub_00198 news_subent_02562 news_subent_09358 news_dlsub_00101 news_subent_02696 news_subent_17124 news_sub_00244 news_dlsub_00045 news_sub_00049 news_dlsub_00575 news_dlsub_00163 news_subent_03497 news_subent_10972 news_subent_05406 news_sub_00039 news_subent_14976 news_subent_20148 news_subent_02955 news_sub_00245 news_subent_02399 news_dlsub_00669 news_subent_12423 news_dlsub_00180 news_dlsub_00013 news_dlsub_00075 news_sub_00264 news_dlsub_01833 news_sub_00040 news_sub_00257 news_dlsub_00021 news_subent_14967 news_subent_03495 news_dlsub_00035 news_subent_21377 news_sub_00059 news_dlsub_01260 news_sub_00232 news_dlsub_00316 news_dlsub_00014 news_dlsub_00023 news_dlsub_00046 news_subent_02007 news_dlsub_00458 news_dlsub_00269 news_subent_04653 news_subent_06231 news_dlsub_01751 news_dlsub_00186 news_dlsub_00043 news_dlsub_00128 news_subent_05276 news_sub_00259 news_dlsub_00102 news_sub_00268 news_dlsub_00185 news_sub_00041 news_subent_09122 news_dlsub_00116 news_subent_09210 news_subent_07733 news_subent_06393 news_dlsub_00244 news_dlsub_00622 news_sub_00226 news_sub_00043 news_dlsub_00067
news_subent_03827 news_dlsub_00065 news_sub_00251 news_dlsub_01826 news_subent_17688 news_subent_07649 news_subent_02941 news_dlsub_00100 news_subent_08198 news_subent_02990 news_dlsub_00033 news_subent_02562 news_dlsub_00043 news_dlsub_00024 news_dlsub_00015 news_subent_07628 news_subent_07045 news_dlsub_00234 news_subent_09178 news_dlsub_00458 news_subent_02923 news_sub_00226 news_dlsub_00120 news_sub_00247 news_dlsub_00014 news_dlsub_01830 news_subent_02946 news_dlsub_00086 news_dlsub_00046 news_dlsub_00038 news_subent_16554 news_subent_03073 news_dlsub_00128 news_dlsub_00098 news_subent_02905 news_subent_09117 news_dlsub_00021 news_dlsub_00143 news_subent_03054 news_dlsub_00126 news_subent_16372 news_dlsub_01833 news_subent_03495 news_sub_00245 news_dlsub_00101 news_sub_00258 news_subent_11431 news_sub_00148 news_subent_09320 news_sub_00232 news_subent_02460 news_dlsub_00032 news_dlsub_00067 news_dlsub_00064 news_dlsub_00045 news_dlsub_00116 news_subent_11663 news_subent_03501 news_subent_02030 news_dlsub_00035 news_dlsub_00476 news_dlsub_00039 news_subent_14505 news_dlsub_00091 news_sub_00244 news_sub_00268 news_dlsub_00130 news_subent_02007 news_subent_03014 news_dlsub_00022 news_dlsub_00019 news_subent_09358 news_dlsub_00270 news_subent_17124 news_dlsub_00071 news_sub_00266 news_subent_06429 news_subent_02621 news_sub_00248
news_subent_03497 news_subent_03495 news_dlsub_01326 news_sub_00151 news_sub_00070 news_dlsub_00143 news_dlsub_00012 news_dlsub_00212 news_subent_04653 news_subent_02022 news_dlsub_00101 football_club_187 news_subent_02902 news_dlsub_00116 news_dlsub_00925 news_sub_00137 news_dlsub_00120 news_sub_00036 news_subent_02889 news_subent_14976 news_dlsub_00269 news_dlsub_00687 news_subent_15202 news_dlsub_00669 news_dlsub_00126 news_sub_00248 news_dlsub_00437 news_sub_00071 news_dlsub_00177 news_dlsub_00694 news_dlsub_00618 news_sub_00051 news_sub_00043 news_subent_14997 news_subent_02411 news_subent_16059 news_sub_00245 news_subent_02923 news_dlsub_00035 news_sub_00069 news_subent_05320 news_sub_00082 news_sub_00259 news_dlsub_01035 news_dlsub_00413 news_sub_00072 news_dlsub_00020 news_sub_00052 news_dlsub_00023 news_subent_03496 news_subent_02893 news_subent_16508 news_sub_00065 news_sub_00047 news_subent_05740 news_subent_13389 news_sub_00055 news_subent_09439 news_subent_02991 news_sub_00268 news_dlsub_00003 news_subent_04609 news_subent_03509 news_subent_04069 news_dlsub_00128 news_dlsub_00099 news_dlsub_00206 news_dlsub_00582 news_sub_00037 news_dlsub_00021 news_sub_00247 news_dlsub_01179 news_sub_00057 news_dlsub_00046 news_sub_00039 news_sub_00050 news_subent_03014 news_sub_00042 news_dlsub_01826 news_sub_00038 news_dlsub_00410 news_subent_12422 news_sub_00048 news_subent_13648 news_dlsub_01807 news_subent_20148 news_sub_00084 news_sub_00049 news_dlsub_00029 news_subent_11392 news_dlsub_00412 news_sub_00246 news_sub_00244 news_subent_16385 news_dlsub_00634 news_subent_13536 news_subent_03073 news_sub_00226 news_subent_11478 news_sub_00035 news_subent_14967 football_club_192 news_sub_00232 news_sub_00054 news_subent_06587 news_dlsub_00014 news_subent_02399 news_dlsub_00013 news_dlsub_00102 news_sub_00040 news_subent_01990 news_dlsub_00007 news_subent_07675 news_subent_07719 news_sub_00041 news_subent_04655 news_dlsub_00300 news_dlsub_00019 news_subent_07756 news_dlsub_00234 news_sub_00076

While that every line is a sentence and news_dlsub_00001 is just an intact word. I do not want the fasttext to construct subword embedding and what I want is just the embeddings for the intact words like news_dlsub_01326 news_subent_12402 and so on.
There are 15354 distinct words in my corpus and about 10m rows(sentences) overall.
Here is the training script :
./fasttext skipgram -input user_profile_tags_rows.txt  -output model_user_tags -lr 0.01 -epoch 50 -wordNgrams 1 -bucket 200000 -dim 128 -loss hs -thread 80 -ws 5  -minCount 1

So how can I set the training script that disable the embedding representation training for subwords for efficiency ? Thanks.
Answer: If you want to train word embeddings with no subword information, you can set the -maxn parameter to 0. This means that you only use character ngrams with a max length of 0, i.e., no character ngrams are used.
Comment: will this method significantly improve the training speed?
Comment: I'm not sure, I never tried this myself. But you can try with less data and fewer epochs first to see if there is a speed-up. By the way, I don't think you will need to train for 50 epochs. The default value is 5, which should be fine when you have quite a lot of data. Or maybe try with 10.
Answer: Set both options to zero: -maxn 0 -minn 0


Which active directory group contains all users in a domain?

Question: I want to grant permissions to all of the users in a specific domain. Let's say I have a domain called ACME. I tried to use "ACME\Users" but I received an error stating "The user or group name 'ACME\Users' is not recognized". Which active directory group contains all users in a domain?
Answer: If you create a bunch of users on your domain, they will by default by added to the ACME\Domain Users security group (using your example domain name). Normally, users should be left in that group and that group should be their primary group.
If someone else has made accounts on the domain before you, they may have taken steps to remove users from the ACME\Domain Users group, which is possible. In particular, there is also a built-in ACME\Domain Guests group which might be used for guest or temporary accounts. So while you can't guarantee that every domain user is a member of ACME\Domain Users, it's still your best bet for granting access to something for "everyone on the domain". If an account has been removed from ACME\Domain Users, there is/was probably a good reason, and you probably don't want those accounts to have access to the resource in question anyway.
Note that another important built-in security group is ACME\Domain Admins. By default, whenever a computer is joined to the domain, the ACME\Domain Admins group is added to the local Administrators group, making domain admins local administrators for all domain-joined computers. Be careful with adding or removing accounts from ACME\Domain Admins since it's a very powerful group, and some accounts will need to be in it for your domain to work correctly.


My new grand piano sustain pedal has a small noise when activated

Question: Recently purchased a new baby grand. Previously I had an upright. I noticed the sustain pedal has @ small noise when using at certain times. Do I need to work it out by playing ? Do I need to adjust my pedal technique?
Answer: A small amount of mechanical noise is common, and usually easily rectifiable.  Probably not worth invoking the warranty on a new piano, though it might be worth contacting the retailer and mentioning it, just to cover yourself.
I wouldn't advise trying to lubricate or adjust any moving parts yourself, unless you know what you're doing (and, with respect, you obviously don't :-) ).  When the piano has settled into its new home and your tuner makes his next visit, ask him to have a look at it.
Answer: Don't adjust your pedal technique.
The noise could come from the pedal pivot, or the cup connecting the pedal to the pushrod, or one of the pushrod guides, or the pushrod-action joint, all of which are best left to a professional technician to both troubleshoot and correct.  The noise could even come from the sole of your shoe on the pedal, or a creaky floorboard!


Azure Search Filter search.ismatch function doesnt work with mixture of special characters like hiphen and single quote

Question: I have a following code,
<code>filter="search.ismatch('Paris\-l''Hopital*', 'DestinationAddress/City', 'full', 'all')"
</code>
This filter should give me the record that has City with the name Paris-l'Hopital. Please note i am escaping the single quote in the middle of the search term with another single quote. Hiphen is escaped using backslash. Moreover the city field uses Microsoft Analyzer.
While i can see the record exists in the search index i cannot understand why this filter doesnt return the record i am expecting. Any input will be highly appreciated.
References
https://learn.microsoft.com/en-us/azure/search/search-query-odata-full-text-search-functions
https://learn.microsoft.com/en-us/azure/search/query-simple-syntax
Thank you
Answer: By default it considers hyphen as a stopword. You need to change the default analyzer to not break into different words when it finds the '-'.
Comment: Thank you for the input. Not sure if we really need to change that. for e.g. if we are searching for something like "stockton-on-tees". It works fine. I have a feeling if we have a search term with dash and singlequote then it breaks
Answer: Normally, I would suggest considering a language-specific analyzer if you have content in a specific language. For addresses, this is tricky since you probably have to support all types of addresses. Have you tried using one of the French analyzers? It would probably do better at tokenizing typical French content.
Comment: Thank you Dan, This field not only stores French cities but cities from all over the world. Therefore i cannot rely only on French Analyzers.