Neo4j - Performance: Find Nodes with a certain label with a relation to the source node

Question: i have the following requirements:

Given a source node
Find all nodes within a certain range (e.g. 4 hops)
and the destination nodes has a special label "x"
Restrict the label type of the nodes in the path to the destination
return only the shortest path length (e.g. if i find a node with 2 hops, dont find also nodes with 3 or 4 hops)
Return all nodes needed for showing the destination nodes and the path between

i managed to create a query but the performance is not so well. i assume it is because of the high amount of nodes with the label "x"
MATCH path = allShortestPaths((source)-[*..4]-(destination))
WHERE source.objectID IN ['001614914']
AND source:Y
AND destination:X
AND ALL(x IN nodes(path)[1..] WHERE any(l in labels(x) WHERE l in ['A', 'B', 'C']))
WITH path
LIMIT 1000
WITH COLLECT(path) AS paths, MIN(length(path)) AS minLength
WITH FILTER(p IN paths WHERE length(p)= minLength) AS pathList
LIMIT 25
UNWIND pathList as path
WITH [n in nodes(path)] as nodes
return nodes

Profile:

if i change the query to use not the shortest path function, this works well when the source has not a lot of outgoing Paths
MATCH path = ((source)-[*..4]-(destination))
WHERE source.objectID IN ['001614914']
AND source:Y
AND destination:X
AND ALL(x IN nodes(path)[1..] WHERE any(l in labels(x) WHERE l in ['A', 'B', 'C']))
WITH path
LIMIT 1000
WITH COLLECT(path) AS paths, MIN(length(path)) AS minLength
WITH FILTER(p IN paths WHERE length(p)= minLength) AS pathList
LIMIT 25
UNWIND pathList as path
WITH [n in nodes(path)] as nodes
return nodes

Profile:

But if i have a source node with many children this has also a bad performance...
in the moment i am thinking if i start with a simple search for all destinations and call a shortestPath on each found destination this might be better but i am not very sure.
e.g.
MATCH (source)-[*..4]-(destination)
WHERE source.objectID IN ['001614914']
AND source:Y
AND destination:X
WITH destination
LIMIT 100
call apoc (shortest path ...)
...

Or is there a better approach?
Answer: You may want to try APOC's path expander using 'NODE_GLOBAL' uniqueness, it typically performs better than a variable-length match. It also has a means for whitelisting nodes during traversal, but this does apply to the start node too, so we'd have to include :Y in the whitelist.
See if this works for you:
MATCH path = (source:Y)
WHERE source.objectID IN ['001614914']
CALL apoc.path.expandConfig(source, {labelFilter:'+A|B|C|Y', maxLevel:4, uniqueness:'NODE_GLOBAL'}) YIELD path
WITH path, last(nodes(path)) as destination
WHERE destination:X AND NONE(node in TAIL(nodes(path)) WHERE node:Y)
// all the rest is the same as your old query
WITH path
LIMIT 1000
WITH COLLECT(path) AS paths, MIN(length(path)) AS minLength
WITH FILTER(p IN paths WHERE length(p)= minLength) AS pathList
LIMIT 25
UNWIND pathList as path
RETURN NODES(path) as nodes

Comment: i try to convince my boss of the limitation ^^
Comment: There are some changes on their way on APOC which will make this kind of solution much easier, such as an option on whether or not to apply the label filter to the start node (so you won't need to specify 'Y' in the label filter), and the ability to use multiple filter operations at the same time (so you could specify the label of end-nodes for paths, as well as the whitelist). A limit operation is also on its way. Not sure about when a new release will happen but likely within the next two weeks or so.


DropDownList Cascata e Composta MVC

Question: Tenho uma seguinte duvida
Tenho 1 classe Usuário e composta por outras classes Gênero,Curso e Semestre
Ex
<code>    public int Id { get; set; }
    public string Nome { get; set; }
    public Genero Sexo { get; set; } = new Genero();
    public Curso Curso { get; set; } = new Curso();
    public Semestre Semestre { get; set; } = new Semestre();
</code>
E minha duvida e na minha controller para popular minhas DropDownListFor
Minhas classes DAO Iguais a de Curso e Semestre
<code>    public List<Genero> ListarGenero()
    {
        var Genero = new List<Genero>();
        SqlDataReader reader;

        using (contexto = new Contexto())
        {
            var strQuery = " SELECT * FROM Genero ";
            reader = contexto.ExecutaComandoComRetorno(strQuery);

            while (reader.Read())
            {
                var temObjeto = new Genero()
                {
                    id = int.Parse(reader["Id"].ToString()),
                    Sexo = reader["Genero"].ToString()
                };
                Genero.Add(temObjeto);
            }
        }
        reader.Close();
        return Genero;
    }
</code>
Minha Action
<code>    public ActionResult GetGenero()
    {
        GeneroDAO gen = new GeneroDAO();
        ViewBag.Genero = new SelectList(gen.ListGenero(), "Id", "Sexo");
        return View();
    }
</code>
View
<code>     @Html.DropDownListFor(model => model.Sexo.id, (SelectList)ViewBag.Genero, new { @class = "form-control" })
</code>
Procurei em alguns foruns nao achei nada usando composição
Gostaria de como fazer para popular as dropdown vindo do banco e tambem fazer em cascata no curso, so achei com JavaScript porem nao posso utilizar pq ele tambem nao reconhece a composição das outras classes
Comment: Não seria apenas
`@Html.DropDownListFor(model => model.Sexo  ...`
Answer: Manda na viewbag a lista de generos e na view coloca
<code>@Html.DropDownListFor(model => model.Sexo.id, new SelectList
(
  ViewBag.Genero, "Id", "Sexo"
),"Insira o sexo", new { @class = "form-control" })
</code>

DropDownList Cascata e Composta MVC


what's the purpose for the log4net.Config.XmlConfigurator()

Question: I saw someone put log4net.Config.XmlConfigurator() inside the AssemblyInfo.cs. What exactly does it do?
Answer: Taken from: http://logging.apache.org/log4net/release/manual/configuration.html
<code>// Configure log4net using the .config file
[assembly: log4net.Config.XmlConfigurator(Watch=true)]
// This will cause log4net to look for a configuration file
// called TestApp.exe.config in the application base
// directory (i.e. the directory containing TestApp.exe)
// The config file will be watched for changes.
</code>


How to access the first items in a list of arrays without for loop in Python 3?

Question: I have an ode equation which produces a list like below:
u=[array([ 2.06642033, -0.03448756]),
   array([ 2.03964994, -0.18737285]),
   array([ 1.99884859, -0.21461016]),
   array([ 1.95476809, -0.2254584 ]),
   array([ 1.90875336, -0.23472173]),
   array([ 1.86082857, -0.24471069]),
   ... ]

I want to plot u[0] and u[1] based on time. I try to access all first and second elements of u in two list with l1=u[0:len(u)-1][0] and l2=u[0:len(u)-1][1], but it gives me only the first item from list.
Does anyone have a solution for it?
Thanks
Comment: I have a time list which has the same length as u, like this: t=[0,0.001, ...]
Comment: What do you mean when you say "based on time"? Please provide some examples.
Answer: You should convert your list of arrays into a single numpy array.
Also note that numpy array indexing in 2d is performed by arr[row, column]. If you don't filter by a dimension, just use :.
from numpy import array

u = [array([ 2.06642033, -0.03448756]), array([ 2.03964994, -0.18737285]),
     array([ 1.99884859, -0.21461016]), array([ 1.95476809, -0.2254584 ]),
     array([ 1.90875336, -0.23472173]), array([ 1.86082857, -0.24471069])]

u = np.array(u)

res = u[:, 0]

# array([ 2.06642033,  2.03964994,  1.99884859,  1.95476809,  1.90875336,
#         1.86082857])


Predicting from RPart using a subset of variables

Question: I fitted a RPart model from all of a couple dozen variables. Now, I want to test predictions using just a couple of variables that seem significant to me.
If it was the iris dataset, for example, I would have fit the model to all the characteristics but I wanted to test the prediction just from Petal.width and Sepal.length.
When I try making a new dataframe with only those values to enter as newdata, it complains the dataframe is missing Sepal.width, for example.
What am I doing wrong?
Comment: I am not sure if this will be considered on topic here (given the software emphasis). However, in order for anyone to help, I think you will need to provide a few lines of code showing what you tried.
Answer: I'm not quite sure why you would want to do that... Fitting a tree with more variables that the ones you are going to use to predict will bias the results: the splittings you are using are suboptimal.
In any case, if you really want to go ahead, you could create the missing columns and fill them with NAs, being careful to change their classes to their corresponding ones in the training dataframe. For example:
<code>mod <- rpart(Species~., iris)
iris2 <- iris[,-3]
iris2$Petal.Length <- rep(NA, nrow(iris2))
class(iris2$Petal.Length) <- 'numeric'
predictions <- predict(mod, newdata = iris2, na.action = na.pass)
</code>
How rpart handles the NAs (na.action) is explained here: https://stat.ethz.ch/R-manual/R-devel/library/rpart/html/predict.rpart.html


how can i echo item price in php

Question: this code create barcode image and echo the item name with barcode
but i want to echo item name with unit price
 how can i do this please help me to fix this issue
thanks
im edit after this code
$text = $item['name'];

to
like this
$text = $item['name'];

$text2 = $item['unit_price'];

but its notworking can anybody tell me whats the problem and how can i fix it
this is my php barcoder script

        <title><?php echo $this->lang->line('items_generate_barcodes'); ?></title>

    <?php
    $count = 0;
    foreach($items as $item)
    {
        $barcode = $item['id'];

        $text = $item['name'];

        if ($count % 2 ==0 and $count!=0)
        {
            echo '

';
        }
        echo "	";
        $count++;
    }
    ?>

this is mysql structure
name            varchar(255)     latin1_swedish_ci          No
category    varchar(255)    latin1_swedish_ci       No
supplier_id int(11)         Yes NULL
item_number varchar(255)    latin1_swedish_ci       Yes NULL
description varchar(255)    latin1_swedish_ci       No
cost_price  double(15,2)            No
unit_price  double(15,2)            No
quantity    double(15,2)            No  0.00
reorder_level   double(15,2)            No  0.00
location    varchar(255)    latin1_swedish_ci       No
item_id int(10)         No      auto_increment
allow_alt_description   tinyint(1)          No
is_serialized   tinyint(1)          No
deleted int(1)          No  0
expire

here is my mysql barcode function
function generate_barcodes($item_ids)
{
    $result = array();

    $item_ids = explode(':', $item_ids);
    foreach ($item_ids as $item_id)
    {
        $item_info = $this->Item->get_info($item_id);

        $result[] = array('name' =>$item_info->name, 'id'=> $item_id);
    }

    $data['items'] = $result;
    $this->load->view("barcode_sheet", $data);
}

Comment: You have to make sure you have the data `item_price` available through the query your reading data from
Comment: yes i have a data in item_price
Answer: First, you need to have unit_price available in your $item array from the database.
In your foreach loop, replace this line $text = $item['name']; with this:
$text = $item['name'] . ' $' . number_format($item['unit_price'], 2);

This is how the code should look:

        <title><?php echo $this->lang->line('items_generate_barcodes'); ?></title>

    <?php
    $count = 0;
    foreach($items as $item)
    {
        $barcode = $item['id'];

        $text = $item['name'] . ' $' . number_format($item['unit_price'], 2);

        if ($count % 2 ==0 and $count!=0)
        {
            echo '

';
        }
        echo "	";
        $count++;
    }
    ?>

Comment: dear i update and check it then showing error Disallowed Key Characters and image is also not showing of barcode
Comment: url showing like this index.php/barcode?barcode=1&text=Laptop%20$0.00&Laptop%20$0.00&width=256 and unitprice is not came in url see %20$0.00&
Answer: I have the strong feeling that your SELECT statement lacks the unit_price column.
Please show us your SELECT statement that poppulates your $items array.
Comment: function generate_barcodes($item_ids)
 {
  $result = array();

  $item_ids = explode(':', $item_ids);
  foreach ($item_ids as $item_id)
  {
   $item_info = $this->Item->get_info($item_id);

   $result[] = array('name' =>$item_info->name, 'id'=> $item_id);
  }

  $data['items'] = $result;
  $this->load->view("barcode_sheet", $data);
 }
 here is my select statement i think how can i edit a unit_price in that

how can i echo item price in php


Verificar se há palavras em maiúsculas

Question: Como verificar se uma string contém palavras em maiúsculas em PHP? Eu tenho uma página de registro, checar isso quando o usuário faz o registro.
Comment: Bem vindo, Veja [como criar um exemplo Mínimo, Completo e Verificável](http://pt.stackoverflow.com/help/mcve)
Comment: Como assim? quando achar as letras maiusculas faz o que?
Comment: Pode usar uma regex `[A-Z]`
Comment: @Brayan Você pode explicar melhor a dúvida? A resposta do rray funcionou? Afinal, você quer saber se o texto tem 1 ou mais letras maiúsculas, saber se ele está todo em maiúsculas, se tem pelo menos uma palavra em maiúsculas?
Comment: Sua pergunta está muito ampla, explique mais o que você quer, dê um exemplo e mostre aonde você quer chegar, recomendo as leituras citadas pelo @rubStackOverflow
Answer: Para descubrir se existem letras maiusculas em uma string pode utilizar uma regex simples [A-Z] com a função preg_match().
<?php
$entradas = ['Um', 'min abc', 'aÇão', 'ação', 'CAPS'];

foreach($entradas as $item){
   if(preg_match('/\p{Lu}/u', $item)){
      echo "Entrada: $item - existe pelo menos uma letra maiuscula\n";
   }else{
      echo "Entrada: $item - não existe pelo menos uma letra maiuscula\n";
   }
}

Exemplo - ideone
Comment: `/[A-Z]*/` avalia `''`, `'sominusculas'`, `'qualquercoisa'` para true pois o pattern aceita zero matches devido ao `*`. Mesmo retirando o `*` a solução ainda não é robusta pois não lida com unicode, qualquer `É` ou `Ç` será rejeitado.
Comment: @brunorb, para caracteres Unicode basta adicionar o modificador u. Depois arrumo isso, obrigado pela dica
Comment: @BrunoRB alterei a resposta, está de acordo agora?
Comment: Seu código diz que todas as entradas tem maíusculas, rode para ver. Ele está quase correto, você precisa usar a propriedade `Lu` para especificar que são "uppercase letters", [referência](http://php.net/manual/en/regexp.reference.unicode.php).  No caso a regex correta é `/\p{Lu}/u`.
Answer: Dar para fazer da seguinte forma com a função strtoupper:
<?php

$palavra = 'PALAVRA1';

if (strtoupper($palavra) == $palavra) {//TRUE
    echo 'Verdadeiro';
}

$palavra = 'pALaVRA1';

if (strtoupper($palavra) != $palavra) {//FALSE
    echo 'Falso';
}

Verificar se há palavras em maiúsculas


JMS Channel not using multi threading

Question: I am reading a message , transforming it and outputting on the JMS channel. The JMS channel uses a WorkManager Task Executor  to read the messages and processes it.
Even though we configured the WorkManager in application server to have 10 threads, only one thread is being used.
<si:chain id="prenotifchain" input-channel="preNotificationChannel"  output-channel="notificationJMSChannel">
    <si:transformer id="prenotif"  method="transformRequest"  ref="notificationTransformer"/>
</si:chain>

<si-jms:channel id="notificationJMSChannel" queue="notificationQueue" connection-factory="queueConnectionFactory" transaction-manager="txManager" task-executor="notificationTaskExecutor"  />

<jee:jndi-lookup id="notificationQueue" jndi-name="jms/notifqueue"/>

    <bean id="notificationTaskExecutor"
    class="org.springframework.scheduling.commonj.WorkManagerTaskExecutor">
    <property name="workManagerName" value="notifWM" />
    <property name="resourceRef" value="true" />
</bean>

Are we missing any configuration or is there another way to read multiple ?
Comment: What server are you using Weblogic or Websphere? Where did you configure the threads? Can you please show the configuration?  Please provide the full name for your work manager class.
Comment: The threads are configured in websphere admin console. We are using reference here in the executor
Answer: Please, use concurrency attribute:
<xsd:attribute name="concurrency" type="xsd:string">
        <xsd:annotation>
            <xsd:documentation><![CDATA[
The number of concurrent sessions/consumers to start for each listener.
Can either be a simple number indicating the maximum number (e.g. "5")
or a range indicating the lower as well as the upper limit (e.g. "3-5").
Note that a specified minimum is just a hint and might be ignored at runtime.
Default is 1; keep concurrency limited to 1 in case of a topic listener
or if message ordering is important; consider raising it for general queues.
            ]]></xsd:documentation>
        </xsd:annotation>
    </xsd:attribute>

Comment: Thank you.If we add the concurreny attribute then what is the difference between concurrency and adding the taskexecutor threads ?  Does taskexecutor threads ignored in this case ?  Do I remove the taskexecutor attribute if it is ignored
Comment: The task executor doesn't have value without concurrency, but it's definitely better to support an executor as you do. Only the point that it is not going to work in parallel without concurrency

JMS Channel not using multi threading


How do I prove that $\operatorname{rank}{AB}+\operatorname{rank}{BC}\le\operatorname{rank}{B}+\operatorname{rank}{ABC}$?

Question:
Possible Duplicate:
How do you prove $\def\rank{\operatorname{rank}}\rank(f_3 \circ f_2) + \rank(f_2 \circ f_1) \leq \rank(f_3 \circ f_2 \circ f_1) + \rank(f_2) $?

The Frobenius inequality of linear algebra, with $A,B,C\in M_n(\mathbb{F})$, is: $$\operatorname{rank}{AB}+\operatorname{rank}{BC}\le\operatorname{rank}{B}+\operatorname{rank}{ABC}$$
Comment: In wikipedia, I've already read the proof you referred to. What I don't understand is, what is $\ker{ABC}/\ker{BC}$ and why that projection is one-to-one?
Comment: This is also a duplicate of http://math.stackexchange.com/questions/497830/frobenius-inequality-rank .
Answer: To answer your more focused question in the comment:
The clear candidate map is $x\mapsto Cx +\ker (B)$, which gives you a homomorphism from $\ker(ABC)\rightarrow \ker(AB)/\ker(B)$.
Modding out by this map's kernel, which happens to be $\ker(BC)$, the new map from $\ker(ABC)/\ker(BC)\rightarrow \ker(AB)/\ker(B)$ is necessarily an injection. (This is just an isomorphism theorem.)
I'll also add that there is no indication that it is (or even needs to be) onto, so it's not really a projection.
From that point on, presumably you are working with all finite dimensional spaces, so this isomorphism gives you the inequality $\dim(\ker(ABC))-\dim(\ker(BC))\leq \dim(\ker(AB))-\dim(\ker(B))$


Access denied for user anonymous for node retrieve service

Question: I have installed services module and added a service. And then, enabled the retrieve and index resources for node. I also enabled the permission to view the published content for anonymous users. cache is also cleared. When i call the retrieve or index service, i am getting the below response.

http://example.com/endpoint/node/1.json

Response:
<code>["Access denied for user anonymous"]</code>
Is there any thing i missed here?
Version D7 - Services 7.x-3.20
Update:
It was issue with domain module. Domain strict module was enabled. After disabling, it started working.
Comment: Did you enable `Session authentication` under `/admin/structure/services/list/[my-endpoint-name]`?
Comment: Yes, session authentication is enable. But i found that the issue is with domain strict module which was enable in my site. I updated the question. Thanks.
Answer: It was issue with domain module. Domain strict module was enabled. After disabling, it started working.
Answer: Make sure node/1 status must be published, otherwise you will get this error.
Comment: Yes, it is published node.
Comment: I had simply installed the module and after end point creation enabled the node indexing and retrieving. It works fine without any issue.


How do I interpret this residual diagnostics plot?

Question:
I am just learning to understand how to utilize residual plots to improve regression models. It seems like the following residual vs. fitted plot is hugely problematic as it has a pattern. But how do I go about identifying the most likely causes for such an issue?
The following is a residual vs fitted plot when the dependent variable is log-transformed. I guess the same issue of pattern persists:

Comment: Thank you @IsabellaGhement. The dependent variable is the number of days it took for an individual to get a loan. The predictors in the model include requested loan size (in $), the number of borrowers, and loan description (text analytic measures as relative frequency counts of words; e.g., positive tone/negative tone). The model does not include any interactions. I hope this provides some clarifications.
Comment: Can you elaborate more on the model that generated this residual plot? What was the dependent variable? What were the independent variables? Did the model include any interactions between any of the independent variables? We can't really comment on improvements to your model if we don't even know what the model is. Also, what is the final purpose of your model?
Answer: A "good" residuals vs fitted plot for a linear model might look something like this
library("ggplot2")
theme_set(theme_bw())
set.seed(1)
df <- data.frame(e = rnorm(2000, 0, sd = 1.5),
                 yhat = runif(2000))
ggplot(df, aes(x = yhat, y = e)) +
  geom_abline(intercept =  0, slope = 0) +
  geom_point() +
  geom_smooth() +
  labs(y = "Residuals", x = "Fitted")

Notice

how the residuals are spread evenly around 0 throughout the range of the fitted value,
the residuals have the same variance --- they are evenly spread the ~ the same distance either side of zero throughout the range of the fitted values (i.e. there's about the same number of residuals $>|3|$ for example at each location on the x-axis.)
there is no strong systematic pattern in the residuals; the blue line is similar to the red one in your plot and is a scatterplot smoother showing pattern in the mean of residuals.

In your plot we notice two signifant problems:

There is clear non-constant variance. The spread of the residuals towards the left of the plot is much less than the spread towards the right of the plot.
There is substantial bias in the estimated values; all the residuals are negative above a fitted value of ~40. Similarly, all the residuals at small fitted values (towards the left of the plot) are positive.

These suggest that

the conditional distribution of the response is not Gaussian. In other words, once you account for the effects on the response of your predictor variables (covariates), the response is not normally distributed.

From your reply to @Isabella, an immediate problem is that the response variable is number of days to get a loan. This is unlikely to be conditionally distributed Gaussian because you can't have a negative number of days; the distribution of the response is bounded at 0. Typically, such count data have a non-constant mean-variance relationship; the variance (spread of data about the mean) increase as the mean value increases.
Counts like this are typically modelled as being conditionally distributed Poisson, using a Generalised Linear Model (GLM) with a Poisson family and log link. This is often a useful starting point but other distributions are also used for integer counts that can account for more complexity in the observed counts than can be accounted for in the Poisson.
If your response is not an integer number of days (2.4 days is an allowed value) then you would need a distribution that has support on the positive real values (any value > 0). Such distributions include the Gamma distribution, which also can be fitted as a GLM.
If you do not have an 0 day values in the data set, then you could quickly try to fix the problem of the wrongly assumed mean-variance relationship by applying a log-transformation to the response variable (lm(log(y) ~ x1 + x2) in pseudo code) and see if that improves things. But typically one would prefer a GLM-like model so that one can estimate the mean of the response directly rather than the mean of the log of the response.
From the limited amount of information you have provided, there is little more than I can say beyond the above.
Comment: Thanks @GavinSimpson for such detailed and very helpful clarifications and suggestions. Based on your input, I first attempted the log-transformation of the dependent variable (days-to-fund-loan). The residual vs fitted plot shows an even spread until fitted value < 8, and then a clear (somewhat steep) downward slope pattern. As I understand, this is problematic as well. I will try GLM with Poisson family.  Are similar residual diagnostic plots and interpretations applicable for Poisson family?
Comment: To your other point @GavinSimpson, I have the flexibility of coding the days-to-fund the loan as either 2.4 days or round to 2 days, and similarly code the same day funded loans as either 0.5 or 0 days. As you suggested, I will check out Gamma distribution as well.
Comment: You can't just reply on or use this one diagnostic plot to identify all modelling issues. Your model clear still has considerable bias at larger fitted values. Look at the fitted versus observed values and you'll see the bias problem. Also, you can plot residuals against your predictor variables to diagnose if you need different functional forms for the effects of your covariates.


Como corrigir problemas com site responsivo ao redirecionar a janela do navegador no DESKTOP?

Question: Estou criando um site responsivo, ao redirecionar o tamanho da janela no DESKTOP alguns ajustes vão sendo feito e ao RETORNAR ao tamanho normal (maximizar) os ajustes retornar. Até aí tudo Ok.
O problema está no MENU e em parte do site mas eu vou mostrar um exemplo mais simples e de fácil compreensão abaixo que ocorre erro no site ok.
Eu tenho o seguinte:
TITULO
CHAMADA
Conteúdo
Nesse caso o título está em h1 a chamada em h2 e o conteúdo em h3 (este no caso está dentro de uma  que eu vou explicar o porque daqui a pouco).
Quando visualizamos no DESKTOP tudo é exigido direto pois temos espaço para isso, mas quando é exibido em uma tela menor (smartphone ou tablet) a ideia seria 'ocultar' a div que está com o h3 e só exibir se o usuário solicitar. Sendo assim colocamos um botão então para executar isso.
TITULO
CHAMADA
botão para exibir conteúdo
Conteúdo
O PROBLEMA é o seguinte:
Se diminuir o tamanho da janela o CONTEÚDO some e ao aumentar novamente o CONTEÚDO aparece. Tudo CORRETO, porém, se eu diminuir o tamanho da janela, posso clicar no botão para exibir o conteúdo lembra? Isso acontece com um efeito em jQuery para dar um SLIDE.
Ao clicar no botão o CONTEÚDO aparece e ao clicar no botão novamente o CONTEÚDO 'some' novamente com o efeito slide, perfeito. agora se eu maximizar a janela o CONTEÚDO simplesmente não aparece... ele continua oculto (porque ele sumiu devido ao SLIDE do jquery e não devido ao display:none do CSS então mesmo que o CSS diga que agora ele tem o display:block novamente ele não aparece...)
Mas eu já vi muitos sites com esse tipo de efeito, como por exemplo no MENU, eu tenho um MENU no topo do site inline mas que ao redirecionar ele muda (para lista e fica fixo ao lado direito).
Até aí ok... porém nesse processo eu aplico o display: none também e ele só aparece se clicar no 'botão menu' como qualquer site faz.
Se eu clico o MENU aparece com slide e pode ser fechado que também vai ser feito por SLIDE do jquery mas agora se aumentar a janela cadê o MENU inline do topo? Mesmo que volte o display:block devido ao width especificado no CSS como o MENU sumiu com o efeito SLIDE ele não aparece mais (só se eu diminuir a janela, abrir o MENU e então maximizar a janela denovo agora ele volta ao normal mas isso está esquisito sei lá).
Alguma ideia de como fazer isso pessoal?
Eu acho que o ideal seria NÃO utilizar o SLIDE do jquery para fazer aparece e sumir, mas então como fazer isso?
Muito obrigado.
HTML

Lorem Ipsum

O que é Lorem Ipsum?

<input class="btn" type="button" value="Mostrar/Esconder" onclick="conteudo();">

Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos, e vem sendo utilizado desde o século XVI, quando um impressor desconhecido pegou uma bandeja de tipos e os embaralhou para fazer um livro de modelos de tipos. Lorem Ipsum sobreviveu não só a cinco séculos, como também ao salto para a editoração eletrônica, permanecendo essencialmente inalterado. Se popularizou na década de 60, quando a Letraset lançou decalques contendo passagens de Lorem Ipsum, e mais recentemente quando passou a ser integrado a softwares de editoração eletrônica como Aldus PageMaker.

CSS para esconder o CONTEÚDO ao redimensionar a janela
.btn {display: none}
.conteudo {display: block}

@media screen and (max-width:640px){
.conteudo {display: none;}
.btn {display: block}
}

JS utilizado para 'linkar' o JQUERY e poder usar o efeito em questão.

<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

JS utilizado para mostrar/ocultar o CONTEUDO quando estiver com exibição 'mobile'.

Se o efeito SLIDE não for utilizado tudo funciona bem, o CONTEUDO fica com display: none com janela pequena e volta a ficar com display: block ao maximizar... porém se usar o efeito SLIDE ocorre isso, mesmo maximizando ele não volta.
Comment: Cara, tua pergunta tem MUITO texto, pouco código e nenhum exemplo do que não está funcionando.
Tá bem difícil de entender o que tu preciso ou de ler até o final.
Comment: Olá Fernando, realmente coloquei muito texto pois é difícil explicar isso, não vi outra forma. Quanto ao código é que é algo relativamente simples, era só para mostrar/esconder o menu conforme o tamanho da tela do usuário.

Isso funcionou mas se eu usar um efeito tipo SLIDE o conteúdo some e não volta mais ao aumentar a tela.

Vou editar a pergunta e colocar o código HTML para ver se assim fica mais fácil de entender sei lá, mas acho que isso em si é o de menos, o é complicado é saber porque o SLIDE impede a div de ficar visível novamente.
Comment: Pronto! Códigos agora estão na pergunta, coloquei tudo para poder até testar se quiser... html, css e JS, se só ficar redimensionando a janela vai ver que funciona legal, mas se tentar usar o botão (quando a janela estiver 'pequena' vai ver o problema que estou tendo.
Answer: Isso acontece porque a função $.toggle aplica uma animação e no final desta animação adiciona display: none; ao style do elemento que ela animou.
Então o que está acontecendo é que depois de esconder o conteúdo tua div fica dessa maneira:
.
Por isso não está mais mostrando. Tu pode arrumar isso de duas maneiras diferentes, por CSS ou JS.
CSS (Aconselhável)
@media screen and (min-width:640px){
    .conteudo {
        display: block; !important
    }
}

Dessa maneira quando tua div estiver em "tela grande" estará sempre com display: block.
JS (Nope):
var $document = $(document),
    $conteudo = $("#conteudo");

$(window).on('resize', function(){
  if ($document.width() > 640) {
    $conteudo.show()
  }
});

OBS: Estou deixando esse exemplo apenas caso a solução com CSS não resolva teu problema. Porém deixo a advertência de que esse código não está otimizado e se for usá-lo pesquise primeiro sobre throttle e debounce de eventos javascript.
Comment: Muito obrigado pelo retorno meu amigo... mas infelizmente nenhum dos 2 casos deu certo...

O primeiro inclusive eu já havia feito mas não funcionou... o segundo eu testei agora e nada também... ela continua sem aparecer...

Estou usando o Google Chrome aqui e continua o erro =/


Hellinger distance bounds

Question: The squared Hellinger distance is, for two densities $f(x)$ and $g(x)$,
$$HD^2(f,g)=\frac{1}{2}\int \left[\sqrt{f(x)}-\sqrt{g(x)}\right]^2dx$$
Using that $\int f(x)dx=\int g(x)dx=1$, we may write this as
$$HD^2(f,g)=1-\int \sqrt{f(x)g(x)}dx$$
The Wikipedia entry invokes the Cauchy-Schwarz inequality to show that
$$0\leq HD^2(f,g)\leq1$$
My question: Is that necessary?
The first display shows $HD^2(f,g)$ to be an integral over the nonnegative function $\left[\sqrt{f(x)}-\sqrt{g(x)}\right]^2$, which will be nonnegative, too, so that $HD^2(f,g)\geq0$. The second display subtracts $\sqrt{f(x)g(x)}$ from one, i.e., the square root of the product of two densities, which are nonnegative, so that the integrand is again nonnegative, so that $HD^2(f,g)\leq1$.
What, if anything, is wrong with that reasoning?
Answer: Your derivation is correct. You don't need Cauchy-Schwarz here, unless you are looking for a simple application of it for illustrative purposes.

Hellinger distance bounds


How can I add a delay interval to quick sort algorithm for client-side visualization of it?

Question: I am trying to make a sorting algorithm visualizer to learn more about sorting algorithms as well as coding in Angular and TypeScript in genereal.
I am currently doing quick sort and have the sorting algorithm working fine but can't get the visuals to appear on client-side. My code for the sort is below:
performQuickSort(arr, min, max) {
    if (min >= max) { return; }

    let i = min;
    let j = max;

    const pivot = arr[Math.trunc((min + max) / 2)];

    while (i < j) {
      while (arr[i] < pivot) {
        i++;
      }

      while (arr[j] > pivot) {
        j--;
      }
      this._swap(arr, i, j);
    }

    this.performQuickSort(arr, min, i);
    this.performQuickSort(arr, i + 1, max);
  }

  _swap(arr, min, max) {
    if (min === max) { return; }

    const temp = arr[min];
    arr[min] = arr[max];
    arr[max] = temp;
  }

I've tried using setTimeout() and performing the swap inside of it with a 1 second delay but it doesn't work since I think the outer while loop executes too fast and causes a consecutive one second delay.
Does anyone have any ideas how I can get a 1 second interval between swaps so the sorting can be visualized?
Thanks in advance.
Answer:
I've tried using setTimeout() and performing the swap inside of it
  with a 1 second delay but it doesn't work since I think the outer
  while loop executes too fast and causes a consecutive one second
  delay.

Well, setTimeout() executes asynchronously, so before your _swap executes, the next lines after it (this._swap()) get executed immediately with  the values at the time before _swap() execution:
    //These get executed before your _swap if you put your _swap under a setTimeout

    this.performQuickSort(arr, min, i);
    this.performQuickSort(arr, i + 1, max);

So try putting these inside setTimeout()
 setTimeout(()=>{
   this.performQuickSort(arr, min, i);
   this.performQuickSort(arr, i + 1, max);
  }, 1000);

Comment: The visuals when using this are choppy but at least it somewhat works, thanks
Answer: Nope.. setTimeout () should work fine.
First declare your function in the component.Then if you wanna set the sorting for a button click event.
<button
(onClick)="sortArray()">

Then inside your component.ts
sortArray (){
    this.sorted = false;
    setTimeout(()=>{
    this.performQuickSort();
    this.sorted = true;
    }, 3000);
    }

Now add a css loader which uses something like this.
<app-loader *ngIf="sorted">
</app-loader>

Declare a boolean class variable called "sorted" to handle the ending of the sorting.


count unique text values based on condition in another column between date criteria

Question: What i need  is formula to count unique values in TITLE based on criteria of column FIAP/Medium & Year.
This needs to begin by looking at the date in worksheet column M/Year, the range is 23/03/13 - 01/06/16.  It then needs to check column I/FIAP Medium looking for 'Digital' and finally count the unique images in A/Title.
This is the working sheet column
<code>   Title              FIAP/Medium      Year
  Conors Push        Digital         3/23/2013
  Conors Push        Digital         4/1/2013
  Flippin Hell       Digital         4/1/2013
 Narrowing the Gap   Digital         4/1/2013
 The Perfect Storm   Digital         4/8/2013
 Conors Push         Digital         4/12/2013
 Splash and Dash     Digital         4/12/2013
 Wind Power          Digital         4/12/2013
 Conors Push           -             4/28/2013
 Eyes On The Ball      -             4/28/2013
 Narrowing the Gap     -             4/28/2013
 The Bunkers Demise    -             4/28/2013
 A Few Inches More   Digital         5/1/2013
 Entwined            Digital         5/1/2013
 Conors Push         Digital         5/14/2013
 Fosbury Delight     Digital         5/14/2013
 Narrowing The Gap   Digital         5/14/2013
 Sprint For The Lin  Digital         5/14/2013
</code>
I have come up with formula
<code>=SUM(--(FREQUENCY(IF(International!M2:M1000>="6/1/2016",IF(International!M2:M1000<="3/23/2013",IF(International!I2:I1000<>"",IF(International!I2:I1000="Digital",MATCH(International!A2:A1000,International!A2:A1000,0))))),ROW(International!A2:A1000)-ROW(International!A2)+1>0)))
</code>
but its showing zero value. It may be because date condition requires two condition with one column.
Please help me with this formula or any other method to count unique based on this conditions.Specially dates
Comment: Are there constant additions/deletions to the list? Would you have to modify the formula constantly ad change the ranges?
Answer: There is a fairly common method of a pseudo-COUNTUNIQUE¹ based on the SUMPRODUCT and COUNTIF functions that looks like this.
<code>=SUMPRODUCT(1/COUNTIF(A2:A19, A2:A19&""))
</code>
But that does compensate for the conditions. To add conditions, you need to change to a COUNTIFS function. Additionally, both the numerator and denominator of the division operation have to be adjusted by the conditions and the inverse of the conditions in order that you return a true count without erroring on with a <code>#DIV/0!</code>.
<code>=SUMPRODUCT(((C$2:C$19>=F2)*(C$2:C$19<=G2)*($B$2:$B$19=E2))/
             (COUNTIFS(A$2:A$19, A$2:A$19&"", C$2:C$19, ">="&F2, C$2:C$19, "<="&G2, $B$2:$B$19, E2)+
              (C$2:C$19<F2)+(C$2:C$19>G2)+($B$2:$B$19<>E2)))
</code>

Now that formula is hard to maintain of there are constant additions and deletions to the number of rows. To create dynamic ranges, we can INDEX each full column and use MATCH to locate the last date as the terminator for each column.
<code>=SUMPRODUCT(((C$2:INDEX(C:C, MATCH(1E+99,C:C ))>=F2)*(C$2:INDEX(C:C, MATCH(1E+99,C:C ))<=G2)*($B$2:INDEX(B:B, MATCH(1E+99,C:C ))=E2))/
    (COUNTIFS(A$2:INDEX(A:A, MATCH(1E+99,C:C )), A$2:INDEX(A:A, MATCH(1E+99,C:C ))&"", C$2:INDEX(C:C, MATCH(1E+99,C:C )), ">="&F2, C$2:INDEX(C:C, MATCH(1E+99,C:C )), "<="&G2, B$2:INDEX(B:B, MATCH(1E+99,C:C )), E2)+
      (C$2:INDEX(C:C, MATCH(1E+99,C:C ))<F2)+(C$2:INDEX(C:C, MATCH(1E+99,C:C ))>G2)+($B$2:INDEX(B:B, MATCH(1E+99,C:C ))<>E2)))
</code>
Yes, that looks like a mess but it dynamically adds and subtracts rows processed by the SUMPRODUCT function so that calculation efficiency is at a premium.

¹ For an explanation on how this works see Count Unique with SUMPRODUCT() Breakdown.
Comment: It really only **looks** complex because of the repetitious MATCH functions that are need to truncate the full column references at the row containing the last date. SUMPRODUCT should never be used with full column references unless you are getting paid by the calculation cycle. 1,000 or even 25,000 rows may seem like a lot but both are a lot less than 1,048,576 rows. The formula can be simplified with a dynamic named range but that would be another question.
Answer: You formula works with a few tweaks:

The date strings need to be converted to date values using DateValue() function
The comparison operators for the dates are interchanged (it should be <= 2016 date and >= 2013 date)
The comparison against "digital" needs to be reversed
The innermost IF statement needs a zero as value for situations where the condition fails
I removed the outermost parentheses which are not needed

Here is the modified version that works:
=FREQUENCY(IF(International!M2:M1000<=DATEVALUE("6/1/2016"),IF(International!M2:M1000>=DATEVALUE("3/23/2013"),IF(International!I2:I1000<>"",IF(International!I2:I1000<>"Digital",MATCH(International!A2:A1000,International!A2:A1000,0),0)))),ROW(International!A2:A1000)-ROW(International!A2)+1>0)
Comment: What should the correct answer be? I set up the worksheet as you showed in the question and the formula works; I tested by changing some of the values and saw the count change appropriately. It is possible there are aspects you've not mentioned that are impacting the solution. At any rate, if answer from @Jeeped works for you, you're good anyway.


If $M\cong M_1\oplus M_2$ is a torsion-free module, does it follow that $M_1$ is a torsion-free module?

Question: Suppose $M$ is a module over some ring $R$ such that $M\cong M_1\oplus M_2$. If $M,\,M_2$ are both torsion-free modules, does it follow that $M_1$ is also? Intuitively I would expect this to be the case, for if $M_1$ had a torsion element, then surely that means $M$ would also?
Comment: There is also shown $Tor(M_1\oplus M_2)\cong Tor(M_1)\oplus Tor(M_2)$, see part $a)$.
Answer: You are right. If $m\in M_1$ were a torsion element, then $(m, 0)\in M$ would be one too.


Proof by induction on $\{1,\ldots,m\}$ instead of $\mathbb{N}$

Question: I often see proofs, that claim to be by induction, but where the variable we induct on doesn't take value is $\mathbb{N}$ but only in some set $\{1,\ldots,m\}$.
Imagine for example that we have to prove an equality that encompasses $n$ variables on each side, where $n$ can only range through $n\in\{1,\ldots,m\}$  (imagine that for $n>m$ the function relating the variables on one of the sides isn't welldefined): For $n=1$ imagine that the equality is easy to prove by manipulating the variables algebraically and that for some $n\in\{1,\ldots,m\}$ we can also show the equation holds provided it holds for $n\in\{1,\ldots,n-1\}$. Then we have proved the equation for every $n\in\{1,\ldots,m\}$, but does this qualify as a proof by induction ?
(Correct me if I'm wrong: If the equation were indeed definable and true for every $n\in\mathbb{N}$ we could - although we are only interested in the case $n\in\{1,\ldots,m\}$ - "extend" it to $\mathbb{N}$ and then use "normal" induction to prove it holds for every $n\in \mathbb{N}$, since then it would also hold for $n\in\{1,\ldots,m\}$ .)
Comment: Could you be thinking about the principle of strong (or complete)  induction? See: http://en.wikipedia.org/wiki/Mathematical_induction#Complete_induction
Answer: If the statement in question really does not "work" if $n>m$, then necessarily the induction step $n\to n+1$ at least somewhere uses that $n<m$. You may view this as actually proving by induction
$$\tag1\forall n\in \mathbb N\colon (n>m\lor \phi(m,n))$$
That is, you first show
$$\tag2\phi(m,1)$$
(which of course implies $1>m\lor \phi(m,1)$) and then show
$$\tag3(n>m\lor \phi(m,n))\Rightarrow (n+1>m\lor \phi(m,n+1)),$$
where you can more or less ignore the trivial case $n\ge m$.
Of course $(2)$ and $(3)$ establish a perfectly valid proof of $(1)$ by induction on $n$.
Answer: This "form" of induction is called finite or finitistic induction. If we want to prove a property $p$ holds $\forall x\in A$ where $A$ is a finite set $A=\left\{x_1,x_2,...,x_n\right\}$, then we just have to check if $p(x_1),p(x_2),...,p(x_n)$ are true. If $A=\left\{0,1,...,m\right\}$ then we can also perform finite induction.
As you said, finite induction is much more weaker and restricted compared to infinite induction. In fact if we want to prove a property holds for a finite number of natural numbers and we can prove that it holds in $\mathbb{N}$ by (infinite) induction, then it holds automatically for these numbers as well.
Use of finite induction is not neccessary to prove a property holds for a finite set, as we can check if every element of a finite set has a certain property. Infinite induction however, is a very important axiom in Peano Arithmetic and in many cases necessary to prove properties of all natural numbers.


How to design User authentication for 2 servers

Question: I need to authenticate a user from 2 servers. First, a user would be authenticated from Server A, on success, his AD (Active Directory) credentials would be authenticated to Server B (which is AD).
Should, server A, send an OKAY signal to Server B (Active Directory) that server A has done with authentication and its okay. I am confused about this part, since if I apply this security constraint then i have to do extra work on server side. I want to keep servers independent of this approach. The point is, Server A might be on Internet or some server which is not in the Network and Server B (the Active Directory) would be in the very network.
Need guidance
P.S:
A user credentials for Server A would be different from his Active Directory Credentials.
Comment: Is there something more that I am not providing in my answer?
Answer: If you are doing this in C# code, why not just check each authorization in sequence?  This is likely your best bet.  For example maybe something similar to:
<code>Private bool authenticateUser()
{
   if(authenticateWithServerA(username1, password1))
   {
     if(authenticateWithServerB(username2, password2))
       return true;
   }

   return false;
}
</code>


Maven cannot find com.oracle:ojdbc6:jar:11.1.0 in intellij

Question: I keep getting the below error when trying to run my app thru Maven.

Failed to execute goal
  org.mortbay.jetty:jetty-maven-plugin:8.1.4.v20120524:run (default-cli)
  on project MoveOrder: Execution default-cli of goal
  org.mortbay.jetty:jetty-maven-plugin:8.1.4.v20120524:run failed:
  Plugin org.mortbay.jetty:jetty-maven-plugin:8.1.4.v20120524 or one of
  its dependencies could not be resolved: Failure to find
  com.oracle:ojdbc6:jar:11.1.0 in http://repo.maven.apache.org/maven2
  was cached in the local repository, resolution will not be reattempted
  until the update interval of central has elapsed or updates are forced

I also added
<dependencies>
                        <dependency>
                            <groupId>com.oracle</groupId>
                            <artifactId>ojdbc6</artifactId>
                            <version>11.1.0</version>
                        </dependency>
                    </dependencies>

near the bottom before the final </plugin> tag. I also created a lib folder under my webapp/WEB-INF folder and pasted over ojdbc6-11.1.0.jar file in there hoping it would solve the issue, but it does not.
Here is my pom.xml file. Any ideas what I'm doing wrong?
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.wwt.moveorder</groupId>
    <artifactId>MoveOrder</artifactId>
    <name>MoveOrderUI</name>
    <packaging>war</packaging>
    <version>1.1</version>
    <properties>
        <java-version>1.6</java-version>
        <org.springframework-version>3.1.0.RELEASE</org.springframework-version>
        <org.aspectj-version>1.6.9</org.aspectj-version>
        <org.slf4j-version>1.5.10</org.slf4j-version>
    </properties>
    <repositories>
        <repository>
            <id>webbuild</id>
            <name>Local Nexus</name>
            <url>http://prodcit01.wwt.com:8081/nexus/content/repositories/public</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>com.wwt</groupId>
            <artifactId>security</artifactId>
            <version>22.214.171.124</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>

                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>org.springframework.transaction</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>org.springframework.core</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>org.springframework.jdbc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>org.springframework.orm</artifactId>
            <version>${org.springframework-version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.8</version>
            <exclusions>
                <exclusion>
                    <artifactId>xml-apis</artifactId>
                    <groupId>xml-apis</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>nu.xom</groupId>
            <artifactId>xom</artifactId>
            <version>1.2.7</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>org.springframework.test</artifactId>
            <version>${org.springframework-version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.5.3</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.6.4</version>
        </dependency>

        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>
                                            net.alchim31.maven
                                        </groupId>
                                        <artifactId>
                                            yuicompressor-maven-plugin
                                        </artifactId>
                                        <versionRange>
                                            [1.3.0,)
                                        </versionRange>
                                        <goals>
                                            <goal>compress</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <execute></execute>
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${java-version}</source>
                    <target>${java-version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <warName>MoveOrderUI</warName>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>install</id>
                        <phase>install</phase>
                        <goals>
                            <goal>sources</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>weblogic-maven-plugin</artifactId>
                <version>2.9.1</version>
                <executions>
                    <execution>
                        <phase>deploy</phase>
                        <goals>
                            <goal>deploy</goal>
                            <goal>start</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <name>${project.name}</name>
                    <adminServerHostName>devjas1.wwt.com</adminServerHostName>
                    <adminServerPort>7001</adminServerPort>
                    <adminServerProtocol>t3</adminServerProtocol>
                    <userId>shenoys</userId>
                    <password>pass123</password>
                    <upload>false</upload>
                    <remote>true</remote>
                    <verbose>false</verbose>
                    <debug>false</debug>
                    <targetNames>WWTServer1</targetNames>
                    <noExit>true</noExit>
                    <artifactPath>${project.build.directory}/${project.name}.war</artifactPath>
                    <noExit>true</noExit>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>weblogic</groupId>
                        <artifactId>wlfullclient</artifactId>
                        <version>10.3.0</version>
                    </dependency>
                    <dependency>
                        <groupId>weblogic</groupId>
                        <artifactId>webservices</artifactId>
                        <version>10.3.0</version>
                    </dependency>
                    <dependency>
                        <groupId>weblogic</groupId>
                        <artifactId>com.bea.core.descriptor.wl</artifactId>
                        <version>22.214.171.124</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <warName>${project.name}</warName>
                    <webappDirectory>${project.build.directory}/${project.name}</webappDirectory>
                </configuration>
            </plugin>
            <plugin>
                <groupId>net.alchim31.maven</groupId>
                <artifactId>yuicompressor-maven-plugin</artifactId>
                <version>1.3.0</version>
                <executions>
                    <execution>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>compress</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <webappDirectory>${project.build.directory}/${project.name}</webappDirectory>
                    <aggregations>
                        <aggregation>
                            <removeIncluded>true</removeIncluded>
                            <output>${project.build.directory}/${project.name}/resources/js/app.js</output>
                            <includes>
                                <include>**/*-min.js</include>
                            </includes>
                        </aggregation>
                        <aggregation>
                            <removeIncluded>true</removeIncluded>
                            <output>${project.build.directory}/${project.name}/resources/css/app.css</output>
                            <includes>
                                <include>**/*-min.css</include>
                            </includes>
                        </aggregation>
                    </aggregations>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>8.1.4.v20120524</version>
                <configuration>
                    <scanIntervalSeconds>1</scanIntervalSeconds>
                    <stopKey>STOP</stopKey>
                    <stopPort>8089</stopPort>
                    <webApp>
                        <contextPath>/MoveOrderUI</contextPath>
                    </webApp>
                    <systemProperties>
                        <systemProperty>
                            <name>jetty.port</name>
                            <value>9900</value>
                        </systemProperty>
                        <systemProperty>
                            <name>userName</name>
                            <value>hummela</value>
                        </systemProperty>
                    </systemProperties>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>com.oracle</groupId>
                        <artifactId>ojdbc6</artifactId>
                        <version>11.1.0</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

Answer: Your problem is that the jdbc driver is marked as a provided dependency. Remove the <scope>provided</scope> and undo all the other hacks you mentioned and things should work just fine.
Provided dependencies should be made available by the container, rather than mentioned explicitly on the classpath. In this case I'm guessing that your container doesn't have the relevant library, so if you remove the scope maven should be able to manage the dependency like all the others and it should just work.
In general, the only scope you should use is test. Provided, in particular, is insidious and should be avoided. You can remove the compile scope lines too. You might want to keep the servlet dependency as provided, but I wouldn't.


How to read from an input stream into a file stream?

Question: I am trying to bind input stream with a file stream , I hope that  input something  from input stream and then automatic flush to the file stream
It does not work...I enter something from keyboard , outfile is still empty
<code>#include <iostream>
#include <fstream>
#include <stdexcept>
using namespace std;

int main(int argc, char const *argv[])
{
    ofstream outfile("outfile" , ofstream::app | ofstream::out);
    if(!outfile)
        throw runtime_error("Open the file error");
    ostream * old_tie = cin.tie();//get old tie
    cin.tie(0);//unbind from old tie
    cin.tie(&outfile);//bind new ostream
    string temp;
    while(cin >> temp)
    {
        if(temp == ".")//stop input
            break;
    }
    cin.tie(0);
    cin.tie(old_tie);// recovery old tie
    return 0;
</code>
}
Comment: What are you really trying to do here? Reassign the `cin` buffer? Because that's not what `tie` manages.
Answer: Your program is too complicated and is misusing tie(). Try the following:
<code>#include <iostream>
#include <fstream>
int main() {
    using namespace std;
    ofstream outfile("outfile" , ofstream::app | ofstream::out);
    if(!outfile) {
        cerr << "Open the file error";
        return 1;
    }
    char data(0);
    while(data != '.') {
        cin.get(data);
        cin.clear(); // Prevents EOF errors;
        outfile << data;
    }
    return 0;
}
</code>
It reads char by char until it finds a .
Answer: Errors:

why make throw exception if you don't catch it...
close file please
do you put data from file to temp and go through it to find "." and
end program?
Why do you use pointer for old_tie use it for the first ofstream file
like this ofstream * file.
fix if statement and break
include string library -- //This might solve your problem
what is filename??
is tie(0) function to unbind?

//EDIT
Explanation:
once you find first period with find_first_of function you create a substr and copy it into outfile. The Solution is so efficent and works every time. The logic is as simple as it can get. Don't use unnecessary functions and initialize unnecessary variables because it is more complex and more prone to errors when you have too many variables.
Solution: - No need for cin.tie()
<code>#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char const *argv[])
{
    ofstream outfile("outfile" , ofstream::app | ofstream::out);
    string s;
    getline(cin, s);
    int i = s.find_first_of(".");
    if(i!=std::string::npos)
    {
        s = s.substr(0, i);
        outfile << s;
    }
    else
    {
        cout << "No periods found" << endl;
    }

}
</code>
Compiled code - http://ideone.com/ooj1ej
If this needs explanation please ask questions in comments below.
Comment: Tip: use [std::getline](http://en.cppreference.com/w/cpp/string/basic_string/getline) instead of `cin.getline` to get rid of that nasty array.
Comment: the OP wants to input something from input stream so std::getline wouldn't work because you need cin.getline to get input stream.


Mod Security2 deactivation rule only from a specified IP addresses

Question: Is it possible to disable a rule by Mod Security2, only for one specified IP addresses?
Only for one specified IP addresses & only for one specified path ( /administrator ) ?
I tried this:
<LocationMatch /administrator>
Allow from 123.456.78.999
 SecRuleRemoveById 000000
</LocationMatch>

But it does not work. :(
I have Ubuntu 14.04 LTS Server and just I managed to install mod security2.
Answer: Did not try it, but I think it should work
<LocationMatch /administrator>
  <IfModule mod_security2.c>
    SecRule REMOTE_HOST "@ipmatch 184.108.40.206" \
    "id:12345,phase:2,t:none,pass,nolog,noauditlog,ctl:ruleRemovebyID=000000"
  </IfModule>
</LocationMatch>


How to grant User Points after Quiz questions are answered correctly?

Question: I have the User Points module enabled and I want to use the Rules module to create a rule which lets a user win User Points whenever the user answers correctly my questions.
I don't know what should I put as Rules Event and as a Rules Condition.
How can I specify that the user only earns User Points when the answer is correct?
Comment: Have you tried Quiz userpoints(https://www.drupal.org/project/quiz_userpoints) module?
Comment: Please provide more details on how you've built the Quiz in Drupal that will define which Rule event/condition will fit in your case.
Answer: If using Quiz 7.x-5.x
Assuming you're using the 7.x-5.x-rc3 version of the Quiz module, you can take advantage of integration with the Rules module that this new release comes with.
To do so, have a look at the delivered rule, which looks like so:
<code>{ "rules_send_results_at_the_end_of_a_quiz" : {
    "LABEL" : "Send quiz results at the end of a quiz",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "quiz_result_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "quiz-result-unchanged:is-evaluated" ], "value" : "0" } },
      { "data_is" : { "data" : [ "quiz-result:is-evaluated" ], "value" : "1" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "quiz-result:uid:mail" ],
          "subject" : "[site:name]: Your results for [quiz-result:nid:title]",
          "message" : "[quiz-result:uid:name],\r\n\r\nYou finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nYour score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz-results\/[quiz-result:result-id]",
          "language" : [ "" ]
        }
      },
      { "mail" : {
          "to" : [ "quiz-result:nid:author:mail" ],
          "subject" : "[site:name]: [quiz-result:uid:name]\u0027s results for [quiz-result:nid:title]",
          "message" : "[quiz-result:nid:author:name],\r\n\r\n[quiz-result:uid:name] finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nTheir score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz\/results\/[quiz-result:result-id]\/view",
          "language" : [ "" ]
        }
      }
    ]
  }
}
</code>
After you enable Rules (and Rules UI, a submodule of it), just clone the above rule (using the Rules UI) and replace both Rules Actions with a Rules Action to grant an amount of User Points that you may want to be related to <code>[quiz-result:score]</code> (note that this token is also shown in the Rules example above (within the Rules Action).
If you're not familiar with how to use Rules to grant user points, then have a look at the answer to "How to grant userpoints only for modifying nodes last changed at least 20 days ago?" (which also includes a Rules example to make that happen).
If using Quiz 7.x-4.x
For the 7.x-4.x version of the Quiz module, you may want to try the patch from fago (aka the Rules maestro ...), attached to issue # 1300420, which has a description like so (note the last phrase in it ...):

... adds basic rules integration to quiz. It includes an event when users have finished taking a quiz, a condition to check whether a user has passed a certain quiz and an action to clear quiz results for a user.
Patch works for me.


Upgrading from Access 2003 to Access 2007 and SQL Server

Question: I am maintaining a pretty large Access 2003 project with a MDB data file on the server and linked tables. The plan is to upgrade to Access 2007 (or even 2010) and SQL Server as the data storage.
As this is a two-step plan, which of these steps is best done first? Does it make a difference if I first upgrade to 2007, or should I link to SQL first?
Answer: It doesn't matter.
I would go to access 2007, let the 2007 do the migration, check everything, and then go for the sql server.
But - nothing will happen if you take the other way.
I think it will be easier to disconnect the mdb and connect to SQL in Access 2007, Rather than in 2003.
Comment: +1 Does 2007 have better support for migration to SQL server? 2003 has the Upsizing Wizard, that is what I have used, but I don't have a lot of experience with 2007.
Comment: Depends on your version of SQL Server. If it's 2005, A2007 will have a better upsizing result than A2003 (which predates SQL 2005). If it's 2008, not so much.
Answer: You may wish to read Allen Browne for additional information on the conversion to 2007.


representation of a vector in an $n$-dimensional vector space $X$ is unique

Question: Show that in an $n-$dimensional vector space $X$, the representation of any $x \in X$ as a linear combination of a given basis $\{e_1,...,e_n \}$ is unique.
My attempt:
Let $\{e_i\}$ be a basis for $X$, and take any $x \in X$. Hence there exists constants $\lambda_i \in K$ such that $x = \sum \lambda_i e_i $. Similarly, can find constants $\mu_i \in K$ such that $x = \sum \mu_i e_i$. Hence
$$ \Theta = x -x = \sum_{i=1}^n(\lambda_i - \mu_i)e_i \implies \mu_i - \lambda_i = 0 \implies \mu_i = \lambda_i \; \; \forall i$$
Hence, the representation of $x$ is unique as required.
Is this a correct approach? I am interpreting the problem correctly? thanks
Comment: Looks OK to me.
Answer: Yes, it's correct. The fact that a basis is a generating family gives the existence of the representation as a linear combination while freeness guarantees, as you notices, uniqueness of this representation.


Why does increasing the number of bootstrapped cases make PLS coefficients significant?

Question: I am running a PLS model with a low number of observations ($n=50$). While several pieces of academic work argue that this sample size is appropriate to run this type of model, I am quite confused when it comes to the number of cases I take in my bootstrapping procedure.
I get some very strong path estimates for certain paths without a significant t-statistic (50 cases, 500 samples). However, when I put the number of cases above n (lets say 100 cases, 500 samples), the t-values are more in line with the path estimates.
Comment: That seems like a logical result to me. If you arbitrarily increase the bootstrap re-sample size, the estimates will be less variable. I presume such an arbitrary increasing of the bootstrap re-sample size is totally inappropriate, so what is your motivation for doing it at all?
Answer: Bootstrapping typically involves sampling with replacement from your sample data. The size of each bootstrapped sample should be the same as your actual sample size (i.e., n=50). This allows you to study the sampling distribution of your estimators in your actual sample size.
As @Andy notes, you can arbitrarily increase your bootstrapped sample size (lets call it $b$).  As $b$ approaches $\infty$ the standard error of your estimator will tend towards zero. All non-zero coefficients will by definition be statistically significantly different from zero. I remember reading a journal article where an author artificially inflated their sample size using bootstrapping and reported the resulting p-values. This is very wrong! It also may help to explain some people's naive mistrust in the concept of bootstrapping.
Bootstrapping is not a tool to make standard errors smaller. It is a tool to, among other things, give an estimate of standard error.
Your sample size is small (i.e., n =50) so presumably you have larger standard errors than you would like. This is the reality. Thus, you can accept the large standard errors or collect more data and increase your n.


How to get multiple output

Question: Declare @divisionid varchar(max)

Select @divisionid = code
from tbl_em_employees
Where code between 10001 and 10020

Print @divisionid

By above query I want to print below output
10001
10002
10003
-----
-----
-----
10020

How to get this output?
Comment: Please be more specific and format your question better, I can't really tell what you expect as a result.
Comment: If you want to print all the lines separately, you need a loop, for example a cursor, but why are you even using print? How about just using select instead?
Answer: wouldn't it be as simple as
  Select  code
    from tbl_em_employees
    Where code between 10001 and 10020

    order by code

it looks way too obvious.. so i'm not sure if o'm missing something! what is the purpose of the declared variable @divisionid??

How to get multiple output


haproxy stats: qtime,ctime,rtime,ttime?

Question: Running a web app behind HAProxy 1.6.3-1ubuntu0.1, I'm getting haproxy stats qtime,ctime,rtime,ttime values of 0,0,0,2704.
From the docs (https://www.haproxy.org/download/1.6/doc/management.txt):
 58. qtime [..BS]: the average queue time in ms over the 1024 last requests
 59. ctime [..BS]: the average connect time in ms over the 1024 last requests
 60. rtime [..BS]: the average response time in ms over the 1024 last requests
     (0 for TCP)
 61. ttime [..BS]: the average total session time in ms over the 1024 last requests

I'm expecting response times in the 0-10ms range. ttime of 2704 milliseconds seems unrealistically high. Is it possible the units are off and this is 2704 microseconds rather than 2704 millseconds?
Secondly, it seems suspicious that ttime isn't even close to qtime+ctime+rtime. Is total response time not the sum of the time to queue, connect, and respond? What is the other time, that is included in total but not queue/connect/response? Why can my response times be <1ms, but my total response times be ~2704 ms?
Here is my full csv stats:
$ curl "http://localhost:9000/haproxy_stats;csv"
# pxname,svname,qcur,qmax,scur,smax,slim,stot,bin,bout,dreq,dresp,ereq,econ,eresp,wretr,wredis,status,weight,act,bck,chkfail,chkdown,lastchg,downtime,qlimit,pid,iid,sid,throttle,lbtot,tracked,type,rate,rate_lim,rate_max,check_status,check_code,check_duration,hrsp_1xx,hrsp_2xx,hrsp_3xx,hrsp_4xx,hrsp_5xx,hrsp_other,hanafail,req_rate,req_rate_max,req_tot,cli_abrt,srv_abrt,comp_in,comp_out,comp_byp,comp_rsp,lastsess,last_chk,last_agt,qtime,ctime,rtime,ttime,
http-in,FRONTEND,,,4707,18646,50000,5284057,209236612829,42137321877,0,0,997514,,,,,OPEN,,,,,,,,,1,2,0,,,,0,4,0,2068,,,,0,578425742,0,997712,22764,1858,,1561,3922,579448076,,,0,0,0,0,,,,,,,,
servers,server1,0,0,0,4337,20000,578546476,209231794363,41950395095,,0,,22861,1754,95914,0,no check,1,1,0,,,,,,1,3,1,,578450562,,2,1561,,6773,,,,0,578425742,0,198,0,0,0,,,,29,1751,,,,,0,,,0,0,0,2704,
servers,BACKEND,0,0,0,5919,5000,578450562,209231794363,41950395095,0,0,,22861,1754,95914,0,UP,1,1,0,,0,320458,0,,1,3,0,,578450562,,1,1561,,3922,,,,0,578425742,0,198,22764,1858,,,,,29,1751,0,0,0,0,0,,,0,0,0,2704,
stats,FRONTEND,,,2,5,2000,5588,639269,8045341,0,0,29,,,,,OPEN,,,,,,,,,1,4,0,,,,0,1,0,5,,,,0,5374,0,29,196,0,,1,5,5600,,,0,0,0,0,,,,,,,,
stats,BACKEND,0,0,0,1,200,196,639269,8045341,0,0,,196,0,0,0,UP,0,0,0,,0,320458,0,,1,4,0,,0,,1,0,,5,,,,0,0,0,0,196,0,,,,,0,0,0,0,0,0,0,,,0,0,0,0,

Comment: I researched this, and I found an reference to the following forum:
https://discourse.haproxy.org/t/total-time-stat-seems-high-on-stats-page/3129/2

It seems like ttime includes http keep-alive connections which are longer lived.  The timing is the average _session_ time for the last 1024 requests.
Comment: you ever figure out the cause of this I'm facing a similar situation where the other times barely add up to the total time? If total time is only about first byte, and not about content response time I'm not sure what's taking it so long.
Answer: In haproxy >2 you now get two values n / n which is the max within a sliding window and the average for that window. The max value remains the max across all sample windows until a higher value is found. On 1.8 you only get the average.
Example of haproxy 2 v 1.8. Note these proxies are used very differently and with dramatically different loads.

So looks like the average response times at least since last reboot are 66m and 275ms.
The average is computed as:
data time + cumulative http connections - 1 / cumulative http connections

This might not be a perfect analysis so if anyone has improvements it'd be appreciated. This is meant to show how I came to the answer above so you can use it to gather more insight into the other counters you asked about. Most of this information was gathered from reading stats.c. The counters you asked about are defined here.
unsigned int q_time, c_time, d_time, t_time; /* sums of conn_time, queue_time, data_time, total_time */
unsigned int qtime_max, ctime_max, dtime_max, ttime_max; /* maximum of conn_time, queue_time, data_time, total_time observed */```

The stats page values are built from this code:
if (strcmp(field_str(stats, ST_F_MODE), "http") == 0)
            chunk_appendf(out, "
- Responses time:	%s / %s	ms
",
                      U2H(stats[ST_F_RT_MAX].u.u32), U2H(stats[ST_F_RTIME].u.u32));
            chunk_appendf(out, "
- Total time:	%s / %s	ms
",
                  U2H(stats[ST_F_TT_MAX].u.u32), U2H(stats[ST_F_TTIME].u.u32));

You asked about all the counter but I'll focus on one. As can be seen in the snippit above for "Response time:" ST_F_RT_MAX and ST_F_RTIME are the values displayed on the stats page as n (rtime_max) / n (rtime) respectively. These are defined as follows:
[ST_F_RT_MAX] = { .name = "rtime_max", .desc = "Maximum observed time spent waiting for a server response, in milliseconds (backend/server)" },
[ST_F_RTIME] = { .name = "rtime", .desc = "Time spent waiting for a server response, in milliseconds, averaged over the 1024 last requests (backend/server)" },

These set a "metric" value (among other things) in a case statement further down in the code:
case ST_F_RT_MAX:
    metric = mkf_u32(FN_MAX, sv->counters.dtime_max);
    break;
case ST_F_RTIME:
    metric = mkf_u32(FN_AVG, swrate_avg(sv->counters.d_time, srv_samples_window));
    break;

These metric values give us a good look at what the stats page is telling us. The first value in the "Responses time: 0 / 0" ST_F_RT_MAX, is some max value time spent waiting. The second value in "Responses time: 0 / 0" ST_F_RTIME is an average time taken for each connection. These are the max and average taken within a window of time, i.e. however long it takes for you to get 1024 connections.
For example "Responses time: 10000 / 20":

max time spent waiting (max value ever reached including http keepalive time) over the last 1024 connections 10 seconds
average time over the last 1024 connections 20ms

So for all intents and purposes
rtime_max = dtime_max
rtime = swrate_avg(d_time, srv_samples_window)

Which begs the question what is dtime_max d_time and srv_sample_window? These are the data time windows, I couldn't actually figure how these time values are being set, but at face value it's "some time" for the last 1024 connections. As pointed out here keepalive times are included in max totals which is why the numbers are high.
Now that we know ST_F_RT_MAX is a max value and ST_F_RTIME is an average, an average of what?
/* compue time values for later use */
if (selected_field == NULL || *selected_field == ST_F_QTIME ||
    *selected_field == ST_F_CTIME || *selected_field == ST_F_RTIME ||
    *selected_field == ST_F_TTIME) {
    srv_samples_counter = (px->mode == PR_MODE_HTTP) ? sv->counters.p.http.cum_req : sv->counters.cum_lbconn;
    if (srv_samples_counter < TIME_STATS_SAMPLES && srv_samples_counter > 0)
        srv_samples_window = srv_samples_counter;
}

TIME_STATS_SAMPLES value is defined as
#define TIME_STATS_SAMPLES 512
unsigned int srv_samples_window = TIME_STATS_SAMPLES;

In mode http srv_sample_counter is sv->counters.p.http.cum_req. http.cum_req is defined as ST_F_REQ_TOT.
[ST_F_REQ_TOT]  = { .name = "req_tot",  .desc = "Total number of HTTP requests processed by this object since the worker process started" },

For example if the value of http.cum_req is 10, then srv_sample_counter will be 10. The sample appears to be the number of successful requests for a given sample window for a given backends server. d_time (data time) is passed as "sum" and is computed as some non-negative value or it's counted as an error. I thought I found the code for how d_time is created but I wasn't sure so I haven't included it.
/* Returns the average sample value for the sum <sum> over a sliding window of
 * <n> samples. Better if <n> is a power of two. It must be the same <n> as the
 * one used above in all additions.
 */
static inline unsigned int swrate_avg(unsigned int sum, unsigned int n)
{
    return (sum + n - 1) / n;
}

haproxy stats: qtime,ctime,rtime,ttime?


Question regarding a linear transformation on the space of real polynomials of degree $\leq n$

Question: Let $V$ be the linear space of all real polynomials $p(x)$ of degree $\leq n$. If $p\in V$, $q=T(p)$ means that $q(x)=p(x+1)$ for all real $x$.
I was able to show the $T$ is a linear transformation. However, I am having some difficulties determining $\ker(T)$ , the range, the nullity and rank.
For the rank, I think that it is $n$.
Thank you
Answer: It's not very complicated. Just note that $T$ has an inverse, given by $S(q) = p$, where $p(x) = q(x-1)$. This means that $T$ is injective, and everything else should follow readily.
Comment: @user43418 Approach 1: since $TS=Id$, the range is the whole space $V$. Approach 2: since $\dim (Im T)=n=\dim V$, the range is the whole space $V$.
Comment: I think you meant bijective.
Comment: Since T is injective, then Ker(T)={0} right?
Comment: @user43418, yes, and then, as julien as noted, also surjective etc.
Comment: @user43418 Yes of course. But we directly have $TS=ST=Id$.
Comment: @julien, injective and surjective, sure, but I started with injective to get the kernel right first.
Comment: So, since Ker(T)={0}, the nullity i.e. dim(Ker(T))={0} and therefore the rank ie dim(Im(T))=dim(V)=n
Comment: @user43418 Yes, you can use the rank-nullity theorem here if you want. But note that the result is still true with the space of all polynomials, without restrictions on the degree. And this is because $ST=TS=Id$.
Comment: What is the range of this application please?


Which menu should a third-party module choose, between "Structure" and "Configuration"?

Question: I noticed that some module prefers to add their menu items under "Structure," while other modules prefer to add them under "Configuration."
I thought that the reason of choosing "Structure" was because the menu items were related to some kind of "entities," but I then noticed that Rules is adding its menu items under "Configuration."
Vice versa, Views and Flags put their menu items in "Structure."
What is then the criteria to use when deciding under which menu a module put its menu items? Does the "Structure" menu contains only menu items that are related to content?
Answer: This and many other D7UX related things are best explained in the UI Patterns session from yoroy and Bohjan: Drupal 7: Interface patterns.
In short, Structure is meant for structural things which are used regularly (mostly during site building). If those modules add their stuff their and are not Views, Panels or similar, chances are that they are doing it wrong. :)
Not everyone exactly agrees on the IA (Information Architecture) of Drupal 7 yet or simply doesn't know about it. Not even Drupal 7 core is very consistent IMHO; I don't think the contact.module settings belong to Structure, for example, when not even those from path.module are, which are most likely way more often used.
Comment: For those that want a quick reference (the drupalcon session contains a video but no text information) the handbook page is http://drupal.org/node/549094.


template argument deduction/substitution failed erro, when iterating two maps simultaneously

Question: I am trying to iterate two unordered maps simultaneously using a pair of two iterators.
This method works fine if we iterate over two vectors;
#include <iostream>
#include<unordered_map>
using namespace std;

int main()
{
    std::unordered_map<std::string,double> mypantry = {{"flour",1.5}};
    std::unordered_map<std::string, int> dubVec = {{"key", 5}};
    std::unordered_map<std::string, std::string> intVec = {"key", "name"};
    double result = 0;

    typedef std::unordered_map<std::string, std::string>::iterator intIter;
    typedef std::unordered_map<std::string, bool>::iterator dubIter;

    for (std::pair<intIter, dubIter> i(intVec.begin(), dubVec.begin());
     i.first != intVec.end() && i.second != dubVec.end();
     ++i.first, ++i.second)
    {
        cout << i.first.first << "\n" << i.first.second << "\n" << i.second.second;
    }
    return 0;
}

prog.cpp: In function 'int main()': prog.cpp:18:70: error: no matching
  function for call to
  'std::pair, std::__cxx11::basic_string >,
  false, true>, std::__detail::_Node_iterator, bool>, false, true>

::pair(std::unordered_map, std::__cxx11::basic_string >::iterator,
    std::unordered_map, int>::iterator)'
         for (std::pair i(intVec.begin(), dubVec.begin());
                                                                          ^ In file included from /usr/include/c++/5/bits/stl_algobase.h:64:0,
                     from /usr/include/c++/5/bits/char_traits.h:39,
                     from /usr/include/c++/5/ios:40,
                     from /usr/include/c++/5/ostream:38,
                     from /usr/include/c++/5/iostream:39,
                     from prog.cpp:3: /usr/include/c++/5/bits/stl_pair.h:206:9: note: candidate:
    template std::pair<_T1, _T2>::pair(std::tuple<_Args1 ...>&, std::tuple<_Args2 ...>&, std::_Index_tuple<_Indexes1 ...>, std::_Index_tuple<_Indexes2 ...>)
             pair(tuple<_Args1...>&, tuple<_Args2...>&,
             ^ /usr/include/c++/5/bits/stl_pair.h:206:9: note:   template argument deduction/substitution failed: prog.cpp:18:70: note:
    'std::unordered_map,
    std::__cxx11::basic_string >::iterator {aka
    std::__detail::_Node_iterator, std::__cxx11::ba
Answer: Couple of typos in your code:
std::unordered_map<std::string, std::string> intVec = {"key", "name"};

should be:
std::unordered_map<std::string, std::string> intVec = {{"key", "name"}};
//                    notice additional curly brackets ^             ^

Previously you tried to initialise your map with a pair of const char[]s, but now you initialise it with a single key-value pair.

typedef std::unordered_map<std::string, bool>::iterator dubIter;

should be:
typedef std::unordered_map<std::string, int>::iterator dubIter;

Previously, dubIter was a typedef to an iterator of unordered map of string-bool entries, but you have string-int entries in your dubVec.

cout << i.first.first << "\n" << i.first.second << "\n" << i.second.second;

should be:
cout <first << "\n" <second << "\n" <second;
// notice here ^^                        ^^                          ^^

i is an std::pair of iterators. Its first and second members are iterators. Iterators to key-value pairs. To access elements of those pairs, you have to either dereference the iterators first, or use -> syntax, instead of ..


Show months outside date range in selector?

Question: I'm using jQuery UI's DatePicker to select a date of birth for consumers on my website.  It is currently showing with the month and year via drop downs  When, for example, I restrict the years to -18y, via maxDate, the month drop down does not show all of the months when the year 1993 is selected.  It only shows the months up until the maximum months.
In usability testing, we've found that our demographic tends to click the month of their birth, then the year, then the day.
Is there a way to show all of the months, even if the dates within that month are not selectable?
Here is the code used to show the DatePicker:
$('.DobWidget').datepicker({
    showOn: 'both',
    buttonImage: '/media/img/admin/icon_calendar.gif',
    buttonImageOnly: true,
    dateFormat: js_date_format, // mm/dd/yyyy
    constrainInput: false, // Handled server-side for type-in.
    changeMonth: true,
    changeYear: true,
    maxDate: '-18y',
    minDate: '-110y',
    showButtonPanel: true,
    onChangeMonthYear: function(year, month, inst) {
        if (inst.currentDay != 0) {
            $(this).datepicker("setDate", new Date(year, month - 1, inst.currentDay));
        }
    }
});

I am currently using jQueryUI v.1.8.16, and jQuery v.1.6.3, both provided by the Google AJAX API's.
Comment: I see no problem with 1990. Could it be 1993?
Comment: You are correct.  I have two ranges, 21 and 18.  I got them mixed up for the example.  1993 is the correct year.
Answer: Fix for jquery ui 1.8.17
I also had this problem I got in to work by changing some things in the jquery code. Now I see all months and I can select them but dates will still be unselectable as you want.
In _generateHTML function in the if statement you add maxDraw.setMonth('11'):
if (maxDate) {
            maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
            maxDraw.setMonth('11');
            while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
                ...
            }
        }

In _generateMonthYearHeader function in the for loop of the else statement you change:
for (var month = 0; month < 12; month++) {
                if ((!inMinYear || month >= minDate.getMonth()) &&
                        (!inMaxYear || month <= maxDate.getMonth()))
                    monthHtml += '<option value="' + month + '"' +
                        (month == drawMonth ? ' selected="selected"' : '') +
                        '>' + monthNamesShort[month] + '</option>';
            }

becomes
for (var month = 0; month < 12; month++) {
                if ((!inMinYear || month >= minDate.getMonth()) &&
                        (!inMaxYear || month <= 11))
                    monthHtml += '<option value="' + month + '"' +
                        (month == drawMonth ? ' selected="selected"' : '') +
                        '>' + monthNamesShort[month] + '</option>';
            }

In _restrictMinMax you add maxDate.setMonth('11'):
...
var maxDate = this._getMinMaxDate(inst, 'max');
        maxDate.setMonth('11');
        var newDate = (minDate && date < minDate ? minDate : date);
...

In _isInRange you add maxDate.setMonth('11'):
var minDate = this._getMinMaxDate(inst, 'min');
        var maxDate = this._getMinMaxDate(inst, 'max');
        maxDate.setMonth('11');
...


how to elegantly substitute repeated values with a different vector?

Question: In R, a vector like this:
x <- c(0,0,1,1,0,0,1,1,0,0,1,1,1,1,0,1,0,1,0,1)

I want x to be like this:
y = c(0,0,1,1,0,0,2,2,0,0,3,3,3,3,0,4,0,5,0,6)

Could anyone help me solve this question?
Answer: An option would be rle
inverse.rle(within.list(rle(x), values[values!=0] <- seq_along(values[values!=0])))
#[1] 0 0 1 1 0 0 2 2 0 0 3 3 3 3 0 4 0 5 0 6

Or with rleid from data.table
library(data.table)
x1 <- x*rleid(x)
match(x1, unique(x1[x1!=0]), nomatch = 0)
#[1] 0 0 1 1 0 0 2 2 0 0 3 3 3 3 0 4 0 5 0 6

Comment: 2nd solution is nice. Didn't think to use match like that.