Why Singular Value Decomposition(SVD) has this specific form...

Question: The SVD is usually written as $A = U\Lambda V^T$. However, V is an orthogonal matrix. So if we represent $V^T$ as $V^*$ (I write asterisk here to differ it from V before), but not the transpose one. It still suffices to the requirement. e.g ${V^*}^T V^*=I$. So why do we bother to write it as transpose version? What's the goodness of doing so? I think $A = U\Lambda V$ is all the same here.
It troubles me for sometimes and I don't find quite valuable info on this topic so far.
Thank you!
Comment: It is written this way because it is conventional to have the singular vectors as the columns of $U$ and $V$. This retains the similarity with the orthogonal diagonalization of a symmetric matrix, $A=PDP^T$, where eigenvectors of $A$ form the columns of $P$. If we wrote the SVD the way you propose, the left singular vectors would be the columns of $V$, but the right singular vectors would be the rows of $V_*$.
Comment: Singular value...
Comment: @Rahul Do you mean the columns of U in the last sentence? So it's the convention to think the rows of the righthand matrix are right singular vectors and thus we use transpose here to make it uniform with U?
Answer: If the (orthonormal) columns of $V$ are $v_1,
\ldots, v_k$, then $x \mapsto V^t x$ expresses $x$ in terms of its coordinates in the $V$-basis. So writing it that way helps one see something about an interpretation of the decomposition.
Also: when the matrix $A$ is not square, the decomposition theorem (in slightly modified form) still applies, and it's still true that the columns of $U$ and the columns of $V$ are orthogonal unit vectors, but since the matrices no longer need be square, it's not necessarily true of the rows. Example:
$$
V = \pmatrix {0 & 0 \\ 1 & 0 \\ 0 & 1 }
$$
the columns are orthogonal unit vectors, but the rows are not.
Could the theorem say that $A$ can be written
$$
U D W
$$
where $U$ has orthonormal columns and $W$ has orthonormal rows? Sure. But the other formulation happens to carry suggestions about rewriting things in other bases that some of us find helpful. (Others, like you, may not.)
(And, as Rahul notes in a comment, this puts the singular vectors in columns; if you're used to mostly working with column vectors, that's nice.)
Comment: I think I got it here. Thank you for your illustration!


Pouring bottles into buckets but not too much: how to configure Maximum Flow with Lower Bounds to solve this assignment problem?

Question: Problem

$n$ jars of water with different volumes $v_i$ have to be assigned to $m$ empty buckets with different volumes $V_j$
$n \ge m$.
A jar can only be poured into 1 bucket.
Multiple jars can be poured into the same bucket.
All jars have to be completely empty at the end.
No bucket can be left completely empty.
We want to find the assignment that minimizes the sum of the volume left empty across buckets (deficit), and the total amount of water that overflowed (excess).

What I tried
So I tried to map this problem to the Maximum Flow Algorithm with Lower bounds: for an input bipartite graph $G$, a source $s$, a sink $t$, two function $l,u : E \rightarrow R^+$ we seek a flow $l(e) \leq f(e) \leq u(e)$ at every edge $e$

arcs $(s,i)_{i\in[n]}$ have capacity $u(s,i) = l(s,i) = v_i$
inner edges $(i,j){i\in[n],j\in[m]}$ have lower bound $l(i,j)=0$ and capacity $u(i,j)=v_i$
arcs $(j,t)_{j\in[m]}$ have lower bound $l(j,t) = (1-\epsilon)V_j$ and upper bound  $u(j,t) = (1+\epsilon)V_j$.

That is, we are allowing for a fraction of the flow to go overload or underload. The attached paper explains how to modify the graph structure to find a feasible flow.
Question
If this parametrization is correct (is it?), I don't know how to guarantee that the inner edges must have an integral value: I don't want the flow from one jars to be split across different buckets. I have read that the Ford–Fulkerson algorithm should proceed with integer values, but I am reaching the end of my knowledge here. Also sorry for butchering the formalism :'/
Comment: As stated, finding an optimal solution to this problem appears to have [subset sum](https://en.wikipedia.org/wiki/Subset_sum_problem) as a special case.
Comment: thank you @MishaLavrov! You actually gave me a pointer to the class of problem I wanted! From link to link I ended up to the [bin packing problem](https://en.wikipedia.org/wiki/Bin_packing_problem) that is quite close from what I want :-)
Answer: You can solve the problem via integer linear programming as follows.  Let binary decision variable $x_{ij}$ indicate whether jar $i$ is poured into bucket $j$.  Let nonnegative decision variables $d_j$ and $e_j$ denote the amount of deficit or excess, respectively, for bucket $j$.  The problem is to minimize $$\sum_j \left(d_j + e_j\right)$$ subject to linear constraints
\begin{align}
\sum_j x_{ij} &= 1 &&\text{for all $i$} \tag1\label1 \\
\sum_i x_{ij} &\ge 1 &&\text{for all $j$} \tag2\label2 \\
\sum_i v_i x_{ij} + d_j - e_j &= V_j &&\text{for all $j$} \tag3\label3 \\
\end{align}
Constraint \eqref{1} assigns each jar to exactly one bucket.
Constraint \eqref{2} assigns at least one jar to each bucket.
Constraint \eqref{3} defines the deficit and excess for each bucket.
You cannot relax integrality of $x_{ij}$ and expect to get integer values.  The objective function would encourage splitting of $v_i$ to multiple buckets, yielding fractional values for $x_{ij}$.
Comment: wahoo this is so beautiful when the problem is described with the right formalism! I don't know anything about integer linear programming, but i guess it's time to learn :D thank you :3


Plotting multiple rater: restriction on number of panels

Question: Is there a restriction on how many raster I can plot using using the plot function? For e.g
library(raster)
mystack <- stack()

for(i in 1:25){

  df <- data.frame( x = rep( 0:1, each=2 ),
                    y = rep( 0:1,  2),
                    l = rnorm( 4 ))
  dfr <- rasterFromXYZ(df)
  mystack <- stack(mystack, dfr)
  }

plot(mystack)

It plots only 16 plots no matter how many iterations I do.
Answer: You were on the right track, from ?`plot,Raster,ANY-method`:

## S4 method for signature 'Raster,ANY' plot(x, y, maxpixels=500000, col, alpha=NULL,    colNA=NA, add=FALSE, ext=NULL, useRaster=TRUE,
  interpolate=FALSE,     addfun=NULL, nc, nr, maxnl=16, main, npretty=0,
  ...)

Notice maxnl = 16. All you need is to change that to the desired number of layers:
plot(mystack, maxnl=25)


Virtual Host showing "Index of /" instead of displaying my site

Question: So I just ran a clean install of Mountain Lion OSX 10.8 and am trying to get everything back up and running again. I uncommented the php module and vhosts in http.conf, added brew, mcrypt, autoconf etc.. I use VirtualHostX and I set my domain and local path but when I pull it up it shows Index of / instead of my app.
I have an index.php in my root and my vhosts looks like this:
NameVirtualHost *:80

<Directory "/Users/me/Sites/mysite.com/public/">
    Allow From All
    AllowOverride All
    Options +Indexes
</Directory>

<VirtualHost *:80>
    ServerName "mysite.dev"
    DocumentRoot "/Users/me/Sites/mysite.com/public"
</VirtualHost>

I've spend hours troubleshooting issues like these in the past...getting better, but this is a new one and I can't seem to track down the issue.

I'm using a php framework called Laravel and the doc root must be directed to public directory.
Comment: Something stupid, do you need a trailing slash at the end of you virtual host like you do in directory
Answer: Find DirectoryIndex in your apache config files (probably in the httpd.conf), and check whether index.php is there. I assume that it is not.
Comment: thx, worked for me :)
Answer: You need to disable indexes in vhost
 <Directory /www/somefolder>
 Options -Indexes FollowSymLinks
 AllowOverride None
 </Directory>


.click function .load not working

Question: I am a total novice at jQuery, but giving it a go. I cant seem to get the .click function below to work.  Can anyone tell me were I am going wrong?
$(".news").click(function() {
    $("#contentarea").load("console/news.php");
});

Comment: It should work fine, although you don't give a definition of what "work" means. Make sure an element with the `new` class exists, and that it wasn't dynamically generated.
Comment: works on jsfiddle http://jsfiddle.net/z5AUX/1/
Comment: in case you are creating the element dinamically, use .live() (now deprecated) or .on()
Answer: You need to run the code in the ready event, so that the news element(s) are loaded:
$(document).ready(function(){

  $(".news").click(function() {
    $("#contentarea").load("console/news.php");
  });

});

Answer: wrap the code inside the ready handler
$(function(){
 //your code
});

or you can put the javascript code at the end of the markup like
//your html

.click function .load not working


How to estimate the hazard function?

Question: I model the survival data with a piece wise constant exponential distribution at time t. Let R be the total number of the population at time t, and D be the number of deaths observed at time t+dt. So, we may estimate the local hazard function as D/dt from the Poisson process or as D/R from the Kaplan-Meier model. Could we make connections between the two formulas or am I wrong somewhere?
Comment: "constant exponential distribution"?
Comment: "a piece wise constant". Who is constant?
Comment: Yes! It's constant in the interval [t, t+dt].
Answer: You probably mean that you assume a piece-wise exponential distribution of survival times, which implies a piece-wise constant hazard function. The respective model is called the Piece-wise exponential model (PEM).
There is a connection between the PEM and Cox PH, in fact they are equivalent in some situations (see example here and the Whitehead 1980 reference therein).
However, it is usually better to use an extension of the PEM, the Piece-wise exponential additive (mixed) model (PAMM) that can be estimated using GAMMs.
I wrote an R package pammtools specifically to do so.
See this vignette to get started with PEM and PAMM: https://adibender.github.io/pammtools/articles/baseline.html
In the articles section there are many more examples (and comparisons to other models, e.g. survival::coxph: https://adibender.github.io/pammtools/articles/

How to estimate the hazard function?


Linear transformation $S$ with $S\circ S=S$.

Question: I need help with the next problem. Really I don't know how can I solve it. The problem is the next:

Let $S:\mathbb{R}^{2}\rightarrow\mathbb{R}^{2}$ be a linear
  transformation such that $S\circ S=S$. Proof the next sentences.
a) $S=0$, i.e., the zero transformation.
b) $S=1_{\mathbb{R}^{2}}$, i.e., the identity transformation.
c) Exist $\beta$ basis of $\mathbb{R}^{2}$ such that
$$ [S]_{\beta}^{\beta} = \left( \begin{array}{cc} 1 & 0\\ 0 & 0 \\
 \end{array} \right) $$

For the b), I thought the next
Let $x\in\mathbb{R}^{2}$. Then, $S(x)=v$ with $v\in\mathbb{R}^{2}$. Using the hypothesis, then $S(v)=S(S(x))=S(x)=v$. Hence, $S(v)=v$. Therefore, $S$ is the identity transformation.
Comment: Your proof that the operator is identity is wrong. You said S(v) = v. But, this does not hold for any general v, as v belongs to range(S) as you assume v = S(x). In general, T need not be the identity or null operator. The identity and zero operator are special cases.
Comment: A linear transformation such that $T^2 = T$ is known as a [projection](http://mathworld.wolfram.com/ProjectionMatrix.html)
Comment: The way you wrote is confusing: all three claims (a), (b), (c) are false, so **what** exactly is that you have to do?  To refute them with examples or what?
Answer: I think that this is the solution:
If $Ker(S)=\{\bar{0}\}$, then, $Im(S)=\mathbb{R}^{2}$. Now, let $x\in\mathbb{R}^{2}$. Then, $S(x)=v$ with $v\in\mathbb{R}^{2}$. Using the hypothesis, $S(v)=S(S(x))=S(x)=v$. Hence, $S(v)=v$ for all $v\in\mathbb{R}^{2}$ Therefore, $S$ is the identity transformation.
If $Im(S)=\{\bar{0}\}$, then clearly $S$ is the zero transformation.
If $Im(S)\neq\{\bar{0}\}$ and $Ker(S)\neq\{\bar{0}\}$, i.e., the $Kernel$ and the $Image$ of $S$ are not trivial. Like $S\circ S=S$, then $S$ is a projection. One of the properties of a projection (in this particular case) is the next: $$\mathbb{R}^{2}=Ker(S)\bigoplus Im(S)$$Take $r\in Im(S)$ and $u\in Ker(S)$ such that $r\neq\bar{0}$ and $u\neq\bar{0}$. We claim that the set $\{r,u\}$ is linearly independent
(The proof is by contradiction. Suppose that $\{r,u\}$ is not linearly independent, then, $r=\lambda_0 u$ with $\lambda_0 \in\mathbb{R}$). But, $r\in Im(S)$ and $u\in Ker(S)$ and by the fact of $Ker(S)$ is subspace, then $(\lambda_0 u=r)\in Ker(S)$. Hence, $r\in Ker(S)\cap Im(S)$ but $r\neq\bar{0}$. A contradiction).
Now, $\{r,u\}$ is a basis for $\mathbb{R}^{2}$.
Then, $S(r)=a$ with $a\in Im(S)$ and $S(u)=0$ because $u\in Ker(S)$
Now (again), take $\beta=\{a,u\}$ a basis for $\mathbb{R}^{2}$ (is linearly independent. The proof is the same). Then
$$ S(a)=S(S(r))=S(r)=a=1a+0u \ \ \ \text{and} \ \ \ S(u)=0=0a+0u$$
Therefore $$[S]_{\beta}^{\beta}= \left( \begin{array}{cc}
1 & 0 \\
0 & 0 \\
\end{array} \right) $$


Path of Iphone crash logs on device

Question: Where are Iphone crash logs stored on the real device? Is there a reasonable way to get them without syncronizing the device with Itunes? I am not using Xcode as my main development environment. I am using Airplay sdk thus my primary dev environment is on Windows.
Answer: You can sync your phone and then look on your computer in:
/Library/Logs/CrashReporter/MobileDevice
You can also use a service like Crittercism to upload crash logs automatically.
www.crittercism.com
Answer: You can access the crash logs from the Organizer window in Xcode.
Comment: My question didn't provide all the information needed. I am not using Xcode to develop.
Answer: Try iPhone Configuration Utility, available for Windows and Mac.
Comment: I have done a little bit of research based on the suggestions I received here. It seems that there isn't a quick and easy way to access to crash logs under windows without using Itunes. The Configuration Utility can show only the device console. I will accept this answer since it is the one that comes closer to satisfy my need.
Comment: Just saw this was answered before, apparently iTunes syncing is not required: http://stackoverflow.com/questions/171633/accessing-crash-logs-on-iphones-used-for-ad-hoc-distribution
Answer: paths on device are:
<code>/var/mobile/Library/Logs
/var/logs
</code>
But you can get it only in jailbroken device

Path of Iphone crash logs on device


CSS 3 Skew serrilhado no Chrome

Question: Ao utilizar a propriedade transform: skew(valor) em browsers webkit ele apresenta um certo serrilhado onde fica com angulo:
<code>-webkit-transform: skew(20deg);
-moz-transform: skew(20deg);
-ms-transform: skew(20deg);
transform: skew(20deg);
</code>
Existe alguma propriedade específica pra "consertar" isso?
Comment: Usei bem a cabeça e me veio o código: -webkit-backface-visibility: hidden; que resolveu meu problema. Vou fechar  pergunta obrigado : )
Comment: Boa tarde dsantoro, poste isto como resposta, pode ser útil a outras pessoas. Não precisa fechar é só responder :)
Comment: Valeu a dica Guilherme.
Answer: Usei bem a cabeça e me veio o código: <code>-webkit-backface-visibility: hidden;</code> que resolveu meu problema.

CSS 3 Skew serrilhado no Chrome


Como executar uma procedure oracle via c# sem retorno de dados?

Question: estou desenvolvendo um WEBAPI em c# que executa uma procedure no Oracle e após esse procedimento,
ele consulta uma tabela. Essa procedure apenas deleta dados de uma tabela temporaria e insere o
os dados  informados na mesma e em seguida exibe eles com mais algumas informações.
Quando executo diretamente no Oracle a procedure ela funciona: (execute Minha_procedure(CHAVE, ANO,MES)).
obs: Ela tem um cursor.
Porém no meu código não está executando, Segue abaixo meu método:
<code>public void ExecutarProcedure(string chave, string mes, string ano)
    {
        OpenConnection();

        OracleCommand cmd = new OracleCommand("BDRH_APPS.SP_CARGA_SITE", Con);
        cmd.CommandType = System.Data.CommandType.StoredProcedure;

        OracleDataAdapter da = new OracleDataAdapter();

        cmd.Parameters.Add("CHAVE_PAR", chave);
        cmd.Parameters.Add("ANOFOLHA_PAR",ano );
        cmd.Parameters.Add("MESFOLHA_PAR",mes );

        // execute the command to open the ref cursors
        cmd.ExecuteNonQuery();

        cmd.Dispose();

        CloseConnection();

    }
</code>
Obrigado!
Comment: E qual é o erro?
Comment: não dá erro, simplesmente não está dando o execute na procedure no banco
Comment: OracleCommand has been deprecated. http://go.microsoft.com/fwlink/?LinkID=144260
Comment: Mas o problema parece ser na gestão da conexão, o que faz o método `OpenConnection();` e de onde vem o atributo `Con`?
Comment: Se não da erro mas também não "executa", pode ser que falta fazer commit. Difícil dizer...
Comment: Leandro, essa classe herda de uma outra classe de conexão com o banco  protected OracleConnection Con;    //Conexão com a base de dados..
        protected OracleCommand Cmd;       //Executar comandos SQL..
        protected OracleDataReader Dr;     //Ler dados de consultas..
        protected OracleTransaction Tr;    //transações (commit/rollback)
Comment: sem ver essas outras não tem como ajudar, mas ainda acho que você não está executando o comando na conexão aberta... apresente um um [MCVE]
Answer: consegui resolver! Criei um cursor de saída no oracle (prc out sys_refcursor) e consegui trazer os dados.
Obrigado à todos!


How do I get $entity in hook_form_alter()?

Question: hook_add_form() gets $entity_type and $entity as parameters, but hook_form_alter() does not have any of those parameters.
How do I get the entity type and the entity object in hook_form_alter()in Drupal 7?
Answer: I think that it should be possible to do something like this.
if ($form_state->getFormObject() instanceof \Drupal\Core\Entity\EntityFormInterface) {
  $entity = $form_state->getFormObject()->getEntity();
  $entity_type = $entity->bundle();
}

UPDATE: In Drupal 7 it should be done like this:
$node = $form['#entity_type']; // E.g this could be, (#node, #user etc.)

Take a look at this site, drupal discussion.
Comment: This isn't right - nodes are just one type of entity, you'll never find any other type of entity in `$form['node']`
Comment: You may also want an if like in [this answer](https://drupal.stackexchange.com/a/213156/48114) to make sure you're operating on an entity form before making these calls.
Comment: Oh sorry guys I am working with Drupal 7 and forgot to mention in hurry :(. Any way similar functions work with D7? Thanks a lot!
Comment: Try to take a look at the updated answer.
Comment: Yes this will work! Thank you a lot!!! Saved me a ton of time.
Comment: Nice I'm glad that it worked :)
Comment: Well I need commerce_product entity from hook_form_alter() actually. I am working on adding a button to add_to_cart form with functionality but I need access to entity.
Comment: Thank you @Clive, I see, I have updated the answer to display it more clearly.
Comment: THat's fine for the type, but how do you get the entity object itself?
Comment: @Jdrupal See my answer for an explanation
Answer: Entity types each implemented their own form in D7, there wasn't a generic one. You're at the mercy of what the author of each bit of code decided at the time.
For example you can find consistency with some of the core entity types:

node -> $form['#node']
user -> $form['#user']
comment -> $form['#comment']

But not all the way through:

taxonomy_term -> $form['#term']

You might find it easier to target the specific types of entity you're interested in, determine what the correct array key is for each, and store them in a map somewhere for later access.


Fingers and fretboard

Question: I am glad to join this community :)
I am a beginner in guitar and I have the following question: When I play a chord (for example G7) my fingers aren't vertically aligned with the fretboard, but they create an angle. This happens, I think, because I don't have long fingers. Is it correct and acceptable to do something like this or I have try harder to make them aligned with the fretboard? Below I have a link with a video that they player does exactly the same.
http://www.youtube.com/watch?feature=player_detailpage&v=xWkXb8jt82g#t=1m24s
Thanks :)
Answer: Your fingers don't have to be perfectly aligned to the frets/fingerboard when playing chords, or any thing else really.
The important thing is that you can hear all the notes clearly when you strum, no 'dead' notes or buzzing.
Even if your fingers were longer/stronger, there are some chords where it would be physically impossible to align your fingers as you describe.
Also for you info, the guy in the video is Justin Sandercoe, he's a pro guitarist, so if he does it, you should be fine :)
Stuart
Comment: thanks @Stuart Marsh really appreciate your answer (and of all other guys). Thanks again :)
Answer: I think it's absolutely fine that your fingers aren't vertical, just make sure that they are firmly placed on the strings and that you don't get string buzz when you play.  You also need to be concerned that your thumb is placed correctly at the back and middle of the fretboard and that your wrist is slightly bent and arched.  It'll be uncomfortable at first, but it will get easier with time.
Answer: You need to understand why you are supposed to align your fingers with the fretboard: this way it is sometimes easier to stretch your fingers or make every string sound clear.
However, that does not mean you have to do it, it does not mean you won't be able to play anything or play good if you won't. It's just a matter of style and habit. As you mentioned your self (giving a link to Justin's tutorial), there are many players not having their fingers fully vertical.
As you progress, you will notice many things like that: one says, that you have to do something in only a certain way and there will be a great guitar player right next to him that does just the opposite.
Once again: it's not important what you do, it's why you are doing it.
Good luck!

Fingers and fretboard


Apache fills up root volume

Question: Once in a while the root disk (16G) on my Apache 2.4.7/Ubuntu14.4/AWS server gets full.
Restarting Apache clears a few gigs.
I found that Apache leaves deleted log files locked so they aren't really deleted.
What is the best practice to avoid the disk fill-up besides restarting Apache weekly?
Comment: How exactly did you find that Apache leaves the log files locked?
Answer: You should be able to create a daily or weekly cron job to clean up these log files, however, it might be a good idea to figure out why the log files are getting so large to begin with ...
If your server is filling up multiple gigs of log files in a weeks worth of time it might be caused by a misconfiguration and the logs are merely a symptom of the root cause.
If your server is being attacked (even if attacks are unsuccessful) it could cause you to get a large number of logs.  Installing fail2ban might be worth while.
If you really do not care about the logs and just need them to not fill up your harddrive, you could create a symlink to /dev/nul ... although this is NOT recommended.
Answer: Something like logrotate can help to keep your logs under control if properly configured.
Other than that you can launch apache with custom options defined in order to change its working folder to another partition or mount point.

Apache fills up root volume


How to deal with discrete and continuous output multi variables in neural network?

Question: I have created neural networks using nnet for either discreate or continous output variables, but not using both at once. Now I have a problem in which the output contains both discrete and continuous variables, like this:
Y1              Y2             Y3  Y4   Y5
0.3821665898    1.2883648663    X   E   1
0.6514063927    0.5815594038    Y   B   10
0.2811264971    0.5610311362    X   D   4
0.4887534697    1.1842930657    X   A   5
0.5851027465    0.6844661487    Y   B   11
0.8273730366    1.0426096583    X   C   6
0.9663713202    1.2532121355    X   D   7
0.5929174765    1.4039754421    Y   E   5
0.8357351425    1.1997673572    Y   C   4

where Y1 and Y2 are continuous output variable and Y3-Y5 are discrete variables. Can I use discrete and continuous variable together as an output to train a neural network using nnet?
If we come across discrete variables in features we could transform them into a continuous form, like this:
X1  A   B   C
A   1   0   0
B   0   1   0
C   0   0   1
A   1   0   0
C   0   0   1
C   0   0   1

where X1 is the real feature and A,B, and C are transformed columns. Do we need to do such transformation in output variables also? What should else I looking for when doing such kind of neural network training?
Answer: Using a mix of continuous and categorial outputs as they are with nnet does not work:
> model <- nnet(x = iris[,1:3], y = iris[,4:5], size = 3, linout = T, maxit = 10000)

# weights:  20
Error in nnet.default(x = iris[, 1:3], y = iris[, 4:5], size = 3, linout = T,  :
  NA/NaN/Inf in foreign function call (arg 2)
In addition: Warning message:
In nnet.default(x = iris[, 1:3], y = iris[, 4:5], size = 3, linout = T,  :
  NAs introduced by coercion

Therefore, as you did, one-hot encoding categorial features into dummy variables is the way to go. You should consider two things when using continuous and dummy variables in nnet output at the same time:

nnet was designed to have either logical or continuous outputs (see the linout, entropy, and softmax parameters). You therefore cannot get both logical and continuous output at the same time. Using logical output with continuous data will not work by concept, so you would need to first use lineout=T, then derive the logical output you want to have from the linear output yourself.
consider properly scaling your data, e.g. mean=0 and SD=1 (you might encounter weird effects otherwise).

Here's the small reference example I just used to check that this actually works:
# example data: feature 1-3 are IN, feature 4-5 are OUT
exampleData <- iris
# one-hot encoding
library(caret)
d <- scale(data.frame(predict(dummyVars(~., data = exampleData), exampleData)))
# fit model
model <- nnet(x = d[,1:3], y = d[,4:7], size = 3, linout = T, maxit = 10000)
# used model to predict on training data (overfitting! use test data instead!)
predicted <- predict(model, d[,1:3])
plot(predicted[,1], d[,4], main = 'Petal.Width', ylab = 'observed')
plot(predicted[,2], d[,5], main = 'Species.setosa', ylab = 'observed')
plot(predicted[,3], d[,6], main = 'Species.versicolor', ylab = 'observed')
plot(predicted[,4], d[,7], main = 'Species.virginica', ylab = 'observed')

As you see, the class output (which should be logical) is continuous instead. But the separation between classes is clearly visible, so making a class probability/class membership out of it using a logistic function should be easy.


Give non-root user access to log into phpMyAdmin

Question: I'm attempting to give a non-root mysql user access to log into phpMyAdmin and only see the DB they have access to.
I've already looked at the following articles and tried their advice:
Configuring phpmyadmin for Multiple Users
I've granted the mysql user access with password to their DB and to select items in mysql db (as stated in one of the articles). I have configed phpmyadmin to use cookie auth_type, I have a pma control user, I've granted the user from not just '%' but from localhost and IPs, etc.
When the user logs in, they get #1045 Cannot log in to the MySQL server
My root user can log in fine to phpmyadmin. The user that needs access to phpmyadmin can log in from the command line fine as well.
The phpmyadmin directory has chmod -R 777 on it, except for the config file, which isn't world writable.
The applicable lines from the mysql logfile are:
130507 14:40:00 [Warning] 'user' entry 'someusername@mydomain' ignored in --skip-name-resolve mode.ve mode.
130507 14:40:00 [Warning] 'db' entry 'somedbname someusername@mydomain' ignored in --skip-name-resolve mode.
130507 14:40:00 [Warning] 'tables_priv' entry 'db someusername@mydomain' ignored in --skip-name-resolve mode.
130507 14:40:00 [Warning] 'tables_priv' entry 'host someusername@mydomain' ignored in --skip-name-resolve mode.
130507 14:40:00 [Warning] 'tables_priv' entry 'tables_priv someusername@mydomain' ignored in --skip-name-resolve mode.
130507 14:40:00 [Warning] 'tables_priv' entry 'user someusername@mydomain' ignored in --skip-name-resolve mode.

Just as a note, the actual someusername@mydomain does was granted privs with password.
My phpmyadmin config looks like this:
$cfg['blowfish_secret'] = '*******************';
$i = 0;
$i++;
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '**********';
$cfg['Servers'][$i]['hide_db'] = 'information_schema';
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';
$cfg['MaxRows'] = 500;
$cfg['AllowUserDropDatabase'] = true;

Any ideas on how to solve this issue?
Thanks.
Comment: `The phpmyadmin directory has chmod -R 777 on it, except for the config file, which isn't world writable.` - Uhm, if you are going to let people write to any other file why are you trying to protect the configuration file?  As a general rule, nothing should ever be set to `0777`, that is wrong 99% of the time.
Answer: You started MySQL with the skip-name-resolve option, either on the command line or in /etc/my.cnf, but you have MySQL users whose names include a hostname, rather than IP address. Since MySQL isn't resolving IP addresses to hostnames, it can't authenticate those users.
To resolve the issue, do one or both of:

Remove the skip-name-resolve option.
Create MySQL users with IP addresses rather than host names.
Comment: When I granted, I used the FQDN, IPs, and Aliases for everything, just to see if that would fix the problem. It didn't. I'm going to try and remove the skip-name-resolve thing and see if that works. Thank you for your quick reply!
Comment: I removed the skip-name-resolve and it worked!!!  Thank you so much!
Comment: Welcome to Server Fault. After 15 minutes you'll be able to accept the answer by clicking the outline of the check mark; be sure to do so since it marks the question as solved, and you also gain reputation by doing so.
Comment: Yep.  I wanted to accept the answer immediately, but it told me I had to wait 8 minutes, so I set a timer. :)


Setting up smtp on Windows 7 IIS 7.5

Question: I have configured a php/mysql app on my local laptop using iis7 for testing.
I use php mail() to send emails using localhost smtp service on the server and want to replicate locally for testing. (it has been working fine for a long time on the server so I just want to replicate locally for testing purposes.)
Using the technet article: http://technet.microsoft.com/en-us/library/cc772058(WS.10).aspx I was able to configure my SMTP settings however, I still can't send email.
I have recycled the server a number of times with no effect.
I've ran a netstat -an and there is nothing listening on port25 - is there something else I need to do to get the smtp service listening on port25?
ERROR:

PHP Warning:  mail() [function.mail]:
  Failed to connect to mailserver at "localhost" port 25,
  verify your "SMTP" and "smtp_port" setting in
  php.ini or use ini_set()

php.ini:
<code>SMTP = localhost
smtp_port = 25
</code>
Answer: IIS of Windows  Vista  and Windows 7 dont have SMTP server available.
So following the document you used you should write another SMTP as a Windows Server 2008 R2, not the localhost. SMTP server it's not available.
You can instead use another SMTP for your tests like this.
Check this blog post of a Microsoft MVP of IIS.
Comment: I have seen all those documents however, nowhere in any of these documents did it state that the smtp feature in iis will not work without a locally installed smtp server! what purpose does the iis smtp feature serve??? If I install a local smtp server, there is no point using iis smtp feature! would have been much easier if the simple line was added to the documentation "this does not act as an smtp server - you will still need to install an smtp server for this feature to work" what a waste of my time!!!
Comment: Yes @php-b-grader. It could be an error of the Microsoft Technet documentation.

The SMTP feature that you see, is only a UI to setup the ASP.NET/System.Net SMTP configuration. Windows 7 and Windows Vista do not include the SMTP Server.

Setting up smtp on Windows 7 IIS 7.5


MYSQL GROUP BY Query results seem limited to 31

Question: I have a Raspberry Pi temperature monitoring system setup and all is running fine except I now noticed that my Daily Min, Max and AVG query do not show more then 31 results. The problem seems to be with the GROUP BY statement and when I limit the amount of days to anything less then 31 I get all the latest data, but anything more then it will only show the 31 oldest days of data.  I have a chart that is supposed to show every days MIN, MAX and AVG temperature.
Please if somebody can help me.
With this it will only show me data from the 26/05/2014 (first day of my logging) till 27/06/2014 and stop there:
SELECT DATE_FORMAT(date,'%d') AS date2,
   MAX(temperature),
   MAX(temp2), MIN(temperature),
   MIN(temp2), AVG(temperature), AVG(temp2)
FROM data
GROUP BY date2
ORDER BY id ASC

With this it will show the last 31 Days of data (from today minus 30 days) - not what I want:
mysql_select_db("mysensors", $con);
$result = mysql_query("SELECT DATE_FORMAT(date,'%W %e %b %Y') AS date,
                              MAX(temperature),
                              MAX(temp2), MIN(temperature), MIN(temp2),
                              AVG(temperature), AVG(temp2)
                FROM data
                WHERE DATE(`date`) > DATE_SUB(NOW(), INTERVAL 30 DAY)
                GROUP BY DAY(date)
                ORDER BY id ASC") or die ("Imposible");

Comment: You are grouping the results by day, which is why you are seeing only 31 results.

There are only 31 unique days (01-31).
Comment: @Alwin Why not make that an answer? That's freaking brilliant!
Comment: Use something as simple as **`GROUP BY DATE(date)`** to get a row for each distinct "date" (yyyy-mm-dd) value. There are other expressions you can use in the GROUP BY clause to get an equivalent result e.g. `GROUP BY DATE_FORMAT(date,'%y-%m-%d')`.  (This is a comment, and not an answer, because it's not clear what question you were actually asking.)
Comment: @spencer7593 - Thank you - That worked!  Sorry, I am a total noob and only started with PHP, MySQL and Python a month ago an busy learning a lot! Thank to all. This site is the best!
Answer: You are grouping the results by day, which is why you are seeing only 31 results.
There are only 31 unique days (01-31).
Comment: As suggested by spencer7593, you could use `GROUP BY DATE_FORMAT(date,'%y-%m-%d')` to group by date.
Comment: Unbelievable. Spotting something like that.
Comment: You guys are like Ninjas! Took a minute after I asked the question for you to tell me my mistake :-)  Thanks.  A pointer to how I can group it differently like Day of Year ?


Render two taxonomy fields in one alphabetical list

Question: I have two term reference fields: colours and tags.
I have a poppy, it has tags: pretty and colours: red, green.
I want html like:

This flower is: green, pretty, red

i.e.

I want to take the terms from two fields and merge them into one collection.

I tried in Twig:
I started in twig. I could combine the terms but I couldn't sort them.
{% set alltags = content.field_tags['items']|merge(content.field_colours['items']|keys|map(i => content.field_colours[i])) %}
{{ alltags }}

I tried in pre process
I then moved to PHP in a mytheme_preprocess_node() function. I thought I could sneak a few of the colours terms in under the tags field... It seemed to add them to the object OK, but none of the colour ones were output.
/** @var Drupal\Core\Field\EntityReferenceFieldItemList */
$coloursTags = $variables['content']['field_colours']['#items'] ?? NULL;
if ($coloursTags && $coloursTags->count()) {
  $tags = $variables['content']['field_tags']['#items'];
  foreach ($coloursTags as $item) {
    /** @var Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $item */
    $tags->appendItem($item->getValue());
  }
}

I have since found a couple of ways that work, which I'll post in an answer so as to attract better answers than mine!
Answer: I found a couple of ways to achieve it, posting here, but I'm open to better/cleaner ways. I'm especially unhappy in my answers with the way to access the tag name - seems so overly complicated trying to get the raw name?!
Both code blocks live in a mytheme_preprocess_node():
Answer 1: create a new variable with all the tags in it:
<?php

  $allTags = [];
  $addTags = function($fieldName) use (&$allTags, $variables) {
    if (isset($variables['content'][$fieldName])) {
      foreach (\Drupal\Core\Render\Element::children($variables['content'][$fieldName]) as $i) {
        $allTags[]= $variables['content'][$fieldName][$i];
      }
    }
  };
  $addTags('field_colours');
  $addTags('field_tags');
  usort($allTags, function ($a, $b) {
    $tagA = $a['#taxonomy_term']->name->getValue()[0]['value'];
    $tagB = $b['#taxonomy_term']->name->getValue()[0]['value'];
    return strcasecmp($tagA, $tagB);
  });
  $variables['content']['allTags'] = $allTags;

Then in Twig for the node template: {{ allTags }}.
Answer 2: mix the tags from the colour field into the tags field in the render array
<?php

  $allTagsTemp = [];
  foreach (\Drupal\Core\Render\Element::children($variables['content']['field_tags']) as $i) {
    $tag = $variables['content']['field_tags'][$i];
    unset($tag['#weight']);
    unset($variables['content']['field_tags'][$i]);
    $allTagsTemp[] = $tag;
  }
  foreach (\Drupal\Core\Render\Element::children($variables['content']['field_colours']) as $i) {
    $tag = $variables['content']['field_colours'][$i];
    unset($tag['#weight']);
    unset($variables['content']['field_colours'][$i]);
    $allTagsTemp[] = $tag;
  }
  usort($allTagsTemp, function ($a, $b) {
    $tagA = $a['#taxonomy_term']->name->getValue()[0]['value'];
    $tagB = $b['#taxonomy_term']->name->getValue()[0]['value'];
    return strcasecmp($tagA, $tagB);
  });
  $variables['content']['field_tags'] += $allTagsTemp;

Then in Twig {{ field_tags }}.
Comment: `$a['#taxonomy_term']->name->getValue()[0]['value']` can be shortened to `$a['#taxonomy_term']->label()`
Comment: @Clive thank you, I thought there must be a short cut!!


Cifs losing data or changing permissions on files on Ubuntu 11.10 ((12)Cannot allocate memory: file permissions deny server access:)

Question: I hope this is the right place for this. I have a Ubuntu 11.10 server with Apache on. Apaches doc root is on a shared folder sourced via cifs from a windows Machine.
All this is fine on every network I have set it up on until today when I came to set it up at home.
I am viewing my website, on my Apache server in a web browser (lets say Firefox) and every couple of refreshes I get a 403 response or no data at all back for certain files from the servers cif share in Firebug.
Now through the process of elimination I have been able to determine it is cifs. I came to this conclusion by copying my doc root to a local folder on the Ubuntu install and trying to get the same behaviour, which I did not.
Now I understand this is very hard to grasp through plain text so here are a couple of pictures to describe the problem.
This first picture shows everything on one refresh and it is all fine:

This picture shows the next refresh, as you can see Firebug responds that apache suddenly cannot access my files, not only that but what Firebug is not reporting that there are also images missing off of that page. I should mention the images actually come from DB, so not sure how cifs is interferring with that but the images work with the local version of the site so it must be.

This problem is intermitant.
Now I did try and Google this but then I realised, after a couple of tries, I wasn't actually quite sure what to Google for.
Can some one point me in the right direction to diagnose my problems? Maybe some one has had this problem before and can share their solution?
Thanks,
Update: Ok so I did a little searching around in the APache logs and it comes up with this:
[Thu Jan 19 20:59:03 2012] [error] [client 192.168.153.1] (12)Cannot allocate memory: file permissions deny server access: /server_ws/htdocs/css/960.css, referer: http://stagex.co.uk/stream

I have seen this error quite a lot and it always has a different meaning. So first I decided to check the actual file permissions in Linux before I did a refresh after this problem:
drwxrwxrwx 1 www-data sam      0 2012-01-17 18:33 .
drwxrwxrwx 1 www-data sam   4096 2012-01-17 21:40 ..
-rwxrwxrwx 1 www-data sam  10641 2012-01-17 18:33 960.css
-rwxrwxrwx 1 www-data sam      0 2012-01-20 18:58 c_css.css
-rwxrwxrwx 1 www-data sam 129488 2012-01-17 18:33 main.css
-rwxrwxrwx 1 www-data sam   1086 2012-01-17 18:33 reset.css
drwxrwxrwx 0 www-data sam      0 2012-01-17 18:33 .svn

Everything looks tip top there. So I checked Windows to make sure I will always have access to it. I have shared the server_ws folder from windows using the built in protocol and have assigned my Windows user "Sam" as the owner. I have told cifs to hook into this Windows like so:
//192.168.0.2/server_ws/the_stage /media/server_ws cifs username=Sam,password=****,rw,uid=www-data,gid=sam,iocharset=utf8,dir_mode=0777,file_mode=0777 0 0

Nothig immediately wrong there and if there was something terrible there why would it only happen every so oftern.
Though now that I've found the error in Apache Ima do more Google searching.
If anyone knows something please let me know :)
Comment: Perhaps you can find further information in the `error.log` file? grep facebox.js /var/log/apache2/error.log
Comment: Originally I didn't see anything special but I'll take another look tonight see if I can find some kind of error message or code, thanks
Comment: I actually found something this time around, I have updated the post thanks.
Answer: I think I found it. This is actually a subset of a more common problem: http://alan.lamielle.net/2009/09/03/windows-7-nonpaged-pool-srv-error-2017. I found this solution a long time ago for another problem but never thought of using it here.
It seems on some installs you must tell Windows to act as a file server by setting the registry keys above. If you do that then it seems Windows will always allocate the resources required to complete a transfer even if its intensive.
I cannot get my server to repeat this problem now :D.
Thank you, Luis for you help without the thought of checking Apache again I would never have got to the bottom of it.
Answer: I'll have to go out on a limb here and guess a bit. I can't be sure which directory the DocumentRoot for stagex.co.uk points to.
Whichever it is, you can wait until you get an error and impersonate the www-user using sudo, and then try to find which folder has wrong permissions:
sudo -u www-data -s
cd /path/to/your/docroot

If this fails, cd /  and then cd to each path component in turn until you get a permission-denied error.
If you're really serving from /media/server_ws, it's possible that the permissions on /media are being changed under your feet. If you are suffering from this, I'd mount it under /srv which I think it's the usual place.
Comment: Thanks for the reply, My DocumentRoot now points to `/srv/server_ws/htdocs` that is where I am serving the files from. I tried to find a permissions problem as ww-data but I could not, I even edited and save `960.css` when I got the problem. Tested it with another permissions problem too on a `query-ui.js` source file but that turned up nothing :(. I changed my mount point from media to srv just incase but still to no effect. Overall this seems a very elusive problem.
Answer: I've found myself returning to this question and its answers because as we onboard new hires, we seem to have to redo this step. Therefore, I created a registry file based off the accepted answer's link so we can easily make the adjustment that I wanted to offer up.
You'll want to open notepad, and enter the following:
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management]
"LargeSystemCache"="1"

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters]
"Size"="3"

Save the file as whatever_you_want.reg and run it (will require administrator access, so you'll likely have to accept UAC). This has been tested on Win 7 x64 Pro
hope this helps!


Need help with a certain integral

Question: Sorry, this is my first post ever and formatting is bad. I appreciate all assistance
Given the equation
   y= $ 3.8x^2-4.4x+1444 $
Find the definite arc length integral between 0 and 1200.
I am not sure on how to format $(\frac {dy}{dx})^2$ ,so I left it alone.
$$\int_0^{1200} \sqrt{1+ (\frac{dy}{dx}})^2 dx$$
Comment: Good. Can you compute $\int \sqrt {1+x^2} dx?
Comment: I think this ought to read $y=3.8x^2-4.4x+1444$  As it is, your equation  has two complex solutions (no real solutions)...it does not define a curve.
Comment: OH my I am so sorry. I knew I would mess up the formatting. It is fine now, right?
Comment: Your formatting is fine!  Can you solve the problem from here?  $\frac {dy}{dx}$ isn't hard to compute.
Comment: $(7.6x-4.4)$. My issue is I dont know how to expand the integral with the square root.
Comment: To be clear:  that integral is doable, but it isn't exactly easy.  Here's a discussion of the "arclength of a parabola" issue...not hard to adapt to your situation:  http://math.stackexchange.com/questions/229642/length-of-a-parabolic-curve
Comment: Indeed it does, though as I say it gets you to an integral which, while standard, is not straightforward.  It's unintuitive....I think one would expect the parabola to have a straightforward arclength.  Mind you, things like ellipses are even worse.
Comment: Is there any website or place you recommend that I can learn such derivatives? I haven't really dealt with hyperbolic functions in high school yet.
Comment: You can avoid the hyperbolic functions.  Use the substitution $z=tan(z)$.  That gets you to $\int sec^3(z) dz$.  Have you done that one yet?  Here is a fairly clear discussion:  http://hubpages.com/education/How-to-Integrate-Sqrt-1-x2-Sqrt-a2-x2
Comment: Final question. How many pages would this take to solve and explain?
Comment: I think the link I just sent pretty well does it...so I'd say about one page.  The integrals of  $sec(x)$ and $sec^3(x)$ are worth studying, they do tend to come up.
Comment: So the equation I put up in the question would be one page right? :)
Comment: Absolutely.  You can do it in less if you assume your audience knows $\int sec^3(x) dx$ (or if you are willing to simply write down the solution for that without discussion).
Answer: In the same spirit as David G. Stork'answer, consider the general case of $$y=ax^2+bx+c$$ $$\frac{dy}{dx}=2ax+b$$ So $$L=\int \sqrt{1+ (\frac{dy}{dx})^2}\, dx=\int \sqrt{1+ (2ax+b)^2}\, dx$$ Now, make a change of variable $$2ax+b=t \implies x=\frac{t-b}{2 a}\implies dx=\frac{dt}{2 a}$$ So $$L=\frac{1}{2 a}\int \sqrt{1+t^2}\,dt$$ Again, a standard change of variable $$t=\sinh(z)\implies dt=\cosh(z)\,dz$$  $$L=\frac{1}{2 a}\int \cosh^2(z)\,dz=\frac{1}{2 a}\int \frac 12 \left(1+\cosh(2z)\right)\,dz=\frac{1}{4 a}\left(z+\frac 12 \sinh(2z)\right)$$ Back to $x$, this gives $$L=\frac{(2 a x+b)\sqrt{1+(2 a x+b)^2} +\sinh ^{-1}(2 a x+b)}{4 a}$$
Comment: The final derivative is the indefinite, right? If so, do I need to calculate boundaries, or can I simply use $F(b)-f(a)$ to calculate the length?
Comment: Yes to the question. You have $L(x)$ and so the arc length is $L(b)-L(a)$
Comment: Oh sorry for asking this a bit late. Why change t into $sinh$? why not $tanh$? Or why not any other expression? Sorry, I am not well educated on hyperbolic functions and when to use them. In the future, when should input a hyperbole and when shouldn't I ?
Comment: @Michael. When I see $\int \sqrt{1+t^2}\,dt$, I always think about $t=\sinh(z)$ but, as you say, we could have used $t=\tan(z)$ for the same reason. In such a case, $$L=\frac{1}{2 a}\int \sec ^3(z)\,dz$$. If you want me to continue the calculations, let me know.
Comment: The goal of substitution is to arrive to simpler expressions to be integrated.
Comment: Integration by parts in also part of the story in many cases. Again, the goal of substitution is to arrive to something simpler for which we almost know the result.
Answer: Take the derivative and plug into your integral and use the fact that
$\int \sqrt{1 + (a + b x)^2} dx = \frac{\sqrt{(a+b x)^2+1} (a+b x)+\sinh ^{-1}(a+b x)}{2 b}$.

Need help with a certain integral


Windows Server log history

Question: I have established that someone has logged into my desktop while I was on vacation, I believe it was done through our server from our administrator but I am not sure how. I am not IT friendly but I have Admin privileges on my server, so i figured before I blame the IT for accessing my Desktop i would see if he was logged on the server during the same time as it was during non working hours. Can someone provide me a step by step process on how to view previous log-ins on Server 2008
Comment: *"blame the IT for accessing my Desktop"* - You do realise that (unless you have very specific exemptions) that doing that is simply their job?
Answer: Open the Event Viewer – press the Windows key, type Event Viewer, and press Enter to open it.
Navigate to the Windows Logs –> Security category in the event viewer.
Look for events with event ID 4624 – these represent successful login events.
Scroll down in the logs to the time you believe he logged in and have a look.
You can double click on any log to open them, usually you will see the first line:
"An account was successfully logged on."
Then several more lines down
"New Logon:
Security ID:        domain\user
Account Name:       user"
Comment: Please note the OP is stuck if auditting was not set prior to the incident. *By default, this value is set to No auditing in the Default Domain Controller Group Policy object (GPO) and in the local policies of workstations and servers. (https://technet.microsoft.com/en-us/library/cc976395.aspx)*

Windows Server log history


Provide an interpretation where a formula $\forall x \exists y G(x,y) \wedge \neg \exists z G(z,z)$ of predicate logic holds true

Question: Provide an interpretation where $∀_{x}∃_{y}G(x,y) ∧ ¬∃_{z}G(z,z)$ holds.
G(x, y)  = x "greater than" y
This gives us the meaning that for all numbers, there exists a number where x is greater than y. However, there is no number that is greater than itself.
M = {U = Natural numbers, G(x, y) = 'x is greater than y'}"
Is this correct?
Comment: yes that's correct
Comment: You could also say $G(x,y)$ is $x \neq y$, with any universe of more than one object.
Answer: Your interpretation (in which the domain is the set of natural numbers $\{1,2,3,...\}$) is incorrect. To see why, first note the formula $\forall x \exists y G(x,y)$ is interpreted as follows: "for every $x$, there exists at least one $y$ such that $x > y$." In other words, there must always be an element $y$ that is less than every element $x$ in the domain. Now, let $x=1$. In that case, there is no natural number $y$ such that $x > y$ because $x=1$ is already the smallest natural number. As a result, the formula $\forall x \exists y G(x,y) \wedge \neg \exists z G(z,z)$ does not hold because the first conjunct $\forall x \exists y G(x,y)$ is false.
Instead, let your domain be the set of integers $\{...-2,-1,0,1,2,...\}$. Then, there will always be an integer $y$ smaller than every integer $x$ because $x-1$ always exists in the domain. It will also be the case that every integer cannot be greater than itself. Hence, both conjuncts of the formula $\forall x \exists y G(x,y) \wedge \neg \exists z G(z,z)$ will always be true.


Delete or Vote to Close my own question

Question: I asked certain questions on SE on which i never got an answer. Moreover i too didn't solve it either so never got a solution for it. So the question remain as it is without use to anyone.
What should i do in this case? Should i delete the question or vote to close it?
Some of the Ref Link are:
1) How to apply Fixed Special price intead of Percentage Special price in Bundle Product
2) Use SOAP and REST API Together
Comment: If you are still hoping for an answer leave the open.  If you think the have no value for the future, delete or close them.
Answer: You're the judge. We're not a high-voting culture yet, so just because you haven't seen anyone fave or upvote your question doesn't mean it's not valuable. If there were structural or obvious content issues the questions would have probably been mod'ed by now.
Comment: seems fair. I think the questions are pretty valuable and useful for the future use. I'll keep them open.
Answer: If the question is well formulated with enough information to recognize the "requirement" the question will be worthy to keep even if you would never show up again.
SE is very good in the area of self curation, means if your question is useless, it will get removed by either close/delete votes, or simply by voting it far enough down(which causes automatic deletion, if the question is old enough)
As Example, sometimes I post interesting Questions here which are not even important for me, just because I think it is worth to get asked, because there will come the time, someone will search for this.

Delete or Vote to Close my own question


Função criada para executar outras funções

Question: Estou fazendo um projeto que calcula quanto o usuário gasta por mês e o seu lucro através das informações que ele digitou nos inputs, então ele irá clicar em um botão e aparecerá o seu resultado dentro de box's. A minha pergunta é... eu posso criar uma função que o seu objetivo é na execução de outras como mostra no código abaixo?

function resultados(){

    function mostraContainer(){
    let containerResultado = document.querySelector("#div-resultado");
    containerResultado.style.display = "block";
    } mostraContainer();

    let rendaPorMes = document.getElementById("rendaMensal").value;
    let aguaPorMes = document.getElementById("aguaMensal").value;
    let luzPorMes = document.getElementById("energiaMensal").value;
    let mercadoPorMes = document.getElementById("mercadoMensal").value;
    let habitacaoPorMes = document.getElementById("habitacaoMensal").value;
    let internetPorMes = document.getElementById("internetMensal").value;
    let televisaoPorMes = document.getElementById("TVMensal").value;
    let telefonePorMes = document.getElementById("telefoneMensal").value;
    let saudePorMes = document.getElementById("saudeMensal").value;
    let impostoPorMes = document.getElementById("impostoMensal").value;
    let veiculoPorMes = document.getElementById("automovelMensal").value;
    let despesasPessoaisPorMes = document.getElementById("despesasPessoaisMensal").value;
    let lazerPorMes = document.getElementById("lazerMensal").value;

    const somaDosGastosMensal = () => Number(aguaPorMes) + Number(luzPorMes) + Number(mercadoPorMes) + Number(habitacaoPorMes) + Number(internetPorMes) + Number(televisaoPorMes) + Number(telefonePorMes) + Number(saudePorMes) + Number(impostoPorMes) + Number(veiculoPorMes) + Number(despesasPessoaisPorMes) + Number(lazerPorMes);
    const lucroMensal = () => Number(rendaPorMes) - somaDosGastosMensal();

    // Resultados Mensal: Lucro e Soma dos Gastos
    function resultadoLucroMensal(){
        let resultadoMensal = document.querySelector("#saldoDoMes");
        if(lucroMensal() > 0 ) resultadoMensal.innerText = `Seu mês fecha ANIMADO com um SALDO POSITIVO de  ${lucroMensal()} reais.`;
        else if(lucroMensal() === 0) resultadoMensal.innerText = `Seu mês fecha ZERADO!`;
        else resultadoMensal.innerText = `Seu mês fecha TRISTE com um SALDO NEGATIVO de  ${lucroMensal()} reais.`;
    } resultadoLucroMensal();

    function resultadoSomaMensal(){
        let somaMensal = document.querySelector("#somaDosGastosDoMes");
        somaMensal.innerText = `O seu gasto mensal é de ${somaDosGastosMensal()} reais.`;
        if(somaDosGastosMensal() === 0) somaMensal.innerText = `O seu gasto mensal está ZERADO!`;
    } resultadoSomaMensal();
}
#div-resultado{
    display: none;
}

Sua Renda

Quanto é o seu salário ou renda familiar mensal?

                    Digite seu salário ou renda Mensal
                        <input type="number" name="rendaMensal" placeholder="R$" id="rendaMensal" required>

Agora vamos as perguntas que dirão o seu resultado. Okay?
 Ahh outra coisa! Se você não possui gasto ou não se lembra de algum valor das seguintes opções, SEM PROBLEMA é só pular!

            <form>

Quanto você gasta com ÁGUA por mês?

                            Digite quanto gasta com água por mês
                                <input type="number" name="aguaMensal" placeholder="R$" id="aguaMensal">

Quanto você gasta com ENERGIA por mês?

                            Digite quanto gasta com energia por mês
                                <input type="number" name="energiaMensal" placeholder="R$" id="energiaMensal">

Quanto você gasta com compras ao MERCADO por mês?

                            Digite quanto gasta com mercado por mês
                                <input type="number" name="mercadoMensal" placeholder="R$" id="mercadoMensal">

Quanto você gasta com ALUGUEL ou PRESTAÇÃO?

                            Digite quanto gasta com habitação(alguel ou prestação) por mês
                                <input type="number" name="habitacaoMensal" placeholder="R$" id="habitacaoMensal">

Quanto você gasta com INTERNET por mês?

                            Digite quanto gasta com internet por mês
                                <input type="number" name="internetMensal" placeholder="R$" id="internetMensal">

Quanto você gasta com TV (planos de assinatura) por mês?

                            Digite quanto gasta com TV (planos de assinatura, etc) por mês
                                <input type="number" name="TVMensal" placeholder="R$" id="TVMensal">

Quanto você gasta com TELEFONE (planos, créditos ou assinaturas) por mês?

                            Digite quanto gasta com telefone(planos, créditos ou assinaturas) por mês
                                <input type="number" name="telefoneMensal" placeholder="R$" id="telefoneMensal">

Quanto você gasta com SAÚDE (planos, dentista, medicamentos, etc) por mês?

                            Digite quanto gasta com saude(planos, dentista, medicamentos, etc) por mês
                                <input type="number" name="saudeMensal" placeholder="R$" id="saudeMensal">

Quanto você paga em IMPOSTO (IR, INSS ou outros) por mês?

                            Digite quanto gasta com imposto(IR, INSS ou outros) por mês
                            <input type="number" name="impostoMensal" placeholder="R$" id="impostoMensal">

Quanto você gasta com o seu AUTOMÓVEL (prestação, combustível, seguro, etc) por mês?

                            Digite quanto gasta com automóvel(prestação, combustível, seguro, etc) por mês
                            <input type="number" name="automovelMensal" placeholder="R$" id="automovelMensal">

Quanto você gasta com DESPESAS PESSOAIS (vestuário, academia, cosméticos, etc) por mês?

                            Digite quanto gasta com despesas pessoais(vestuário, academia, cosméticos, etc) por mês
                            <input type="number" name="despesasPessoaisMensal" placeholder="R$" id="despesasPessoaisMensal">

Quanto você gasta com LAZER (restaurantes, passeios, livraria, etc) por mês?

                            Digite quanto gasta com lazer (restaurantes, passeios, livraria, etc) por mês
                            <input type="number" name="lazerMensal" placeholder="R$" id="lazerMensal">

            </form>

                <input type="button" role="button" value="Calcular" id="botaoCalcular" onclick="resultados()">

Sua média de gasto anual

(De acordo com as informações fornecidas).

MUITO OBRIGADO por ter usado o meu projeto!
 Espero que tenha gostado da experiência

Comment: Cadê o HTML desse código? Poderia esclarecer a pergunta *eu posso criar uma função que o seu objetivo é na execução de outras como mostra no código abaixo?*
Comment: Por link não, nós temos uma regra que código deve estar aqui na página.
Comment: Opa, não sabia Augusto. Alias desculpa pela demora para arrumar aqui, sou novato no stack também. Mas voltando ao assunto deixa eu ver como eu posso me expressar. O usuário preencheu tudo certinho, e clicou em calcular, quando ele clicou em calcular aparece os resultados. Tenho duas coisas aqui: tenho que fazer aparecer o container que está os resultados e além disso calcular eles. Tentei fazer isso de várias formas e não consegui, a única forma foi colocando as funções dentro de uma outra que vai abranger a todas. Achei bem estranho isso, e eu queria saber se pode isso ou se tem algo melhor.
Comment: No caso se teria alguma solução melhor para esse "problema". Muito obrigado pela paciência meu amigo.
Comment: Você está falando disso `function resultadoLucroMensal(){... ...) resultadoLucroMensal();` que dentro de uma função você declara outra função e logo em seguida a chama? Se for isso pergunto se já viu as [IIFE (Immediately Invoked Function Expression)](https://developer.mozilla.org/pt-BR/docs/Glossary/IIFE) são semanticamente mais adequadas para isso.
Comment: Vou ver sobre isso também, mas estou falando da function resultados(){.... .....} e se não é estranho ter várias outras funções dentro dela. O que acha?
Comment: No seu caso o mais simples é criar as funções de forma independente (em vez de uma dentro da outra), e na função `resultados` vc só chama elas. Criar uma função dentro de outra tem usos bem específicos que não se aplicam ao seu caso (como [esse](/q/1859/112052)), e além disso é mais ineficiente porque as funções internas [são recriadas toda hora](/q/493372/112052)
Comment: E não faz sentido esse monte de arrow function (a sintaxe`() => etc`) pois no seu caso vc podia ter o valor diretamente: `somaDosGastosMensal = Number(aguaPorMes) + etc` (assim a variável `somaDosGastosMensal` já tem o valor direto, sem precisar dos parênteses pra usá-la).
Comment: do jeito q vc fez ai até é executado sim! mais fazer isso é meio estranho.. rss
Comment: Uma sugestão: vc pode adicionar uma classe nos inputs que são despesas (por exemplo, `class="despesa"`), aí basta fazer `document.querySelectorAll('input[type="number"].despesa')` que vc já terá todos eles, bastando um `for` para somá-los. Algo assim: https://jsfiddle.net/ypx4ezs5/ (veja também que aqui as funções estão separadas, e algumas recebem parâmetros - que é inclusive uma das ideias de uma função: generalizar o seu funcionamento com base em parâmetros). Veja como fica - na minha opinião - mais simples
Comment: Caraca!!! Muito obrigado pelas dicas. Com essa do class="depesas" vai simplificar demais, ao invés de ficar adicionando cada categoria nos gastos. De novo, muito obrigado pela dica!
Answer: Uma das coisas mais importantes para se pensar enquanto programa com JS é que,
basicamente, tudo é objeto.
Claro que isso pode soar como uma generalização, mas basicamente qualquer estrutura de dados em JavaScript é um objeto, ou seja, um espaço na memória que guarda informações que você fornece. Até aí tudo entendido, certo?
Agora chegando direto na sua dúvida. Sim, funções também são objetos, e podem guardar suas próprias informações, como no caso, outras funções. A título de exemplo (em uma função não construtora):
function a()
{
  function a1(){} // 1st child
  function a2(){} // 2nd child
}

Nesse caso, para acessar uma das funções de dentro da função a, uma das formas é chamá-la e em seguida, sua função filha em formato de método. Nesse caso:
a().a1();
Visto isso, acredito que a maior dúvida tenha sido sanada. Agora como você poderia receber o resultado de todas as funções filhas uniformemente?
Em JS, utiliza-se a declaração return para, naturalmente, retornar valores de dentro da execução de uma função. Imagine a seguinte situação:
function resultado(a, b, c)
{
let soma;
let multi;
  function soma () {soma = a + b}
  function multi () {multi = a * c}
}

Como poderia receber, da melhor forma, ambas as variáveis soma e multi?
Utilizando, exatamente, a declaração return no final da função, adicionando-a numa função.

    function resultado(a, b, c)
    {
    let soma;
    let multi;
      function somar() {soma = a + b}
      function multiplicar() {multi = a * c}

      somar();
      multiplicar();

      return {soma, multi}
    }

    let result = resultado(2, 3, 5);
    console.log(result)

Como pode-se observar, as chaves ( {} ) indicam que o valor retornado será também um objeto, com ambos os resultados soma e multi. Este objeto está sendo guardado na variável result.


How to analyse reaction times in SPSS?

Question: I've learnt basic stats but I'm a bit confused on how I should so this, I'm gonna try and explain it as best as I could.
So I had participants doing a driving simulation which includes two different alerts inserted at different times throughout, and I have 3 different programs to counterbalance the order of the alerts.
So my reaction time looks like this in the end:
]1
Each row is a different participant doing a different order of alerts, and the transparent vs highlighted indicates two different alert.

So how do I find out whether the highlighted RT is significantly shorter than the transparent one?

How should I organise my data in SPSS since the alerts are in different order ...?
Comment: I'm not sure I fully understand the order thing but I would organize the data in long format so that there would be 3 rows per participant, each corresponding to one reaction time, then one variable indicating which alert was used and one variable indicating in which "order program" the participant was in (this variable would have only one value per participant).
Answer: To continue my comment, if there are two alert types (that vary within participants) and 3 possible orders (that do not vary within, only between participants), and 3 reaction time measurements per participant, I would organize the data like this:
<code>   id_nro alert_type order        RT
       1          2     1 4.6689560
       1          1     1 3.7079620
       1          2     1 1.3768914
       2          1     2 2.0971152
       2          1     2 2.0333446
       2          2     2 3.2799651
       3          2     3 2.4166309
       3          1     3 2.7533185
       3          1     3 2.4714532
       4          2     1 2.4571295
...
#this is generated example data so ignore the weird "reaction times"
</code>
And I'd analyze the data with a multilevel model (e.g. linear mixed model) with alert type (as categorical/factor predictor) predicting reaction time and including the random intercept of participant (to deal with repeated measures) and the fixed effect of order (to control for order).

How to analyse reaction times in SPSS?


Integrate Gaussian PDF over another gaussian, to get probability of imprecise datapoint

Question: I have a Gaussian PDF and an observation datapoint. To get a probability, I cannot use the datapoint itself--I need a range around it. But say the datapoint is imprecise and obeys a normal distribution, whose mean and variance I know. How can I integrate the PDF over the datapoint's mean and variance?
I think I get the gist of the necessary integral. For each piece of the domain, integrate the main PDF (get the likelihood it falls in that little piece), integrate the datapoint PDF (get the likelihood the datapoint falls in that piece), multiply them, and integrate over all the pieces. What is the solution to this integral?
EDIT: Let me give the full context. I am investigating automatic speech recognition. It uses Gaussian Mixture Models to calculate the probability that a feature vector (39 numbers that characterize a 10ms audio frame) would be produced by a phoneme. Essentially, the feature vector is input to a 39-dimensional multivariate Gaussian. However, the value is used directly. No integration is done. Therefore it's not a probability at all, which is a problem because other algorithms (eg Hidden Markov Models) expect probabilities. (Quite suprising how this cludge is central to ASR.) I am trying to figure out what I can do to get real probabilities. Treating the feature vector as also a multivariate gaussian (or a n-dimensional cube with sides equal to the variances) is a way of giving it some volume to integrate over.
Comment: You may want to be more explicit in describing the problem, but I think you are describing a convolution integral of two normal distributions, which ends up being a normal distribution in which the means and variance is the sum of the means and variances, respectively, of the original normal distrbutions.
Comment: I am not sure, whether I understood your question correctly. If you mean that you have two random variables $X$ and $Y$ where $Y$ represents somehow a datapoint, and $X$ is normally distributed conditional on $Y$ - you just use the law of the total probability.
Answer: What I was looking for is the overlap coefficient. It takes two Gaussians and returns the common area of overlap.
https://stats.stackexchange.com/questions/12209/percentage-of-overlapping-regions-of-two-normal-distributions


Change element class in angularjs directive link function

Question: I'm trying to set up a simple drag/drop interface using custom directives in Angularjs.  I'm working from a number of samples collected from this site and others and it all seems fairly straightforward, but doesn't quite work.  Specifically, I'm trying to implement a 'dragenter' handler that will change the appearance of a drop target when a dragged element passes over it.  First, I'll show the HTML I'm working with:

Drag Me!

Drop target 1

Drop target 2

Drop target 3

Here's the code for the two directives:
ems2App.directive('sesDraggable', function () {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            angular.element(elem).attr("draggable", "true");
        }
    };
});

ems2App.directive('sesDropTarget', function () {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            elem.bind('dragenter', function (e) {
                angular.element(e.target).addClass('divDragOver');
            });
            elem.bind('dragleave', function (e) {
                angular.element(e.target).removeClass('divDragOver');
            });
        }
    };
});

Here's the divDragOver class:
.divDragOver {
    border: 3px solid black;
    background-color: green;
}

This all works fine as far as the function is properly called when the dragged element is drug over one of the drop targets, however the class change isn't shown on the browser.  Nothing shows up in the browser console, so no errors being thrown, just doesn't change the appearance of the drop target element.
Answer: If you are using exactly the same HTML as in your post, the reason why you don't see the style change is simply due to the CSS.
The elements in the markup are defined with some inline styling, and those will take precedence over any styles defined in a class (without the !important). So your class is probably applied correctly, but the border and background displayed are still the ones with higher priority, which are the ones defined inline.
If you remove the inline styles and instead use CSS classes it will work as you expect, as long as the divDragOver class takes precedence over the new one that you define. To do that, it is sufficient to define the new class before defining the divDragOver one.
Comment: Oh boy...  Do I ever feel stupid.  Thanks very much for not saying something like "really stupid question".  I would've deserved it.  I really do understand the rules of CSS precedence.  Think I couldn't see the forest for the trees.  The funniest part of it is I stared at this for at least an hour before resorting to posting the question.  Thanks for your very polite answer!


Proof of Universal Mapping Property for tensor product of vector spaces

Question: Let $V$ and $W$ be two vector spaces. We define the tensor product of $V$ and $W$, denoted by $V \otimes W$, like wikipedia does that (https://en.wikipedia.org/wiki/Tensor_product). I want to prove the UMP. It is: if
$$
\begin{array}{llccl}
\pi & : & V \times W & \to & V \otimes W
\\
& & (v , w) & \mapsto & v \otimes w\mbox{,}
\end{array}
$$
$U$ is a vector space on $K$ and $l : V \times W \to U$ is a bilinear map, then there exists a unique linear map $\tilde{l} : V \otimes W \to U$ such that $\tilde{l} \circ \pi = l$ on $V \times W$. Thank you very much in advance.
Comment: What have you tried? Where do you get stuck? Can you define $\tilde l$? Can you prove that if it exists, that it is unique?
Comment: Simply I don't know how I can prove it. This result has many consequences (which I can see and prove) but particularly I don't know how the UMP can be proved (neither existence nor uniqueness).
Answer: For existence define $\tilde{l}(v\otimes w):=l(v,w)$ and you extend this linearly. This means you furthermore define $\tilde{l}(a\otimes b+c\otimes d):=\tilde{l}(a\otimes b)+\tilde{l}(c\otimes d)$ and $\tilde{l}(\lambda(v\otimes w)):=\lambda\tilde{l}(v\otimes w)$. Then check that this is well-defined and $l=\tilde{l}\circ\pi$.
Uniqueness follows because the diagram has to commute, i.e. any different choice for $\tilde{l}$ would contradict $l=\tilde{l}\circ\pi$
Comment: Thank you by your apportation. But if I take two vectors ${(v \otimes w)}_1 , {(v \otimes w)}_2 \in V \otimes W$, how I can show that
$$
\tilde{l}({(v \otimes w)}_1 + {(v \otimes w)}_2) = \tilde{l}({(v \otimes w)}_1) + \tilde{l}({(v \otimes w)}_2)?
$$
Comment: I forgot to mention that you have to extend the map linearly, I edited the answer
Comment: Thank you very much by your apportation! :)


2nd int-casting input-taking variables causes problem

Question: I'm working in PyCharm. I haven't been programming for a few months and when I came back I saw a problem.
There are 2 user-input-taking variables, input is converted to int.
height = int(input())
width = int(input())

(it's literally entire code, there's nothing more)
When I run the program and give the 1st integer value, it's still fine, but the 2nd integer causes the following error:

ValueError: invalid literal for int() with base 10: ''

For some reason, it is "ValueError", though I just give it integer value (see screen at the end) and it seems to indicate that I gave it an empty string which is untrue (again, see the screen - I even marked the values I had given; in this case it was 4 and 5).
If I put some code between the 2 variables, like below, the problem doesn't appear:
height = int(input())
print(height)
width = int(input())

Also note that if it's just one variable, the problem doesn't appear.
And the problem appears only in PyCharm, I did the same in VSCode and everything worked properly. I also reinstalled PyCharm to check if it helps, but it didn't.
I suppose the problem is related to PyCharm, but since hard reinstall (deleting all that Revo Uninstaller found being related to PyCharm) didn't help I have no more ideas...
Visualization:
error
Answer: Please, check your python --version in virtual environment (it should be python 3.x)
Comment: You mean python.exe in venv/Scripts? If so, it's 3.10.4
Answer: I just ran the code myself (with a few amendments just to see the prompts) and it runs completely fine in my vs code even before my prompt amendments.
height = int(input("Input Height: "))
width = int(input("Input Width: "))# Write your code here :-)
area = height * width
print(area)

I would suggest checking you have the most update version of python and that everything is configured correctly on your machine.
Also it might help to re-save the file and re run.
Answer: It seems to be a known issue which will be fixed in the next PyCharm version.
See: https://youtrack.jetbrains.com/issue/PY-54238/STDIN-is-lost-for-a-second-input-call
As suggested by the support current workaround is to enable the "Emulate terminal in output console".


MySQL won't start after setting external bind-address

Question: I want to enable remote access to my MySQL server so I've set the bind-address option under [mysqld], which looks like:
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
bind-address=**.**.**.66
port=3306
# skip-networking
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

When I comment bind-address, the server starts normally. However, when I comment it out it won't restart. The port is open and listens.
Can you please help me sort this out? Thanks
Comment: Probably I should clarify this, in the actual my.cnf file I use the real IP address. I use * just to hide it here.
Comment: `**.**.**.66` isn't a valid IP address...
Comment: @womble, eh?  Isn't that just standard address obfuscation?
Comment: @Zoredache: We don't know, do we?  Perhaps that really is what he put in, and that's why it's not working.  The correct way to obfuscate addresses is to use the RFC5737 documentation networks.
Comment: What was your configuration file? Was it "/etc/mysql/my.cnf"? Also do you solve the error?
Answer: Why do you think you need to use bind-address to enable remote access?
Without the bind-address option try running the command netstat -ntlp | grep 3306.  If you see output like below, then mysql is listening on every IP associated with the computer.
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      23465/mysqld

You only really need the bind-address if you want to listen on a specific IP.  If you want to listen for requests on all addresses you should leave that commented out or set it to 0.0.0.0.  Some packaged versions of mysql come with startup/maintenance scripts that will attempt to access mysql on 127.0.0.1.  If you use the bind-address option then mysql will only be bound to that specific IP, and nothing else, possibly breaking any scripts that you currently have.
Comment: netstat: option -p requires an argument
Comment: It does not require an argument on the net-tools version of netstat on Linux.  What OS are you running on?  I know netstat has different syntax/options on Windows, and on BSD.
Answer: Maybe this will help some folks:
It appears that if bind-address is declared in 2 places, the service fails to restart.
Perhaps you quickly scanned your /etc/conf/my.cnf file and did not see a 2nd appearance of bind-address. However, note that the file may contain a !includedir directive, and some of those included files can contain a 2nd bind-address.
Answer: Make sure there isn't a stalled mysqld instance already started. Check
ps aux|grep mysqld

and kill all processes with
kill -9

then try to start mysqld again.
Pay attention to mysqld processes in "Sl" state.
Comment: and make sure the sky isn't falling and that the power grid is still alive.  Am I still breathing?


Ldap group configuration - Derive from attribute

Question: I am using Lightweight Directory Access Protocol (LDAP) and I have a question about how to put Active Directory users in a certain role based on an attribute such as memberOf.
In version 1.0, you could say in drupal authorization under II.B. DERIVE DRUPAL ROLES that you could look for memberOf or ... and when the user that logs in, has the particular role in that attribute, he receives the role that is defined in part IIA.
For example, you can have this in section IIIA - Role Mapping:
CN=Head,OU=Roles,OU=Accounts,DC=Domain,DC=be|beheerder
How can we do the mapping in version 2.0?
My groups that I have, are stored in the active directory in extensionattribute14
Kind Regards
Answer: I've handled this by calling a update user account function during validation against the AD.
First fetch the attributes of that account:
$filter = "(sAMAccountName=" . $username . ")";
// This is where you will need to add in extensionattribute14.
$attributes = array('sAMAccountName', 'givenName', 'sn', 'description', 'telephoneNumber', 'userAccountControl', 'distinguishedName', 'memberOf', 'proxyAddresses', 'Mobile', 'facsimileTelephoneNumber', 'mail', 'employeeNumber');
$result = ldap_search($conn, $ldap_base_dn, $filter, $attributes) or exit("Unable to search LDAP server");
$entries = ldap_get_entries($conn, $result);
$entryid = ldap_first_entry($conn, $result);
$attrs = ldap_get_attributes($conn, $entryid);

And then then call the update account function ($attrs from above is passed in as $values):
/**
 * Makes updates to the users account based on values passed from the AD
 * @param  object $account
 * @param  array $values
 */
function update_user_account($account, $values) {

    // ...
    // Code here to update other values from the AD
    // ...

    if(isset($values['memberOf'])) {

        // Loop over groups.
        foreach($values['memberOf'] as $k => $group_dn) {

            switch($group_dn) {
                case 'CN=GRPHO Intranet Editor,OU=Groups - Restricted,DC=universe,DC=int':
                    $updates['roles'][8] = 'Editor';
                    break;
                case 'CN=GRPHO Intranet User Editor,OU=Groups - Restricted,DC=universe,DC=int':
                    $updates['roles'][9] = 'User Editor';
                    break;

                // etc. etc.

            }

        }
    }

    // add back in any roles that this user had that are not controlled from the AD
    if(isset($account->roles[3])) $updates['roles'][3] = 'administrator';
    if(isset($account->roles[15])) $updates['roles'][15] = 'site admin';

    user_save($account, $updates);

}


Como centralizar um texto no meio da página?

Question: eu estou utilizando o bootstrap 3.
Quero centralizar um texto conforme o exemplo abaixo.

@import url('https://fonts.googleapis.com/css?family=Anton|Black+Han+Sans|Open+Sans+Condensed:300');

/*
font-family: 'Black Han Sans', sans-serif;
font-family: 'Anton', sans-serif;
font-family: 'Open Sans Condensed', sans-serif;
*/

#topo {
  text-align: center;
  font-family: 'Black Han Sans', sans-serif;
}

#titulo {
  text-align: center;
  font-family: 'Anton', sans-serif;
}

p {
  text-align: justify;
  font-size: 20px;
  position: relative;
  margin-left: 50px;
  margin-top: 10px;
  margin-right: 25px;
  font-family: 'Open Sans Condensed', sans-serif;
}

hr {
  border: #fde192 solid 2px;
  width: 200px;
  margin: 0 auto;
}

  <title>ÂNCORAS DE CARREIRA</title>
  <meta charset="utf-8" />

  <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="css/style.css">

Teste

Âncoras de Carreira

Na década de 1970, Edgar Schein, PhD em psicologia social pela Universidade de Harvard e professor emérito da Sloan School of Management, a escola de negócios do Massachusetts Institute of Technology (MIT), nos Estados Unidos, desenvolveu a teoria
      das âncoras da carreira. Apesar de antiga, a teoria do teste âncora de carreira continua sendo válida para quem busca maior autoconhecimento para direcionar a própria vida profissional.Segundo Schein, as âncoras – oito no total – são pilares que
      norteiam as decisões de carreira dos profissionais. O teste âncoras de carreira, se objetiva em fazer com que cada profissional possa descobrir quais são as suas âncoras:

autonomia;

      segurança; competência técnico-funcional; competência administrativa geral; criatividade empreendedora; dedicação a uma causa; desafio puro; estilo de vida Elas representam a combinação única de cada um em relação à percepção de competência de carreira,
      motivos e valores. Sabendo quais são as suas âncoras, fica mais fácil encontrar a melhor empresa para você trabalhar, em que seu perfil esteja alinhado com a cultura organizacional. O teste é longo – 40 perguntas -, por isso reserve um tempo para
      fazê-lo. Mas dá para fazer sozinho! Tome fôlego e dê mais um passo rumo à sua felicidade profissional.

Como fica na minha página aqui no meu computador.

Fica um lado maior que o outro.
Aí eu utilizei o col-md-10, daí queria ele centralizado.
Como faço isso?
Comment: Utilize a classe `col-offset-md-2` ou `center`
Answer: ultilize a tag com a classe:

Comment: Resolveu! Valeu!
Answer: Uma outra hipótese era dentro da div com a class="col-md-10" tivesse o seguinte style

Answer: Boa Tarde,
Você Precisa fazer algumas alterações no seu css para que a centralização, funcione separando os textos em dois parágrafos como representado,
@import url('https://fonts.googleapis.com/css?family=Anton|Black+Han+Sans|Open+Sans+Condensed:300');

/*
font-family: 'Black Han Sans', sans-serif;
font-family: 'Anton', sans-serif;
font-family: 'Open Sans Condensed', sans-serif;
*/

#topo {
  text-align: center;
  font-family: 'Black Han Sans', sans-serif;
}

#titulo {
  text-align: center;
  font-family: 'Anton', sans-serif;
}

p {
  text-align: justify;
  font-size: 20px;
  position: relative;
  margin-left: 50px;
  margin-top: 10px;
  margin-right: 25px;
  font-family: 'Open Sans Condensed', sans-serif;
}
li {
 font-size: 20px;
 position: relative;
 margin-left: 50px;
 margin-top: 10px;
 margin-right: 25px;
 font-family: 'Open Sans Condensed', sans-serif;
 /*list-style: none*/
 /*font-weight: bold;*/
}
hr {
  border: #fde192 solid 2px;
  width: 200px;
  margin: 0 auto;
}

e se você preferir pode alterar ou remover o estilo da sua lista, como no que foi comentado , e também converter o texto das listas para negrito


How can I store a text field permanently in react native?

Question: Sorry if this is a fairly basic question, I am new to react native and mobile development in general.
I have recently begun building a mobile application using expo and react native, but I have run into an issue in doing so. What I am trying to accomplish is to build a page where users can edit profile details that are not required to be stored in the backend. I need these text fields to save permanently until they are potentially edited at a later time by the user.
Initially, it seemed that using AsyncStorage would be the way to go about this, however, I discovered that upon closing the expo server and restarting it, the text is deleted and replaced with the placeholders. Does this mean that I improperly set up AsyncStorage, or is this simply the nature of expo? Would this data save permanently if the app in question were actually exported and deployed? I considered using something like realm instead, but it appears that this is not compatible with expo.
Any guidance on the best way to approach this problem would be appreciated. Again, sorry if the answer to this is obvious, I tried searching for information about this but found very little.
Comment: Can you post your AsyncStorage codes?
Answer: You're on the right path here, I use AsyncStorage for the same reason you do and it should be able get your data after the expo server restarts. I believe in your case you're using:
AsyncStorage.setItem("exampleData")

And in order to retrieve that exampleData again you have to use:
AsyncStorage.getItem("exampleData")

And store that exampleData into your redux. (I'm assuming you're using redux, but if you're not let me know!)

You can also implement this in a screen setup so the first screen of your app retrieves that AsyncStorage data. I'll give you an example of how my code works.
Here I have my navigation set up as:
const MainNavigator = createSwitchNavigator({
  Startup: StartupScreen, // <-- This is the screen that gets the item
  StartAuth: StartSignup,
  Intro: IntroStack,
  Project: FullAppNavigator,
});

And the StartUpScreen as:
import React, { useEffect } from "react";
import { View, StyleSheet, ActivityIndicator } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useDispatch } from "react-redux";
import { authenticate, logout } from "../store/actions/auth";
import { getUserData } from "../store/actions/user";

const StartupScreen = (props) => {
  const dispatch = useDispatch();
  useEffect(() => {
    const tryLogin = async () => {
      const userData = await AsyncStorage.getItem("exampleData"); // <-- here
      if (!userData) {
        props.navigation.navigate("StartAuth");
        return;
      }
      const transformedData = JSON.parse(userData);
      const { localId, token, introing } = transformedData;

      if (!token || !localId) {
        props.navigation.navigate("StartAuth");
        return;
      }

      if (introing) {
        await dispatch(getUserData());
        await dispatch(authenticate(localId, token));
        await props.navigation.navigate("Intro");
      } else {
        await dispatch(getUserData());
        await dispatch(authenticate(localId, token));
        await props.navigation.navigate("Project");
      }
    };

    tryLogin();
  }, [dispatch]);

  return (
    <View style={styles.screen}>
      <ActivityIndicator size="large" color="white" />
    </View>
  );
};

const styles = StyleSheet.create({
  screen: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
});

export default StartupScreen;

So as you can see it gets the item from await AsyncStorage.getItem("exampleData") and then navigates to the next screen once it retrieves that item. In my case it receives a token, and when it receives that token it gets another item from the action getUserData, then navigates.
Going this route also allows you to implement a loading screen as you retrieve that data from AsyncStorage, as you can see with the ActivityIndicator in that StartupScreen.


Apache + tomcat + jnlp

Question: We have an instance of Tomcat behind an Apache. We use mod_jk.
The module config is:
LoadModule jk_module modules/mod_jk.so
<IfModule mod_jk.c>
  JkWorkersFile conf/workers.properties
  JkLogFile     logs/mod_jk.log
  JkLogLevel    info
  JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "
</IfModule>

And here the VirtualHost config:
<VirtualHost *:9090>
...
  JkMount  /Web/* worker-Web
  JkMount  /Web worker-Web
</VirtualHost>

The workers.properties file:
worker.list=worker-Web
worker.worker-omiapWeb.port=8209
worker.worker-omiapWeb.host=localhost
worker.worker-omiapWeb.type=ajp13

This config works great for jsp, html... but we have a JNLP file:
<?xml version="1.0" encoding="utf-8"?>
  <jnlp spec="1.0" codebase="$$codebase">
    <information>
      <title>Gestor Impresiones</title>
      <vendor>.</vendor>
    </information>
    <resources locale="es">
      <jar href="gestorImpresiones.jar"/>
      <jar href="jasperreports-1.2.5.jar"/>
      <jar href="commons-httpclient-3.1-beta1.jar"/>
      <jar href="commons-logging-1.1.jar"/>
      <jar href="commons-codec-1.3.jar"/>
      <jar href="commons-javaflow-20060411.jar"/>
      <jar href="commons-collections-3.1.jar"/>
      <jar href="poi-3.0.1-FINAL-20070705.jar"/>
      <jar href="jdic.jar"/>
    </resources>
    <resources os="Windows">
      <jar href="windows/jdic_stub.jar"/>
      <nativelib href="windows/jdic-native.jar"/>
    </resources>
    <resources os="Linux">
      <jar href="linux/jdic_stub.jar"/>
      <nativelib href="linux/jdic-native.jar"/>
    </resources>
    <resources locale="es">
      <j2se version="1.3+" href="http://java.sun.com/products/autodl/j2se"/>
    </resources>
    <security>
      <all-permissions/>
    </security>
    <application-desc main-class="stacks.printing.cliente.GestorImpresionLauncher"/>
  </jnlp>

The problem is that downloading the JNLP resources fails randomly (It fails more if the connection speed are poor).
If we access directly to Tomcat, everything works fine.
Any ideas?
Edited 1:
Apache log error:
[Thu Jul 01 09:51:45 2010] [868:5096] [info] jk_connect.c (566): connect to 127.0.0.1:8209 failed (errno=61)
[Thu Jul 01 09:51:45 2010] [868:5096] [info] jk_ajp_common.c (869): Failed opening socket to (127.0.0.1:8209) (errno=61)
[Thu Jul 01 09:51:45 2010] [868:5096] [error] jk_ajp_common.c (1359): (worker-omiapWeb) connecting to backend failed. Tomcat is probably not started or is listening on the wrong port (errno=61)
[Thu Jul 01 09:51:45 2010] [868:5096] [info] jk_ajp_common.c (2186): (worker-omiapWeb) sending request to tomcat failed (recoverable), because of error during request sending (attempt=2)
[Thu Jul 01 09:51:45 2010] [868:5096] [error] jk_ajp_common.c (2204): (worker-omiapWeb) Connecting to tomcat failed. Tomcat is probably not started or is listening on the wrong port
[Thu Jul 01 09:51:45 2010] [868:5096] [info] mod_jk.c (2364): Service error=-3 for worker=worker-omiapWeb

Edited 2:
server.xml AJP section:

<Connector port="8209"
       maxThreads="300" connectionTimeout="600000"
       enableLookups="false" redirectPort="8443" protocol="AJP/1.3" />

Comment: What versions of Tomcat, Apache, and connector modules are you using?
Comment: Tomcat 5.5.27, Apache HTTP 2.0.63 and Tomcat Connector 1.2.26
Answer: Why do you serve the JNLP application from tomcat? WebStart uses plain HTTP GET requests to acces the JNLP file and then the .jar files. You could place these outside of Tomcat, and let Apache do the work alone.
Answer: Try setting your worker timeouts to higher than default values:

worker.worker-omiapWeb.socket_timeout=60
worker.worker-omiapWeb.connect_timeout=2000
worker.worker-omiapWeb.prepost_timeout=1000
worker.worker-omiapWeb.reply_timeout=30000

That goes in your workers.properties file.  You may have to go higher with one or more of them - we'd need to see your apache log files to be sure which one is causing the issue for you.
Comment: To help out: http://tomcat.apache.org/connectors-doc/reference/workers.html
Comment: I already tried to change the default settings without any results.
Answer: You may also want to post the bits of your server.xml for the AJP connector. One possibility is that your connector on the Tomcat side doesn't have enough capacity (maxThreads & timeout) to handle the number of connections Apache is sending it.

Apache + tomcat + jnlp


Entity metadata wrapper, get field collection in field collection

Question: I want to get (and to set after) the value of a field collection in a field collection (multidimensional field content).
This is my code :
// The node is a custom content.

// I get the list of first collections fields.
$temp = field_collection_get($node,'field_top');
// Shows the structure you can see below in the screenshot.
dpm($temp->value()[0]);

// Now, I want to get the value of field_website_informations.
// I've tried several ways but I couldn't find the right way.
// The following line returns an error.
$testage = entity_metadata_wrapper($temp->value()[0], 'field_website_informations');

Is it possible to do with the Entity API?
The screenshot :
Comment: Do yourself a favour @user2137454 by learning how to set-up and use a php debugger like xdebug. You'll never look back to `dpm()` ever again, particularly in Drupal with its heavy reliance on multi-dimensional arrays to pass around data.
Answer: Yes it is possible. Let's say you have a content type with a field collection named field_collection_parent, which has a field collection in it named field_collection_child, which has a field in it named field_child.
// First you need to wrap the node with entity_metadata_wrapper
$node_wrapper = entity_metadata_wrapper('node', $node);

// To get the value of field_child:
$value = $node_wrapper
           ->field_collection_parent
           ->field_collection_child
           ->field_child
           ->value();

// UPDATE: If a field accepts multiple values, treat it like an array
// The following line would get the first value of field_collection_child in the
// first field_collection_parent.
$value = $node_wrapper
           ->field_collection_parent[0]
           ->field_collection_child[0]
           ->value();

// To set/modify the value of field_child
$node_wrapper
  ->field_collection_parent
  ->field_collection_child
  ->field_child
  ->set('Some new value');

// To save the node after modifying
$node_wrapper->save();

Comment: Thanks for help =)
When I try :
    $value = $temp->field_top->field_website_informations->value();
I obtain this error :
Undefined property: EntityListWrapper::$field_website_informations

I don't understand... My custom content contain a field collection named "field_top".
In the admin panel for field collection, I can see the "field top" who contain the sub-collection field "field_website_informations"
Comment: Ok, as it seems, the field `field_top` is a multi-value field. I updated my answer accordingly.
Comment: It's ok with your update !
ReeeaaalllyyyYYY thanks guy from french country!
Comment: Glad that it works :)
Comment: please see my solution: https://drupal.stackexchange.com/questions/144466/change-values-of-nested-fields-with-entity-metadata-wrapper/307791#307791


Overloading method throws Duplicate error in Typescript

Question: I have the next piece of code:
public async insert(data: iFlower | iFlower[]): Promise<iFlower> | Promise<iFlower[]> {
 await this.insert(data);
}

private async insert(data: iFlower): Promise<iFlower>{
 ....
 return data;
}

private async insert(data: iFlower[]): Promise<iFlower[]> {
 ....
 return data;
}

iFlower is:
export interface iFlower {
   color: string;
   number: string;
}

I get the following errors:
The return type of an async function or method must be the global Promise<T> type.
Duplicate function implementation.
'insert' is declared but its value is never read.
Is it because iFlower is an interface?
Answer: When you do an overload in typescript, the only thing you provide multiples of is the types. The actual implementation is just a single function. So, you'll do a series of types for the function, then one implementation which is compatible with all those types, as in:
private async insert(data: iFlower): Promise<iFlower>;
private async insert(data: iFlower[]): Promise<iFlower[]>;
private async insert(data: iFower | iFlower[]): Promise<iFlower> | Promise<iFlower[]> {
  // Your code here. Maybe something like:
  if (Array.isArray(data)) {
    ...
    return data;
  } else {
    ...
    return data;
  }
}