Dropdown menu não mostra subitens

Question: Já vi várias postagens, todas com várias respostas, mas não consigo colocar meu dropdown para funcionar no menu. Ele simplesmente não abre. Será que preciso instalar algo a mais?
Meu código é esse:

                  Page 1

Page 1-1

Page 1-2

Page 1-3

Estou usando o typescript.
Answer: Testei aqui e esta funcionando perfeitamente, verifique se os arquivos do bootstrap estão sendo incluídos corretamente no head do seu código.
segue o exemplo:

    <title>teste</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

                  Page 1

Page 1-1

Page 1-2

Page 1-3

Comment: Boa tarde Daniel, continua não funcionando. Estou achando que deve estar faltando algo. Suspeito de alguma configuração que eu não tenha feito, afinal, sou bem iniciante no assunto.
Comment: Boa tarde, faça o seguinte copie este código inteiro e cole no seu editor, salve como teste.html e abra-o no seu navegador. Caso funcione verifique os arquivos do bootstrap que você incluiu no seu projeto, eles podem ser incluidos via CDN que é a forma que eu lhe passei acima ou você pode baixar os arquivos e inclui-los manualmente nas pastas do seu projeto.
Aqui tem um link de como você pode inclui-los corretamente:

https://www.w3schools.com/bootstrap/bootstrap_get_started.asp

Aqui um link com exemplos de dropdowns e navbars:

https://www.w3schools.com/bootstrap/bootstrap_navbar.asp
Comment: Daniel, criei a página teste.html e funcionou.
Eu acho que meu problema é que estou usando o ng server em ambiente de desenvolvimento. Por que digo isso? Fiz a alteração que você posou, salvei e o servidor recompilou o arquivo e atualizou a página com o menu, porém, "lá" no localhost/4200 ele não funciona. Será que falta alguma coisa no meu ambiente de desenvolvimento?
Comment: Provavelmente, tente verificar nas pastas do seu projeto se está tudo ok com os links, se não os inclua ou os corrija. Se mesmo assim não funcionar tente baixar os arquivos do bootstrap e coloca-los dentro do repositório do seu projeto, então os inclua diretamente pelo nome dos arquivos.
Comment: Daniel, esse é o problema. Não sei ver ainda se está tudo OK e quais arquivos colocar dentro do repositório e em qual repositório. Mas sua dica valeu muito. Já vou avançar para outro nível do meu problema. Obrigado pela ajuda.
Comment: O download fica aqui: http://getbootstrap.com/docs/3.3/getting-started/#download . se você preferir pode instalar o bootstrap 4 mais ainda esta em desenvolvimento. Você poderia tbm instala-lo via npm, já que trabalha com um ambiente dev. Para instala-lo manualmente vc tem que ir dentro das pastas do seu projeto, colar os arquivos que vc baixou e chama-los dentro do arquivo principal ou só no arquivo atual para testar. Existem diversos guias de como fazer isso pela internet, inclusive pelo próprio site do bootstrap. Se houver qualquer dificuldade a mais estou a disposição.
Comment: Eu já instalei via npm. Acho que falta alguma referência em algum lugar. Algo que tenho que fazer a mais para funcionar.

Dropdown menu não mostra subitens


Comparing AUC and classification loss for binary outcome in LASSO cross validation

Question: I'm analyzing biological data where I'd like to see the impact of scaled gene expression on the classification of the sample. I binarized the response variable as 0 and 1 and used lasso with cross-validation. My goal is inference rather than prediction at this point.
I compared two different type.measure parameters (auc and class) in cv.glmnet function and plotted coefficient estimates in a scatter plot:

Correct me if I'm wrong, but the documentation suggests both methods can be suitable for binary classification problems. I'm trying to understand the differences I see here. When using misclassification error (class) loss function, more variables shink to zero compared to the area under the ROC curve (auc) What is the reason for this different behavior?
Comment: Does this answer your question? [Measuring accuracy of a logistic regression-based model](https://stats.stackexchange.com/questions/18178/measuring-accuracy-of-a-logistic-regression-based-model)
Comment: I got some great insights from that link, but I don't think it necessarily answers my question. I'm trying to get a sense of why misclassification loss function is shrinking more variables, where in essence, the ROC curve is drawn using the frequency of true and false predictions. Is the situation I'm looking at here that the accuracy of the model measured at a certain point as opposed to the entire continuum of the possible values (ie a fixed (average?) point on ROC curve versus the whole area under the curve?)
Answer: The main point is that accuracy is not really "suitable for binary classification problems" despite its frequent use as a criterion in model evaluation.
In an important sense there is no single "accuracy" measure as it depends on selection of a particular probability cutoff for assigning class membership. For binary classification this selection is often hidden from  view (as it seems to be in cv.glmnet() when class is selected as the criterion) and set at a value of p = 0.5; that is, class membership is assigned to whichever class has the highest probability. That's only appropriate if you assign the same cost to false-positive and false-negative errors. Other relative costs would lead to different choices of the probability cutoff. See this recent page for an introduction and links to further discussion about selecting cutoffs.
So your sense expressed in a comment is correct: the difference is that AUC examines the whole range of potential false-positive versus false-negative tradeoffs versus the single choice imposed by the p = 0.5 class-assignment threshold. As this page discusses, auc is thus preferable to class as a criterion for comparing models as you are effectively doing with cross validation.
This answer describes how the best way to evaluate such models is with a proper scoring rule, which is optimized when you have identified the correct probability model. The deviance criterion in cv.glmnet() (the default for logistic regression) is equivalent to a strictly proper log-loss scoring rule. That may be bit more sensitive than auc for distinguishing among models; see this page.
I can't say with certainty why the class criterion maintains fewer genes in the final model than does auc. I suspect that's because the class criterion is less sensitive to distinguishing among models, which is what you're doing when you try to minimize over a range of penalty values, so it ends up with larger weights on fewer predictors. But that's an intuitive heuristic argument with no formal basis.
A final note: inference following LASSO is not straightforward. See this page for some discussion. With gene-expression data you typically have a large number of correlated potential predictors, among which LASSO will make choices that can be very data dependent. So even if you calculate p-values and CI properly that doesn't mean you have identified "the most important" genes for the classification, just a particular set that is justifiable. Try repeating the modeling on multiple bootstrapped samples of the data to gauge how stable the gene-selection process is.
Comment: @Thomas yes I think that's the safest choice from what's available built-in to `cv.glmnet()`; it's the default. Log-loss is far from the only proper scoring rule, but it comes directly from the maximum-likelihood calculations used to solve the logistic regression. It puts a lot of weight on extreme cases. In principle you could use any proper scoring rule for choosing the logistic-regression penalty by cross validation, although you would have to adapt the cross-validation code yourself.
Comment: @Atakan this is an inherent problem with LASSO. How you will be using the results matters. Signaling pathways are most important; multiple genes can be proxies for the same altered pathway. For a test to distinguish 2 classes, just using the original LASSO model would be fine as which particular proxy is chosen doesn't matter much.  As a guide to further experiments you want to examine a wider set of genes. You might consider instead the `limma` Bioconductor function (or its more recent extensions) to gauge differentially expressed genes, together with pathway analysis.
Comment: would you then suggest one should use `type = "deviance"` over `auc` even with binary outcomes as it equals a proper log-loss scoring? This of course also relates to my question, you refer to in this answer?
Comment: Interesting. I will definitely give it a shot to compare models. Can you readily obtain the log-loss once the `cv.glmnet` has run then? Thank you.
Comment: @Thomas yes, it's [equivalent to the deviance error criterion](https://stats.stackexchange.com/a/157930/28500). The cross-validated error (by whatever criterion was chosen) as a function of $\lambda$ is in the `cvm` part of the object returned by `cv.glmnet()`. Be carful when comparing models with different numbers of parameters, however; see the [Akaike Information Criterion](https://en.wikipedia.org/wiki/Akaike_information_criterion) and its [relationship with deviance](https://stats.stackexchange.com/a/191235/28500).
Comment: Thank you for the insightful answer. Do you have a recommendation on how to proceed if bootstrapping reveals unstable models? Since we don't know which correlated genes are important, is it better to be inclusive and consider all the estimated non zero coefficients in different models?


Should I anticipate any problems trying to use the same SSL Cert on 2 computers (primary, backup)?

Question: We have a production machine running IIS6 with a wildcard SSL certificate.  The certificate that was installed is not exportable.
We want to upgrade the system to IIS7.  As part of this venture, we're creating a backup/failover server that will serve the exact same websites - when we take the primary down for upgrade, the secondary will take over.  As such, the secondary also needs the SSL certificate.
However, since the certificate was not exportable, this means re-keying it from Go Daddy.
Per http://help.godaddy.com/article/867, I know that by re-keying the certificate the original will stop working.
I'm still pretty new to SSL certificates, so are there any problems I should anticipate when installing the same SSL certificate on 2 different machines?
Answer: I would re-key the certificate and install it on the secondary machine and make sure that it's exportable.  Then, export the certificate and install it on the existing server.  This ensures that they both have the same exact certificate in place.  Keep a copy of the PFX export file in a safe place in case you need to restore it again later.
Answer: As long as the certificate is valid for both of them, you should be fine.
Comment: Please elaborate - under what circumstances would a certificate be valid for one machine, but not the other?
Comment: A certificate contains a domain name, list of domain names, or wildcard domain name that it is valid for. For example, a certificate for alpha.domain.com cannot be used on beta.domain.com, but one for *.domain.com can be used on both.
Answer: What does GoDaddy mean when they say the original cert will be deactivated, without revoking it? And unless the browser checks the CRL, even revoking does nothing ... the browser and web server would still use the cert ok.
Or am I off base?
Back to the real question, in my experience you can use the same cert on multiple web servers as long as you use the same URL to get to it.
EDIT: Ah-ha, I read the GoDaddy site wrong ... "it is not necessary to request revocation" ... they do it automatically. My mistake.
Comment: I wondered that too (how it was 'deactivated'), but assumed it true given the statement on that linked page...
Comment: When you "rekey" a certificate using GoDaddy's interface, it is revoked, and another is issued.


My regular expression matches unexpected patterns

Question: would anyone know why is the second pattern displayed it should not match the regex...
$grep [[:digit:]{4}] file
99g66
9888
$

Comment: The answer is probably that you've written a character class containing digits, as well as `{` and `}`.  Hence, both the first lines match.  By the way, we can't read your question at all after your latest edit.
Comment: @TimBiegeleisen thanks for the answer
Answer: Because the englobing [] will escape your {4} part.
The correct way of achieving this is the following
[[:digit:]]{4}
Comment: Thanks for the answer!
Answer: Your expression [[:digit:]{4}] is a character set that matches either a digit, a {, or }. You probably meant [[:digit:]]{4}. Use that regular expression in extended mode with grep -E or egrep or escape the braces when using basic regular expression mode:
$ egrep '[[:digit:]]{4}' file

$ grep '[[:digit:]]\{4\}' file  # braces escaped

Comment: For the record, I upvote solid material :-)
Comment: it worked for me thanks @jspcal


C++: almost identical header files, but one gives a peculiar inheritance-related error

Question: For a C++-project, I need to make a game with Doodlebugs and Ants, which are both Organisms. So, I made a class called Organism with the following definition (although I'll probably add way more member functions and member variables, of course).
Organism.h:
#ifndef ORGANISM_H
#define ORGANISM_H

#include "World.h"

class Organism
{
    public:
        Organism();
        ~Organism();

        virtual void Move() = 0;

        friend class World;

        int survivalTime;
};

#endif

Organisms live in 'the World', which is a class with (among others) a member variable Organism*** field, a two-dimensional dynamic array containing pointers to Organism objects.
World.h:
#ifndef WORLD_H
#define WORLD_H

#include "Organism.h"
#include "Ant.h"
#include "Doodlebug.h"

class World
{
    public:
        World();
        ~World();

        void gameplay();

        Organism*** field;
};

#endif

You probably already guessed it: Ant and Doodlebug are derived from Organism.
Ant.h:
#ifndef ANT_H
#define ANT_H

#include "Organism.h"

class Ant : public Organism
{
    public:
        Ant();
        ~Ant();
        void Move();
};

#endif

Doodlebug.h:
#ifndef DOODLEBUG_H
#define DOODLEBUG_H

#include "Organism.h"

class Doodlebug : public Organism
{
    public:
        Doodlebug();
        ~Doodlebug();
        void Move();
};

#endif

As you can see, Ant.h and Doodlebug.h are almost identical, except for the words Doodlebug and Ant. However, I have two errors.

In World.h, line 16: "'Organism' does not name a type."
In Doodlebug.h, line 7: "expected class-name before '{' token"

Why is this? The first error can be solved by putting class Organism; right before the definition of class World, but I don't understand why that changes anything, since the complete definition of Organism is in Organism.h, which I include.
The second error is the one I'm VERY confused by (and kind of the main reason I'm asking this question), since Ant.h is identical to Doodlebug.h except for the words Ant and Doodlebug, but in Doodlebug.h I get an error but not in Ant.h???
Any help is greatly appreciated.
Comment: `Organism` needs a virtual destructor.
Comment: `Organism.h` now does not include any files.
`World.h` now only includes `Ant.h` and `Doodlebug.h` which include `Organism.h`.
Fortunately, `Organism.h` does NOT need to know anything about `World` since `friend class World` does not require the definition of `World`. So no forward declarations needed.
Answer: You have circular dependency between World.h and Organism.h.
World.h has
#include "Organism.h"

and Organism.h has
#include "World.h"

You can remove the above line from Organism.h and replace it with a forward declaration.
class World;

Use forward declaration in header files if you don't need the definition of a  as a matter of principle. That will not only avoid problems like the one you encountered but it will also reduce compile time dependecies.
Additional references:
Forward declaration vs include
When can I use a forward declaration?
Comment: I would add that one should use forward declarations whenever it's possible. It allows to avoid most of problems like the given above.
Comment: Forward declarations also improve compilation speed, possibly _a lot_.
Answer: You did not post your compile command (and most importantly what is the file you try to compile?), but below is what I think your problem is.
The main problem is that your Organism.h includes World.h, which in turn tries to include Organism.h once again, but does not actually include it due to include guards. Therefore, in World.h the compiler still does not know what Organism is and thus generates the first error. You can use forward declaration to solve this: just write
class Organism;

in World.h before class World...; you can also remove #include "Organism.h" from World.h.
I suppose that your second problem can be related to this also.
Note that you can use -E parameter to g++ to generate the file as compiler sees it after preprocessing. Very useful to catch these include-related problems.
Answer: The first issue derives from your include "mess". When Organism.h is processed (maybe because a corresponding Organism.cc is compiled) the include statement is replaced by the actual contents, i.e. it is replaced by the contents of World.h. That effectively yields a translation unit where the declaration of World stands before the declaration of Organism, hence leading to the error.
Comment: So in `Organism.h`, before `#include "World.h"`, I put a forward declaration, `class Organism`. In `World.h`, I still write `#include "Organism.h"`, because it will not be defined a second time.    I now see why this solves the problem. I didn't realize that `#include` statements basically (or actually) copy the code to the place of the `#include` statement.
Comment: Simply do not include `World.h` in `Organism.h` at all. Just forward-declare `class World;`, that will suffice. And as well don't include `Organism.h` in `World.h`, put a forward declaration for `class Organism;` there instead.
Comment: Yes indeed, `#include` statements _are_ actually copy-and-paste instructions to the preprocessor, literally.
Answer: You could also probably remove #include "Organism.h" from your World.h as you have included that in both your Ant and Doodlebug classes, and both of those are included in your World class.


hiding field -reference option limit

Question: Helloo !
I am using the D7 reference option limit module. I have two fields "primary" and "secondary" and I managed to reduce the choices of secondary based on the value of primary using this module. Both of them are required field in the user registration form.
I have a small question, when I set no value for primary, I get for the secondary field: No options are available for the current form values. Try selecting different values for the following fields: Primary.  This is the good behaviour that I want but I want to hide secondary when no value is set for primary instead of displaying this message..
Is that possible? In other words I want to keep secondary hidden until primary has a value.
Answer: have you try any alter functions to implement ?
if you can try with alter then try #states in hook_form_alter() to hide field, if primary field default value is empty/null.
here is e.g
/**
 * @param type $form
 * @param type $form_state
 * @param type $form_id
 * Implements hook_form_alter()
 */
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'form_id') {
    // Hide secondary field.
    if (isset($form['secondary_field'])) {
      $form['secondary_field']['#states'] = [
        'visible' => array(
          'input[name="primary_field"]' => array('!value' => ''),
        ),
      ];
    }
  }
}

'input[name="primary_field"]' => array('!value' => ''), change this as per need i.e if its select list then 'select[name="primary_field"]' => array('!value' => ''), etc.
hope this will solve your issue.
Comment: Thank you very muchh

hiding field -reference option limit


Insert login form in a personalized form

Question: I'd like to insert the login form in my own form.
To be clear, I have a quotation form and after we answer all the questions I would like to find the user login block.
And after the user is logged in, I would like to reload the page to show differents elements.
In the form, I insert this code to show the login block:
$dgf_login_block = drupal_get_form('user_login_block');
$render_login_block = drupal_render($dgf_login_block);
$form['envoi']['login_block'] = array(
    '#markup' => $render_login_block ,
    '#prefix' => '
',
    '#suffix' => '
',
);

But it doesn't work.
My question is: what is the best way to insert the user login form inside an other form? Or does it better to define two fields (username and password) and validate them (and how can I validate the login)?
Thanks in advance for your help.
Alexandre
Answer: In general it is not possible to have one form inside of another form. So even if you do it with pure HTML, you can't have another form inside of the form tag.
To have login block you will need to add it as a separate form. So either you can redirect user to a page where you have login form after they have filled your original form.
I don't have reputation to comment but I would like to know how have you created your original form. That way I might be able to help you with what you want to achieve.
Comment: Thanks a lot Bharat for your answer and your help.

I've created my form in a personalized module. It's a multistep form.

My aim is to have at this step (the result of the quotation) two choices :

if you're not logged in, you only see the price;
if you're logged in, you can see details.
So if the loggin form is in an another page, I think it's difficult to reload the second step of the form with the user answers.

But I may be on a wrong track…

Thanks again.
Answer: I found a solution for a multistep form.
I used the user login block, and in my module :
function mymodule_form_user_login_block_alter(&$form, &$form_state) {
  $form['field_data_hidden'] = array('#type'=> 'hidden');
  unset($form['#action']);
  $form['#submit'][] = 'mymodule_user_redirect';
}
function mymodule_user_redirect($form, &$form_state) {
  drupal_goto('my-form-page-to-reload', array('query'=>array('data'=>$form_state['values']['field_data_hidden'])));
}

The hidden field stores the datas for the query from the multistep form (with JS).
The query is used for reload the form with the previously entered data.
Note: if you have trouble for redirect the page in the module, take care that the "TRIGGER: AFTER A USER HAS LOGGED IN" has no assign.
There's may be a best way to do this, but it works.


How can I speed up the opcode cache response time?

Question: I've got a moderately powerful VPS (quad core Xeon, 3GB ram, ssd) running Ubuntu 12.10, PHP 5.5.8 and Opcode cache is enabled.
I'm using memcached, opcode cache and mod_pageSpeed.
I'm monitoring the app using New Relic.
The issue is that no matter what I've tried, increasing memory limits, cache sizes, etc, I cannot get the request response time below about 80 ms.
The database is running Percona and that is spending about 40ms per request, and PHP is spending about 40ms per request.
All requests are being served up from OpCode compiled cache, so I don't understand where all the latency is coming from.
What am I missing?
Thanks.
Apologies in advance if I've missed some crucial info, all can be supplied on request.
Comment: Execute less code?
Comment: So just rm /var/www/* then yeh?

:P
Comment: Yes, that will minimize your response time. :)
Comment: My concern is that considering opcache compiles, executes, then caches the result, it shouldn't do anything more than serve up a response from memory. It is being held in memory, and I've got a 99.9N % hit rate on the cache... So I don't know why there's that much delay... It's as if it's executing the compiled code every time, and not caching the output. :(
Comment: That's because that's exactly what it's doing.
Answer: The opcode cache doesn't "compile, execute and cache the result". On the first request, your PHP code is compiled to bytecode, that bytecode is saved, and then it is executed. On subsequent requests, the saved bytecode is executed. Without an opcode cache, the PHP code would be compiled to bytecode during each request.
If you want to cache the output generated by your program and serve it rather than executing your program on each request, you need to look into additional caching techniques.


Como posso separar essa string javascript em duas variáveis php?

Question: Segue o código____________________________________
<!DOCTYPE html>

Click the button to get your coordinates.

<button onclick="getLocation()">Map On</button>

<?php
  $teste = "";
  echo $teste;
  $latAqui = explode(" ", $teste);
  print_r($latAqui);
?>

Retorno até o presente momento_______________________________________

Localizacao: -22.3588937,-47.3859919

Array ( [0] => )

Answer: Só vai conseguir passar esse dado via Ajax.
Quando o PHP renderiza a página ele escreve literalmente que $teste = "";. Para ele "" é simplesmente uma string. Não tem nenhum significado e não executa nada.
Quem executa o Javascript é o browser depois que o HTML puro gerado pelo PHP está pronto e é renderizado para o usuário final. Nesse momento o PHP não tem mais poder nenhum sobre a página.
O que você pode fazer é criar uma função que execute esse comando e envie o resultado via AJAX para o seu projeto PHP.
O AJAX é separado em duas etapas. O envio do browser feito com Javascript que você pode ler mais sobre no próprio stackoverflow: Requisição Ajax com Javascript puro (sem APIs)
E a API no PHP que vai receber essa requisição. Aqui tem um pequeno tutorial falando a respeito também: http://www.devmedia.com.br/criando-um-cadastro-com-php-ajax-e-jquery/28046
Não é um processo trivial. Vai precisar estudar um pouco para entender como realizar até porque são chamadas assíncronas, mas é a única forma de pegar a localização do usuário pela API do Browser.
Comment: Poderia dar um exemplo ou um site para que eu possa ver, por favor?
Comment: @JulioRamos complementei a resposta. Entenda que não é um processo trivial. Não dá para colocar o código completo do projeto aqui porque é preciso mexer em várias pontas, mas é a única forma de realizar essa verificação.

Sem depender de integração com o browser só se fizer por IP. Mas vai precisar consultar um serviço externo ou comprar uma base de IP geolocalizados.
Comment: Por ip não é possível, ele retorna ips da região, pois o ip é dinâmico.
Comment: A base de IP pega o prefixo da região. Geralmente tem precisão no nível das cidades.

Mesmo o usuário tendo IP dinâmico ela consegue acertar porque pega o prefixo do local.

Usando as API's de geolocalização do browser só passando por AJAX mesmo. Você consegue passar dados do PHP para o browser diretamente na página, mas jamais consegue passar do Javascript pro PHP sem ser por outra conexão como AJAX e Websockets por exemplo.
Answer: Primeiro remova a localização da função e deixe assim:
return position.coords.latitude+","+ position.coords.longitude;

Depois:
 $teste = "";
 echo $teste;
 $latAqui = explode(",", $teste);
 echo($latAqui[0]);
 echo($latAqui[1]);

Comment: @LucasTorres o valor que ele espera é o retorno da função `getLocation`.  Como esse script só é executado no browser ele acaba pegando literalmente a string que está definida no PHP que não tem valor nenhum para ele.

Não vai funcionar dessa forma.
Comment: Recebo o seguinte erro : Notice: Undefined offset: 1 in C:\xampp\htdocs\testeGEOIP.php on line 35
Comment: Qual é a linha 35?
Comment: Essa aqui:  print_r($latAqui[1]);
Comment: Editei a resposta
Comment: Ainda esta com erro, amigo ^-^
Comment: De um print_r($latAqui). Qual o retorno?
Comment: Array ( [0] => )
Comment: e no echo($teste), qual o retorno?
Comment: -22.3588937,-47.3859919
Comment: Minto, o resultado da function é nulo
Comment: Editei novamente a resposta
Comment: E lembre-se. A variavel teste precisa ter conteúdo


Como retornar o location correto para route com resources no singular?

Question: Ao utilizar o nome da controller no singular, a rota é prefixada com _index ao final do nome da rota (ex. dispute_conference_index). Dentro da controller no método create o parâmetro location em render recebe a URL do registro.
Infelizmente o nome passado para location é dispute_conference_url ao invés de dispute_conference_index.
Veja abaixo a configuração de rota que estou usando:
resources :disputes, shallow: true do
  scope module: :dispute do
    resources :conference, except: :index
  end
end

Veja os detalhes de routes:
                 Prefix Verb    URI Pattern                                Controller#Action
conferences              GET    /conferences(.:format)                     conferences#index {:format=>:json}
dispute_conference_index POST   /disputes/:dispute_id/conference(.:format) dispute/conference#create {:format=>:json}
conference               GET    /conference/:id(.:format)                  dispute/conference#show {:format=>:json}
                         PATCH  /conference/:id(.:format)                  dispute/conference#update {:format=>:json}
                         PUT    /conference/:id(.:format)                  dispute/conference#update {:format=>:json}
                         DELETE /conference/:id(.:format)                  dispute/conference#destroy {:format=>:json}
                         PUT    /conference/:id/start(.:format)            dispute/conference#start {:format=>:json}
                         PUT    /conference/:id/cancel(.:format)           dispute/conference#cancel {:format=>:json}
                         PUT    /conference/:id/finish(.:format)           dispute/conference#finish {:format=>:json}

Qual a forma correta de corrigir está questão, passando o location correto?

Corrigindo a pergunta: O motivo do erro é por conta do parâmetro shallow: true, ele altera o path das rotas fazendo com que seja necessário uma intervenção manual ou através de uma função (url_path).
Ao tentar rodar o método create será obtido um erro pois não será possível encontrar a location.
Comment: Adicionar estaticamente não é uma boa ideia... `location: :dispute_conference_index`
Answer: Depois de varias tentativas e erros a solução pareceu. Primeiro deve ser movido shallow: true para a chamada de resources e por fim deve ser adicionado o atributo shallow_prefix: :dispute. Veja abaixo como fica:
resources :disputes do
  scope module: :dispute, except: :index do
    resources :conference, shallow: true, shallow_prefix: :dispute
  end
end

Feito isso routes será montado da forma desejada:
Prefix Verb         URI Pattern Controller#Action
conferences              GET    /conferences(.:format)                     conferences#index {:format=>:json}
dispute_conference_index POST   /disputes/:dispute_id/conference(.:format) dispute/conference#create {:format=>:json}
dispute_conference       GET    /conference/:id(.:format)                  dispute/conference#show {:format=>:json}
                         PATCH  /conference/:id(.:format)                  dispute/conference#update {:format=>:json}
                         PUT    /conference/:id(.:format)                  dispute/conference#update {:format=>:json}
                         DELETE /conference/:id(.:format)                  dispute/conference#destroy {:format=>:json}
                         PUT    /conference/:id/start(.:format)            dispute/conference#start {:format=>:json}
                         PUT    /conference/:id/cancel(.:format)           dispute/conference#cancel {:format=>:json}
                         PUT    /conference/:id/finish(.:format)           dispute/conference#finish {:format=>:json}

Perceba que minha controller está montada no modulo dispute isso também está relacionado ao problema.


How to get fields of certain content type in template file without writing iteration loops in tpls?

Question: Here I'm getting all fields of certain content type in my .tpl.php file with the help of hook_theme.
return theme('carousal', array('carousal' => $fields));

And my template file is something like this:
<?php
global $fields;
foreach($fields as $key => $value){
echo $value['title'];
print render ($value['fields']['body']);
}
?>

Now, what I want is, I don't wanna use foreach loop in my template file. And if possible, not even any php tags.
How far is it possible to render fields in template file without using any loop?
Can't we write only "BODY" and we get "body" field rendered itself automatically?
I don't know whether it's possible or not. If it's possible, kindly let me know the way out of this.
Comment: It's strange thinking. Why do you want to do that?
Answer: You can pass your $fields to a custom function. Run your logic or foreach loop in the custom function and pass the title,body values back. Thus you would not need to use the foreach loop in template file.
Here is some sample code if it helps.
$field_data = _my_function($fields);
$data = theme('carousal', array('carousal' => $field_data));
return $data;

Comment: In `return theme('carousal', array('carousal' => $fields));`, `$fields` contains all necessary fields that I need to get output, the only this is I don't wanna iterate over this variable `$field`s. Without using `foreach($fields)` I want the fields to get rendered.
Answer: Try this
print render($content['your_field_name']);

this will print that field value .
Comment: what is $content here? It will not work.


Motivation for looking at the product module

Question: Let $M$ be an $A-$module, $A$ a commutative ring with identity. Then we have the following result that , $\frac{A}{I} \otimes M \simeq \frac{M}{IM}$ for any ideal $I$ in $A$.
This simply follows by the observation that, $IM \le \text{Ker}(\psi)\le M$, where $\psi:M \to \frac{A}{I} \otimes M$ can be extended to a map $\phi:\frac{M}{IM}\to \frac{A}{I} \otimes M$ and showing $\phi$ is indeed an isomorphism.
My question is, why is it natural to look at the submodule $IM$? What intuition lies behind this choice?
Answer: It comes from the short exact sequence $$0 \rightarrow I \rightarrow A \rightarrow A/I \rightarrow 0$$ of $A$-modules. As you might know, tensoring with $M$ is a right exact functor, from which we get the following exact sequence $$I\otimes M \rightarrow A\otimes M \rightarrow (A/I) \otimes M\rightarrow 0.$$ The middle term $A \otimes M$ is canonically isomorphic to $M$, thus $(A/I) \otimes M$ is isomorphic to the quotient of $M$ by the image of $I \otimes M$ in $M$.
Now if you follow the definitions closely, then with a moment of reflection you will realize that the image of $I \otimes M$ in $M$ is exactly what we call $IM$.


Getting root and intermediate certificates from an end-entity

Question: still being a noob in cryptography I stumble upon simple things every day. And today is just one of those days.
I want to validate smime messages in java with the bouncy castle library, and I think I almost figured it out, but the problem at this moment is the building of the PKIXparameters object.
Let's say, I have an end-entity x509certificate with the following structure:
root certificate
 +->intermediate certificate
    +->end-entity certificate

In order to validate message I need to build a chain of trust first, but I cannot figure out how to extract a root and intermediate certificates from the end-entity.
I tried to use end-entity as root but it didn't work:
InputStream isCert = GetFISCertificate();

List list = new ArrayList();
X509Certificate rootCert = (X509Certificate) certificateFactory.generateCertificate(isCert);
list.add(rootCert);
CollectionCertStoreParameters params = new CollectionCertStoreParameters(list);
CertStore store = CertStore.getInstance("Collection", params, BC);

//create cert path
List certChain = new ArrayList();
certChain.add(rootCert);
CertPath certPath = certificateFactory.generateCertPath(certChain);
Set trust = Collections.singleton(new TrustAnchor(rootCert, null));

//validation
CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX", BC);
PKIXParameters pKIXParameters = new PKIXParameters(trust);
pKIXParameters.addCertStore(store);
pKIXParameters.setDate(new Date());
try {
CertPathValidatorResult result = certPathValidator.validate(certPath, pKIXParameters);
System.out.println("certificate path validated");

} catch (CertPathValidatorException e) {
System.out.println("validation failed on certificate number " + e.getIndex() + ", details: " + e.getMessage());
}

Got this exception:
validation failed on certificate number -1, details: Trust anchor for certification path not found.

And btw, can I just use only the end-entity certificate to validate messages, as if it were the self-signed certificate?
Answer: I've used BouncyCastle 1.56 for this test.
One way to get the issuer's certificate from the end entity is to look for the Authority Information Access extension.
This extension may be present (it's not mandatory) and may contain the URL to get the issuer's certificate (issuer is the certificate "above" the current one, so the end entity's issuer is the intermediate, and the intermediate's issuer is the root).
You can get this extension value with BouncyCastle:
import java.security.cert.X509Certificate;
import org.bouncycastle.asn1.x509.AccessDescription;
import org.bouncycastle.asn1.x509.AuthorityInformationAccess;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.X509ObjectIdentifiers;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.x509.extension.X509ExtensionUtil;

X509Certificate cert = // end entity certificate

// get Authority Information Access extension (will be null if extension is not present)
byte[] extVal = cert.getExtensionValue(Extension.authorityInfoAccess.getId());
AuthorityInformationAccess aia = AuthorityInformationAccess.getInstance(X509ExtensionUtil.fromExtensionValue(extVal));

// check if there is a URL to issuer's certificate
AccessDescription[] descriptions = aia.getAccessDescriptions();
for (AccessDescription ad : descriptions) {
    // check if it's a URL to issuer's certificate
    if (ad.getAccessMethod().equals(X509ObjectIdentifiers.id_ad_caIssuers)) {
        GeneralName location = ad.getAccessLocation();
        if (location.getTagNo() == GeneralName.uniformResourceIdentifier) {
            String issuerUrl = location.getName().toString();
            // http URL to issuer (test in your browser to see if it's a valid certificate)
            // you can use java.net.URL.openStream() to create a InputStream and create
            // the certificate with your CertificateFactory
            URL url = new URL(issuerUrl);
            X509Certificate issuer = (X509Certificate) certificateFactory.generateCertificate(url.openStream());
        }
    }
}

So you can use this code with the end entity certificate to get the intermediate. Then you use it again with the intermediate to get the root.
Then you add the root to your TrustAnchor and the validation should work.

Note: But as I said, this extension is not mandatory and may not be present. In this case, getExtensionValue will return null, and the only alternative that I know is to search for the certificates in google and download them (those certificate chains are usually public and not hard to find)
Comment: The extension Authority Info Access is quite common for OCSP info. But I think I've never seen a certificate with this extension containing  id-ad-caIssuers. Anyway, good answer.
Comment: @Hugo, I'm very grateful, once again. It compiled and it works, but I still feel like going through darkness, there are so many things I do not fully understand and it bugs me a lot. Can you please recommend something to read? I was thinking about David Hook's  "Beginning Cryptography with Java", but it's kinda outdated (2005). I have basic understanding of cryptography, not really completely newb, but very far away from a pro also.
Comment: I think you can start by studying [Public Key Infrastructure](https://en.wikipedia.org/wiki/Public_key_infrastructure) and [Public Key Cryptography](https://en.wikipedia.org/wiki/Public-key_cryptography). And don't worry, it took me years to really understand how all this stuff works (and I still don't feel like a pro, there's a lot of details that I don't have a deep understanding). Anyway, if you understand how (and why) it works, that's enough for most applications (you don't need to learn all the math details, they're already implemented in the API's)
Comment: One more thing: as I said, the end entity certificate **might** contain information about its issuer (in the AIA extension, as explained in the answer). But it doesn't contain information about the whole chain. You must go through each step: end entity to intermediate, then intermediate to another intermediate, until you get the root (there are theoretically no limit to the number of intermediates, I believe, but 1 or 2 are the most common cases). But some intermediates might not have information about its issuer (it's not mandatory), and that's really annoying..
Comment: @Egl I've seen certificates with both id-ad-caIssuers and OCSP (google.com's certificate and Brazil's PKI end entities are good examples). I've also seen certificates with just one of them, unfortunately it seems that there's no standard among the CA's.
Comment: Thanks a lot for your answer! You helped me a lot!
Comment: Can you please clarify following - as I understood, the end-point certificate doesn't contain information about the issuers (up to the root) chain, windows (idk what about other systems) only makes it look just as if does (when you check "Certification path" tab while checking certificate info). So whenever I click certification path, windows rebuilds this chain also? Or for example, mail clients as thunderbid or outlook for example, are doing the same work when checking mail signature?
Comment: Windows comes with lots of pre-installed certificate chains, from Authorities that are part of [Microsoft Root Program](https://technet.microsoft.com/en-us/library/cc751157.aspx), so Windows is not rebuilding the chain - it already has it installed as a trusted authority. Other softwares can choose to use this windows pre-installed list of certificates (aka "Repository" or "Trust store"), or have a separate list (firefox, for example, has a list apart from Windows).
Comment: I believe that Outlook uses Windows repository. Thunderbird and Firefox probably share the same repository (separate from Windows). Java also has its own repository (in `JAVA_HOME/jre/lib/security/cacerts`), but I think it's possible to merge it with Windows repository. Many application servers can use java cacerts or have its own as well (some allow you to have different truststores per instance). Anyway, every software (usually) provides a way to add new certificates to its repositories (and it's usually documented). That's how a certificate chain is validated in any system/application.
Comment: `X509ExtensionUtil.fromExtensionValue` is now replaced by `JcaX509ExtensionUtils.parseExtensionValue` (I haven't tested whether it works)
Answer: btw, if we have out certificate installed in windows, everything is much simpler:
KeyStore ks = KeyStore.getInstance("Windows-MY");
ks.load(null, null);
String alias = "your alias";
ArrayList<X509Certificate> certsChain = new ArrayList<>();
if (ks.isCertificateEntry(alias)) {
    Certificate[] chain = ks.getCertificateChain(alias);
    System.out.println("Chain length: " + chain.length);
        for(Certificate c : chain) certsChain.add((X509Certificate)c);
}

Collections.reverse(certsChain);
certsChain.forEach(MainClass::printDBG);

boom, and the whole certificates chain is ready


What Java version do I need to install to run the Ardor blockchain public server node?

Question: I am trying to run compile.sh for the Ardor public node server. But the latest Java 11 isn't working.
Answer: The most reliable option is  to install Java 8 on ubuntu like this:

apt install openjdk-8-jdk


Does compact normal space implies metric space?

Question: I know compact Hausdorff space is normal, and metric space is normal.
What about compact normal space? Is it a metric space?
My naive guess is that normality is nothing to do with metric and compactness(finiteness) is also nothing to do with metric so it seems it is not a metric space. But how one can prove or disprove this more than my idea?
Comment: What about $[0,1]^{[0,1]}$ with product topology?
Comment: Some examples [here](https://topology.jdabbs.com/spaces?q=compact%20%2B%20normal%20%2B%20~metrizable)
Comment: Not necessarily, since any compact space is normal.
Comment: @KaviRamaMurthy . Also $\{0,1\}^{[0,1]},$ with the discrete topology on $\{0,1\}.$
Answer: A beautiful example to the contrary is the Double Arrow Space, one of the classics in topology.
It's compact, perfectly normal ($T_6$), hereditarily Lindelöf, hereditarily separable, first countable, but not metrisable as it does not have a countable base.
Comment: Another elementary example is the lexicographic-order topology on $X=[0,1]^2$. All linear spaces are normal, and $X$ has the $lub$ property (every subset has a $lub$) so $X$ is compact. A compact metrisable space is separable, but $\{\{r\}\times (1/3,2/3):r\in [0,1]\}$ is an uncountable family of pairwise-disjoint open subsets of $X,$ so $X$ is not separable.
Comment: @DanielWainfleet double arrow is a subspace of that square. But it's nicer ( hereditarily separable/ Lindelöf).
Comment: Yes.  The lex. square is not $T_6$, among other things. The Double-Arrow is a great example of how far you might go and still not be metrisable.


Similar entries 7.x-2.0 known error

Question: When I try the view for out-of-the-box use that comes with Similar entries 7.x-2.0 i get this error:
Strict warning: Declaration of similar_handler_argument_nid::query() should be compatible with that of views_handler_argument_numeric::query() in require_once() (line 11 of C:\xampp\htdocs\drupal\sites\all\modules\similar\views\similar_handler_argument_nid.inc).
I searched drupal.org and found someone with the same problem: http://drupal.org/node/1270404
with no answer since September so I decided to try here.
I have tried the beta1 and dev version, run cron, tried to find some tutorial on how to use the module, read the readme for the module and had no luck. Am I missing something obvious?
I also get the error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'score' in 'order clause'
Answer: This is not you, it is a bug in the module. I'm sorry to say that the fact that the bug goes back to September does not bode well for a fix.  Neither does the fact that there is only one active maintainer who has not made any changes since the releases in August.  If you are a coder, you might try fixing the code.  If not, you may want to look for other options.
Comment: OK, thanks. BTW I created something with views that can be used as similar content so no need for code fixing

Similar entries 7.x-2.0 known error


symfony2 : How to disable APC cache selectively on few routes

Question: I am using symfony version 2.3 . I have used following in my config.yml
metadata_cache_driver: apc
result_cache_driver: apc
query_cache_driver: apc

I want to disable caching at following URL . www.domain.com/dashboard
How can I achieve this ? Any help
Comment: Can you provide a bit more information of why you want to do that?
Comment: As soon as I submit any form to Edit , Symfony somehow not recognizing new values and submit it with old values.
However it works absolutely fine with APC disabled. I want to handle my admin CMS without APC for same reason
Comment: I think this is not related to APC. Usually, if the form is not valid, symfony2 renders the same content. Have you check the form errors?
Comment: Yes , did this for sure , have written all validations inside if (Form isvalid) block.
May be I am missing something but if without APC it is working fine , It has to do something with APC only
Answer: In your app.php or index.php you should have something like this :
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
$apcLoader = new ApcClassLoader(sha1(__FILE__), $loader);
$loader->unregister();
$apcLoader->register(true);

require_once __DIR__.'/../app/AppKernel.php';
require_once __DIR__.'/../app/AppCache.php';

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
$kernel = new AppCache($kernel);

// ...

so you can have a condition with $_SERVER['REQUEST_URI']
e.g
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';

require_once __DIR__.'/../app/AppKernel.php';

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();

if (!preg_match('#dashboard#'), $_SERVER['REQUEST_URI']) {
    $apcLoader = new ApcClassLoader(sha1(__FILE__), $loader);
    $loader->unregister();
    $apcLoader->register(true);

    require_once __DIR__.'/../app/AppCache.php';

    $kernel = new AppCache($kernel);
}

// ...

hope it helps
Comment: Worked like charm , Thanks Buddy !!
Comment: How would it actually work then ?  I feel it is something at global level , I need it at route level , For this matter if it is just a user level , I am okay with it
Comment: you could use an event listener on kernel.request to change the container parameter dynamically
Comment: @vishalvasudeva with or without listener ?


What embouchure and mouth configuration is the best for singing soul music?

Question: I only started singing soul music well when I started keeping a large horizontal embouchure and I started pushing the back of my tongue up and the soft palate down, sounding more "nasal". This creates a soulful/squeezed sound that is great when I sing Otis Redding, John Belushi, Wilson Pickett, James Brown, The Doors, Stevie Wonder and so on... Is that the right mouth configuration for that style of singing?
Unfortunately, I cannot find a teacher that seems to agree. One coach, recently told me to try to sing with a more neutral mouth and a lowered jaw, rather than an American large configuration of the mouth. His intention was to reduce the tension, but in the end he also realised I cannot have that same nice soulful sound if I sing in that way, and it sounds more like Pavarotti singing rock n roll.
Other times I was told to keep the tongue neutral and raise my soft palate. That also doesn't work well when I listen back to my recordings.
Is there any standard way of singing for soul singers? any standard mouth configuration or embouchure?
Comment: I just want to reassure you that it can take some time to adjust to a change in technique.  I hope that after you get used to the change this coach has suggested, you'll be able to integrate the new with the old.  I do think it is worthwhile to make some changes in order to reduce tension.  Best of luck!
Answer: yo, I agree,
you can have your 'standards' that have good technique meaning healthy singing and also experiment with ya voice.
Did you record yourself? It is more important how you project, then how 'nasal'/soulfull it sounds to yourself.
Mostly the tone should come out clearly and then is 'styled' within this projection (be it nasal/soul-ish) imho.
Have fun!
Answer: It seems you've already found the way that gives you the tone you want. As long as you don't feel you're straining or otherwise injuring yourself, that's all you need.
My strong recommendation is that you study with a teacher to learn "proper technique" and mastery of "the apparatus" — which means you might sound like Pavarotti for a while. (You could do worse than Pavarotti.)
But once you have good enough control of your breathing, palate, glottis, vowel shape, diction, etc., you'll be able to adjust to the demands of whatever style you choose.
As examples, I'll point to Lada Gaga and Meryl Streep. Both trained classically, but Lada Gaga can adjust her voice to sing pop and jazz, and Meryl Streep can sing Abba with the best of them.


Solution of non linear ODE system is always positive if its initial valus is positive

Question: Given a system of nonlinear differential equation \begin{eqnarray}\frac{dx}{dt}=2x(3-y) \\ \frac{dy}{dt}=3y(4-x)\end{eqnarray}
If $r(t)=$($x(t)$,$y(t)$) is a solution of the system with initial value $x(0)>0$ and $y(0)>0$, would you help me to prove that $x(t)>0$ and $y(t)>0$ for all real $t$.
Here is my argument:
I prove it by contradiction.
Let $r_1(t)=(x_1(t),x_2(t))$ be an orbit of the ODE with $x_1(0)=0$. Since, for $x=0$ we get $\frac{dx}{dt}=0$ then $x_1(t)=x_1(0)=0$. Thus, $x=0$ is an invariant manifold of the ODE. By the same argument, $y=0$ is also an invariant manifold. So the orbit that passing through a point in $x=0$ (resp $y=0$) always lies in $x=0$ (resp $y=0$).
Assume there is a $t_1$ such that $x(t_1) \leq 0$ then $r(t)$ must intersect an orbit in $x=0 $( or $y=0$) hence $r(t)$ must lies on $x=0 $ (or $y=0$), contradicting $x(0)>0$ and $y(0)>0$.
Is there any a direct proof (or even elementary/simple proof)?
Answer: It is not quite clear what exactly you mean by "direct proof", but the main idea is very simple: the boundaries of $\mathbf R^2_+$ consist of orbits and due to the uniqueness and existence theorem the orbits cannot cross, which means that there is no way to cross a boundary.
Comment: Note that our idea is similar right, assume there is a negative x or y then the orbit intersect invariant manifold which contain different orbit. I mean direct proof is using inequality start from $x(0)>0$ and $y(0)>0$ then by invariant manfold information and some analytic process  to conclude $x(t)>0$ and $y(t)>0$
Comment: @beginner Yes, of course, your idea is right. What I mean is the following: It seems to me that you overcomplicate the problem, the reasoning along the line: orbits do not cross and the boundary is composed of orbits together imply the solution will stay positive. This last sentence is a *proof* for me and does not require any additional arguments.


Python: parsing and extracting op-codes from asm

Question: I would like to parse an assembly file and extract only the opcodes, stripping-of the operands. Each line in the input file consists of exactly 3 opcodes. Should I extract the first word after the "[" in each line and accumulate in list ? Is there a better way of doing this?
Here is my input file format:
<code>[slli a3,a3,4] [add.n a3,a3,a8] [l32i a11,a3,128]
[add.n a3,a3,a8] [l32i a11,a3,128] [l32r a9,0x1fff8954]
[l32i a11,a3,128] [l32r a9,0x1fff8954] [l32i.n a10,a11,4]
[l32r a9,0x1fff8954] [l32i.n a10,a11,4] [l8ui a8,a11,0]
</code>
My Expected output should be something like this:
<code>[ slli  : add.n  : l32i   ]
[ add.n : l32i   : l32r   ]
[ l32i  : l32r   : l32i.n ]
[ l32r  : l32i.n  : l8ui  ]
</code>
Comment: Your approach sounds reasonable to me...
Comment: what is the reason for the colons in the expected output?
Comment: @cchristelis : That's just for distinguishing opcodes. I can add-in a space or comma instead.
Comment: @user3769674 great and your input is a string?
Comment: @cchristelis  Yes, its a string.
Answer: This is quite easy to do with regular expressions.
<code>import re
pattern = re.compile(r'\[(\S+)')
output = []
with open('inputfile') as f:
    for line in f:
        output.append(pattern.findall(line))
</code>
Now you have a list of opcode lists.
<code>>>> from pprint import pprint
>>> pprint(output)
[['slli', 'add.n', 'l32i'],
 ['add.n', 'l32i', 'l32r'],
 ['l32i', 'l32r', 'l32i.n'],
 ['l32r', 'l32i.n', 'l8ui']]
</code>
This list can then be processed to produce your required output, e.g.
<code>>>> for line in output:
...     print '[ %s ]' % ' : '.join(line)
...
[ slli : add.n : l32i ]
[ add.n : l32i : l32r ]
[ l32i : l32r : l32i.n ]
[ l32r : l32i.n : l8ui ]
</code>
Answer: finding op-codes:
<code>>>> import re
>>> re.findall(r'\[(?=([a-z0-9.]+))','[slli a3,a3,4] [add.n a3,a3,a8] [l32i a11,a3,128]')
['slli', 'add.n', 'l32i']
</code>
You should wrap that into a function.


When is an interaction in quadratic regression significant?

Question: I run a regression with a continuous variable $x_2$ and a binary grouping variable $x_1$. We suppose that the effect of $x_2$ is quadratic on the dependent variable $y$ and our question is whether the effect of $x_2$ on $y$ depends on $x_1$.
The formula is $y\sim x_{1} + x_{2} + x_{2}^{2} +  x_{1} : x_{2} +  x_{1} : x_{2}^{2}$. So I get two signifince tests for interaction, i.e. $p$ for $x_{1} : x_{2}$ and $p$ for $x_{1} : x_{2}^{2}$. What of the following statements is true:

We can say that there is a significant interaction if one of the both interaction coefficiens is significant, no matter whether it is a significant $p$ for $x_{1} : x_{2}$ or a significant $p$ for $x_{1} : x_{2}^{2}$
We can say that there is a significant interaction if both interactions coefficients are significant
We must first run a model without any interaction, then a model with both interaction terms, than compare both models using ANOVA. If the $p$ of the F test is significant we can say that there is a significant interaction.

Or is there another approach one must choose in order to test whether the effect of $x_2$ depends on $x_1$ significantly?

Edit
To make clearer point three:
model1 <- $y\sim x_{1} + x_{2} + x_{2}^{2}$
model2 <- $y\sim x_{1} + x_{2} + x_{2}^{2} +  x_{1} : x_{2} +  x_{1} : x_{2}^{2}$
ANOVA(model1, model2)
The p value of F in this ANOVA will show whether the effect of x2 depends on x1, i.e. whether the interaction is significant.
Answer: Don't think of indidivual coefficients when a variable is represented by more than one term in the model.  Think of composite (AKA "chunk") tests which test more general hypotheses.  Chunk tests use likelihood ratio, Wald, score, or $F$-tests and have multiple degrees of freedom.  From the model specified above here are some useful chunk tests:

test all coefficients jointly that relate simultaneously to $x_{1}, x_{2}$ (2 d.f., tests whether effect of $x_2$ depends on $x_1$
test all coefficients relating to $x_1$ (3 d.f., tests whether $x_1$ is associated with $Y$ for any value of $x_2$)
test all coefficients relating to $x_2$ (4 d.f., tests whether $x_2$ is associated with $Y$ for any value of $x_1$)

All these chunk tests are provided automatically in the R rms package's anova function:
require(rms)
f <- ols(y ~ x1 * pol(x2, 2))
anova(f)  # provides F stats since using a linear (ordinary least squares) model

Chunk tests have interpretability and importantly do not depend on the coding/centering of variables.  They also provide perfect multiplicity adjustment in frequentist modeling.
Comment: Does this correspond to point three in my question? Also see edit of my question.
Comment: Shouldn't "test all coefficients relating to x2" be df 4? x2 has four coefficiens
Comment: Thanks for the correction; fixed.  Yes point 3.
Answer: The first one seems right to me.
The second one seems wrong.
The third one answers a somewhat different question: Do the interactions add a significant amount to the model?
However, I think it would be better to be more specific in the question and answer, by specifying the two different interactions.
Comment: You can state the 3rd either way, i.e., it tests whether the effect of one variable varies with the level of the other variable.   I wouldn't stress "two different interactions".  $x_2$ is expressed as 2 terms in the model and these terms need to be kept together, otherwise the tests are very coding/origin-dependent.


Inductively constructing a homeomorphism between CW complex and polyhedron

Question: This is 5-18b of J. Lee's "Introduction to Topological Manifolds".
Suppose $X$ is a regular CW complex. Then let $\mathcal{E}$ be the set of open cells of $X$, $\mathcal{K}$ the collection of all nonempty finite subsets $\{e_0,...,e_k\}\subseteq\mathcal{E}$ with the property that the dimensions of the elements are all distinct, and $e_{i-1}\subseteq\partial e_i$. I have shown that $\mathcal{K}$ is an abstract simplicial complex in part a) of the question. Part b) proceeds as follows:
Suppose $K$ is a Euclidean simplicial complex whose vertex scheme is isomorphic to $\mathcal{K}$. Show that $X$ is homeomorphic to $|K|$ (the polyhedron of $K$) via a homeomorphism that sends the closure of each cell of $X$ onto the polyhedron of a subcomplex of $K$.
The reader is given the following hint: begin by choosing $v_e$ in each simplex $e\in\mathcal{E}$. Then define a homeomorphism inductively, one skeleton at a time, in such a way that it sends each point $v_e$ to the vertex of $K$ corresponding to $e$.
In previous exercises, I proved that any homeomorphism $f:\partial D\to\partial D'$ can be extended to a homeomorphism $F:D\to D'$, for two closed cells $D$ and $D'$. I understand that this fact should help me construct the homeomorphism in some inductive fashion, but I am not sure how to realise this construction. For the $0$-skeletons, it seems clear that the map should take every $e_0$ to $\{e_0
\}$. Then, assume the homeomorphism has been constructed for the $(n-1)$-skeleton. Denoting by $|K|_i$ the $i$-skeleton of the polyhedron $|K|$, we have a homeomorphism $F_{n-1}:X_{n-1}\to |K|_{n-1}$. From this, how would I create the homeomorphism for the $n$-skeleton?
Answer: That earlier exercise is not going to be sufficient, because your description of the induction has a flaw.
As you say, the homeomorphism between $X$ and $|K|$ is being constructed inductively on the skeleta $X_0 \subset X_1 \subset X_2 \subset \cdots$. However, your induction hypothesis is incorrect, because the image $f(X_n)$ is not going to be equal to the entire $n$-skeleton of $|K|$; instead it is only going to be a subcomplex of the $n$-skeleton of $|K|$.
For example, $f(X_0)$ is not the entire $0$-skeleton of $|K|$, it is only the subcomplex of the $0$-skeleton corresponding to singleton sets $\{e_0\}$ such that the dimension of $e_0$ is equal to $0$.
More generally, given a cell $e \subset X$ of dimension $d \ge 1$ corresponding to a $0$-simplex $\{e\}$ of $|K|$, the point of $X$ which is mapped to that $0$-simplex by $f$ is going to be the chosen point $v_e$ in the interior of $e$. Thus the $0$-simplex $\{e\}$ is not contained in $f(X_{d-1})$, but it is contained in $f(X_d)$.
With that said, let me strengthen the hint from Lee's book somewhat. The description of $f$, and the induction hypothesis of the construction of $f$, should both state with more precision what is the image under $f$ of each closed cell in $X$:

Given an open cell $e \subset X$, what will $f(\overline e) \subset |K|$ be?

If you can answer that question, you should be able to reformulate your induction and then proceed with the construction.
Comment: I have a question about your statement that $f(X_0)$ is not the entire $0$-skeleton. In the book, the definition of the $k$-skeleton of $K$ is the set of all simplices of $K$ with dimension at most $k$. What other simplices that aren't singleton sets with dimension $0$ does $|K|_0$ contain?
Comment: As said in my answer, those other sets are singleton sets $\{e\}$ with $\text{dimension}(e)\ge 1$.
Comment: Unless I've fully misunderstood the definition, aren't those prohibited from being in $|K|_0$ due to their dimension being greater than $0$? I apologise if this seems like a stupid question, but I must confess I find this subject rather confusing.
Comment: I think you may indeed have misunderstood the definition: "$\mathcal{K}$ the collection of all nonempty finite subsets $\{e_0,...,e_k\}\subseteq\mathcal{E}$ with the property that the dimensions of the elements are all distinct, and $e_{i-1}\subseteq\partial e_i$." Other than requiring that the natural numbers $\text{dimension}(e_0),...,\text{dimension}(e_k)$ are all distinct, there is no other requirement on those natural numbers.
Comment: So, for example, in the case $k=0$, which is a singleton subset $\{e_0\} \subset \mathcal E$, there is no requirement whatsoever, **any** singleton subset of $\mathcal E$ is an element of the abstract simplicial complex $\mathcal K$.
Comment: What it looks like to me is that you have some confusions arising in the relations between the "abstract" simplicial complex $\mathcal K$, and the Euclidean simplicial complex whose vertex scheme is isomorphic to $\mathcal K$.
Comment: An important example to study is the case where $X$ is already a simplicial complex to begin with. In that case, $K$ turns out to be the first barycentric subdivision of $X$, with one $0$-simplex of $K$ for every simplex of $X$ (without any restriction on dimension).


How does `drush features-update` work?

Question: I have made changes to a Feature on a Drupal 7 site.  I want the same feature to be updated in another website. How to do it using the drush features-update command? When I run it, it asks to overwrite the previous Feature, but nothing new comes in the Feature.
Answer: Drush feature-update updates the feature code with overwritten settings. So the function is used to export changes to code.
If you want to take those changes to another site, you will have to copy the updated feature to the other site unless they share the same code (and then revert the feature and clear cache (not always needed)).
In code it could look like this
$ drush fu feature_module
$ cp -r feature_module ./DIR
$ cd DIR
$ drush fr feature_module

Comment: No. All that feature-update does is update the feature code with customizations of the *existing* components of the feature (E.g. new fields on content type, changed field settings). If you want to add additional components, you need to do it through the UI or by manually updating the .info file of your feature and then run drush fu. drush fu has nothing to do with moving code between multiple sites, search for version control/git if you're looking for that.
Comment: @subhojit777 Update takes the changes from the site and into the feature code, revert is the reversed process of removing (reverting) the custom changes in a site and using those defined in the feature code.
Comment: @Berdir ... adding components can be done via the command line with "drush features-export" as explained here http://www.alexweber.com.br/en/articles/drupal-development-boss-using-drush-and-features

How does `drush features-update` work?


Is there anyway to change the path of a blob from URL.createObjectURL

Question: I am using GMS1.4 HTML5 module and i'm currently trying to import sprite images to it. The issue is i don't want to save it in the local directory and since there is a built in function that allows the sprite to be added from a URL i was thinking of just using a blob to get the job done so the temp sprite is erased from memory after the user is done with the game.
The problem is 1.4 is sandboxed so all url links and references seems to point to the Local storage. instead of
blob:http://mysite.co/85cad96e-e44e-a1f9-db97a96ed3fe

it'll preapped like this
http://mysite.co/html5game/blob:http://mysite/85cad96e-e44e-a1f9-db97a96ed3fe

Im only assuming its due to the sandbox nature of GMS and there does not seem to be a way to turn it off. my next idea is since it wants to be stubborn about using the sandbox directory, was to just create the blob within that folder. Is it possible to create at path and URL.createObjectURL?
Comment: [No you can't](https://stackoverflow.com/questions/41947735/custom-name-for-blob-url), you'd be better just asking the original question: how to make game-maker not preprocess your links.
Answer: You could adapt an approach based on what I did for "Allow Data URI" to also allow blob URIs. Excerpt follows,
GML:
#define gmcallback_AllowDataURI
if (AllowDataURI()) {
    AllowDataURI(sprite_add("", 1, 0, 0, 0, 0));
}

JS:
function AllowDataURI() {
    var p0 = "\\s*\\(\\s*";
    var p1 = "\\s*\\)\\s*";
    var eq = "\\s*=\\s*";
    var id = "\\w+";
    //
    var init_js = window.gml_Script_gmcallback_AllowDataURI.toString();
    var sprite_add_js = window[
        /\bAllowDataURI\s*\(\s*(\w+)/.exec(init_js)[1] // AllowDataURI(sprite_add(...
    ].toString();
    var sprite_add_url = /function\s*\w*\s*\((\w+)/g.exec(sprite_add_js)[1];
    var sprite_add_url2 = new RegExp(
        "("+id+")"+eq+sprite_add_url+"\\b", // `sprite_add_url2 = sprite_add_url`
    "g").exec(sprite_add_js);
    sprite_add_url2 = sprite_add_url2 ? sprite_add_url2[1] : sprite_add_url;
    //
    var image_add_js = window[new RegExp(
        id+eq+"("+id+")"+p0+sprite_add_url2+p1, // `_ = image_add(sprite_add_url2)`
    "g").exec(sprite_add_js)[1]].toString();
    var image_add_url = /function\s*\w*\s*\((\w+)/g.exec(image_add_js)[1];
    //
    var url_proc = new RegExp(
        id+eq+"("+id+")"+p0+image_add_url+p1, // `_ = url_proc(image_add_url)`
    "g").exec(image_add_js)[1];
    window[url_proc] = (function() {
        var f = window[url_proc];
        return function(url) {
            if (url.substring(0, 5) == "data:") return url;
            if (url.substring(0, 5) == "blob:") return url; // new!
            return f.apply(this, arguments);
        };
    })();
    //
    return false;
}


The imporance of having SELinux enabled on a web server

Question: This question is probably a matter of personal opinion but I wanted to gather your thoughts on how important having SELinux enabled on a web server is.
In your opinion, is the added security a must or just nice to have?
Is the performance hit worth it?
Is it worth the trouble?
Do you recommend an alternative (ex: mod_security)?
I look forward to hearing everyone's thoughts!
Comment: I found some useful answers here: http://stackoverflow.com/questions/97816/do-you-disable-selinux
Comment: Asking about 'worth' is highly subjective as it is currently written.  The requirements for a 'brochure site' would be completely different then the requirements for an online banking site.  This question would also be a better fit over on http://security.stackexchange.com/ where you could possibly get some useful answer if you adjusted your question to be less subjective.
Answer: I honestly don't think it's worth the trouble.  Yes, it provides an added level of security, but at significant cost.  Security isn't an absolute; all you have to do is be better than other targets that are at a similar risk of being targetted (or that have a similar benefit to the attacker if they're compromised).  Given the number of servers that can still be popped open using some simple password brute-forcing, trivial web application vulnerabilities, and massively out-of-date patch levels, if you're actually do all that stuff, then you're so invulnerable relative to millions of other systems that your risk of intrusion is already so low as to be not worth any additional faffing around.
This is, of course, assuming that your risk analysis centers around untargeted attacks.  If you're likely to be a target of a particularly skilled or motivated attacker (either because you're a valuable target, like a bank, or people particularly want to take you down, like Sony) then you might want to look at SELinux, or some other niche security products.
Comment: I disagree with the line "be better than other targets that are at a similar risk of being targetted" because for a lot of attacks there isn't a human picking targets. It's an automated botnet scanning ip addresses, and then trying exploits when it hits a web server or other service. If none of the library of exploits crack that service, it moves on. Your odds of being attacked don't depend on your relative level of security, only on having an ip address reachable by an attacker. You need to not be vulnerable to their library of automated attacks.
Comment: Yes, that's my point: keep yourself patched against the library of exploits for (usually *really* old) publically-known vulnerabilities, and then "your risk of intrusion is [...] so low as to be not worth any additional faffing around [ie running SELinux]".


Como evitar arquivo php ser executado quando estiver sendo processado?

Question: Como é possível impedir que um arquivo em php quando ele esta sendo executado não seja executado por outro usuário?
um exemplo:
Usuário X abre o arquivo exe.php o tempo de processamento dele vai ser em 25 segundos neste tempo o usuario Y resolve abrir o arquivo exe.php mas ele não pode ser executado pois o usuario X ainda esta processando o arquivo.
Existe uma solução para isto?
Comment: Até tem uma série de maneiras diferentes para isso, como a resposta do colega @epx (que ja levou meu +1) mas a impressão que dá é que você está com um [Problema XY](https://pt.meta.stackoverflow.com/questions/499/70), ou seja, perguntando do caminho que você acha que é a solução, em vez de expor o verdadeiro problema.
Answer: Você pode tentar criar um arquivo temporário, se for Linux poderia ser algo como /tmp/exe.php.lock, e apagar quando o processamento termina. Mas há um grande risco de o arquivo não ser removido se o PHP falhar no meio do caminho.
Outra saída é criar um socket numa porta bem-definida e fixa. Se o bind() falhar é porque outra instância já criou o socket naquela porta e ainda não saiu. Você pode consultar o exemplo em http://php.net/manual/en/sockets.examples.php para ver como criar o socket; só precisa ir até o bind(), e não esquecer do socket_close() ao final.
e fechar o socket quando acaba o processamento. A chance do socket ficar aberto se o PHP falhar no meio do caminho é menor, ou talvez inexistente.
Comment: Sua resposta está melhor do que as da postagem original do fechamento (inclusive eu mencionei na original o problema do lock "órfão", que você sabiamente resolveu com o `bind()`). Pena que o pessoal do SOpt não faz _merge_ de postagens.


Using Views' Contextual filters in a Panel for one taxonomy term

Question: I have one taxonomy term, Country, which is linked to another, People. One people is from one country.
How can I make a view in my Panel, using Contextual filters, in order to show the specific view I prepared for "Country" ? I tried to use contextual filters to do so, and it works when I use the preview with the Country ID - but not in Panels.
Comment: I'm not sure I follow what you're ACTUALLY asking - perhaps you could provide a little more information?
Comment: Are you sure you mean taxonomy **term** or do you mean **vocabulary** (collection of terms)?  Terms: US, Canada, Mexico / Vocabulary: Countries
Comment: Sorry if unclear, I just wanted to know how to display a view related to a taxonomy term link, while using a contextual filter for example.
Comment: @PatrickKenny I want to use **terms** and not vocabularies, my mistake while I typed ... If my people is from France, I want to show a view I created for France - is it clearer ?
Answer: If you want to display a different view for a country, I think what you probably want to do is use the Taxonomy Term override page rather than using contextual filters.
To do this, go to the pages admin screen (/admin/structure/pages).  Then, enable the Taxonomy term template panel to override the display of taxonomy terms using Panels.
To show a custom view, you can edit the Taxonomy term template panel.  This will allow you to use the taxonomy term as arguments for your view, because Panels understands that you are overriding the taxonomy term display.
Comment: Thanks for your answer, but I admit my question is not very well asked ...

In fact, I need to have 2 blocks, with one for the "People" and one from the "country"

Like

Block 1 :
France
Capital: Paris
[Photo]
President: blabla

Block 2 :
Name: aaaa
Surname: bbb
Address: ccc
Country: France

Am I clearer ?
Comment: In that case, you can add two different views to the taxonomy term override page.  View 1 shows the country information (capital, photo, etc.)  View 2 shows the people in that country.  You can just create both views and add them to the "content" of the panel.
Comment: But how do I get the country ID from one view to pass it as a contextual filter parameter in my second view ?
Comment: If you are using Panels, and you are overriding the taxonomy term display, use a *Content Pane* display (in Views, instead of a block display) and enable "use panel argument" (you will have to set the appropriate context).  This will allow you to populate your contextual filter with the country ID being passed to panels.
Comment: Yes, this is what I am trying to do - but how can I pass the country ID to the other panel ? Since I only have the country name displayed in my term view ?
Comment: You use one *panel*, the term override panel.  Then you attach multiple panes (made with Views).
Comment: Sorry I mistyped pane and panel ! I have one term override PANEL with two PANES actually (think it's time to change their taxonomy lol)
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/10256/discussion-between-marcandria-and-patrick-kenny)
Answer: I managed to do what I wanted to by taking the problem reversely :

I created my view, then added a contextual filter not by "Country ID", as I did, but by "People ID"
Then I configured the argument input in Views by taking the source from the argument of the panel (which matched my "People ID") and it was taken in account by my Views and actually works.

Drupal is quite complicated to understand sometimes ! :) Thanks for advice Patrick Kenny ;)
Bye


Trazer apenas certas quantidades de informações do banco MVC

Question: Preciso trazer apenas 6 registos do banco de dados para mostrar na View,  em vez de trazer apenas 6 registos, ta trazendo todos.
O código é o seguinte:
public PartialViewResult Cursos()
{
    ViewBag.Cursos = new CursoRepositorio().BuscarTodos().Take(6).ToArray();
    return PartialView();
}

Comment: podes mostrar a função buscar todos? e a partial view
Comment: A buscar todos é `public IEnumerable BuscarTodos()
        {
            return Db.Set().ToList();
        }` e a partial view so tem um foreach que vo monta com os 6 dados do banco, nada de mais
Comment: Grande erro!!! uma vez que você já foi no banco e retornou todos os dados  (((return Db.Set().ToList();))) tente alterar isso com a quantidade que você quer antes de lança a consulta contra o banco de dados.
Comment: Mais uma grande falha causada por tentar implementar *repository pattern* em cima do EF.
Answer: Na sua consulta do Entity Framework é necessário informar quantos registros seram listados ...
Tente criar um objeto
DaoCurso

E utilize uma lista desse curso
List<DaoCurso> curso = null;

curso = entity.TBCURSO.Select(x=> new DaoCurso() { idcurso =x.idcurso , nomecurso = x.nomecurso ).Take(6).ToList();

E adicione isso na sua ViewBag;
ViewBag.Cursos = curso;


Is it learned or innate our reaction of happiness or sadness in music?

Question: Are we born with the response telling us that the chord tones or melody has a sad or happy quality? Or is it learned by our culture?
The minor scale and chords have a serious or sadness to them while the major scale and chords are brighter or happier. That is usually the interpretation in the western world.
I wanted to know of any research that has been done to investigate this.
Comment: I'm voting to close this question as off-topic because it is a psychology question.
Comment: I want to say that our culture tells us what are reactions should be, but I cannot expand that into an answer; for the sadness of the minor chords, take a look here: [Why do minor keys sound "sad"?](http://music.stackexchange.com/questions/3/why-do-minor-keys-sound-sad)
Comment: it's both. our brains are wired from birth (most likely) or at least very early on for either the 12 tones or multiples/subsets thereof. there's a whole lot of research that's been done. But I have no references for ya - that's on you. It's kind of the main question of music theory - Why/how is music the way it is? Why/how does it sound good?
Comment: @Dave I don't think this is off topic; we've had similar questions
Comment: @Shevliaskovic (r lo) I consider it right at (but over) the edge, and probably better addressed by psychology. /How/ do we come to associate sound patterns with emotions? is a (developmental) psychology question.  /Which/ sound patterns are associated with different emotions? is a question that can be answered in terms of ethno-musicology. (The similar questions that I'm aware of fall in the latter category).
Comment: @Dave I believe that part of the practice of music and theory relates to composition and song writing.  To me as a performing songwriter, I am very interested in how sound patterns affect emotional response.  If I write sad lyrics, I need to know how to effectively convey that emotion through the music.
Answer: Well, I'm not aware that any "bright and happy" Country & Western songs have ever been written, and they all seem to be harmonized with nothing beyond three major chords :)
More seriously, the history of European/western music is very well documented for the last 1000 years, and within that time frame - insignificantly short in the context of biological evolution - there have been huge cultural shifts in the "meaning" of musical constructs. Go back 1000 years, and both major and minor thirds were considered to be discords that were hardly ever used in any musical context.
You might also consider western/European ethnic instruments. For example the Highland bagpipes have a range of just 9 notes approximating to a major scale (the tuning of the scale is actually unique to that instrument, but the important point here is that there are no "chromatic" notes at all in the traditional playing style) and they were (and still are) used to play lively dance music, laments for dead heroes, and everything in between.
Outside of western and European music, the ground rules are completely different. Consider Indian "classical" music, or even Bollywood film scores, for example.
Answer: I'm reminded of the Biblical story of IIRC David's medallion. Where King David commissions an object which will make him happy when he is sad and make him sad when he is happy. The result was a medallion, with the same message inscribed upon both sides: This too shall pass.
Music (properly executed) does indeed contain within it a certain emotional content. I'm reminded of the immortal words of Jack Black: "What about the power to move you?"
But music clearly has a different effect upon different people (with the possible exception of special forms like hymns). It can even have a different effect upon the same person at different times. Yeah, love this song. Yep, still catchy. You know, I've heard this song a lot lately. This song, again??
One possible explanation for this is the Brahminical idea of The Wheel of Samsara. That there are 6 distinct moods that each person traverses in the same order, but at different speeds. But, as one commentator feared, this is definitely the territory of psychology and not music, per se.


'Object reference not set to an instance of an object' - what does this mean?

Question: I am making an MVC 3 app which contains data about "associates", however I also need to be able to delete these "associates" through the app. I am using the Delete ActionResult but every time I try to delete an entry I get the following server error:
Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 14:

Line 15:
@Html.LabelFor(model => model.FirstName)

Line 16:
@Model.FirstName

Line 17:

Line 18:

Source File: c:\Users\Jackie\Documents\Visual Studio 2010\Projects\Associate Tracker versions\Associate Tracker v5\LoginFormExample\Views\Associate\Delete.cshtml    Line: 16

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
   ASP._Page_Views_Associate_Delete_cshtml.Execute() in c:\Users\Jaskharan Shoker\Documents\Visual Studio 2010\Projects\Associate Tracker versions\Associate Tracker v5\LoginFormExample\Views\Associate\Delete.cshtml:16
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +207
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +81
   System.Web.WebPages.StartPage.RunPage() +19
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +65
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +220
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +303
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +23
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +260
   System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +19
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
   System.Web.Mvc.Controller.ExecuteCore() +116
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8969117
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

The controller:
//
// GET: /Associate/Delete/AssociateId
public ActionResult Delete(int id)
{
    using (var db = new AssociateDBEntities())
    {
        return View(db.Associates.Find(id));
        }
    }

//
// POST: /Associate/Delete/AssociateId
[HttpPost]
public ActionResult Delete(int id, Associate associate)
{
        try
        {
            using (var db = new AssociateDBEntities())
            {
                db.Entry(associate).State = System.Data.EntityState.Deleted;
                db.SaveChanges();
            }
            return RedirectToAction("ViewAll");
        }
        catch
        {
            return View();
        }

'Delete' view:
@model LoginFormExample.Models.Associate

@{
    ViewBag.Title = "Delete";
}

Delete

Are you sure you want to delete this associate?

<fieldset>
    <legend>Associate</legend>

        @Html.HiddenFor(model => model.AssociateId)

@Html.LabelFor(model => model.FirstName)

@Model.FirstName

@Html.LabelFor(model => model.LastName)

@Model.LastName

@Html.LabelFor(model => model.Email)

@Model.Email

@Html.LabelFor(model => model.AddressLine1)

@Model.AddressLine1

@Html.LabelFor(model => model.AddressLine2)

@Model.AddressLine2

@Html.LabelFor(model => model.Postcode)

@Model.Postcode

@Html.LabelFor(model => model.Phone)

@Model.Phone

@Html.LabelFor(model => model.Mobile)

@Model.Mobile

</fieldset>

@using (Html.BeginForm()) {

        <input type="submit" value="Delete" /> |
        @Html.ActionLink("Back to view all", "ViewAll")

}

'Associate' class
namespace LoginFormExample.Models
{
    public partial class Associate
    {
        public int AssociateId { get; set; }

        [Required]
        [Display(Name = "First name:")]
        public string FirstName { get; set; }

        [Required]
        [Display(Name = "Last name:")]
        public string LastName { get; set; }

        [Required(ErrorMessage = "Please enter a valid email address")]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email address:")]
        public string Email { get; set; }

        [Display(Name = "Address line 1:")]
        public string AddressLine1 { get; set; }

        [Display(Name = "Address line 2:")]
        public string AddressLine2 { get; set; }
        public int RegionId { get; set; }
        public int CityTownId { get; set; }

        [Display(Name = "Postcode:")]
        public string Postcode { get; set; }

        [Display(Name = "Phone number:")]
        public string Phone { get; set; }

        [Display(Name = "Mobile number:")]
        public string Mobile { get; set; }

Does anybody have any ideas as to why I keep getting this error? I have checked against example applications and I can't seem to spot any differences.
Comment: Do you get an error when calling the delete-page, or after pressing the 'Delete' button on the delete-page (so on POST)?
Comment: I get the error when I press the 'Delete' button.
Comment: Then the answer of Antony Scott below probably is your solution.
Comment: possible duplicate of [What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)
Comment: don't forget to accept the answer which solved your problem :)
Comment: I actually couldn't find a solution to this problem and so ended up deleting my database and creating a new one which seemed to solve the problem as I haven't seen the same error come up again. Thanks all for your help!
Answer: It means that in the line
return View(db.Associates.Find(id));

either db or Associates is null.
This is easy to check using Debug.Assert or a breakpoint. Set a breakpoint on the offending line and run your program again, or insert the following code before the offending line:
Debug.Assert(db != null);
Debug.Assert(db.Associates != null);

Answer: In your controller you are not setting the model when returning the view ...
    catch
    {
        return View();
    }

or this is not finding anything ...
db.Associates.Find(id)

and in your view you are assuming it is set ...
    @Html.HiddenFor(model => model.AssociateId)

Comment: The delete page actually displays the details of the associate so the 'db.Associates.Find(id)' must be working, the error occurs when I hit the delete button
Answer: Your model is probably null because your call to db.Associates.Find(id) is returning null. Do you have a valid id that exists in the table?
If the error occurs during the Delete post, then it will be because you are returning a view without a model.
You are also swallowing any exceptions that occur.
Change
catch
{
    return View();
}

To
catch (Exception exception)
{
    return View();
}

and you can place a breakpoint on the return View() line and view the exception message.
Comment: Yes a valid entry does exist in the database table it is just having trouble removing it from the database.
Comment: After adding the '(Exception exception)' I received the following error message:
'Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.'
Comment: Have a look if any of these answers solve your problem - http://stackoverflow.com/questions/1836173/entity-framework-store-update-insert-or-delete-statement-affected-an-unexpec
Answer: It means that this line
db.Associates.Find(id)

did not find an entity with that id so returned null, therefore inyour view your model is null
further to your edit and looking at the stack trace:
This is throwing an exception
try
        {
            using (var db = new AssociateDBEntities())
            {
                db.Entry(associate).State = System.Data.EntityState.Deleted;
                db.SaveChanges();
            }
            return RedirectToAction("ViewAll");
        }

then this bit
catch
        {
            return View();
        }

Just swallows the exception (hiding your real issue) and returns an empty delete view so your model is null.
Remove the try catch, debug and you will find your real problem.
Comment: The delete page actually displays the details of the associate so the 'db.Associates.Find(id)' must be working, the error occurs when I hit the delete button.
Comment: Thanks Ben, now ' I get the following error message: 'Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.' Just need to figure out how to solve this now :s
Comment: Check the primary key value of your associate entity in your delete statement, the error means you are trying to delete something that does not exist in the database


Verificar se a webview está carregada

Question: Preciso verificar se a webview está carregada para poder executar uma função javascript que se encontra na webview, mas não sei como verificar se a webview já está carregada 100%.
segue o código:
<code>    WebView webView = (WebView)findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new webViewClient());
    webView.loadUrl("http://meusite.com");
</code>
Answer: Você pode implementar o onPageFinished() da classe WebViewClient.
<code>webView.setWebViewClient(new WebViewClient() {
     public void onPageFinished(WebView view, String url) {

     }
});
</code>
Comment: Obrigado Vitor.

Verificar se a webview está carregada


Rcpp and C++ dependencies to gdal, sqlite3 and boost

Question: I am trying to make an hybrid C++/python/R project more easily available for non-programmers.
I am considering the possibility to wrap the C++ code with Rcpp to make it available within an R package and hopefully hide some of the complexity to the end-user.
This question aims to understand to which extend it would be actually easier.
For example, when trying to source my project.cpp, I get  the following error:
fatal error: gdal_priv.h: No such file or directory #include <gdal_priv.h>

Is it possible to write something cross-platform similar to LinkingTo: BH, GDAL, sqlite3 ?
How to know what C++ libraries have been made compatible with Rcpp (like BH for Boost)?
The C++ sub-project works fine using cmake: can I somehow take advantage of these cmake files to help Rcpp finding the external dependencies ?
Answer: That's really three questions.
For 1) I do not know if/how gdal and or sqlite3 export themselves as header-only libraries. I kinda doubt it; gdal is well-known, and also somewhat well-know as a source of "trouble" when building.  GeoSpatial foks may know and can possibly help you.
For 2), the question is ill-defined. What is "compatible with Rcpp" supposed to mean?  There are currently over 1800 packages on CRAN using Rcpp; maybe take those as an "existence proof" and search among them?
For 3), R and CRAN use autoconf / configure a lot more than cmake. You can of course use cmake, but you then need to declare that dependency in SystemRequirements.
In short, packaging external libraries is still difficult, chiefly because you now have to look after their installation on up to three different operating systems.  This has nothing to do with Rcpp, and Rcpp cannot really help. :-/
Comment: The infamous "No Free Lunch" theorem comes at us again!  I wish it was easier, I am fighting that very issue myself in a few projects.  Header-only really is the best, sadly not all projects can be expressed that way.  Docker can be a way out though.
Comment: Thank you for your quick and detailed answer. I imagined that the R packaging system and Rcpp would make it easier to handle external dependencies, but it seems I was wrong :)
Comment: "You can not have both the butter and the butter money" is the equivalent French idiom ;) Docker was next in my list of way out. Next I was thinking about snap to make it easy at least on Ubuntu.
Why is header-only easier to manage ? Because it makes possible to just copy the files in the R package ?
Comment: You know, snap is interesting but ... more difficult. I was at a Ubuntu-organized hackathon for it last year and we couldn't really get R done for package building reasons.  Try Docker. _Et enfin: on dit ca comment en Francais?_
Comment: Bye bye snap then ! Your feedback saves me some time, thank you!
"On ne peut pas avoir le beurre et l'argent du beurre" ;)
Comment: Mind you snap may work to just wrap a package and its libraries. We couldn;t really ship R as an extensible system as the compilable extensions (you know, Rcpp) run afoul the path and env settings of snap.  Too bad really.  But I use some apps as snap and it is good system, and more direct than Docker.
Comment: Ok! I may give it a try after Docker, it seems an interesting system!


Latest Developments in Classical Guitar Strings?

Question: I've put my classical instrument down for a few years, to focus on period instruments.  Now I'm playing the modern instrument again -- the strings are in sad shape!  Before I buy new strings...  Are there any recent developments in strings that I should know about?  I was using Hannabach Blues.  Has anything better come out?
Comment: Hannabachs still seen great to me.
Answer: The D'Addario company has developed some new ideas.
One is a coating applied to the wound strings (similar to the Elixir brand, but for nylon-string classical and not for steel-string acoustic or electric). These three wound strings in the set last longer because they are mostly impervious to oil and dirt from the fingers. D'Addario calls their coated strings the "EXP Coated" line.
The other D'Addario innovation is a new "composite" formulation for the unwound G string to make it sound more like the wound strings. These are found in their Pro-Arte Composite line. Not everybody likes the sound or the feel of these strings.
The Aquila company sells "Nylgut" strings, which are a proprietary synthetic nylon string that is designed to sound more like traditional sheep gut strings (sheep gut is what all classical guitarists used before the 1960s when modern nylon strings were invented). Nylgut strings are very popular for ukuleles but they also have sets for classical guitar.
Comment: There's a great horror story by Helena Blavatsky about the world's second-best violinist (second only to Paganini). In order to summon new depths of music, he fashions strings from his own teacher's guts (willingly donated for the gruesome purpose).