Configure nginx to serve a 503 if a file exists

Question: I'm trying to setup nginx to return a 503 if a particular file exists (probably something like "upgrading").  I'm trying to use the try_files directive, but when it finds the /upgrading.html file, it serves it rather than following the directive.  Why is that?
location / {
    try_files /upgrading.html @keepgoing;
}

location = /upgrading.html {
    return 503;
}

location @keepgoing {
    #do stuff here to do whatever I would normally do...
}

In the log when I turn on debugging I see the following:
3388    2010/07/01 19:44:21 [debug] 76327#0: *8 test location: "/"
3389    2010/07/01 19:44:21 [debug] 76327#0: *8 using configuration "/"
3390    2010/07/01 19:44:21 [debug] 76327#0: *8 http cl:-1 max:52428800
3391    2010/07/01 19:44:21 [debug] 76327#0: *8 generic phase: 2
3392    2010/07/01 19:44:21 [debug] 76327#0: *8 post rewrite phase: 3
3393    2010/07/01 19:44:21 [debug] 76327#0: *8 generic phase: 4
3394    2010/07/01 19:44:21 [debug] 76327#0: *8 generic phase: 5
3395    2010/07/01 19:44:21 [debug] 76327#0: *8 access phase: 6
3396    2010/07/01 19:44:21 [debug] 76327#0: *8 access phase: 7
3397    2010/07/01 19:44:21 [debug] 76327#0: *8 post access phase: 8
3398    2010/07/01 19:44:21 [debug] 76327#0: *8 try files phase: 9
3399    2010/07/01 19:44:21 [debug] 76327#0: *8 try to use file: "/upgrading.html" "/usr/local/nginx/html/upgrading.html"
3400    2010/07/01 19:44:21 [debug] 76327#0: *8 try file uri: "/upgrading.html"
3401    2010/07/01 19:44:21 [debug] 76327#0: *8 content phase: 10
3402    2010/07/01 19:44:21 [debug] 76327#0: *8 content phase: 11
3403    2010/07/01 19:44:21 [debug] 76327#0: *8 content phase: 12
3404    2010/07/01 19:44:21 [debug] 76327#0: *8 http filename: "/usr/local/nginx/html/upgrading.html"

Seems like it can't find the directive, but it's there, so not sure what I'm doing wrong.
Also, more generally, is this an acceptable approach to solving this problem?  Other ways to do it?
Answer: From this page: https://calomel.org/nginx.html
## System Maintenance (Service Unavailable)
if (-f $document_root/system_maintenance.html ) {
    error_page 503 /system_maintenance.html;
    return 503;
}

The important part being the '-f', I believe - it tests to see if the file exists.
Comment: Not recommended: http://wiki.nginx.org/IfIsEvil

try_files is the correct approach.
Comment: quote from there `The only safe things may be done inside if in location context are: return ...; and rewrite ... last; `
Comment: Martin, SaveTheRbtz: the example I pointed to did not use 'if' within a 'location' statement - it was at the 'server' level, which is considered fine.

However, it is good to point out that it's not recommended within a 'location' statement - that might come up for the OP or anyone else stumbling across this reply.
Comment: Not sure if this has changed over time, but in the version of nginx (1.8) that I am using, error_page is only allowed in an if nested in a location.
Answer: I suggest that you don't use the try_files here and instead look for the file and return the error code if it exists. Then you can handle the error code separatly. Look at the example below.
# If the maintenance.html file exists, return status 503
if (-f $document_root/maintenance.html) {
  return 503;
}

# Then on status 503, use the @maintenance location
error_page 503 @maintenance;

# I  the @maintenance location, render the maintenance.html
location @maintenance {
  rewrite ^(.*)$ /maintenance.html break;
}

If you plan to do this regualry and whant the same maintenance.html every time you could also change the first part to be something like below. Then you can have the maintenance.html always in place and just att the empty .maintenance file when needed.
if (-f $document_root/.maintenance) {
  return 503;
}


Convert z-scores to percentile rank

Question: Does anyone know the formula to convert a z-score to a percentile rank instead of using the z-score table? I searched the website, but did not find the formula.
thank you
Comment: The formula is given by the Normal cumulative density function, defined as $\int_{-\infty}^z \exp(-x^2/2)dx /\sqrt{2\pi}.$ There are many ways to compute this as exactly as one would like: conceptually it's no different, say, than the definition of the logarithm as $\log(z)=\int_1^z dx/x.$ This is why @Glen_b seeks more information concerning your objectives, which you can provide by editing this question.
Comment: There are approximation formulas of various kinds for computing the cdf or survivor function of a standard normal; which might be suitable depends on the circumstances. What are you using it for - e.g. are you writing code?
Answer: Like in the comments, there's a known function that describes the relationship. The reason you use a table is that the function is ugly. It can be calculated very easily by a computer but not at all by hand. So before everyone had R in front of them it was the best way to "calculate" a value from $F(x)$ when you needed one -- just look it up in the table.
If you want to know more about the theory, I'd refer you to any intro probability textbook... which imo you should already be using if you're going to be using z-scores.
This is done in R with function pnorm. This is the standard set of functions for a distribution in R:

r:  input $N$, get $N$ random values
p:  input $X$, get $F(X)$
d:  input $X$, get $f(x)$
q:  input $p$, get $F^{-1}(p)$

Try it out:
dt(1.65,df=30)
df(2,df1=2,df2=30)
df(-2,df1=2,df2=30) # F distribution is for positive random variables
qnorm(0.95)
pnorm(1.65)
dnorm(1.65)
runif(15)

And if you want to know more about how exactly the computer calculates $\frac{1}{2\pi}\int_{-\infty}^x e^{\frac{-t^2}{2}}dt$ when you give it an $x$, you'll be wanting to know about numerical integration.
Comment: Thank you for taking the time to answer my question, but I went ahead and created a hash table from the z-scores & I'll use that instead, unless someone knows what Java class I could find a function to do this in. I thought if I had the formula I could use that , but I don't think I would be able to figure out how to use it without a big investment in time.
Comment: @user3787792 http://stackoverflow.com/questions/6011943/java-normal-distribution

Convert z-scores to percentile rank


Neural network weights

Question: This is going to be a long question :
I have written a code in MATLAB for updating the weights of MLP with one hidden layer . Here is the code :
weights_1 : weight matrix for input to hidden layer
weights_2 : weight matrix for hidden to output layer
function [ weights_1,weights_2 ] = changeWeights( X,y,weights_1,weights_2,alpha )
%CHANGEWEIGHTS updates the weight matrices
%   This function changes the weight of the weight matrix
%   for a given value of alpha using the back propogation algortihm

m = size(X,1) ;     % number of samples in the training set

for i = 1:m
    % Performing the feed-forward step
    X_i  = [1 X(i,1:end)]    ;
    z2_i = X_i*weights_1'    ;
    a2_i = sigmoid(z2_i)     ;
    a2_i = [1 a2_i]          ;
    z3_i = a2_i*weights_2'   ;
    h_i  = sigmoid(z3_i)     ;

% Calculating the delta_output_layer
    delta_output_layer = ( y(i)' - h_i' )...
        .*sigmoidGradient(z3_i')  ; % 3-by-1 matrix

% Calculating the delta_hidden_layer
    delta_hidden_layer =  (weights_2'*delta_output_layer)...
        .*sigmoidGradient([1;z2_i']) ; % 5-by-1 matrix
    delta_hidden_layer = delta_hidden_layer(2:end) ;

% Updating the weight matrices
    weights_2 = weights_2 + alpha*delta_output_layer*a2_i ;
    weights_1 = weights_1 + alpha*delta_hidden_layer*X_i  ;
end

end

Now I wanted to test it on the fisheriris dataset given in MATLAB which can be accesed by load fisheriris command . I renamed meas to X and changed species to a 150-by-3 matrix where each row depicts the name of species (as for example first row is [1 0 0])
I compute error of the output layer using the following function :
function [ g ] = costFunction( X,y,weights_1,weights_2 )
  %COST calculates the error
  %   This function calculates the error in the
  %   output of the neural network

  % Performing the feed-forward propogation
  m = size(X,1) ;
  X_temp  = [ones([m 1]) X]   ;  % 150-by-5 matrix
  z2 = X_temp*weights_1'       ; % 150-by-5-by-5-by-4
  a2 = sigmoid(z2)       ;
  a2 = [ones([m 1]) a2]            ; % 150-by-5
  z3 = a2*weights_2'     ; % 150-by-3
  h  = sigmoid(z3)       ; % 150-by-3

  g = 0.5*sum(sum((y-h).^2)) ;
  g = g/m ;
end

Now in the course the prof gave an example of toy network with 3 iterations , I tested this on that network and it gives the right values but when I test it on the fisheriris data the cost keeps on increasing . And I am not able to understand where it is going wrong .
Here is the toy network for which it runs fine :

there is only training example for this set .
PS : Ignore the comments ( they are size of matrix used for checking the validity of matrix multiplication for a sample case )
Finally here is the test-bench execute.m , sigmoid.m and sigmoidGradient.m which I have shared just in case to run the functions and test them
Comment: Decrease your alpha. You are diverging during gradient descent
Comment: Why do you use the same bias unit for different layers?. That seems odd to me. The bias term compensates for the difference between the mean value of training data and the mean response of neurons. Each layer corresponds to a different mapping of the data, so I would expect a different bias unit per layer.
Answer: My first questions/thoughts are:

I use a different training method.  I like the Eric Wan diagrammatic method[1].  It allows me to compute a "gradient" for my network using an adjoint network. I can detect errors in one using the other and basic test cases.  Coupled debugging.
Have you compared your results to the built-ins?  Did you make a technical error in the implementation of the code that you can detect there?  I don't have resources right now to test this.
I'm sure someone has made a NN that tests the Fischer Iris data using a NN.  Have you looked in peer-reviewed published literature?  The reason I ask is I was once tasked with something that sounded clever in Q-learning, but when I reviewed the literature, it was shown to be impossible.  That went over very well with my professor.  Never be afraid to stand on the shoulders of giants.
Make a linear (planar) fit first, and then train the NN on the variation from the plane.  This keeps your values closer to the origin, and makes your learning rates higher.  It also makes the Neural Network do the heavy lifting of fitting the nonlinear part instead of wasting the training/learning on the planar part.  A pseudo-inverse is computationally cheap, comparatively speaking.
I didn't see any scaling or centering on the inputs.  If you have input values in the millions and initial weights in the ones, then you are going to spend all your training iterations increasing the scale for the inputs.  Subtracting the mean, and then dividing by something like the standard variation can help.

[1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.38.5262

Neural network weights


How to execute request-specific tasks after page response is returned. Does hook_exit() actaully do this?

Question: I'm trying to figure out if it's possible to "hide" the perceived execution time of some end-of-request logging tasks that are page specific and depend on the availability of the Drupal DB API. Essentially I'd like to run these tasks after the page response is returned in full to the browser. I've always just assumed that hook_exit() was the right choice for this kind of thing but after looking at its invocation within drupal_page_footer() in some detail, I'm not so sure. Here's the notable snippet from drupal_page_footer():
module_invoke_all('exit');

// Commit the user session, if needed.
drupal_session_commit();

if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
drupal_serve_page_from_cache($cache);
}
else {
  ob_flush();
}

So it looks like both cached and un-cached responses are not sent to the browser until after all hook_exit() implementations run (flushing the buffer and executing drupal_serve_page_from_cache() both happen after module_invoke_all('exit')). This seems a bit contrary to the hook_exit() documentation which states that, "This hook MUST NOT print anything because by the time it runs the response is already sent to the browser."
Am I perhaps misinterpreting the way hook_exit() implementations work in relation to the response delivery? If not, is there some alternative way to trigger custom logging logic later in the response (while DB access is still available)? Perhaps by registering a shutdown function or something to that effect?
Answer: You're looking for fastcgi_finish_request(). Recommend using it inside of a shutdown function. If you need something else the HTTPRL module should be able to do what you need with threading.
Comment: Very interesting. I guess that indirectly confirms my initial conclusion that hook_exit() was not an option for this (despite what the docs may say). By moving things to a shutdown function I guess I can at least get the page markup delivered **before** the logging task, but it seems that your specific recommendation would be the only way to also get the connection closed before that point? I'm guessing this would ensure that js triggerd by $(document).ready() fires sooner, etc.?
Comment: General rule is that the faster the connection is closed by PHP the faster the browser can do it's thing.
Comment: I guess that sums things up pretty nicely.
Answer: I want to follow-up on this with an answer to my own question. This just expands on the already accepted answer.
For anyone wanting to achieve this in a reusable module, that may be implemented on multiple environments, a simple call to fastcgi_finish_request() will of course not be possible as there is no guarantee that FastCGI is being used. That said, it still looks like fastcgi_finish_request() is the best option for this when available.
To still leverage some advantage when FastCGI is not available, I've found it's useful to at least attempt to flush all content to the client before running the logging task. This would allow the browser to begin displaying content, start fetching any render-blocking js, etc., before the logging happens. It would not allow the connection to be closed, as fastcgi_finish_request() would do (so DOM ready events would still be held up), but it still seems better than not doing anything at all.
Here's what I've been testing in my shutdown function (this would only be applicable in a shutdown function and would not work in any hook implementations):
/**
 * Shutdown function used for logging purposes.
 */
function mymodule_shutdown() {
  // Try to ensure that our logging happens after the page content has been sent
  // to the browser, and ideally after the connection is closed.
  // fastcgi_finish_request() is our best option as it's designed for exactly
  // this purpose, but php may not always be running under FastCGI. As an
  // alternative we just force buffers to be flushed (this will not close the
  // connection but it will at least get the page content pushed out).
  if (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request();
  }
  else {
    flush();
  }
  run_expensive_logging_task();
}

There is some useful info in this post about all this as well. I can't be too sure if calling flush() alone will always do the job as there are some indications that output buffering must be explicitly killed (ob_end_flush()) as well. However, in the context of a Drupal shutdown function it seems like this is unneeded as wrapping-up all the output buffering stuff was likely handled by core already. Of course if fastcgi_finish_request() is used it takes care of all this in one line.
Comment: See this function for how to do it: [httprl_background_processing()](http://cgit.drupalcode.org/httprl/tree/httprl.module?h=7.x-1.x#n2540)
Comment: Thanks, that function is a very useful reference! I'm going to make note of those details for sure. However, I think the application of that httprl_background_processing() logic may be a little limited, as it assumes that I have full control of the page headers. If I'm needing to trigger a logging task that fires for *all* page requests regardless of how the response is built, and when headers are sent (basically a shutdown function that's registered on all pages), I'm assuming the best I can do is flush any buffers?
Comment: The headers you need for sure are `Connection: close` and `Content-Length: ob_get_length()`.
Comment: Yes, I think that makes sense, as a browser receiving those headers, along with a matching-length data response, would close the connection while things still churn-away on the server. However, unless I am missing something, I don't think I can set those headers without full control of menu callback, or at least some guarantee that no content/headers have been sent yet. Without this control or access to `fastcgi_finish_request()`, is there actually anything else I can do besides flush buffers?
Comment: [hook_page_delivery_callback_alter()](https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_page_delivery_callback_alter/7) might be the way to control the output
Comment: Yeah, that's what I figured, and what I was hoping to avoid. For a generic/global logging task I'd have to alter *all* page callbacks to really do it right, which seems pretty heavy-handed. In my case it's probably safer to just take the performance hit on non-FastCGI environments than try and get into all that. Either way, these comments help confirm my understanding of the variables at play.
Comment: If you do discover some magic; we're looking into this for D8 poormanscron https://www.drupal.org/node/1599622
Comment: Will do, and thanks for all the notes. The poormanscron problem is actually quite analogous to this case. I'll be keeping an eye on that issue no matter what.


SQL query for Time between multiple Events of multiple criteria

Question: I need a query that can calculate the time between events by multiple criteria. I need the last column to be calculated (days since last event)

EventId
Date
Location
Equipment
Part
DaysSinceLastEvent

1
1/5/20
Site1
XYZ
P1
0

2
2/1/20
Site2
ABC
P2
0

3
3/1/20
Site1
XYZ
P1
56

4
2/5/20
Site2
XYZ
P1
0

5
3/5/20
Site1
XYZ
P1
4

6
2/20/20
Site2
ABC
P2
29

7
2/10/20
Site2
XYZ
P1
5

The table needs to evaluate 4 main columns, Date, Location, EQuipment, Part to calculate the days since the last event. The above is just an example. There are hundreds of locations, thousands of sites, and thousands of part combinations. I could concatenate Location, Equipment, Part together, but i still need the days between the events of that unique combination.
Thanks in advance!
Comment: 1) tag DBMS , 2) provide expect output , 3) also provide what you have tried (and that output as well).
Comment: "database" isn't a specific "database product". What T.Peter was referring to if you use PostgreSQL, Oracle, SQL Server, DB2, ...?
Comment: Is `DaysSinceLastEvent` the value you want to calculate?
Comment: Yes, Days since last event is what i want to calculate. Just note that there will be multiple events. Ideally i don't have to concatenate Site, Equipment, PArt for a single unique value. @a_horse_with_no_name
Comment: @T.Peter 1) done, 2) the table is the output i'm looking for. specifically the last column where the first 5 columns are what i'm trying to calculate the last column from. 3) I've only been able to calculate for min and max events, but i need every event. I've been able to do it in PowerBI, but i need to have the table from SQL output it.
Comment: @stretch88 my dear, [database] is not a DBMS (e.g. oracle, sql-server), as it provide nothing more to us than [sql] tag. also if the table you show us is expect output then 1) you should mention clearly this is expect output, 2) provide sample data which you want it to become expect output.
Comment: also about "what you have tried" is provide your `code sample` even it didn't get what you want, because it still provide us what step you have already did, and a lot of time a small adjustment can get the result you want. (p.s. also this make people more likely to help since you do your best rather then "Gimme Codz")
Comment: @T.Peter  ah thanks for the feedback. first timer here, so appreciate the help. Using Microsoft SQL Server management Studio. Let me reformat some of the sensitive information and then i will share what i've tried so far. thanks!
Answer: You can do that with a window function:
<code>select eventid, date, location, equipment, part,
       date - lag(date) over (partition by location, equipment, part order by date) as days_since_last_event
from the_table
order by eventid, date;
</code>
This uses standard ANSI SQL date arithmetic where subtracting one date from another yields the number of days. Not all DBMS products support this, you would need to consult the manual of your DBMS to find the corresponding function.
Comment: Thank you, this did the trick! Really appreciate it and will be better about the inputs next time. Thanks!


Remoção de valores repetidos

Question: Tenho dois vectors, cada um com coordenadas (x,y). Eu preciso inverter o segundo vector, ficando com (y, x) e mesclar com o primeiro, mas não posso ter repetição no primeiro campo, por isso pensei em usar um set.
Entretanto, preciso que o segundo valor da estrutura seja sempre o maior possível. Por exemplo, se eu tiver os seguintes valores: {(3, 2); (3, 10)}, preciso que fique no set o par (3,10).
É possível fazer isso com set?
Exemplo em pseudo-código:
vector<pair<int, int> > vector1 = {(10, 2); (10, 1); (3, 7)};
vector<pair<int, int> > vector2 = {(1, 3); (9, 10)};

Invertendo as coordenadas do segundo vetor, ficaria com:
vector2 = {(3, 1); (10, 9)};

Ao mesclar com o primeiro vetor, quero que os valores do primeiro campo sejam únicos, enquanto que o do segundo sejam sempre os, maiores. No caso eu queria um set com os seguintes valores:
set1<pair<int, int> > set1 = {(10, 9); (3, 7)};

Comment: Sim, Guilherme. Editei o post para tentar explicar melhor a dúvida.
Comment: Sua dúvida não está clara. Por vector e set você se refere ao `std::vector` e `std::set`? Pode mostrar um exemplo de código?
Answer:
Considerando C++11, o seguinte é válido:
vector<pair<int, int>> vec1 = {{10, 2}, {10, 1}, {3, 7}};
vector<pair<int, int>> vec2 = {{1, 3}, {9, 10}};

Para inverter as coordenadas de cada elemento do segundo vetor, você pode fazer o seguinte:
for (auto& coord : vec2)
    swap(coord.first, coord.second);

Agora quanto a inserir eles em um std::set mantendo apenas o valor mais alto, você provavelmente está fazendo algo muito errado aqui. Verificar se o valor da coordenada já está no set vai lhe custar um loop passando por todos os elementos do set. Isso para cada inserção. Então para inserir n itens, você precisa de n² operações. É muita coisa.
Do que entendo você tem uma coordenada que identifica o par e outra que é apenas um valor. Claramente você tem um par de chave e valor e quer ter uma lista deles, sem repetir chaves. O que você precisa é de um std::map.
map<int, int> m;

void insertPair(const pair<int, int>& p) {
    if (m.find(p.first)) // Se já tem a key
        m[p.first] = max(m[p.first], p.second);
    else
        m[p.first] = p.second;
}

for (const auto& coord : vec1)
    insertPair(coord);

for (const auto& coord : vec2)
    insertPair(coord);

Essa função tem complexidade de n log(n) agora que não precisa procurar em todos os elementos pela chave.
Se ainda assim pretende usar um std::set, tem que ir pelo caminho longo:
set<pair<int, int>> s;

void insertPair(const pair<int, int>& p) {
    for (const pair<int, int>& p2 : s) { // percorra todo o set em busca do elemento
        if (p2.first == p.first) { // ao encontrar
            p2.second = max(p2.second, p.second); // troque o valor pelo maior
            return; // e retorne
        }
    }
    s.insert(p); // se não encontrou, basta inserir
}

for (const auto& coord : vec1)
    insertPair(coord);

for (const auto& coord : vec2)
    insertPair(coord);

Comment: Obrigado, Guilherme. Era exatamente esta a dúvida.
Vou utilizar um std::map então.
Answer: Solução alternativa só com vetores (usando generic lambdas do c++14):
#include <vector>
#include <utility>
#include <iostream>
#include <algorithm>

using namespace std;

int main() {
    vector<pair<int, int>> v1 = { {10, 2}, {10, 1}, {3, 7} };
    vector<pair<int, int>> v2 = { {1, 3}, {9, 10} };

    for(auto &p : v2)
        swap(p.first, p.second);
    v1.insert(end(v1), begin(v2), end(v2));
    sort(rbegin(v1), rend(v1));
    v1.erase(
        unique(begin(v1), end(v1),
            [](auto lhs, auto rhs) { return lhs.first == rhs.first; }),
        end(v1));

    for (auto &p : v1)
        cout << '(' << p.first << ", " << p.second << ')' << endl;
}

ou:
#include <vector>
#include <utility>
#include <iostream>
#include <algorithm>

using namespace std;

int main() {
    vector<pair<int, int>> v1 = { {10, 2}, {10, 1}, {3, 7} };
    vector<pair<int, int>> v2 = { {1, 3}, {9, 10} };

    for(auto &p : v2)
        swap(p.first, p.second);
    v1.insert(end(v1), begin(v2), end(v2));
    sort(rbegin(v1), rend(v1));
    vector<pair<int, int>> v3;
    unique_copy(begin(v1), end(v1), back_inserter(v3),
        [](auto lhs, auto rhs) { return lhs.first == rhs.first; });

    for (auto &p : v3)
        cout << '(' << p.first << ", " << p.second << ')' << endl;
}

Comment: Creio que fosse melhor você usar `std::unique` ou `std::unique_copy` nesse seu exemplo pois deixa mais claro o que esta acontecendo e simplifica seu código. Bastaria definir uma função ou um lambda que compare apenas o primeiro elemento dos pairs passados para ele. Veja um exemplo: http://ideone.com/7Bvi3k
Comment: @TiagoGomes muito melhor Tiago, `std::unique` me escapou, e o uso de `std::transform` pra swap está legal também, integrarei estas dicas, obrigado.
Comment: pepper_chico, essa solução não garante que terei sempre o maior valor no campo second do pair para chaves repetidas, não?
Comment: @lfelix sim ela garante, dê uma olhada sobre o que ocorre quando se compara grandeza entre dois `pair`s. (2, 1) > (2, 0) > (1, 2) > (1, 1), etc. Eles fazem uma [comparação lexicográfica](http://en.cppreference.com/w/cpp/utility/tuple/tie).
Comment: @lfelix A sacada é, fazer uso disto e, tacar tudo no vetor, ordenar, e então, correr o vetor pescando `pair`s somente quando o `first` muda. Por exemplo, fazendo essa "pesca" na lista que dei anteriormente, pega-se o primeiro (2,1), o próximo é igual, o próximo não, então pesca esse, (1, 2), e o outro é igual. No final só (2, 1) e (1, 2) foram pescados.
Comment: @lfelix dei uma mudada no código, recomendo uma lida antes no [_erase-remove idiom_](http://en.wikipedia.org/wiki/Erase-remove_idiom)

Remoção de valores repetidos


Algebraic manipulation of $Var(Y|X)=E[(Y-E(Y|X))^2|X]$

Question: Q: Show that $Var(Y|X)=E[(Y-E(Y|X))^2|X]$ is equal to $Var(Y|X)=E[Y^2|X]-(E[Y|X)]^2$.
Answer: I know I have to use the law of iterated expectation to get to the second statement but I am having trouble with that. I understand that $E[E(Y|X)]=E[Y]$ but how can I use that to solve this problem?
Help would be greatly appreciated.
Many thanks in advance!
Comment: There is no iterated expectation there, since everything is conditional to $X$. This is simply the definition of the variance for the conditional distribution.
Answer: Just expand the first expression (i.e. $(Y - E(Y \mid X))^2$) and use that $E(E(Y \mid X) \mid X) = E(Y \mid X)$.
Comment: Can you please give a bit more hint as how to expand the first expression? Like just multiply it out since the term is squared? Thanks!
Comment: Yes indeed: $(a+b)^2 = a^2 + 2ab + b^2$


IF ELSE with NULL values mysql

Question: im having problems creating a function that must return the amount of goals of a team as a home and away
First it sums all local goals, and then it sums all visitor goals, and saves into variables, but the problem is, i want to know what can i do if there is NO data, i mean, what can i do when it returns NULL, i tried with IF ELSE but still not working, here is the code:
CREATE DEFINER=`root`@`localhost` FUNCTION `vgoles`(`veq` int) RETURNS int(11)
BEGIN
#Routine body goes here...
DECLARE vgloc INT;
DECLARE vgvis INT;
DECLARE vgoles INT;
SELECT SUM(gloc) INTO @vgloc FROM partidos WHERE eqloc=@veq;
SELECT SUM(gvis) INTO @vgvis FROM partidos WHERE eqvis=@veq;
IF @vgloc = NULL THEN
SET @vgloc = 0;
END IF;
IF @vgvis = NULL THEN
SET @vgvis = 0;
END IF;
SET @vgoles=@vgloc+@vgvis;
RETURN @vgoles;
END

Thanks and have a nice day
Answer: The IF @vgloc = NULL THEN does not work as you expect because you can't check NULL with equality (=). NULL is a special value that is not equal to anything, not even to itself.
SELECT (3 = NULL)          --yields--> NULL
SELECT NOT (3 = NULL)      --yields--> NULL
SELECT (NULL = NULL)       --yields--> NULL
SELECT (NULL <> NULL)      --yields--> NULL
SELECT (NULL IS NULL)      --yields--> TRUE

To check for NULL value, you need: IF @vgloc IS NULL THEN.
But you can also use COALESCE() function for further simplicity:
SELECT COALESCE(SUM(gloc),0) INTO @vgloc FROM partidos WHERE eqloc=@veq;
SELECT COALESCE(SUM(gvis),0) INTO @vgvis FROM partidos WHERE eqvis=@veq;

Comment: It worked! Thanks so much!
PD: Since is a function, i cant put an '@' on the parameter variable, that was the other problem, but now it works very good!

IF ELSE with NULL values mysql


How to create a ".gram" file for voice recognition application using CMUSphinx?

Question: I am doing a project for searching a word in a text file using voice. So I need to write a grammar file for few words (min 10).
Can anyone tell me how to write it.
Answer: Grammar file are simple text files which you can create in a text editor, they just describe possible recognition variants, for example open a text editor and type the following:
<code>#JSGF V1.0;

grammar hello;
public <greet> = (good morning | hello) ( nitin | rohit | ajit );
</code>
Then save it as a file with <code>.gram</code> extension and use in cmusphinx. This is a grammar file in JSGF format. You can learn more about JSGF syntax from documentation:
http://www.w3.org/TR/jsgf/
Comment: How to make a grammar file to accept all the dictionary words?
Comment: @NIket for all words you should create Language model with software. Like Srilm. I created from this link. It may help someone. https://hoxuanvinh.wordpress.com/2016/04/22/install-srilm-on-ubuntu/
Comment: @adnan ali: please send download link for windows (Srilm ). http://www.speech.sri.com/projects/srilm/download.html this link are not working.


How to attach a single node multiple times to an entity (e.g. badges)?

Question: For an experimental Drupal 7 site, I would like attach a single node to another entity (this might be users, other nodes or even organic groups). The reasoning is fairly simple, say I have several users active and they can gain badges for activity just like in any stackexchange platform. Each badge is represented by a single node. Now, how could a user get the same badge multiple times?
Using entityreference, I can attach the same reference multiple times, but I am struggling with the output, it will show the same badge multiple times instead of only badge name and a counter. Is there already a module for that I haven't found yet? Can you think of a better way to do it?
Badges might not be the best example as you normally wouldn't lose any. Think of a trading card game might be better, as you can have the same card multiple times and trade it with another user. So, in the end I would need a way to add and remove the references. But this will be custom code, I guess.
EDIT (in answer to Webdrips' comment):
As said in the very beginning, it's just an experiment so far, we are trying to use Drupal in unconventional ways in order to explore the full capacity of Drupal as a framework.
So, I came up with a better example to illustrate what I would like to achieve: let's say I am building a browser game. Game users will be normal Drupal user entities. An user may have several normal fields like health (number), name (text) and gender (list). Additionally, this user can collect items where each individual item type can be found multiple times.
Several players can be in a clan (organic group). This group has a central storage. So, each individual player of that group can place an item in the central storage.
Technically, I need a relation between user and item (for each item type) which also holds the number of items (e.g. Player1 has 5 nails). If he places 2 nails in the central storage, I need to change the relation between user and item (e.g. Player1 now has 3 nails) as well as the relation between organic group and item (e.g. Group1 has 2 nails).
So I am actually looking for a way to connect an item node (e.g. nails) to other entities (users, organic groups, ...) along with an additional value (item count).
I hope this renders my problem/question in an easier-to-understand way.
I've come across the User Points module and for keeping track of game points in my example this might be the right way to go, but imho it's not suited for the item thing.
Comment: Have you looked at the User Points module, and the slew of contributed modules that go with it: https://www.drupal.org/project/userpoints_contrib? There's a module called Userpoints Badges, but you say that's not exactly what you're looking for. Unfortunately, I don't really understand exactly what you're trying to accomplish, so I recommend re-wording your question with a specific example.
Comment: @Webdrips I have added a new section to the question.
Answer: Somehow it kept slipping my attention, I was probably focussed too much on specific ideas, but as it turns out, there is already a module for that, it's simply called Relation.
It's not that straight forward to use (imho), but it essentially creates relations between entities. The created relations are also entities and thus fieldable. By creating a relation type (A [owns] B / B [is owned by] A), I can add a custom field "amount" which holds the information how many Bs are owned by A.
The result (one custom view block added plus a single line of CSS) looks like this.

Answer: Note: The following approach would work but is very custom. Some contributed modules for badges functionality exist and may work for your case, but I have not tried them.
You could still use Entity Reference module and create a custom field formatter for the reference field.
You need to group and count the references that have the same node id, and then pass it to a theme function or template, alongside the fields you want to display of that content type.
For how to create a field formatter for entity reference fields, see both Entity Reference and Examples modules source code. The source code of Entity reference multiple display and Field Extractor contributed modules may help as well.


Dovecot expunge all emails marked as deleted regardless of folder

Question: I would have thought that this would be a FAQ but I haven't found a useful answer.
How do I expunge all email messages deleted using the email client regardless of which folder it's in?
Comment: using [`doveadm`](https://wiki.dovecot.org/Tools/Doveadm/Expunge) this is easy. For a user this question is better suited for [su].
Comment: Thank you for coming back to me.  I did think that doveadm was the answer, although I could not find any reference to help with the search criteria. Thank you for pointing me to Super User. I will look at that
Comment: I restored the answer I wrote originally. I deleted it because I thought I misread your question.
Answer: From a quick glance at the manual, this should do it:
doveadm expunge ALL

This would affect all mailboxes.
To adapt an example from the search-query manual:
doveadm expunge mailbox-guid 44f68b13ce97044b837f000035ca9452 ALL

This would only affect a single mailbox.
Comment: **Danger:** That search query does not include a filter for messages flagged as deleted yet.


Which is the most performant way of overriding views field output

Question: This question sureley can only be answered by people with some drupal experience.
As I have quite different and complex views, which I need to control totally, I need to come to a design decision. Which way has the highest performance putting out view content?

Define the fields in the Views UI, don't output them and use them in custom text? Like described here: http://highrockmedia.com/blog/rewriting-drupal-views-output-custom-theming-css
Provide a views-view-field--field-machine-name-of-field.tpl, get the $row['_field_data']['nid']['entity']->{'field_machine_name'} and iterate over its contents?
Another or better way of which I'm not aware off?

Example, of how a result could look like:

  Dell UltraSharp 30" LCD Monitor

    87
    out of 100
    based on 24 user ratings

    $1250
    to $1495
    from 8 sellers
  Sellers:

     Save A Lot Monitors - $1250

    Jon Doe's Gadgets - $1350

Comment: You can normalise the performance by turning caching on for the View; that will let you choose whichever method you prefer (I'd prefer a template, for example, but you may prefer the UI method)
Comment: @tenken [Views Content Cache](https://www.drupal.org/project/views_content_cache) module is exactly for that problem. It caches the view till a new content of a selected content type added or updated.
Comment: Moreover, you can more precisely clear any cache in a hook or whatever logic you want using [cache_clear_all($cid)](https://api.drupal.org/api/drupal/includes%21cache.inc/function/cache_clear_all/7).
Comment: Have a look at the new kid on the block, [Views Accelerator](https://www.drupal.org/project/views_accelerator). It is for sites that cannot be cached normally, and it has a performance summary on the view so you can do comparisons.
Comment: @Clive maybe i'm being niave but most of my clients expect a "real time" report for like any view ... how can views caching play well with "new content is there and when i goto the page i shouldnt wait for 5 minute intervals (cache effects)"
Answer: I would go for Template based solution for the sake of maintainability and flexibility. For example, if you are using the same field in two different views, you can use a .tpl file that applies to all views that have that field. But if you depend on Views UI, you will have to configure each field in every view separately which may complicate things in the long run. Also, the fewer access to database to retrieve configuration the better.
Comment: Sounds good, thank you. And is the way of going over $row['_field_data']['nid']['entity']->{'field_machine_name'} the way to do? Or is there another approach?


How to find a condition that "decides" the value of a name for an ordinal

Question: In a paper I'm reading involving forcing, the following is used without proof, and it seems to be stated as if it is "obvious," but I don't see why.  It's probably either easy or known, but I might not read the appropriate reference. Can anyone help?
Let $\overline{\alpha}$ be a $P$-name for an ordinal. Then for any $p\in P$ there is a $q\leq p$ and an $\alpha$ in the ground model such that $q\Vdash \overline{\alpha} = \check\alpha$.
(Here $\check\alpha$ is the canonical name).
Answer: Given any $p \in P$, let $G$ be a generic filter for $P$ containing $p$.  Since forcing adds no new ordinals, and as $\overline{\alpha}$ is a $P$-name for an ordinal, there is an ordinal $\alpha$ in the ground model such that $\overline{\alpha}[G] = \alpha = \check{\alpha}[G]$.  By the Forcing Theorem there is a $q \in G$ such that $q \Vdash \overline{\alpha} = \check{\alpha}$, and by extending if necessary we may assume $q \leq p$.
The above both gives the result you are looking for, and, equivalently, proves that the set
$$\{ q \in P : ( \exists \alpha ) ( q \Vdash \overline{\alpha} = \check{\alpha} \}$$ is dense in $P$
Comment: The fact that the set in your first sentence is dense is precisely what I don't see.  I believe that V[G] has no new ordinals, but the "essentially because" is I guess where I'm getting stuck.  Your parenthetical sentence seems to suggest that you're using the forcing theorem: if ã = a is true in V[G] then this fact must be forced.
Comment: By the way, I would upvote your answer if I had enough "reputation" to do so.
Comment: Actually, the two parts work on each other, and perhaps I should rearrange the answer.  Knowing that forcing adds no new ordinals allows you to use the Forcing Theorem to conclude that every $p \in P$ has an extension which decides the $P$-name $\bar{\alpha}$, which then means that the set I defined is dense in the partial order.
Comment: That's exactly what my interpretation was.  Thanks, this helped.
Comment: @Albert: You're welcome!
Answer: This is true because forcing extensions do not add ordinals to the universe. So if we know that $\bar\alpha$ is a name which will be interpreted as an ordinal, it would have be interpreted as some ordinal from the ground model.
Which one may depend on the generic filter, but this really just means that at some point there will be a condition that will decide the value of that ordinal.
To see why forcing does not add ordinals, here is a Boolean-valued model approach Boolean-valued models have no essentially new ordinals.
Comment: Isn't the statement the OP wants proof of just a way to state formally _that_ forcing extensions don't add new ordinals?
Comment: @Henning: I thought so at first, but upon further reflection I felt that there is a delicate difference between the two questions. I gave a link to such proof, anyway.


Edit the classess applied to a field from outside the field template

Question: I am creating my own Panels Style Plugins.
The styles are applied to a Panel Pane which contains a field.
From the Style, I can add a wrapper DIV to modify the display of the field.
However, I would like to be able to modify the actual class on the field itself (this would negate the need for a wrapper DIV).
In my field.tpl.php file I have placed a PHP variable for the class, but I'm not sure how I can access and modify this variable from outside the field.tpl.php file. Could some one give me some pointers.
Thanks!
Answer: Check out Semantic Panels. It lets you choose HTML element and classes for wrapper, the field and the label. The module provides the same options that are available to customize the field output in Views.
Here's a screenshot from the user interface when you customize the field.
Comment: Thanks! Can I use that to manipulate the class from my Panel style (e.g. the class should only be added if the panel style is active). Thanks for any help you can offer!
Comment: Semantic Panels is a style on it's own so yes, it will only add your settings when active.
Comment: it doesn't seem to let you modify the classes applied to fields contained within the Pane. Is that possible, or am I doing something wrong? Thanks.
Comment: Did you choose Semantic panels as style? What settings did you change? Content, wrapper?
Comment: It seems that module only adds a wrapper with the class to the field. It doesn't add it to the actual field.  e.g. `` would become `` instead of ``
Comment: Yes if the field content itself contains that a tag you can not modify it. It's the same functionality as Views provides basically.
Answer: You should be able to it via hook_preprocess_HOOK . Try to dpm($vars), classes should be one of them, you will then be able to change it.
Comment: Thanks for your help, but I'm not quite sure how to use this. I tried panels_preprocess_HOOK & panels_preprocess_field in my Panel Style, but this didn't do anything. I then tried panels_preprocess, which displays an array, which has a theme_hook_suggestion field of `panels_pane__entity_field` and `panels_pane__entity_field__node:field_call_to_action`. However, neither of these work. Also, once I have made a class for my field, how do I get it to display in field.tpl.php (the class should only appear when the panels style is in use).
Comment: are you doing the style in a module ?
Comment: It's a panels plugin which I have put in my theme (as apparently panels plugins go in the theme folder).  Thanks for any help you can offer!
Comment: then the hook name should start with your theme name : YOUR_THEME_preprocess_field
Comment: Thanks for your help! That works, but it effects all fields. I only want to target one field (called `call to action`). When I use `YOUR_THEME_preprocess_field` it gives the following theme_hook_suggestions: `field__field_call_to_action`  ,  `field__field_call_to_action__content`. I have tried prefixing each of these with `THEMENAME_preprocess_field` ,  `THEMENAME_preprocess_`  and  `THEMENAME_field` but it seems to have no effect. Thanks for any guidance you can offer, I really appreciate your help!
Comment: i think that you will either have to check the field name in the general field hook ($vars['element'][#field_name] == 'field_call_to_action'), or add the field to the theme registry
Comment: Thanks! How do I add a field to theme registry. I tried searching for tutorials but couldn't find anything. Also, once it is added, how do I access it from field.tpl.php
Answer: You should be able to use preprocess_panels_pane(). I use it to remove the default classes from Panels.
<code>function THEME_NAME_preprocess_panels_pane($vars) {
  $content = $vars['output'];
  // basic classes
  $vars['classes'] = '';
  $vars['id'] = '';

  ctools_include('cleanstring');

  // Add id and custom class if sent in.
  if (!empty($content->content)) {
    if (!empty($content->css_id)) {
      $vars['id'] = ' id="' . $content->css_id . '"';
    }
    if (!empty($content->css_class)) {
      $vars['classes'] .= $content->css_class;
    }
  }

  // administrative links, only if there is permission.
  $vars['admin_links'] = '';
  if (user_access('view pane admin links') && !empty($content->admin_links)) {
    $vars['admin_links'] = theme('links', $content->admin_links);
  }

  $vars['title'] = !empty($content->title) ? $content->title : '';

  $vars['feeds'] = !empty($content->feeds) ? implode(' ', $content->feeds) : '';
  $vars['content'] = !empty($content->content) ? $content->content : '';

  $vars['links'] = !empty($content->links) ? theme('links', $content->links) : '';
  $vars['more'] = '';
  if (!empty($content->more)) {
    if (empty($content->more['title'])) {
      $content->more['title'] = t('more');
    }
    $vars['more'] = l($content->more['title'], $content->more['href'], $content->more);
  }
}
</code>
Comment: Thank you so much for your help! How do I make it work so only my Panel style creates the variable that can then be passed into my field.tpl.php file. If I use `THEME_NAME_preprocess_panels_pane($vars)`, it will make all Panel styles effect the output and not just my current style. Thanks for any help you can offer.
Comment: It seems I misunderstood exactly what you were trying to do... This might be an odd question but are you using theme_PLUGINNAME_STYLENAME_style_render_pane()? Can you not access it from there?
Comment: No, the only one that seems to work is  `panels_preprocess()`.
Answer: Seeing as it's just a field that you're trying to alter, have you tried the Field Formatter Class module?

This module allows site administrators to add classes to the outer
  HTML wrapper for any field display.
Classes can be specified at the Manage display settings for content
  types, users and other entities.

On a side note, the Fences module doesn't add classes to your fields, but it is WELL worth knowing about if you want to reduce the markup/div soup that Drupal adds.
Comment: This module seems to change the class on the field, but it effects all fields and not just the one that has my panel style.


Spring Security Oauth + Firebase

Question: Boa tarde.
Estou implementando a camada de segurança da minha aplicação.
Decidi que vamos utilizar o Firebase para realizar a autenticação, e quando o mesmo retornar o token de acesso para o cliente ele enviará esse token para o meu servidor Java que vai verificar no Firebase se o token é válido e ai retornar um token da minha aplicação para o Cliente.
A minha dificuldade é na implementação no meu servidor Java. Como eu recebo esse token(sei fazer com usuário e senha, por exemplo, mas não recebendo o token) no Spring Security Oauth, faço a verificação no Firebase(já sei a implementação dessa verificação) e se correr tudo bem retorno o token pro cliente?
Answer: Talvez seja legal você usar o Firebase Queue pra executar esse tipo de tarefa complexa. Tava escrevendo sobre ele hoje mesmo pro meu time. Se liga só:
O Firebase Queue é um módulo do Firebase que nos permite criar quatro elementos que solucionam o escalonamento da nossa plataforma de uma maneira que os desenvolvedores do Plone não poderiam imaginar nem em seus sonhos mais molhados. Uma "Queue", ou fila, é um lugar no banco de dados em que você joga tarefas para serem completadas. O ciclo de vida de cada Queue é fundamentado em quatro conceitos principais: task, worker, spec e job.
Cada "task" é uma tarefa representada como um objeto no banco de dados e ela pode ser processada por um worker.
"Workers", ou trabalhadores, são processos que ficam esperando por tasks que são adicionadas no banco de dados. A cada tarefa adicionada, os workers observam o spec da task e decidem se vão ou não tentar processá-la. O primeiro worker que começar a trabalhar rouba a task para si e nenhum outro worker pode interferir nela até que ele a tarefa esteja completa ou retorne um erro.
O "spec" é uma definição das coisas que a task faz em relação a outras tasks. Você pode definir ligações entre as tasks como "quando completar a task X, inicie a task Y" ou "inicie a task X com estes parâmetros aqui".
"Job" é um conjunto de specs que definem uma série de operações a serem executadas em ordem.
Para saber como implementar tudo isso, é só ler o guia oficial em https://github.com/firebase/firebase-queue/blob/master/docs/guide.md

Spring Security Oauth + Firebase


Get the minimum value of array with the following code

Question: I don't really understand the logic of the following:
$max = array_reduce($values, function($max, $i) {
    if (is_numeric($i) && $i > $max) {
        return $i;
        //echo $i."max";
    }
    return $max;

});

This will return the maximum value in array. How I can modify the above code to return the minimum value as long is numeric? This will help me understanding how this works. i am aware or min and max functions.
Thanks in advance
Comment: Great thanks a lot. Not sure how to mark the question as answered :)
Comment: there is a check mark under the up/down voting arrows.
Answer: You should break down code then and learn to debug what you have. This is a pretty straight forward piece of code:
// array_reduce — Iteratively reduce the array to a single value using a callback function
//A callback is literally a function that is called for the logic and is started at function
//$values is your values, max is what was run from the last iteration and i is the current value.
$max = array_reduce($values, function($max, $i) {
    // Checking the value is numeric
    // AND
    // $i is greater than $max
    if (is_numeric($i) && $i > $max) {
        //  If the above is true you have a number greater than the current
        //  max value return this iteration value.
        return $i;
        //echo $i."max";
    }
    // It will only reach here is the above is not true so return what was the max
    // example max = 5 i = 2 you will return 5
    return $max;
});

So you need to find what logic get the max in that which is this logic:
if (is_numeric($i) && $i > $max) {}

Now how can you make it the min well > is greater and < is less so:
if (is_numeric($i) && $i < $max) {}

would do the trick (kind of there is a bug) but is confusing because you call the var max personally I would re-write like this:
$min = array_reduce($values, function($min, $value) {
    //Has to check for a null min sets min to value if smaller
    if ((is_numeric($min) && $value < $min) || $min == null) {
        $min = $value;
        //echo $value."min";
    }
    return $min;
});

Answer: the following code gets the job done. it compares the value of two positions in the array, deletes them and then stores the minimum value. thus reducing size of array by one in each step and continues repeating the procedure till array size becomes 1.
$mn = array_reduce($values, function($mn, $i) {
    if (is_numeric($i) && $i < $mn) {
        return $i;
        //echo $i."mn";
    }
    return $mn;

});

Comment: Include some explanations to your code. How does this help OP understand? That is the goal of OP, to understand and you just dump code. That is not a good answer.
Comment: added explaination.
Answer: $min = array_reduce($values, function($carry, $i) {
    if (is_numeric($carry) && $i > $carry ) {
        return $carry;
    }
    return $i;

});

Comment: Include some explanations to your code. How does this help OP understand? That is the goal of OP, to understand and you just dump code. That is not a good answer.
Comment: Not only is there no explanation but this answer doesn't actually work.
Comment: All answers on SO should hava en explanation.
Comment: @Nick It does work. It sets $min to the smallest number in the $values array. I've tested it twice now. In addition, the OP asked, "How can I modify the above code...This will help me understanding [sic] how this works." OP asked for modified code, not an explanation.


Proofs about a group property

Question: I have a set $B$,and for $b$ belonging to $B$,there exists a reverse $b$.
Is it enough if I prove this to be true for $1$ element of the set, then it must be true for the whole set of $B$, or must I prove this property $\forall x$ that belong to $B$.
Comment: This is not clear.  If you need to show a property holds for every element in some set, then that's what you need to show.  In general, it would not be enough to check one element.  Is that what you were asking?
Comment: Well, just think about it in common sense terms...If I assert that every shirt in my closet is yellow, it would not suffice to check one shirt and confirm that it is yellow.
Comment: Yes that is what i was asking.Thanks
Answer: If you want to show that $B$ is a group, you need to show that every element of $B$ has an inverse.
You need to be able to calculate with any group element, so every element must have the basic properties given in the group axioms.

Proofs about a group property


CodeIgniter: Sessão recriada após o recarregamento da página

Question: Tenho um sistema aonde uma sessão é criada para o usuário após o seu login, o problema é que cada acesso que faço ao site uma nova sessão é criada e os dados gravados são apagados, configurei a sessão como autoload e as configurações são:
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'nomequalquer';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

esse é o código de login:
$user = $this->user_model->doLogin($_POST);
if($user != false){
    $this->session->set_userdata(array('logged' => true, 'user' => $user));
    $_SESSION['sess_id'] = session_id();
    echo json_encode(array('1', $_SESSION));
}else ...

Envio os dados da sessão para gravar eles no console do chrome, o redirectionamento é feito aqui:
...
function(data, status, jqXHR){
    if(status == 'success'){
        ...
        var result = JSON.decode(data);
        //debugging
        console.log(result[1]);
        //redirecionamento
        windows.location.replace = <?php echo "'" . base_url(array('admin/usuarios')) . "'"; ?>;
        ...
    }
}
...

Na página some/page eu coloquei um botão que acessa o seguinte código no servidor:
$_SESSION[session_id()] = 'hello!';
var_dump($_SESSION);

é possível ver que o id da sessão se altera a todo momento e os dados inseridos no login não existem mais. Qual seria o motivo disso?
Comment: pq vc mistura a sessão do php padrão com a do CI?
Comment: porquê na documentação diz que eu posso fazer assim...
Answer: Esse é o segundo dia com esse problema, a única solução que eu encontrei foi utilizar a biblioteca nativa do php, copiei essa library: Native session que faz uso dela, além disso ela é mais apropriada pro meu caso porque não salva as informações no computador do usuário.


Is it possible to run a single Android CTS test case from Eclipse?

Question: I am currently dealing with some CTS issues for our own device. It comes to my mind that if we can run a single CTS test case just from Eclipse, that would be very helpful for debugging the CTS issues.
For example, I have create an Android test project, with the manifest file:
<code>    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="android.content.pm.cts"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="android.content.pm" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <uses-library android:name="android.test.runner" />
    </application>

</manifest>
</code>
And the source code:
<code> package android.content.pm.cts;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.ResolveInfo.DisplayNameComparator;
import android.test.AndroidTestCase;

public class ResolveInfo_DisplayNameComparatorTest extends AndroidTestCase {
    private static final String MAIN_ACTION_NAME = "android.intent.action.MAIN";
    private static final String SERVICE_NAME = "android.content.pm.cts.activity.PMTEST_SERVICE";

    public void testDisplayNameComparator() {
        PackageManager pm = getContext().getPackageManager();
        DisplayNameComparator dnc = new DisplayNameComparator(pm);

        Intent intent = new Intent(MAIN_ACTION_NAME);
        ResolveInfo activityInfo = pm.resolveActivity(intent, 0);

        intent = new Intent(SERVICE_NAME);
        ResolveInfo serviceInfo = pm.resolveService(intent, PackageManager.GET_RESOLVED_FILTER);

        assertTrue(dnc.compare(activityInfo, serviceInfo) < 0);
        assertTrue(dnc.compare(activityInfo, activityInfo) == 0);
        assertTrue(dnc.compare(serviceInfo, activityInfo) > 0);
    }
}
</code>
When I right click on the project and select "run as android junit test" it just report: Test run failed: Unable to find instrumentation target package: android.content.pm
I know that I might be totally wrong from the beginning. So could anyone please point out a correct way out for me?
Thanks a lot!
Answer: The error you are seeing is because the android OS cannot find an application installed with the package "android.content.pm" and eclipse does not know about the project in order to install it for you, install the application you want to test (and check its package is in fact android.content.pm which it probably isn't because that is a system package and you will not be able to instrument against that because your debug signature is not the same)
Comment: Yes, after these days I think your explanation is quite reasonable. Thanks.


How to store data in a node in vis.js?

Question: Can you help me please ? I don't know how to put some data in a node in the vis.js library (Javascript)
The only properties I know are "id", "date", "label", "title", "image", "x", "y" but there is no property for storing datas (like user's username, age, etc. if my node represent an user)
At the moment, I store the data's in an input type="hidden" in the title property... But I don't know if there is a cleaner way to do it.
(Sorry if my english is not so good)
Answer: Finally i found how to do that. Simply add the property :
<code>nodes.push({
    id:xxx,
    shape: xxx,
    image: xxx,
    label: xxx,
    title: xxx,
    property_1:xxx,
    property_2:xxx,
    property_3:xxx,
    ...,
    property_n:xxx
});
</code>

How to store data in a node in vis.js?


How to check some condition every 1 sec in java until true

Question: I need to check certain condition in java every 1 second until it is true.Once it is true, need to exit from it and proceed further.
Say a->b->c
check b every 1 sec until it is true, if it is true go to c.
Could someone suggest what is the best possible way to achieve this in Java?
Comment: Try reading up on TimerTask.
Comment: Can i use like this while(!b) { try { Thread.sleep(1000) } catch catch(InterruptedException ie) {} ;}
Answer: Here is what you need:
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(!condition)
                    handler.postDelayed(this, 1000);
                else {
                    // do actions
                    condition = true;
                }
            }
        }, 1000);
    }

Answer: I think you should take a look at the Timer and TimerTask classes. You can use them to schedule certain tasks to take place after a certain amount of time.
You need to extend the 'TimerTask' class and override the run() method. For example, you could do something like this:
Here's an example, which prints Hello World every 5 seconds: -
class CheckCondition extends TimerTask {
    public void run() {
       // if some condition is true
          // do something
    }
 }

Used from another method, which checks your condition once every second (the function takes milliseconds):
Timer timer = new Timer();

// timer.schedule(class, initial delay, interval in milliseconds)
timer.schedule(new CheckCondition(), 0, 1000);

Answer: One option is using the Handler's postDelayed() method:
// do something A

do {
    // Execute some code after 1 second has passed
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            // do something B
        }
    }, 1000);
}
while(condition);

// do something C


How to apply integrals and derivatives in physics?

Question: We have learned how to count integrals and derivatives in maths and we were told we would use this in physics but how do I know when to use integral and when I should differentiate? I know that integral is an area under the curve, but how do I know what the area represents? for eg how do i know that when i make a graph of dependence of velocity on time, that the area under the curve is the $s$ and that the derivative would be $a$?
Answer: You'll know from context once you've learned a bit more of the subject. One common trick is dimensional analysis. For example, do you think we get velocity by differentiating or integrating position with respect to time? Well, since $v$ has the units of $x/t$, it has the units of $dx/dt$. Similarly, $x$ has the units of $vt$, i.e. those of $\int v dt$. Oh, look! Differentiating $x$ gives $v$; integrating $v$ gives $t$. The reverse would be dimensionally inconsistent. That $a=dv/dt$ as opposed to $v=da/dt$ follows similarly.
Comment: "Oh, look!" :) (+1)
Comment: I think this is example is doubtful. It's bad, if you want to be rigorous, because the velocity is defined as $\dot{r}$. However, it really shows the power of the dimensional analysis. (+1)
Comment: @Botond Anyone who felt the need to ask which way the derivative goes is less likely to get that point than they are to remember velocity is measured in metres per second, or that the constant-velocity special case gives $x=vt$.
Comment: @J.G. Yes, I know. That's why I said that it's a great example at the same time. But I thought it's worth to mention. :)


Running multiple docker containers in same host

Question: I am new to docker. I have a doubt regarding docker. Based on the understanding of docker, Docker will help to create the container of the application we can to deploy along with application dependencies.
My question is that if i have web application inside docker container, is it possible to run multiple containers inside single host? If yes, How will i make sure the request be directed to each app?.
Will there be any change in performance depending on number of core of host?
Answer:
Is it possible to run multiple containers inside single host?

Yes, you can run many.

If yes, How will direct requests to the right container?

You have many options, the simplest is just to run the container with port forwarding (which is built in to docker), but you could also run a load balancer or proxy on the host.

Will there be any change in performance depending on number of core of host?

There can be, of course. It depends on whether or not you're already reaching a performance bottleneck of some sort before adding another container. All the containers are making use of the same hardware.


servicestack syncreply removed, not backwards compatible?

Question: We're in the process of upgrading to servicestack v4 and noticed that the default "SyncReply" route was removed in favor of "Reply".  We have customers who are actively using these endpoints in our services.  What is the recommended way to achieve backwards compatibility for these customers, without having to manually register the routes for each content-type+service?
Answer: You can use v3 clients that point to a v4 server by using the UseNewPredefinedRoutes property, provided that the over-the-wire interface stays the same. As you're aware v4 has changed the built in routes, and by setting the above mentioned property the v3 clients will use the new v4 routes.
<code>var client = new JsonServiceClient("http://...");
client.UseNewPredefinedRoutes = true;
</code>


How to display nodes only after certain dates? (An Advent calendar is in progress)

Question: I'd like to build an Advent calendar with Drupal 7 as a warm-up exercise.
What would be the recommended way to protect future calendar entries from being accessed before their time?
I have 3–5 different content types to be used as calendar entries.
Everything should be accessible to anonymous users as well, so I only need to check the current date.
Answer: We have a client who uses the Scheduler module for their blog.  They write a backlog of posts, and then post date them for when they want them to appear.  You should be able to use this.  Make nodes for all of the days, and date them for when you want them to appear.  As long as you have cron workng properly, nodes should appear when they should.
Another option is to use the Date module along with Views.  Make a content type with a date field.  Set the date field to the day you want it to appear.  Then make a view over that content type, and add a filter to compare the date field against the current day.
Of the choices, I would go with Scheduler.
Answer: Try the Calendar module. Crete in each of your five content types fields for date and type and Calendar should automatically hitch data from this fields and show it on calendar. Think that this is the pimpliest way to create references between own content type and events.


Resolução de conflitos com o Meldmerge (Git, Github)

Question:
A ferramenta não me permite subir as alterações do arquivo do meio, são essas as alterações novas que eu preciso comitar, mas ele não está indo, é justamente essa alteração que "ele quer" sobrescrever com uma das duas ao lado, que são desatualizadas.
Como proceder?
Isso ocorreu quando eu tentava fazer um merge da branch que criei para a master $ git checkout MinhaBranch
$ git merge master
Também tentei o inverso, da master para a minhaBranch, e continua o mesmo conflito.
Comment: Consegui resolver. Antes eu abria o arquivo com: `$ meld NomeDoArquvo` e por isso não tinha permissão para alterar os arquivos da *remote* e *local*, então configurei o *mergetool* e digite:

`$ git mergetool`

Pronto! a cada pergunta no terminal, eu dava enter e abria o meld no arquivo de conflito e conseguia prosseguir.
Answer: O problema foi causado por abrir o meld incorretamente, assim ele não "possuia permissão" para alterar os arquivos da local e da remote.
Após configurá-lo, digitei:
$ git mergetool
E o meld inicia em cada conflito normalmente.
Para configurar o mergetool:
git config --global mergetool.meld
Comment: Caso resolvido marque como resolvido assim fica mais facil


Como resolver um Notice: Undefined index?

Question:

Iniciando em PHP e seguindo um tutorial usei o código acima e acabei recebendo este erro:

Notice: Undefined index: submit in C:\wamp\www\mezzo-com\reservas.php on line 3

Como resolvê-lo?
Comment: Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: Como está o formulário que chama o C:\wamp\www\mezzo-com\reservas.php?
Ele precisa ter um botão sendo postado que mande informações para o script PHP. Deve ter algo como:
<input type="submit" value="Submit" name="submit">

Na verdade é possível que você tenha problemas com outros campos (name, mail, age, people, etc.) Sem conhecer a página que chama o script fica complicado dar informações mais precisas. Mas é possível que você sequer esteja submetendo um formulário e chamando o script PHP direto. Ou está chamando mas enviando com GET ao invés de POST. Deve existir algo como:
<form action="reservas.php" method="post">

Mas se você estiver chamando o script em um contexto em que estes dados não estão disponíveis, aí você precisa fazer com que o acesso ao elemento não aconteça trocando seu if na linha 3 para:
if (isset($_POST["submit"])) {

Coloquei no GitHub para referência futura.
Assim você verifica a existência da variável e seu índice sem tentar acessar seu valor, até porque o valor dele não é importante e sim sua existência. Você estará verificando se a operação pode ser feita antes de deixar a falha ocorrer.
Answer: Esse erro indica que não há um valor na sua variável $_POST com o nome "submit". Ou seu formulário não incluiu esse campo, ou a requisição não é um POST (não estou certo quanto a essa segunda possibilidade, pois não tenho experiência prática com PHP).
Verifique o formulário que chama essa URL. Mas se quiser tornar seu código mais robusto, você pode verificar se a chave existe antes de usá-la, através da função array_key_exists ou isset (o segundo também checa se o valor é nulo):
if (array_key_exists("submit", $_POST)){    // Entra se "submit" existe

if (isset($_POST["submit"])){               // Entra se "submit" existe e não é null

Answer: O problema é a falta do campo submit no seu form.
Certifique-se de que o método do form está como POST, caso contrário, o html por padrão usará GET.


Finding Euclidean distance between two list

Question: list1=[(1116.7983351235232, 1311.3754027926993), (1116.7983351235232, 1218.42998120301), (1116.7983351235232, 1125.4845596133205), (1116.7983351235232, 1032.539138023631), (1116.7983351235232, 939.5937164339416)]

list2=[(1215.7983351235232, 1315.130773361976), (1215.7983351235232, 1223.1241944146077), (1215.7983351235232, 1131.1176154672394), (1215.7983351235232, 1039.111036519871), (1215.7983351235232, 947.1044575725027)]

For the above list, I want to find the Euclidean distance between a point in list1 and all the points in list2.
Here, I want to find the min distance from the point in list1 to all the points in list2.
Could any one suggest what is the best way to work on it?
i tried out
for i in list1:
     for j in list2:
         list3=min(sqrt(i,j))
            print(list3)

I am getting error as
  AttributeError: 'Tuple' object has no attribute '_eval_power'
Comment: Have you tried anything yet? Where exactly are you stuck?
Comment: please add details about: your desired goal, expected and actual results of your code + error messages. Describe, what you have tried and show your code.
Comment: You can't just call `sqrt` with two tuples and expect it to work. What would `sqrt((1, 2), (3, 4))` even mean?
Answer: I propose doing this step by step:
First, write a function that calculates the euclidean distance between two points. We can do this by using Pythagoras' theorem on the distance between their respective components:

from math import sqrt

def distance(x, y):
    a, b = y[0] - x[0], y[1] - x[1]
    return sqrt(a**2 + b**2)

Now you can loop over all combinations of points and return all distances. I'll use a generator to do that:
def all_distances(one, two):
    for point_a in one:
        for point_b in two:
            yield distance(point_a, point_b)

Finally, it all falls into place:
>>> min(all_distances(list1, list2))
99.07120069986327

So the minimum distance is (very close to) 99.
Comment: Thanks you, Instead of yield can i return the function.
Comment: Why would you want to return the function?


What is $\beta$ doing exactly in Python's Holt's Forecast Method (Double Exponential Smoothing)?

Question: I am using Holt's Method for forecasting timeseries and try to understand what $\alpha$ and $\beta$ are doing.

$\alpha$ for level control is fine for me: if it's $0$, it's like a normal mean and all observations are equally weighted.
If $\alpha=1$, than it is the naive method, and the last observation will be choosen for next prediction.
This are the two extremes in the interval $[0,1]$.
So now, $\beta$ is controlling trend of the timeseries. But what does this exactly mean?
What happens if I choose $\beta=0$ or $\beta=1$? Is it taking the slopes and then doing the same like with $\alpha$ like when I choose $\beta=1$ it does only consider the last slope?
Thank you in advance, guys!
Comment: $\alpha=0$ looks to me as if it is saying the previous estimated level plus the previous estimated change, without adjusting for the most recent observation
Answer: $\beta =0$ gives $b_t=b_{t-1}$ so the trend, the underlying rate of change, is assumed to stay constant over time
$\beta =1$ gives $b_t=\ell_t - \ell_{t-1}$ so the next change is assumed to be at the rate of the last change, or as you say "the last slope"
Comment: Thank you very much!


HTML CSS: Change the Bootstrap Tooltip Shape

Question: Right now the Bootstrap tooltip looks like this, How do I remove the cartoon bottom triangle, and make it just a regular rectangle?
Currently:

Goal:

https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_tooltip&stacked=h
Original Code:
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

Tooltip Example

  Hover over me

Answer: Use display: none to .tooltip .arrow

$(document).ready(function() {
  $('[data-toggle="tooltip"]').tooltip();
});
.tooltip .arrow  {
  display: none!important;
}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

  Top
  Right

Comment: tell me for more help


Routing table connected entries different than interface assigned IP address

Question: I have a HP ProCurve A7102DL router which has eth1 and eth2 interfaces. I currently have eth1 set as my WAN and eth2 as my LAN side. My eth2 has three IP address assigned to it which are A.A.A.1, B.B.B.1, & C.C.C.1. The LAN side IP addresses all show up in the routing table correctly as A.A.A.0 255.255.255.0 and so on. My eth1 address is my static IP assigned by my ISP. The IP they assigned is X.X.X.252 with a subnet of 255.255.255.248. That connection shows up in my routing table as X.X.X.248. I was wondering why it is changing the IP address of the connected interface and if this is something I should be concerned with.
Answer: The routing table is showing the network-ID, not the interface IP address. (Same as your first case, where your ip is a.a.a.1 and network is a.a.a.0/24).
For example:
<code>$ ipcalc 10.0.0.252/29
Address:   10.0.0.252           00001010.00000000.00000000.11111 100
Netmask:   255.255.255.248 = 29 11111111.11111111.11111111.11111 000
Wildcard:  0.0.0.7              00000000.00000000.00000000.00000 111
=>
Network:   10.0.0.248/29        00001010.00000000.00000000.11111 000
HostMin:   10.0.0.249           00001010.00000000.00000000.11111 001
HostMax:   10.0.0.254           00001010.00000000.00000000.11111 110
Broadcast: 10.0.0.255           00001010.00000000.00000000.11111 111
</code>


SQL error while inserting data in Derby DB

Question: I am getting this:

SQLDataException:"java.sql.SQLDataException: An attempt was made to get a data value of type 'VARBINARY' from a data value of type 'BLOB' at org.apache.derby.client.am.SQLExceptionFactory.getSQLException(Unknown Source) ~[derbyclient-10.12.1.1.jar:na]"

I would appreciate if anyone has insights on this.
Comment: Show use your Java code and the `create table` statement of the table.
Comment: Hello a_horse_with_no_name, thank you for your response. Issues is solved by @LOB annotation in DAO. Thanks.
Answer: This is issue is resolved after doing following:
<code>@Basic
@Column(name = "PARSED_DATA")
@Lob
public byte[] getParsedData() {
    return parsedData;
}
</code>
Since, table column is BLOB type.This is only issue with Derby.


Why is the distance equal to the height between these two circles?

Question: I have a follow up question for a previous question linked here:What is the equation for the distance between these two circles?
In that question asked for an equation to find the distance between the a random point in the green circle's perimeter and the point on the blue circle that the perpendicular line of the tangent line of the green circle's point intersects(The circles I am talking about are in the last two images.). I found a pretty good answer but later found a better solution.
Well after finding the solution I started trying to find the correlation between the point in the green circle's y-coordinate and the distance. And I found that they are the exact same. To show that, that means the purple line and the black line in the image at the bottom of this question are equal.
My question is why. Why are they equal? Is there something that already shows this correlation if so what is it?
I know a lot of people are probably going ask for the equations I used and stuff, and if you want it is in the other question. I don't think the reason is going to be found in deriving the equation though.
For example the Pythagorean theorem of a squared plus b squared equals c squared. Lots of people know the formula and can see it's true, but a lot of people don't know why it's true. But after some close analysis of the square below, you can see why it is true.
Comment: Call the origin $O$. Let $P$ be the upper point ($(0,12)$ in your figure); let $B$ and $G$ be the points on the blue and green circles, respectively; let $F$ be the foot of the perpendicular from $G$; and let $M$ be the midpoint of $\overline{OG}$. Do you know why $\angle OBP$ is a right angle? From there, consider right triangles $\triangle PMG$, $\triangle OBG$, $\triangle OFG$: they're all similar, and the last two are in fact congruent. The result follows.
Answer: Let the equation of the green circle be $r=R$, and the equation of the red circle be $r=R \,\cos  \theta$.
Let the point $A$ on the big circle be  $(R\,\cos\theta,R\,\sin\theta)$.
Then the magnitude of the segment $AB$ will be $R-R\,\cos \theta$, and the perpendicular dropped from $A$   to the line $x=R$ will have magnitude $R-R\,\cos\,\theta$.
Comment: This is super smart. Thank you so much. How did you figure out that the distance from the origin to B was equal to R cos ? I wish I had knew that when I was trying find out the equation to my previous question before this. That one was super long and complicated. You just shrunk it down to 12 - (12 - y) = AB. Thank you so much.
Comment: $r=R\cos\theta$ is the equation of that circle (the small circle) in polar coordinates. If you convert to Cartesian coordinates in the usual way you will see this equation has the form for a circle with radius $\frac{R}{2}$ and center at $\frac{R}{2}$.


Projection operator: why squared norm of the sum of them is equal (or smaller) than the sum of the squared norms?

Question: I am working through the proof of Lemma 2 in this paper (page 25, need it for my own research) and I am stuck at the very first step. Here, I will formulate a bit simplified version of this step.
Suppose we have a causal and stationary error process $\{\mathbf{X}_t\}_{t}$ which can be represented as $ \mathbf{X}_{t} = \mathbf{H}(\ldots,u_{t-1},u_{t})$ with $u_{t}$ being i.i.d. random variables and $\mathbf{H} := (H_{1}, H_{2}, \ldots, H_{d})^\top: \mathbb{R}^\mathbb{Z} \rightarrow \mathbb{R}^d$ being a measurable function such that $\mathbf{H}(\ldots,u_{t-1},u_{t})$ is well defined. Denote $\mathcal{I}_{t} = (\ldots,u_{t-2},u_{t-1}, u_{t})$.
Define a projection operator as
\begin{align*}
&\mathcal{P}_{t}(\cdot) := \mathbb{E}[\cdot|\mathcal{I}_{t}] -\mathbb{E}[\cdot|\mathcal{I}_{t-1}],
\end{align*}
We are interested in the following quantity:
\begin{align*}
\kappa_{s}^{\mathcal{P}} := \frac{1}{T}\sum_{t=1}^T \mathcal{P}_{t-s}( \mathbf{X}_{t}),
\end{align*}
or, more precisely, in $||\kappa_{s}^{\mathcal{P}}||^2$ where $||\cdot||$ denotes a usual $L^2$ norm.
The author states that
\begin{align}
||\kappa_{s}^{\mathcal{P}}||^2 &= \Big|\Big| \frac{1}{T}\sum_{t=1}^T \mathcal{P}_{t-s}( \mathbf{X}_{t}) \Big|\Big|^2 \\
&\leq \frac{1}{T^2} \sum_{t=1}^T \Big|\Big| \mathbb{E} \big(\mathbf{X}_{t}|\mathcal{I}_{t-s}\big) -\mathbb{E} \big(\mathbf{X}_{t}|\mathcal{I}_{t-s-1}\big) \Big|\Big|^2, \tag{1}\label{eq1}
\end{align}
and I just can't get my head around it. It is not neither a triangular inequality, nor Jensen's inequality, and I just do not know how to get there.
Apparently, this type of proof strategy is quite common in the literature, but the only explanation I could find is something like the one here (the end of the proof of Lemma 3, page 528), where they state that $\mathcal{P}_{t-s}(\Delta_t) $, $1 \leq t \leq T$, are martingale differences, hence, the inequality I am interested in is actually an equality. But as I am not an expert in stochastic processes, I also feel a little lost with this reasoning...
To summarise, my questions are as follows:

Can somebody explain me how the author got \eqref{eq1}?
If it is the consequence of the series of projection being a martingale difference sequence, are there any restrictions on the process $\mathbf{X}_t$ such that $\mathcal{P}_{t-s}(\mathbf{X}_t)$ is one?
This one is probably very simple, but still. Suppose $\mathbf{X}_t$ satisfies some property (from 2.) such that $\mathcal{P}_{t-s}(\mathbf{X}_t)$ is a martingale difference sequence. Then how can we get $\big|\big| \frac{1}{T}\sum_{t=1}^T \mathcal{P}_{t-s}( \mathbf{X}_{t}) \big|\big|^2 =  \frac{1}{T^2} \sum_{t=1}^T\big|\big|  \mathcal{P}_{t-s}( \mathbf{X}_{t}) \big|\big|^2$? Which of the properties for mds we should use in order to obtain this equality?
Answer: Will reference the book Stochastic Limit Theory (SLT), 2021, Davidson.
Assuming $E[|X_t|]<\infty$ then $\mathcal{P}_{t-s}(X_t)$ is a martingale difference sequence in $t$ (pg 316 SLT).
This means that by Theorem 16.6 (SLT) that
$$\text{Cov}(\mathcal{P}_{t-s}(X_t),\mathcal{P}_{u-s}(X_u))=0 \;\;\; \text{for $u\neq t$}.$$
Also $E[\mathcal{P}_{t-s}(X_t)]=E\left[E[X_t|\mathcal{I}_t]-E[X_t|\mathcal{I}_{t-1}] \right]=E[X_t]-E[X_t]=0$.
Then we can just write
$$\begin{align} ||\sum_{t=1}^T\mathcal{P}_{t-s}(X_t)||^2&=\text{Cov}\left(\sum_{t=1}^T\mathcal{P}_{t-s}(X_t),\sum_{t=1}^T\mathcal{P}_{t-s}(X_t)\right)\\ &= \sum_{t=1}^T \text{Cov}\bigg(\mathcal{P}_{t-s}(X_t),\mathcal{P}_{t-s}(X_t)\bigg)\\&=\sum_{t=1}^T ||E[X_t|\mathcal{I}_{t-s}]-E[X_t|\mathcal{I}_{t-s-1}]||^2\end{align}$$


Show that $A_5 $ intersection with $im(f) $ is not $\{e\} $

Question: I'm not sure how to continue my proof:
Let $G$ be a simple group of order 60.
Suppose $H \le G $ is of index 5. i want to show that $G  $ is isomorphic to $A_5 $
I have homomorphism $f : G \to S_5 $ , $ ker(f) = \{e\}$ so $G  $ is isomorphic to $im(f) $.
Now i know that $ im(f) \le S_5$ simple and of order 60.
i also know that $A_5  $ is normal in $ S_5$ so the intersection of $A_5$ and $ im(f)$ is normal in $im(f) $.
$im(f) $ is simple , so this intersection is either $\{e\} $ or $ im(f)$.
I want to show that it is impossible that the intersection is $ \{e\} $ but im not sure how.
EDIT:
After some thinking , the answer for this question is not that hard. I added my own answer for it.
Comment: So post your own solution as an answer!
Comment: Why do you want to delete it???
Comment: You shouldn't delete your question because you solved it. Like @SteveD mentioned, you're welcome (and even encouraged) to post your own solution as an answer. Perhaps another user will come up with another way of solving this, which may also be of interest to you. And finally, leaving the question and answer helps anyone else with the same question!
Comment: @SteamyRoot i did write my answer. next time, ask the owner of the post if he could edit it back, and dont just modify it.
Comment: @SteveD i did it .
Comment: @Liad All I did was a "rollback" to before your edit that essentially removed the question, which is [the recommended action to take](http://meta.stackexchange.com/questions/209436/self-vandalism-what-is-correct-action) in case of *self-vandalism*. I did not "modify" anything.
Answer: Hint:
Prove that for any $\;H\le S_n\;$ such that $\;H\lneq A_n\;$ , exactly half the elements of $\;H\;$ are even permutations.
Answer: After some thinking, the answer is quite simple :
The only normal subgroups of $S_5 $ are $\{e\} , A_5 , S_5 $ , and because $im(f)  $ has index 2 , it is normal in $S_5 $ thus $im(f) = A_5 $.


Persistence model vs. view model

Question: Could someone give an example on where "persistence model" should be separated from "view model"? Why?
Persistence model:
<code>@Entity
public class Employee {

    @Id
    private int id;

    // Some other stuff

}
</code>
View model:
<code>public class EmployeeModel {

    private int id;

    // Some other stuff

}
</code>
And where they should not be separated?
Answer: Where they should not be separated: when they match exactly, just as in your example.
Where they should be separated: when they don't match. For example, let's say you want to display a table containing, for each row:

an employee name
the name of his department
the number of projects he's involved in

That doesn't match with any persistence model entity, because in the persistence model, you'll have an Employee, with a ManyToOne association with a Department, and a ManyToMany association with Project. To load the data displayed in the table, you'll use an ad-hoc query which will load the required data from these three entities, using joins.

Persistence model vs. view model


pass in ruby condition as a parameter

Question: I need pass one condition with a field "nombre" as a parameter
Currently I do:
@xcondicion= {:nombre.like => "%#{params[:qyBusqueda]}%"}
clientes= Cliente.all ( @xcondicion )

While this works I need something like :
@xcondicion= { session[:field_selec].like => "%#{params[:qyBusqueda]}%"}
clientes= Cliente.all ( @xcondicion )

It is feasible to do something like this work?
Answer: Perhaps make:
session[:field_selec].like
session[:field_selec].to_sym.like

pass in ruby condition as a parameter


SSH to EC2: Operation timed out. Maybe a resources misconfiguration?

Question: I manually configured my network. The instance identified with 'i-xxxxxxxxxxxxxxxxx' is attached to the NIC 'eni-xxxxxxxxxxxxxxxxx', attached to the subnet 'subnet-xxxxxxxxxxxxxxxxx', routed to the internet via 'igw-xxxxxxxxxxxxxxxxx'  through the 'rtb-xxxxxxxxxxxxxxxxx'.
The instance is attached a Security Group, and that group allows Inbound Connections origined at 0.0.0.0/0 on TCP, port 22. Also, I'm allowed to use a keypair, which I have the private key for.
However, I'm completely unable to do a simple SSH handshaking. The response on my side is "Operation timed out".
Do you think there is something I'm missing?
EDIT: Here's the debug response
➜ ssh -vv firstname.lastname@example.com

OpenSSH_7.9p1, LibreSSL 2.7.3
debug1: Reading configuration data /Users/pandres95/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 48: Applying options for *
debug1: /etc/ssh/ssh_config line 52: Applying options for *
debug2: resolve_canonicalize: hostname 18.104.22.168 is address
debug2: ssh_connect_direct
debug1: Connecting to 126.96.36.199 [184.108.40.206] port 22.
debug1: connect to address 126.96.36.199 port 22: Operation timed out
ssh: connect to host 220.127.116.11 port 22: Operation timed out

Comment: Did you start the instance?
Comment: share `ssh -vv ` output.
Comment: I did @MichaelHampton.
Comment: Here's the output @asktyagi
Comment: Looks like security policy issue, can you test ssh port reachability from your machine?
Answer: Make sure you've got a Public or Elastic IP attached to your instance.
Hope that helps :)
Comment: I made sure there was. I was actually trying to SSH using that IP from my machine.
Also, tried associating an Elastic IP, but didn't work either.
Answer: Do you have only one ENI on the instance or two? If you have two you may run into problems with routing - detach one and see if it helps.
If you only have one ENI and you really have the security group open to 0.0.0.0/0 on tcp/22 and if your VPC networking is all set as you described then the last remaining reason is a host-based firewall blocking the inbound traffic.
For start run iptables -P INPUT ACCEPT; iptables -X and try ssh again.
Oh, wait, you can't login to it to fix the iptables, right? You can use SSM Session for out of bounds access, provided your instance has the SSM agent running. Amazon Linux 2 usually starts SSM agent automatically but you may have to add some permissions to the instance IAM Role - see Using SSM Session Manager for interactive instance access and SSM Sessions the easy way. You may not even need the SSH fixed after you get SSM Session running after all.
Hope that helps :)
Answer: Your subnet will have a Network Access Control List (NACL).
If the subnet is not the default subnet for the VPC, it will have a NACL that blocks all traffic. You will have to permit TCP 22 ingress and global egress in that NACL.
Answer: maybe it's obvious but make sure it is the correct "user" of the EC2, for example:
ssh -i xxx-xxx-xxx.pem email@example.com
Comment: A wrong username does not result in a timeout.


Take turns using semaphores

Question: This might be a trivial problem but I couldn't find any clear answer. How can you make two processes take turns using only semaphores? I don't want to use sleep or other IPCs. The result should be something like:
<code>Process 1 did something
Process 2 did something
Process 1 did something
Process 2 did something
Process 1 did something
Process 2 did something
Process 1 did something
Process 2 did something
</code>
Answer: You need two semaphores, one for each process, lets say S1 and S2. The sequence of interaction between processes P1 and P2 would be as follows:

P1 waits on S1, P2 waits on S2.
Lets say that initially S1 is open, S2 closed.
P1 does its work - closes S1, opens S2, and waits on S1
P2 does its work - closes S2, opens S1, and waits on S2
start over from 3.

Take turns using semaphores


Measure of the coefficients variability for Regularised Regression models

Question: I am working with Regression models.
My idea is to measure the variability of the coefficients of some Regression models.
I used LOOCV split for the training and testing my dataset.
The following are few rows of my coefficients result associated with each independent variable, and since I used LOOCV and my data has 506 rows, I will get 506 models with their coefficients. At this moment I can average the coefficients and have the standard deviation and other variability measures.
                [,1]       [,2]       [,3]        [,4]       [,5]       [,6]      [,7]
      [1,] 0.4833690 -0.2123750 0.10249052 0.008650167 0.05935795 -0.1904433 0.4400553
      [2,] 0.4803859 -0.2129833 0.10221035 0.012684383 0.05947693 -0.1926850 0.4415954
      [3,] 0.4813841 -0.2148075 0.10466271 0.011856752 0.06002647 -0.1917434 0.4401251
      [4,] 0.4812432 -0.2150635 0.10537431 0.013449890 0.05991461 -0.1933659 0.4405225
      [5,] 0.4838644 -0.2157872 0.10701178 0.014210714 0.06007054 -0.1939583 0.4376616
      [6,] 0.4802185 -0.2143879 0.10450493 0.013349886 0.05983871 -0.1924637 0.4424887
      .
      .
      .

My question is as follows
If I want to compare the variability (using standard deviation) of the coefficients of the classical regression methods with Lasso and Ridge and Elastic net Regression, how could that be possible? Because I can not calculate the standard deviation from the glmnet package.
Any idea is highly appreciated!
I am happy to provide more details if needed.
Comment: Are you sure you want to look at the variance of the coefficients, rather than simply variance of model output.
Comment: @seanv507, yes I am interested in testing changes of coefficients for Leave one out cross-validation (LOOCV). I am not sure what do you mean by the variance of model output!
Comment: see bias-variance decomposition: https://en.wikipedia.org/wiki/Bias%E2%80%93variance_tradeoff. come up with data generating process (ie including noise component), generate sample of data, calculate variance of predictions, repeat for n samples.
Answer: Given that the different LOO subsamples are very similar and strongly correlated, and that some instabilities only show up properly if more than one point is left out, (nonparametric) bootstrap is quite certainly better than your LOOCV. Note that there is more than one way of doing bootstrap in regression, which may depend on whether you want to treat your x-values are fixed (and you'd imagine them to be exactly replicated if you replicated your data collection) or random. However, not going into the details of this (it can easily be found in books and on the web googling "regression bootstrap"), standard bootstrap (drawing a random samples of n observations with replacement from your sample) should be an OK thing to do for what you have in mind.
Added after discussion below: For comparing least squares and ridge regression with methods that select variables such as Lasso etc. by empirical standard error and the like, coefficients of variables that were not selected can be set to zero (which is equivalent to not using them, as they are multiplied by their coefficient in most regression models).
Comment: thanks for your time to answer my question. It is ok I can use bootstrapping sampling, but my question is how to compare the variability (using standard deviation) of the coefficients of the classical regression methods with Lasso and Ridge and Elastic net Regression since lasso and elastic net do the vairbale selection??
Comment: A variable that is not selected can be interpreted as having coefficient estimate zero, which can be used for standard error computation.
Comment: what I can see that the comparison with other regression methods is inapplicable since they will have the whole independent variable in the final model. Also, I have no idea how to calculate the standard deviation of lasso and elastic net regression especially using glmnet function.
Comment: I'm not sure whether you saw and understood my previous comment? A variable "not being in the model" is equivalent to having coefficient zero, i.e., multiplying it by zero.Formula for computing the standard error (standard deviation of estimators) doesn't change.  It can be done easily in this way, although it may be somewhat controversial whether this is appropriate. However, if you think it's not, hardly anything can be done.
Comment: many thanks for you. I will also wait for other answers.


Check for invalid input in a menu

Question: I am making a script where the user selects a number 1-5 and it will loop until the user enters 5. I don't want to use the exit command. I wanted to check to make sure the user doesn't enter anything but 1-5 and if they do display invalid input.
any help would be appreciated
#!/bin/bash
  PS3='Please enter your choice: '
options=("1.Move empty files" "2.Check file size" "3.Which files is newer" "4.File check rwx" select opt in "${options[@]}")

 while($opt != 5); do
   case $opt in

        "Option 1")
          echo "you chose choice 1"
          ;;
        "Option 2")
          echo "you chose choice 2"
          ;;

        "Option 3")

     echo "you chose choice 3"
    ;;
 "Option 4")
  echo "you chose choice 3"
               ;;
          "Option 5")
           break
           ;;
   ) echo invalid input;;

Comment: Please take a look: http://www.shellcheck.net/
Comment: Setting `PS3` is meaningless if you aren't using a `select` statement, which is what you appear to want in place of the `while` loop.
Comment: `case` is overkill here, `opt` will be empty if the selection was invalid. You also don't need the `while` since `select` is already a loop.
Comment: You say both "loop until the user enters 5" and "make sure the user doesn't enter anything but 1-5"--so which is it?
Answer: You seem confused. I don't even know where to begin correcting whatever misconceptions you have about how this works
In your original code the way you set options is unlikely to do anything useful.
options=("1.Move empty files" "2.Check file size" "3.Which files is newer" "4.File check rwx" select opt in "${options[@]}"
printf '%s\n' "${options[@]}"

This will emit
1.Move empty files
2.Check file size
3.Which files is newer
4.File check rwx
select
opt
in

The select command will not have been executed.
Here's something that does what you seem to want.
options=(
    'Move empty files'
    'Check file size'
    'Which file is newer'
    'File check rwx'
)

PS3='Please enter your choice: '
select opt in "${options[@]}" ; do
    [[ -n $opt ]] && break || {
        echo "invalid input"
    }
done
echo "user chose '$opt'"

You could go with a while and case solution and get nearly the same results e.g.:
options=(
    'Move empty files'
    'Check file size'
    'Which file is newer'
    'File check rwx'
)

for (( i=0 ; i < ${#options[@]} ; i++ )) ; do
    printf '%d) %s\n' $((i+1)) "${options[$i]}"
done
while true ; do
    read -p 'Please enter your choice: ' opt
    case "$opt" in
        [1-5])
            opt="${options[$opt]}"
            break
        ;;
        *)
            echo "invalid input"
        ;;
    esac
done

echo "user chose '$opt'"

But you don't need both and, as you can see, using select is much simpler.

Check for invalid input in a menu