How can you implement a two-way ANOVA with nesting in R or SPSS?

Question: I currently am conducting a study where I have three variables: one that is binary, and two numerical ratio variables. Each of the subjects in my study has values for each of the three variables.
Variables:

Condition (binary): Values 0 and 1
Pre (ratio)
Post (ratio)

I want to test if there is a significant difference between the the pre and post variables of the 0 control group and the 1 experimental group. Both groups have 103 subjects. The data meet all typical ANOVA assumptions such as normality and the like. I was thinking of nesting the variables as follows and then running a two-way ANOVA.
Variable 1 is exposed / not and variable 2 is pre / post. People are nested in Variable 1 (meaning that each person gives both pre and post information for either exposed or not exposed conditions)
Would this be the correct way to approach this problem? Also how would I implement this statistical analysis, preferably in R or SPSS?
Answer: Pre-post designs are quite common and the standard method is to use the pre-measure as a control variable and the post-measure as the response with the binary variable as the covariate.
This is quite simple:
m0 <- lm(Post ~ Pre, data=dat)
m1 <- lm(Post ~ Pre+Condition, data=dat)
anova(m1,m0) # test for difference in mean(Post) after control for Pre
m2 <- lm(Post ~ Pre*Condition, data=dat)
anova(m2, m1) # test for interaction: different slopes in the two Conditions

If this had been with repeated measures within subject (i.e, pre-post measures in each Condition, you would need to specify the error structure in the aov function: You could compare this model in R where the errors for each Condition are nested in subject-ID:
 m1 <- aov(post ~ pre + Condition+Error(subjID/Condition), data=dat)

Ratio variables are notorious for being poorly behaved statistically (i.e., often having significant skew and blowing up as the denominator goes near zero.) However, if the denominator is far from zero, you should not make the mistake of looking at the raw distributions and deciding that the data fail the assumptions needed for validity of linear methods. You need to look at the residuals before conducting any test. (And even then, there is some doubt whether minor departures from normality invalidate inferences.) The help page for aov warns you to use orthogonal contrasts. There was an article in R-News several years ago on multi-variate (as opposed to multi-variable) methods and this would provide further options for model comparisons and measures of sphericity.
Another option is offered by the Anova function in John Fox's car package.
A useful link: http://blog.gribblelab.org/2009/03/09/repeated-measures-anova-using-r/
Another approach is to analyze the pairwise differences, but that approach has flaws.
Comment: By "ratio variable", I suspect she / he means a variable measured on a [ratio scale](https://en.wikipedia.org/wiki/Level_of_measurement).
Comment: Do you really need to specify an error structure here? I think there is only 1 `post` measurement for each subject. Given that you are using the `pre` measure as a covariate (& I agree w/ you about that) & not as a 2nd response variable, I'm not sure if the `Error(subjID/Condition)` part is necessary.
Comment: That's what I thought initially and had even composed an answer using `lm()`. You may still be correct.
Comment: @gung I apologize if I was unclear. I did mean a variable measured on a ratio scale, not a ratio variable. Also there is only one "pre" and one "post" measurement for each subject.
Comment: OK. I'll post code appropiate to that data setup.
Answer: The standard way of handling repeated measures under the linear regression framework (which encompasses ANOVAs) is to reduce the repeated measures into a series of difference scores, which represent the contrasts of interest.  So, in your example, you might do what is essentially a t-test comparing the difference from pre to post in the control and the experimental conditions.  You can find the details of how to implement this in R in my answer to this question.
Edit:
As described by DWin, an alternative way to analyze these data is to use the baseline measurement as a covariate in your model (i.e., basically just enter the pre-test measurement as a predictor in your linear model).  As described by Van Breukelen (2006), this method will have more power than the difference score approach if you have (or expect) no pre-test differences on your dependent variable.  If you do have pre-test differences on your dependent variable, the covariate approach will introduce bias into your results, and the difference score approach will therefore be preferable.


Como comparar Date com campo em MySQL

Question: Sou iniciante em Java e tenho uma tabela em MySQL que possui um campo do tipo date e as datas estão armazenadas no formato yyyy-mm-dd.
Agora preciso recuperar somente os registro cujo valor do campo data seja maior ou igual a data de hoje.
Estou tentando fazer o abaixo, mas não está funcionando:
Date dataHoje = new Date();
Query consulta = em.createQuery("SELECT c FROM Consulta c WHERE c.dtConsulta >= dataHoje");

Alguém poderia dar uma ajuda?
Desculpem-me se não postei o código por completo, mas segue abaixo:
public List<Consulta> listarDatasLivresParaMarcarConsultas(int mes, int ano){

    em.getTransaction().begin();

    Date dataHoje = new Date();

    Query consulta = em.createQuery("select c from Consulta c " +
            "left outer join fetch c.terapeuta t " +
            "left outer join fetch c.cliente cl " +
            "SUBSTRING(c.dtConsulta, 1, 4) = ?1 AND " +
            "SUBSTRING(c.dtConsulta, 6, 2) = ?2 AND " +
            "c.dtConsulta >= dataHoje AND " +
            "c.cliente = null AND " +
            "c.statusConsulta = 'C'");

        consulta.setParameter(1, ano);
        consulta.setParameter(2, mes);

        List<Consulta> consultas = consulta.getResultList();

        em.getTransaction().commit();
        emf.close();

        return consultas;
    }

O usuário escolhe o mês e o ano através de componentes JMonthChooser e JYearChooser, que devolvem dois inteiros respectivamente.
Obrigado por qualquer ajuda!!!
Augusto
Comment: Olá Augusto seja bem vindo ao SOPT, editei sua pergunta para adicionar marcação nas partes de código, isso facilita a visualização da pergunta, e a vc receber melhores respostas, visite http://pt.stackoverflow.com/tour para entender um pouco melhor do site.
Comment: Augusto, por favor complemente seu código. Por exemplo, como você está usando o `consulta.setParameter(...)` ? Pois seu erro pode estar na ultilização do JPA em si, e não do JPQL
Answer: Você pode fazer isso no própria consulta SQL, exemplo:
SELECT * FROM consulta t
WHERE t.dtconsulta >= curdate();

Veja aqui um exemplo minimalista
Comment: Obrigado a todos pela ajuda! Consegui solucionar o problema utilizando a função do JPA CURRENT_DATE.

Como comparar Date com campo em MySQL


Usar mais de uma linguagem no mesmo projeto?

Question: estou participando de um projeto que vou precisar de duas partes:
1) Extração de dados da internet
2) Criação da Interface Gráfica para Desktop

Para a 1ª, pensei em usar Python por ler que ele é a melhor linguagem para extração de dados e para a 2ª, usar VB.NET. Queria saber se isso é desaconselhável em programação por talvez gerar alguma possível incompatibilidade entre as duas linguagens ou por outro motivo.
Answer: Já respondi isso em Como usar várias linguagens em um único programa?. Mas falando em específico ao que foi perguntando, não tem problema usar mais de uma linguagem em uma solução, você faz uma aplicação em uma e outra nem fica sabendo em que linguagem foi feita outra parte. Isto é bom? Geralmente não, existem bem poucos casos que isso é vantajoso, quase sempre a pessoa opta por fazer isso por não dominar o que está fazendo e por si só pode ser um problema ou porque é por razões políticas de uma organização e não por razões técnicas. Mas tudo funciona se fizer certo, só precisa trocar dados de forma consistente.
Se quer juntar duas linguagens na mesma aplicação, depende das linguagens usadas. Se forem scripts eu nem chamaria de aplicação e dá para mais ou menos misturar, porque no fundo você passa ter uma solução de scripts e não uma aplicação única. Se for gerar um executável, precisa que todas sejam compatíveis em fazer isto e poder se comunicar, falo isto nas outras respostas lá.
Se for usar o VB.NET usará o .NET (Core, por favor) poderá usar outras linguagens porque a plataforma foi feita para isto, mas não qualquer uma. Funciona direitinho, mas provavelmente é gambiarra em grande parte das situações, não quer dizer que será super simples e não tenha trabalho para lidar com isso. Mas o VB.NET já trabalha com mais que uma linguagem, tudo que ele usa internamente é feito em C#.
Eu vejo como problema maior começar algo novo porque gosta mais de uma linguagem por causa da sintaxe, uma linguagem que claramente está com suporte secundário do fornecedor e a comunidade praticamente abandonou de vez. Então está olhando para o problema errado.
Python pode ser usado junto com .NET, mas quase sempre faz pouco sentido. Se for usado fora da plataforma então é só uma solução com duas aplicações isoladas e cai no que eu falei antes. Novamente, não sei se isso é necessário se vai fazer algo do zero, quase sempre esse tipo de coisa é quando há legado ou algo pronto.
O que descreveu parece um caso que o VB.NET dá conta de tudo muito bem. Por outro lado, o Python também dá conta de tudo quase tão quanto o VB.NET (um pouco menos por algumas razões, depende dos detalhes do que precisa).
Não vai nessa do que lê por aí. Python não tem absolutamente nada melhor para extração de dados, isto é só gente fazendo marketing da sua tecnologia favorita. Se você nem sabe porque está adotando, só seguindo o que outras pessoas estão dizendo então toda decisão está errada. Não faça baseado em suposições expostas por pessoas aleatórias na internet que você não sabe quais as motivações dela de dizer aquilo, porque ela acha aquilo, e geralmente ela não dá uma avaliação provando aquilo que ela está afirmando, ou seja, mostra como a linguagem faz melhor que outras, mostrando como se faz nas duas. Mesmo que ela mostre em geral a pessoa é tendencioso, de propósito ou não, afinal ela conhece bem uma das linguagens e não a outra. E muitas vezes ela demonstra um pequeno detalhe melhor, ignora todos os outros pior, ou que dá para fazer na outra de um jeito diferente e melhor, e quando as vezes parece melhor pode ser só gosto e no fundo não faz diferença real. Nem falei que normalmente a pessoa que conhece bem uma não conhece bem a outra, mesmo que tenha algo melhor em uma pode ser que não seja bem explorada pela pessoa que não conhece muito bem aquela tecnologia. Um dos maiores motivos para usar duas linguagens é que tem duas equipes com skills em cada uma delas, e precisa separar o projeto entre as duas. Ou seja, é gambiarra tecnológica para favorecer um melhor gerenciamento de projeto.
Python é bem mais lenta que VB.NET, os fontes são mais expostos que VB.NET, o deploy é mais complicado em quase todas as situações, só para citar algumas questões.
Usar mais de uma linguagem precisa compensar muito, precisa provar antes que será melhor antes de tomar a decisão, não pode ser achismo, porque complica mais o desenvolvimento. Me parece que está decidindo usar mais que uma pelo motivo errado.
Coloquei no GitHub para referência futura.
Answer: Sim é possível usar mais de uma linguagem em algum software, a questão mais importante é se elas precisam interagir entre si.
Por exemplo, os dados extraídos precisam ser exibidos no desktop. Nesse caso, precisa de uma interface comum que as duas partes entendam, pode ser um banco de dados por exemplo, onde uma parte escreva e a outra possa ler os dados, funcionando perfeitamente para quaisquer linguagens que você escolha.
Não vou falar sobre as linguagens em sim porque seria baseada em minha opinião, mas quanto ao VB.NET, se quer usar a plataforma .NET, sugiro usar C#, que é muito mais popular e difundida, não é opinião, são fatos.  Um exemplo é a pesquisa do próprio Stack Oerflow, que você pode ler aqui: Stack Overflow Survey 2019
Comment: Eu sei que C# é mais popular, mas prefiro usar vb.net, gosto mais
Comment: Tranquilo, precisamos usar o que funciona melhor pra nós, só inclui a informação para ajudar na sua escolha :)
Answer: De forma pragmática.
Utilize Python para a extração de dados, (BS, scrapy. requestes.) apos isso armazene os dados em um banco de dados e depois basta acessar os dados com outra linguagem.
O interessante disso é que depois pode-se utilizar qualquer outra linguagem para alimentar o banco de dados.


S3 Sync Not Writable Warning

Question: I am trying to use s3cmd sync (vanilla command remote to local), but for each file I get a not writable: Operation not permitted warning (see below). The files appear to download correctly, however, and if I do an ls on the file it is there. I tried using the --disable-multipart flag but this made no difference. I am using s3cmd version  1.5.0-rc1.
Is there any reason why I might be receiving these warnings?
WARNING: MD5 signatures do not match: computed=11ff15bf.., received="b119cb85b109c6.."
WARNING: ./path/part-r-00003.gz.parquet not writable: Operation not permitted
s3://bucket/path/part-r-00003.gz.parquet -> <fdopen>  [31 of 72] 36101458 of 36101458   100% in 2s    16.30 MB/s  done

Answer: A likely reason is that the S3 objects have been stored with filesystem attributes. When you sync them to a local directory, by default s3cmd sync will try to restore these attributes, including uid,gid ownership.
To prevent s3cmd from doing this, run it with the --no-preserve option, e.g.:
s3cmd sync --no-preserve s3://bucket/my/key/prefix .

Comment: This worked for me; believe it should have been marked as the answer.
Comment: This is the correct answer.  Should be marked as such.

S3 Sync Not Writable Warning


Capturing PySpark logging

Question: I am trying to setup a decent logging configuration in PySpark. I have a YAML configuration file which setups different loghandlers. Those handlers consist of the console, a file, and a SQLite DB using the format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s".
# SETUP LOGGING
with open(cfile, 'rt') as f:
     config = yaml.safe_load(f.read())
logging.config.dictConfig(config)
lg = logging.getLogger("mylog." + self.__name__())

So each time I call the lg.xxxx('message') everything gets handled quite nicely.
Now I found quite some posts on how to get the log4j from PySpark using log_handler = sc._jvm.org.apache.log4j. But now I'm lost on how to add this handler to my existing setup and catch all the messages that happen on the PySpark console and save them to the file and SQLite DB.
Answer: It is not possible to catch spark jvm logs by python handlers, both these are separated environments. You have two options - to log python messages using log4j from the sc._jvm and configure log4j handlers or use separate handlers and merge logs (for example in sqlite) after job finishes.

Capturing PySpark logging


Double rendering with EJS in node.js

Question: I wonder if it's possible to do a double rendering with ejs with different tags.
For example I've got this ejs template
<@= test @>

<% for(var i=0; i<people.length; i++) { %>

        <%= people[i].name %>

<%
    }
%>

In node.js I'm rendering either with the default tags (<%) or with some defined tags (<@) like this
var people = [{"name":"Martin"}, {"name":"Jean"}];

 exports.test = function(req, res) {
    res.render('template', {
        open:'<@',close:'@>',
        people : people,
        test : "Hello world"
    })
}

This code will render
Hello world <% for(var i=0; i
<%= people[i].name %>
<% } %>

And this one
var people = [{"name":"Martin"}, {"name":"Jean"}];

 exports.test = function(req, res) {
    res.render('template', {
        people : people,
        test : "Hello world"
    })
}

will render
<@= test @>
Martin
Jean

And I'd like to find a way to double render it like this:
Hello world
Martin
Jean

Thanks
SOLUTION thanks to bnuhero
 exports.test = function(req, res) {
 var people = [{"name":"Martin"}, {"name":"Jean"}];
     res.render( 'test',
          {open:'<@', close:'@>', test : "Hello world"},
          function(err, html) {
            if (err) {
            console.log(err);
              res.send(500, err);
            } else {
              res.send(require('ejs').render(html, {people: people}))
            }
         });
    };

Answer: First, call res.render() by providing a callback function. Both the possible error and the rendered string are passed to this callback function. res.render() won't perform automated response to the client side.
Second, apply require('ejs').render() to the rendered string in the callback function.
Finally, send the result to the client side.
exports.test = function(req, res) {
  var people = [{"name":"Martin"}, {"name":"Jean"}];
  res.render( 'template',
              {open:'<@', close:'@>', test : "Hello world"},
              function(err, html) {
                if (err) {
                  res.send(500, err);
                } else {
                  res.send(require('ejs').render(html, {people: people}));
                };
             });
};

Comment: Thank you ! Worked perfectly. I edited your code though there was a small typo and also for some reason ejs doesn't like the ";" at the end of the last res.
Comment: I can't edit if it's less than 6 characters so I've edited my question with the answer. Thanks again

Double rendering with EJS in node.js


functional call issue in R

Question: I am trying to calculate the cost rate with a Weibull lifetime distribution in R with the following code:

CR_age <- function(T,lambda,k,cpm,ccm)
{
  cum <- function(T,lambda,k)
  {
    return(1 - exp((-T/lambda)^k))
  }
  survival <- function(T,lambda,k)
  {
    return(exp((-T/lambda)^k))
  }
  mean_cost <- ccm * cum(T,lambda,k) + cpm * survival(T,lambda,k)
  cycle_length <- Vectorize(survival, "T")
  mean_cycle_length <- integrate(cycle_length, 0, T)
  costRate <- mean_cost / mean_cycle_length$value

  return(costRate)
}

as I call the function
 CR_age(2,0.1,1,3,1)

I receive a warning from R saying that :
Error in (function (T, lambda, k)  :
  argument "lambda" is missing, with no default

May I ask what would be the reason in this case? Is that I did not pass the argument lambda in CR_age to the functions cum and survival?
Thanks in advance
Comment: You vectorize survival but don't give defaults for the other parameters. In the next line when you try to integrate it had nothing to use for lambda (or k)
Comment: I guess you maybe should use `integrate(function(x) cycle_length(x,lambda,k), 0, T)`
Answer: You need to give all the parameters of you function survival in the Vectorize and integrate functions
CR_age <- function(Te,lambda,k,cpm,ccm)
{
  cum <- function(Te,lambda,k)
  {
    return(1 - exp((-Te/lambda)^k))
  }
  survival <- function(Te,lambda,k)
  {
    return(exp((-Te/lambda)^k))
  }
  mean_cost <- ccm * cum(Te,lambda,k) + cpm * survival(Te,lambda,k)
  cycle_length <- Vectorize(survival, vectorize.args =c("Te", "lambda", "k"))
  mean_cycle_length <- integrate(cycle_length, 0, Te, lambda, k)
  costRate <- mean_cost / mean_cycle_length$value

  return(costRate)
}

CR_age(2,0.1,1,3,1)

[1] 10
Answer: You miss your arguments lambda and k for the line mean_cycle_length <- integrate(cycle_length, 0, T).
Maybe you should update it to
mean_cycle_length <- integrate(function(x) cycle_length(x,lambda,k), 0, T)

then you can run your code without error, i.e.,
> CR_age(2,0.1,1,3,1)
[1] 10

functional call issue in R


Is there a a way to add a wrapper element during the marshalling in JAXB for non collection element?

Question: I am trying to create the XML using the marshaling method from the JAXB library. For this approach, I am using the standard java class and assigning the annotation to it. I would like to have a wrapper element to some of the element in the class which are not Collections.
I am ware of @XmlElementWrapper which can be used for Collections but I do not have a collection. I have some elements for which I want to have an outer XML element so that it can match the standard XSD.
I just want to know if there is a way to add an outer XML element to some of the elements so that the create XML matches the standard XSD format. If there is no direct approach then what alternative approach can I take?
As we can see from the example XML the carinfo tag is a outer (wrapper) tag for the elements engine and year but this carInfo tag is not present within the Parent or Child class. As these are standard classes I cannot modify the fields/ Add new fields. Hence I would like to handle wrapper XML  tag addition using the JAXB.
Following is the input JSON:
{
   "brand": "Ferari",
   "build": "Italy",
    "engine": "Mercedes",
    "year": "2021"

}

Following is the output XML that I would like to have:
<?xml version="1.0"?>
<Car>
    <brand>Ferari</brand>
    <build>Italy</build>
    <carinfo>
        <engine>Mercedes</engine>
        <year>2021</year>
    </carinfo>
</Car>

Following are my classes:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlTransient
@XmlType(name = "Parent")
public class Parent{
    private String brand;
    private String year;

    //Getters and Setters avoided
}

Class based on which XML is being created:
@XmlRootElement(name = "Car")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Child",propOrder={"brand","engine","build","year"})
public class Child extends Parent{
    private String engine;
    private String build;

    //Getter and Setters avoided
}

The main class which will create the XML: I am using the Jackson library to read the values from the Json file and create the XML based on Jaxb annotations.
public class Main{

     public static void main(String []args){
        JsonFactory jsonFactory = new JsonFactory();
        JsonParser jsonParser = jsonFactory.createParser(new File(Main.class.getClassLoader().getResource("input.json").toURI()));
        Child eventInfo = jsonParser.readValueAs(Child.class);
        JAXBContext context = JAXBContext.newInstance(Child.class);
        Marshaller mar = context.createMarshaller();
        mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        mar.marshal(eventInfo, System.out);
     }

}

Comment: Hello, could you add the input.json ?
Comment: @dariosicily Sorry for missing out on adding the `Json`. I have added now. Please check.
As you can see from JSON I do not have `carInfo` tag but in the `XML` I would like to add `carInfo` tag. Is there a way I can add the additional tag which is not present in the `class` to my `XML`
Comment: It seems not possible to do it by jaxb unless you modify your classes, my suggestion even if ugly is manipulate the xml tree to obtain the desired result.
Comment: Thanks a lot for the time and response. Actually, it's possible and I was able to find a way around it. I have posted as a question here: https://stackoverflow.com/questions/67300882/jaxb-xmladapter-is-there-a-way-to-convert-this-method-into-jaxb-xmladapter Now I am trying to figure out a way to make it as `XML Adapter` rather than keeping it as a method within class.
Comment: Thanks for the link, in the meanwhile I have found a possible solution to your  problem using an xsl file without modify the original classes, so if you are interested I submit an answer.
Comment: @dariosicily Yes please post it. I am really curious to know what are the other ways in which this can be achieved. Thanks a lot.
Answer: From my point of view, it is possible to include a new tag inside your xml preserving the original classes with a combination of jaxb and javax.xml.transform api. The first thing is create a xsl stylesheet file for the transformation like below:
template.xsl
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0"   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<Car>
<brand>
<xsl:value-of   select="/Car/brand"/>
</brand>
<build>
<xsl:value-of   select="/Car/build"/>
</build>
<carinfo>
<engine>
<xsl:value-of   select="/Car/engine"/>
</engine>
<year>
<xsl:value-of   select="/Car/year"/>
</year>
</carinfo>
</Car>
</xsl:template>
</xsl:stylesheet>

Then you can use the set a Transformer and pass to it a new JAXBSource like below:
Child eventInfo = jsonParser.readValueAs(Child.class);
JAXBContext context = JAXBContext.newInstance(Child.class);

// Create Transformer
TransformerFactory tf = TransformerFactory.newInstance();
StreamSource xslt = new StreamSource(xslFile);
Transformer transformer = tf.newTransformer(xslt);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");

//Print to the stdout the desired xml with the new nested tag
//including the two existing tags
StreamResult result = new StreamResult(System.out);
JAXBSource source = new JAXBSource(context, eventInfo);
transformer.transform(source, result);

Comment: Interesting approach. Thanks for the alternative way of creation. However when the XML is a bit complex and keeps changing then it can be a bit tricky to manage these files. Hence, i feel handling it within the class would be an easy approach. But this solution can be helpful for someone in the future.
Comment: @BATMAN_2008 You are welcome, I'm agree with you that if classes can be modifible it it more easier to use them. The XML case was simple so an xsl online generator made the required file usable without any modifies.
Answer: Finally, I was able to get it using the @XmlPath from Moxy which is and library based on the Jaxb. You can use the @XmlPath to any of the elements such as collection, non-collection, String etc. I have spent a lot of time trying to configure and do workarounds so posting the answer here so it can be useful to someone in the future and they do not endup so much time as me :)
Please find the answer for configuring the Moxy here
Also, see how to get the wrapper elements for the XML using the @XmlPath here
You can also read more about it in the EclipseLink documentation.


Approaches for Linux server disk encryption

Question: What are the approaches available for fully encrypting a disk on a remote server (say, colocated in a datacenter)? On Windows, we can just turn on Bitlocker with a TPM. Then the server can reboot, and attacking either requires taking the machine while live and dumping RAM, or breaking the TPM. On Linux, what's available?
So far, I've found an IBM "blueprint" describing how to store dm-crypt keys in the TPM. Is this the best approach?
http://publib.boulder.ibm.com/infocenter/lnxinfo/v3r0m0/topic/liaai/tpm/liaaitpm_pdf.pdf
Answer: To understand the best solution to your issue you need to clarify what you are trying to achieve. In other words, what's your threat-model? Who is your attacker? You mention that to get around the encryption would require 'taking the machine while live' (by which I assume you mean hacking it), but that is the most likely scenario for a colocated server. Disk encryption is mainly of use in the case of physical theft.
You also need to consider what data are you protecting. You mention 'fully encrypting a disk', but does this require encrypting e.g. /usr? If you're running a standard distribution there is nothing of interest there. Without knowing more about what the server will contain it's hard to make recommendation.
But to give a more concrete suggestion, consider the following hypothetical server. It contains the following:

A simple website showing some products
A basic CRUD order application written in Rails/Django/whatever
A Postgres DB for customer information and orders

Of those components, only the database really needs protecting, so here's how I'd approach this:

Leave most of the machine un-encrypted (but make as much of the FS read-only as possible)
Create a separate partition for the database and encrypt it with a strong password using any of the available Linux encryption system (ecryptfs, etc).
After each reboot, login and mount the partition with the key, which is stored elsewhere.
On a reboot have the server alert me

You mention TPM, but TPM doesn't help you in a number of cases, such as if an attacker gains administration privileges. TrueCrypt have rejected support for TPM for this reason.
Comment: Good answer. One more requirement: Does the machine have to boot automatically or can you afford to enter (via remote console) a passphrase?
Answer: You can also use TPM with dm-crypt:
https://github.com/shpedoikal/tpm-luks
http://code.google.com/p/cryptsetup/wiki/FrequentlyAskedQuestions#2._Setup
If integrated on the initrd ramdisk, a small-footprint SSH server allows remotely entering the password to unlock the drive.
Please note none of the above mentioned solutions adequately protects from a skilled  attacker with physical access to the server.


Can any one tell why the previous data is still displayed while saving data using StreamWriter

Question: I am saving data to a file-name using Stream writer but if i run the code for second time the same data is appended to the previous data but i would like to clear the old data and write the data
The data i should have in text file should be as follows
101 435435345 3445454541104021031A094101
52251               1                   1         CCD1         110402110402   1111000020000001
6281110000251                00000000011              1                     1 0111000020000001
822500000100111000020000000000010000000000001                                  111000020000001
 9000001000001000000010011100002000000000001000000000000

My sample code
if (i == 0)
{
  index++;
  string m_strDate = DateTime.Now.ToString("yyyy/MM/dd");
  m_strDate = m_strDate.Replace("/", "");
  StrFilePath = "log" + m_strDate + index + ".txt";
}
  using (StreamWriter sw = new StreamWriter(StrFilePath,true))
    {
     using (StreamReader sr = new StreamReader(new MemoryStream(System.Text.Encoding.ASCII.GetBytes(strLine))))
    {
        while (sr.Peek() >= 0)
         {
           strReadLine = sr.ReadLine();
          if (strReadLine.StartsWith("1"))
           {
                if (i == 0)
              {
                  strFileHeader = strReadLine;
                  sw.WriteLine(strFileHeader);
               }
          }
   if (strReadLine.StartsWith("5"))
     {
     strBatchHeader = strReadLine;
      if (i == 0)
    {
         Btchno = Convert.ToInt32(strBatchHeader.Substring(87, 7));
        BatchCnt = Convert.ToInt16(Btchno);
       }
     if (i > 0)
    {
           BatchCnt++;
           strBatchHeader = strBatchHeader.Substring(0, 87) + Convert.ToString(BatchCnt.ToString().PadLeft(7, (char)48));
      }
    sw.WriteLine(strBatchHeader);
  }
   }
 }
 }

Comment: You should use a `StringReader` instead of your `StreamReader`.
Answer: You're passing true as the append parameter in the StringWriter constructor.
Answer: Second parameter here: new StreamWriter(StrFilePath,true) is set to true, which means append to file. Set that parameter to false and it will work.
Comment: @Dora: That is not true.  StreamWriters work fine with the parameter set to false.
Comment: If i set to false then i can not write the data as per i required
Comment: Gerrie assume the output will be same every time in my file as i mentioned but if i set to false and then proceeding i am not getting that


Password protection for php 5.3.3?

Question: I'm doing an assignment for uni and I've been following guides as far as finding a way to hash a registered password onto the mysqli database but it seem's the university's myphp is only on 5.3.3 and MySQL 5.1.73.
What can I use to hash it instead of using 5.5's password_hash() function? Don't suppose there's a handy tutorial out there for it?
Many thanks!
Comment: `password_hash()` Compatibility pack (if PHP < 5.5) => https://github.com/ircmaxell/password_compat/  - http://www.php.net/manual/en/function.crypt.php <= (PHP 4, PHP 5, PHP 7)
Comment: You *might* be able to use the Compatibility pack (no promises), but `crypt()` would probably be your best bet, since it's supported since PHP 4.
Comment: 5.1.73 is MySQL's version, not a PHP version. You need to check what version of PHP you have to see if you can use `password_hash()`.
Comment: `` will show you what version of PHP you're running under.
Comment: Aha it's using 5.3.3!
Answer: Your best answer:
Have them upgrade to PHP 5.5 or higher and use password_hash() with a high work factor.
Point them to Thomas Pornin's canonical Security.stackexchange answer to How to securely hash passwords? to let him help argue the case for good password security.
Your next best answer:
Have them upgrade to PHP 5.3.7 or higher and use the password_hash() compatibility pack
See above.
Your not as good answer:
You can use crypt on your current PHP 5.3.3 version reasonably IF you change some of the options:
<code>crypt('password', '$6$rounds=150000$PerUserCryptoRandomSalt$')
</code>

$6 - use SHA-512, which has 64-bit operations that reduce the margin of advantage most GPU based attackers have over you as of early 2016.
$rounds=150000 - set the number of iterations to hundreds of thousands or high tens of thousands of rounds.
PerUserCryptoRandomSalt - unlike password_hash, you have to do this yourself.  You need to generate a unique, cryptographically random salt of 12-24 binary bytes (16 is very reasonable)

Note that it's part of the result string, in cleartext, which is correct.
That's binary bytes!  The size in the crypt() function gets doubled if you convert to hex, or increased by 4/3rds if you Base64 it

To compare, you get the user's salt and number of rounds, and use crypt with those on the candidate password entered.  If you get the same answer, it's the same password.
Comment: One can still use BCrypt for PHP 5.3.3 with the `2a` signature. The safest way would probably be to download the [compatibility pack](https://github.com/ircmaxell/password_compat/blob/master/lib/password.php) and change the algorithm from `2y` to `2a`.

Password protection for php 5.3.3?


How to display an image as a property in JavaScript objects

Question:   //construtor created
   function Blog(text, date, image) {
        this.show_image = function(src, width, height, alt){
                        var img = document.createElement("img");
                            img.src = src;
                            img.width = width;
                            img.height = height;
                            img.alt = alt;
                            document.body.appendChild(img);
                    }

    }
 //instance

    var blog = [new Blog("hello!,Welcome to my blog1.", new Date("10/21/2012"),'show_image("images/overlay.png", 20,30, "Google Logo")'),

Hey m calling an image in above instance for that i've written a function show_image performs that part  but the image is not getting displayed...please tell me what is wrong here ...please modify it...I'm new in javascript programming..
        I
Comment: You're not calling anything, it's a string!
Comment: Do you call `show_image()` somewhere?
Comment: When calling the function show_images, you have wrapped it within single quotes. Remove it so that the function gets executed.
Comment: hey its inside the instance you can see the third  property in it where m calling an overlay.png images
Comment: hey hop tell from where i should learn javascript programming
Answer: i have no idea why are you creating constructor and all..this can be done, with creating a simple function
try this
function show_image(src, width, height, alt){
                    var img = document.createElement("img");
                        img.src = src;
                        img.width = width;
                        img.height = height;
                        img.alt = alt;
                        document.body.appendChild(img);
  }

$(document).ready(function(){  //if using jquery
   show_image("images/overlay.png", 20,30, "Google Logo");
});

Answer: You are actually not calling the show_images function. You are just passing a string and that is not going to help.
Remember before finding out why the particular block of code is not working, you need to find out if that block is executed at all.
This is one more way you make it work.
function Blog(text, date) {

    this.show_image = function (src, width, height, alt) {

        var img = document.createElement("img");
        img.src = src;
        img.width = width;
        img.height = height;
        img.alt = alt;
        document.body.appendChild(img);
    }

}
//instance

var blog = new Blog("hello!,Welcome to my blog1.", new Date("10/21/2012"));
blog.show_image("images/overlay.png", 20,30, "Google Logo");

Comment: Anywhere except w3schools. Try https://developer.mozilla.org/en-US/docs/JavaScript/Guide


Recommend a graduate-level regression textbook?

Question: Some friends and I (statistics grad students) would like to work through a good regression book. We're looking for

single and multiple linear regression
logistic regression
model selection
diagnostics
splines
penalized methods
classifiers, trees

Can anyone recommend a book (or books) that cover these topics?
Comment: It doesn't appear that you're actually asking for a *regression* text, per se. But, the "standard" beginning graduate text that is going to cover all of those topics is [ESL](http://www-stat.stanford.edu/~tibs/ElemStatLearn/). Of course, covering so many topics necessarily means that either (a) the book is huge or (b) there is some lack of depth for each topic. ESL takes the latter approach (for the most part).
Comment: Maybe some econometric texts? Graduate level are Greene "econometric analysis", Hayashi "econometrics" and very good for time series is Hamilton "time series analysis". They are quite complete though Greene and Hayashi more or less limit themselves to discrete time.
Comment: Frank Harrell's *Regression Modeling Strategies" might be a good choice for an applied perspective.
Comment: @IMA Hayashi is imo the best graduate econometrics book in existence. Good thinking.
Comment: Here's a similar thread on Wakefield's book. It seems like you have plenty of options, but that's another good one.

https://stats.stackexchange.com/questions/86057/bayesian-and-frequentist-regression-methods-by-jon-wakefield-a-good-introduct
Answer: I believe Graham Cookson's answer to a similar question would be of assistance. Basically, he recommends Gelman and Hill's Data Analysis Using Regression and Multilevel/Hierarchical Models. According to Mr. Cookson, the book "covers basic regression, multilevel regression, and Bayesian methods in a clear and intuitive way" and "would be good for any scientist with a basic background in statistics".
Comment: Well, the OP asked for a graduate level book. Maybe Seber's book will do the job.  http://www.amazon.com/Linear-Regression-Analysis-2nd-ed/dp/8126547286/ref=sr_1_1?s=books&ie=UTF8&qid=1455573774&sr=1-1&keywords=seber++linear     I read in its time the first edition, and it is good. Do not know the second edition, though.


Encontrar valores duplicados num array

Question: Tenho um foreach e ele tem resultados iguais, quero que quando ele tiver o mesmo resultado ele faça um echo
Exemplo do código:
$courses = array('teste', 'teste2', 'teste3', 'teste');
foreach ($courses as $key => $course) {
     if ($course == $course) {
           echo $course;
     }
}

Falta no exemplo a segunda variavel de comparação, no exemplo usei a mesma $course->fullname nos 2 lugares do if
EDIT: preciso que o if identifique os 2 valores 'teste' e dê um  echo
Comment: Edite seu código conforme está fazendo mesmo, por favor.
Comment: Essa segunda variável tem seu valor alterado? é um foreach dentro de outro?
Comment: Edite a pergunta e monte um exemplo mais próximo do código real se não puder mostra ele. Dá até pra sugerir um `array_intersect()` ou afim.
Comment: montei outro exemplo... @rray
Comment: O objetivo é encontrar valores iguais num array?
Comment: sim!!!!!!!!!!!!
Answer: Na verdade você não precisa de um foreach para identificar os valores duplicados:
$courses = array('teste', 'teste2', 'teste3', 'teste');
function getDuplicates( $array ) {
    return array_unique( array_diff_assoc( $array, array_unique( $array ) ) );
}

$duplicates = getDuplicates($courses);

print_r($duplicates);

Obs: Agora é só fazer um foreach nas duplicatas e dar echo em tudo.
IDEONE de exemplo
Answer: Também é possível identificar os elementos repetidos com a função array_count_values() que retorna um array, onde as chaves são os elementos e os valores o número de ocorrências, com isso, basta um foreach e um if perguntando é maior que um? se sim é repetido.
$courses = array('2015', 'teste', 'teste2', 'wow', 'teste3', 'teste', 'wow');
$arr = array_count_values($courses);

foreach($arr as $key => $value){
    if($value > 1){
        echo 'valor repetido: '. $key .'
';
    }
}

Encontrar valores duplicados num array


Estou com problemas no touch da unity, não reconhece todos os toques e ao pressionar o player fica parado

Question: preciso de ajuda, qro clicar na tela e a cada toque mudar a gravidade
meu cod: (ta no update)
<code>if (Input.touchCount > 0)

    {
        eixo *= -1;
    }
</code>
mas parece q ele n ta reconhecendo todos os toques e se vc ficar pressionando vc para o player, tb n qro q isso aconteça, algm pode me ajudar, por favor?
Answer: Ja consegui arrumar, se algm precisar algm dia, ta aq:
if (Input.touchCount > 0)
<code>    {
        Touch touch = Input.GetTouch(0);
        if(touch.phase == TouchPhase.Began)
        {
            eixo *= -1;
        }
        else
        {
            eixo = eixo;
        }

    }
</code>


If $a^2 + b^2 = 1$, then $a = \sin \theta$ and $b = \cos \theta$ for some $\theta \in [0, 2\pi)$. Is there a variation for more than two variables?

Question: Namely, for every integer $n > 2$, are there functions $\phi_1, \dots, \phi_n$ and an interval $[a, b)$ such that: if $a_1^2 + \cdots + a_n^2 = 1$, then there exists a $t \in [a, b)$ such that $a_i = \phi_i(t)$ for $i = 1, \dots, n$?
If not, is there a version of this for at least one integer $n > 2$?
Comment: In general you'll need $n-1$ parameters to describe a hypersurface in $n$-dimensional space.
Answer: The natural generalization of this situation to higher dimensions is given by generalized spherical coordinates. see Wikipedia
For the $(n-1)$-sphere living in $\mathbb{R}^n$, satisfying the equation $x_1^2+x_2^2+\dotsb + x_n^2=r^2,$ we have coordinates $\phi_1,\dotsc,\phi_n$ which parametrize the sphere via
$$
\begin{align}
x_1&=r\cos\phi_1\\
x_2&=r\sin\phi_1\cos\phi_2\\
x_3&=r\sin\phi_1\sin\phi_2\cos\phi_3\\
\vdots\\
x_{n-1}&=r\sin\phi_1\sin\phi_2\sin\phi_3\dotsb\sin\phi_{n-1}\cos\phi_n\\
x_n&=r\sin\phi_1\sin\phi_2\sin\phi_3\dotsb\sin\phi_{n-1}\sin\phi_n\\.
\end{align}
$$
The polar coordinate $\phi_n$ will be a parameter residing in $[0,2\pi]$ just as in the 1-dimensional case. The rest of the coordinates will have a range only half as big, $\phi_i\in[0,\pi]$, for $1\leq i\leq n-1$.


How to make div always top using css?

Question: Like alert bar of stackoverflow here.
It should not be position:fixed,because it's not supported by all browsers.
Absolutely,neither will position:absolute do.
Comment: if u want it top top , like above all the other elements then use z index property and set to greater than the other elements
Answer: You could always use EMCAscript or one of its forms (JScript, JavaScript) to calculate the position of the viewport and set the position equal to that.
function positionView()
{
  return (window.pageYOffset) ?
    window.pageYOffset :
    (document.documentElement.scrollTop) ?
      document.documentElement.scrollTop :
      document.body.scrollTop;
}

function setPosition(object)
{
  object.style.top = positionView() + "px";
}

Then just pass in the DIV object you want to use, with document.getElementById.
I'd use position: fixed;.  Many people still use IE6, though, which does not support it.
Answer: Put the div under the body tag, give it position absolute, top:0, left:0
And if you want it to push the content, just put it there without the CSS I gave you.
Answer: Its very simple step if you are using any class in css apply one more property z-index = 1;
it will make that div to always on top, if that div is relative to its parent div.
Answer: Make sure the element is directly nested under the body tag, use css with absolute position and top:0;
By the way, fixed is used by a large majority of the browsers.
Comment: `absolute` won't keep it always on top when you scroll the bar.
Comment: `fixed` really is what he wants, but this doesn't work on IE6, for example (which unfortunately still has a major market share).
Answer: Only fixed positioning does this, unless you want to use javascript. Which you don't, because it's an ugly way of doing it.
Answer: Just do it like SO does it. Use the "notifycontainer" and populate it with InnerHTML from JavaScript when you need to. Since it's a relative positioning, when you rewrite the InnerHTML the page rerenders based on the contents of the div as they are at that moment. Same deal when you want to clear the alert, you just rewrite the InnerHTML. You don't even need to write animation code. The way browsers render now, the animation will be automagical.

How to make div always top using css?


Dimension of nullspace of difference of two rigid transformations

Question: Given distinct proper rigid transformations $A, B \in \operatorname{SE}(n)$, what is the maximum dimension of the nullspace of $A - B$? That is, what is the maximum dimension of $\operatorname{Eq}(A, B) = \{x \in \mathbb{R}^n\ |\ A(x) = B(x)\}$?
I conjecture that the answer is $n - 2$ by observing simple cases:
When $n = 2$, proper rigid transformations are "defined" by $2$ affinely independent points, so $\operatorname{Eq}(A, B)$ can contain at most one point and has a dimension of $0$.
When $n = 3$, proper rigid transformations are "defined" by $3$ affinely independent points, so $\operatorname{Eq}(A, B)$ is at most the affine hull of two affinely independent points and has a dimension of $1$.
As this line of reasoning is not quite rigorous, I cannot tell if it easily extends to higher dimensions (also hampered by my lack of four-dimensional imagination!). Is my conjecture true for all integers $n \geq 2$?
Answer: Yes. WLOG, suppose $A$ and $B$ are linear (so there are no translations). Let $A,B$ also denote the matrix representations of the two transofrmations. As they belong to $SE(n)$, $A^TB\in SO(n)$. Hence $A^TB=UDU^\ast$ for some unitary matrix $U$ and some complex diagonal matrix $D$ whose diagonal entries have unit moduli. Therefore
$$\operatorname{nullity}(A-B)=\operatorname{nullity}(I-D).$$
If $\operatorname{nullity}(A-B)=n-1$, $D$ must have $n-1$ eigenvalues equal to $1$. However, as $A^TB$ is real orthogonal and $A\not=B$, the remaining eigenvalue of $D$ must be equal to $-1$. But then $\det A^TB=-1$, which is a contradiction. Therefore the nullity of $A-B$ is at most $n-2$.
Comment: @HerngYi Suppose $A(x)=Px+p$ and $B(x)=Qx+q$, where $P,Q$ are matrices and $p,q$ are translation vectors. The nullspace of $A-B$ is then the set $H=\{x: (P-Q)x+(p-q)=0\}$. Suppose $x_0\in H$. Then $H=x_0+\{u: (P-Q)u=0\}$. So the dimension of the *affine* subspace $H$ is equal to the dimension of the *linear* subspace $\{u: (P-Q)u=0\}$. In other words, as long as the *dimension* of the nullspace is concerned, $\dim H$ can be calculated as if $p=q=0$.
Comment: I'm sorry but i can't follow your argument well due to a inadequate exposure to linear algebra. Could you explain why there is no loss of generality in your assumption?


Proof by contradiction: If $x$ is a real number and $x^2 + x - 2 = 0$, then $x \neq 0$

Question: Here's the problem again:
Use a proof by contradiction to prove the following universal statement:
If $x$ is a real number and $x^2 + x - 2 = 0$, then $x \neq 0$
Here's my attempt at it:

Let $p$ be "$x^2 + x - 2 = 0$" and $q$ be "$x \neq 0$".
Assume that $x^2 + x - 2 = 0$ and assume $x = 0$.
(This is where I got stuck)

I'm not sure how to proceed, I've worked with statements like, "If $3n+2$ is odd, then $n$ is odd" but I've never worked with equations like this. How would I proceed with this proof by contradiction?
Comment: Conclude immediately by substitution that $-2=0$. This is false. The end.
Comment: Substitute assumption $x=0$ into $x^2+x-2=0.$ Then...
Comment: So after I substitute it into the proof, I get that -2 = 0 as Andre Nicolas said earlier, I can just say that I proved that x != 0? So it's just a really short proof?
Comment: Since the statement $"-2=0"$ is false, then the assumption $"x=0"$ must be false.
Comment: @Camille : Yes, it is as short as that.
Answer: The key to this proof is that for $x \in \mathbb{R}$, either $x=0$ or $x\neq 0$.
Proposition:
If $x \in \mathbb{R}$ and $x^{2} + x -2 = 0$, then $x \neq 0$.
Proof by Contradiction:
Suppose that if $x \in \mathbb{R}$ and $x^{2} + x -2 = 0$, then $x=0$.
This implies that $0^{2} + 0 - 2 = 0$, i.e. $-2 = 0$. This claim is absurd, and we're done.
(The claim is absurd because $0$, the additive identity, is unique in $\mathbb{R}$.)


Calculate score for multiple variables

Question: My question is similar to this.
I have a large geographical area divided
into small cells (approximately 2.25 km$^2$). I'm calculating some value (heat) for individual cells dynamically. It is an integer value.
We have some people going through these cells.
I want to calculate a score for these people based on their visits to cells.
This score should tell how each person spent their time with an idea about cells  visited. So according to the example below person A should have higher score than person B or vice versa.
As a example, suppose there are 2 people (A, B).
A visits cell C1 and stays there 3 minutes, then visits  C2 for 4 minutes and finally visits  C3 for 2 minutes.
B visits C4 for 3 minutes, then C5 for 4 minutes and finally C6 for 2 minutes.
If the heat values for those cells are

C1 : 8
C2 : 6
C3 : 7
C4 : 2
C5 : 3
C6 : 4

A higher heat means a good place.
My approach was:
score = heat * time_spent
final_score = $\sum$ score/$\sum$time_spent.
According to this,
A's score is:
((8*3) + (6*4) + (7*2))/(3+4+2) = 6.9
B's score is:
((2*3) + (3*4) + (4*2))/(3+4+2) = 2.9
According to this A visited cells with higher heat.
But as you may already notice this is not going to work.
Why?
Let's assume there is a person who visits  4 cells. Cells heats are 16, 1, 1, and 1. If he spent 1 minute in every cell except 16 one. if we assume he spent 2 minutes on it, his score is ((16*2)+(1*1)+(1*1)+(1*1))/5 = 7.00. But you can see he spent most of his time in a low heat place.
Is there a correct way to do this?
Comment: Why won't it work?
Comment: I update the question
Comment: I have slimmed this down but left some puzzling details. For example, why mention a driver? Is this driver to be thought of differently from other people.
Comment: To determine what might be "correct," you need to specify what your "score" is intended to represent.  This question has no definite answer as stated in its abstract form.
Comment: I update question again to give more understand about what is main idea about this score. Please ask any question to clarify this.
Comment: I've edited presentation but so far as I can see this is just as vague as before. The frameworks of cells, heat, visitors seems incidental. You want some kind of weighted average. You have to be precise on why weighting by time spent is not good enough for your purpose,
Answer: There are lots of correct ways to do this. The average (which you say is wrong) is one correct way. It may not answer the exact question that you have, but it's still a useful result. (By the way, it should be 16*1 if he spent one minute in each place; I edited that.)
If you want to totally discount outliers, you could look at the median by minute. Or you could look at the trimmed or Winsorized mean.

Calculate score for multiple variables


Is every integrable function on the real line with compact support also square integrable?

Question: I wonder that whether every integrable function on the real line with compact support is also square integrable ? In other words, is $L^1_c(\mathbb R)\subseteq L^2(\mathbb R)$ holds true? Thanks in advance for any hints.
Comment: If $f\in L^2[a,b]$ for some $a,b\in\mathbb R$, then $f\in L^1[a,b]$. ${}\qquad{}$
Answer: Consider $x \mapsto 1/ \sqrt x$
Comment: How does this function have compact support?
Comment: or any function $x^a$ for $-1\lt a\le-\frac12$. (+1)
Comment: @user2357112 I left the details to the OP.


PHP, MySQL - Trouble downloading uploaded file from database

Question: I have a problem when downloading a file previously uploaded into database, instead of downloading said file the computer downloads a 'download.php' file which is the script to download. I am using some kind of identifier like 'download.php?id=1' to pick and download specific file, and yes, I am aware this code is probably deprecated and not secure.
This is download.php I type:
<?php
session_start();
include("connect.php");
$namatemp=$_SESSION['nama'];
$nistemp=$_SESSION['nislogin'];
$kelastemp=$_SESSION['kelas'];
$mapeltemp=$_SESSION['mapeltemp'];
$chapteridtemp=$_SESSION['chapteridtemp'];

$query=("SELECT mime, name, size, data FROM file WHERE uploader='$namatemp' AND chapter='$chapteridtemp')");
$result=mysql_query($query);
$row=mysql_fetch_array($result);
if($row=1) {
header('Content-Type: '.$row['mime']);
header('Content-Length: '.$row['size']);
header('Content-Disposition: attachment; filename='.$row['name']);
echo $row['name'];
} else {
    echo "You have not uploaded such file.";
}
?>

Comment: plus try to remove the superfluous `chapter='$chapteridtemp')` closing parenthesis in the query. `if($row=1) {` assignment instead of comparison
Comment: you don't output the file
Comment: [**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained [and are officially deprecated](http://j.mp/XqV7Lp). See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. If you choose PDO, [here is a good tutorial](http://j.mp/PoWehJ).
Comment: Doesn't ``header('Content-Disposition: attachment; filename='.$row['name']);`` outputs the file? then ``echo $row['name'];`` calls it?
Answer: You might want to add:
readfile($row['name']);

Yet I think you better check in that page is the file exist to redirect to a download page and if it does not exist, printing the error, because I'm not so sure if the headers can be nested in an if statement. Of course, I might be wrong and get downvoted for saying this.
Comment: Look at [Ghost's comment](http://stackoverflow.com/questions/27350609/php-mysql-trouble-downloading-uploaded-file-from-database#comment43155627_27350609), then look at OP's code again, *very carefully*.


T-test with nested data

Question: I want to test gender differences in an outcome variable called the willingness to pay. My data consists of records with following three fields: person_id, person_gender, and willingness_to_pay (in dollars). Willingness to pay was obtained from some users multiple times. So I have multiple records for some users.
I understand that following would be incorrect:
t.test(willingness_to_pay ~ person_gender, paired = FALSE, data = myData)

How do I account for nesting with person_id? Please help.
Comment: You could try a bootstrap approach, or even better a linear model with random effects as your person_id.
Comment: Formula looks good, check if all other assumptions of the model are met (similar to a linear model).
Comment: Would that mean `lmer(willingness_to_pay ~ person_gender + (1|person_id), data=myData)`?
Answer: It is hard to tell what you actually want to do. In order to test the differences in willingness to pay and formulate the model you have to construct the model in a way that it meets your research question. The central question is: Why do you have repeated measures of willingness to pay? You could for example either compare changes between the groups or within the groups.
If you want to compare between the groups lmer(willingness_to_pay ~ person_gender + (1|person_id), data=myData) is fine and the Random Effect can account for the repeated measures from the same individuals. However, you should consider that it may be necessary to include a time variable that indicates the "measurement moments" because your willingness to pay may be dependent on the moment respondents stated it.
If you interested in within-group-comparison you can also use a paired t-testt.test(x=wtp.moment.1, y=wtp.moment2, alternative = c("two.sided"),var.equal = T, conf.level=0.95) to see if there were significant changes in willingness to pay within the groups (gender) at different moments of measurement. Of course you can also construct a mixed-effect model for this by including a variable that accounts for the "moment of measurement" and its interaction with participants' gender lmer(willingness_to_pay ~ person_gender * moment + (1|person_id), data=myData).

T-test with nested data


Como redimensionar o tamanho da fonte - WPF?

Question: O código a seguir funciona com winforms:
while (label1.Width < System.Windows.Forms.TextRenderer.MeasureText(label1.Text,
    new Font(label1.Font.FontFamily, label1.Font.Size, label1.Font.Style)).Width)
{
    label1.Font = new Font(label1.Font.FontFamily, label1.Font.Size - 0.5f, label1.Font.Style);
}

Como posso fazer isso em WPF ? A ideia é fazer um autoresize num textbox até caber todas as palavras.
Segue a imagem a seguir, que na última linha foi cortada, quero diminuir o tamanho da fonte até mostrar todas as palavras.

A foto acima não é um label, é um textbox.
Alguma ideia de fazer em WPF ?
Answer: Você pode utilizar uma ViewBox para auto redimensionar o tamanho da fonte.
Exemplo
<Viewbox>
     <TextBox Text="TESTE"/>
</Viewbox>


REST com erro de Could not find resource for full path

Question: Estou tentando criar uma aplicação REST, em Java web, bem simples, utilizando Tomcat 8, como  servidor. Porém, ao tentar acessar a aplicação:
http://localhost:8080/aplicacao/rest/teste

Ela me traz o seguinte erro:
Mar 03, 2015 9:18:39 AM org.jboss.resteasy.core.ExceptionHandler
SEVERE: failed to execute
javax.ws.rs.NotFoundException: Could not find resource for full path: http://localhost:8080/aplicacao/rest/teste

Segundo as pesquisas que fiz, meus arquivos de configurações parecem estar corretos:
Classe da aplicação:
@Path("/teste")
public class TesteService {

    @GET
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public Response listar() {

        List<String> listaList = new ArrayList<String>();

        //...populo a lista

        return Response.ok(listaList).build();
    }
}

Arquivo web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>aplicacao</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <display-name>aplicacao rest</display-name>
     <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/rest</param-value>
    </context-param>
    <context-param>
        <param-name>resteasy.scan</param-name>
        <param-value>true</param-value>
    </context-param>

    <servlet>
        <servlet-name>RestServlet</servlet-name>
        <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>RestServlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

Arquivo pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>aplicacao</groupId>
    <artifactId>aplicacao</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>jaxrs-api</artifactId>
            <version>3.0.6.Final</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>3.0.10.Final</version>
        </dependency>

    </dependencies>
</project>

Comment: Qual é o nome da aplicação que você está fazendo o deploy no Tomcat?
Aplicacao?

E sugeriria você tentar acessar a aplicação sem o /rest na URI
http://localhost:8080/aplicacao/rest/teste

Percebi também que você não postou nenhuma classe que extenda Application, você implementou alguma?
Answer: Anote o seu método com @path("/"). Isso significa que este é o caminho raiz do seu recurso. Exemplo:
@Path("/teste")
public class TesteService {

    @Path("/")
    @GET
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public Response listar() {

        List<String> listaList = new ArrayList<String>();

        //...populo a lista

        return Response.ok(listaList).build();
    }
}


Android Studio carregamento infinito

Question: Olá, desde ontem me deparo com um problema no Android Studio, Quando abre ele não termina nunca de carregar o projeto, ontem deixei por mais de 5 horas e nada...
já apaguei a pasta <code>.gradle</code>e não adiantou, tentei abrir por um backup do meu projeto e novamente loop infinito... acabei de criar um projeto novo por enquanto esta em 15 minutos e novamente, nada !

Reparei algo novo aqui.
Exception in thread "png-cruncher_5" java.lang.RuntimeException: Timed out while waiting for slave aapt process, make sure the aapt execute at C:\Users\walla\AppData\Local\Android\Sdk\build-tools\25.0.3\aapt.exe can run successfully (some anti-virus may block it) or try setting environment variable SLAVE_AAPT_TIMEOUT to a value bigger than 5 seconds
      at com.android.builder.png.AaptProcess.waitForReady(AaptProcess.java:108)
      at com.android.builder.png.QueuedCruncher$1.creation(QueuedCruncher.java:121)
      at com.android.builder.tasks.WorkQueue.run(WorkQueue.java:205)
      at java.lang.Thread.run(Thread.java:745)
Exception in thread "png-cruncher_1" java.lang.RuntimeException: Timed out while waiting for slave aapt process, make sure the aapt execute at C:\Users\walla\AppData\Local\Android\Sdk\build-tools\25.0.3\aapt.exe can run successfully (some anti-virus may block it) or try setting environment variable SLAVE_AAPT_TIMEOUT to a value bigger than 5 seconds
      at com.android.builder.png.AaptProcess.waitForReady(AaptProcess.java:108)
      at com.android.builder.png.QueuedCruncher$1.creation(QueuedCruncher.java:121)
      at com.android.builder.tasks.WorkQueue.run(WorkQueue.java:205)
      at java.lang.Thread.run(Thread.java:745)
Exception in thread "png-cruncher_3" java.lang.RuntimeException: Timed out while waiting for slave aapt process, make sure the aapt execute at C:\Users\walla\AppData\Local\Android\Sdk\build-tools\25.0.3\aapt.exe can run successfully (some anti-virus may block it) or try setting environment variable SLAVE_AAPT_TIMEOUT to a value bigger than 5 seconds
      at com.android.builder.png.AaptProcess.waitForReady(AaptProcess.java:108)
      at com.android.builder.png.QueuedCruncher$1.creation(QueuedCruncher.java:121)
      at com.android.builder.tasks.WorkQueue.run(WorkQueue.java:205)
      at java.lang.Thread.run(Thread.java:745)
Exception in thread "png-cruncher_4" java.lang.RuntimeException: Timed out while waiting for slave aapt process, make sure the aapt execute at C:\Users\walla\AppData\Local\Android\Sdk\build-tools\25.0.3\aapt.exe can run successfully (some anti-virus may block it) or try setting environment variable SLAVE_AAPT_TIMEOUT to a value bigger than 5 seconds
      at com.android.builder.png.AaptProcess.waitForReady(AaptProcess.java:108)
      at com.android.builder.png.QueuedCruncher$1.creation(QueuedCruncher.java:121)
      at com.android.builder.tasks.WorkQueue.run(WorkQueue.java:205)
      at java.lang.Thread.run(Thread.java:745)
Exception in thread "png-cruncher_2" java.lang.RuntimeException: Timed out while waiting for slave aapt process, make sure the aapt execute at C:\Users\walla\AppData\Local\Android\Sdk\build-tools\25.0.3\aapt.exe can run successfully (some anti-virus may block it) or try setting environment variable SLAVE_AAPT_TIMEOUT to a value bigger than 5 seconds
      at com.android.builder.png.AaptProcess.waitForReady(AaptProcess.java:108)
      at com.android.builder.png.QueuedCruncher$1.creation(QueuedCruncher.java:121)
      at com.android.builder.tasks.WorkQueue.run(WorkQueue.java:205)
      at java.lang.Thread.run(Thread.java:745)
Comment: Você já tentou fazer o que a mensagem recomendou? Especificamente o trecho "Certifique-se que 'C:\Users\walla\AppData\Local\Android\Sdk\build-tools\25.0.3\aapt.exe' roda corretamente(alguns antivírus podem bloqueá-lo)."
Comment: terminado o café , tentarei.
Comment: botei na lista de exclusões do Avast agora foi, apesar de ter aparecido o mesmo erro no gradle console
Comment: Estou votando para fechar porque [segundo o AP](https://pt.stackoverflow.com/questions/222053/android-studio-carregamento-infinito#comment457599_222062) *"era o firewall que tava bloqueando o arquivo"*
Answer: Conforme a mensagem (tradução livre):

Certifique-se que
  'C:\Users\walla\AppData\Local\Android\Sdk\build-tools\25.0.3\aapt.exe'
  roda corretamente(alguns antivírus podem bloqueá-lo).

Com relação a mensagem no console ela provalmente é persistente, procure por um botão 'Limpar Console' e veja se ela continua aparecendo após reiniciar o Android Studio.
Comment: era o firewall que tava bloqueando o arquivo
Comment: compilei meu projeto algumas e 2 vezes tive que reiniciar por causa desse log, vou desativar o avast e ver como funciona, bem chato isso

Android Studio carregamento infinito


Reading excel file inside a servlet (multipart data)

Question: I am supposed to read an excel file on the server and store it in the database as a table.
I was using ApachePOI to read the excel file by picking up the excel file from the hard disk.
Imagine a client uploads a file and sends it to a server, the server wouldn't have access to the hard disk of the client. So now I want to send it as a multipart form-data and then read it on the server.
I have been reading on the internet as well as Stackoverflow  but have not found an answer(although there are examples to read a text file).
Please guide me. Thank you.
Comment: read [this](https://stackoverflow.com/questions/19237031/uploading-a-file-in-java-servlet)
Answer:
Accept the uploaded multiPart File in your servlet.
The servlet should then write the uploaded file to the server's disk.
The servlet can then read the uploaded file from the server's disk.


Is it allowed to throw the ball and then catch it again in a table tennis serve?

Question: Suppose a table tennis player goes to serve. They throw the ball but for whatever reason decide not to play it. Instead they catch it with their hand.
Is this a service fault and therefore a point for the receiver or a let?
Answer: Throw up and catch - Table Tennis Rules
Q:
If I toss the ball up but I don't serve and catch the ball back,  Is it a fault serve?
A:
Yes that is your opponent's point.  As soon as you throw the ball up it is in play. - Alois Rosario
Ref: https://www.pingskills.com/table-tennis-forum/throw-up-and-catch
Comment: In a tournament, yes. But in casual play where you might be interrupted by someone running right behind you as you are tossing the ball to serve, then no.


how to pass variable in using post method with jquery .load()

Question: I want to pass the variables name, email into the .load() event.
var email = $('#reg-email').val();
var name = $('#reg-name').val();
$("#user-detail").load("proc/reg-step2.php",{ "name": "name" , "email": "email" }, function() {
    $("#ajaxLoader2").remove();
});

What should be the syntax for this section so that the variable is passed instead of jst the strings I've written here { "name": "name" , "email": "email" }??
Answer: You can use a variable instead of a literal:  { "name": name, "email": email }
Comment: is my .load() syntax above incorrect (after changing to what you've told here)?? It is not working. I want to pass the variables and still use the callback function too.
Comment: If I write is the way you've mentioned here, the file `reg-step2.php` is not loaded at all.
Comment: You're passing a string literal.  You need to pass a variable. (eg, `{ propName: someVariable }`
Comment: If i use the the above exact code I've written in my Question, the strings are passed properly. If I change the section `{ "name": name, "email": email }`, than the XHR result doesn't even show that the file reg-step2.php is loaded at all (am using chrome developer tool)
Answer: In an object literal you can use quotation marks around the property names, but you shouldn't use them around the variable names that you use in the values:
{ "name": name, "email": email }

You can also write the object literal without quotation marks around the property names:
{ name: name, email: email }

You can also mix quoted and unquoted property names, as you need:
{ "name": name, email: email }

If you would have a property name with special characters, like name+email, you need quotes around it in the object literal:
{ "name+email": name + ', ' + email }


Incorrect IP address of docker container

Question: I use RockyLinux and I have installed Docker for my services. My docker-compose.yml file looks similar like this:
<code>version: "3.9"

services:
  service_a:
    container_name: service_a
    build: ./images/service_a
    hostname: service_a
    restart: always
    environment:
      TZ: 'Europe/Warsaw'
    networks:
      default_network:
        ipv4_address: 172.16.238.20
        aliases:
          - service_a.lan

  service_b:
    container_name: 'service_b'
    build: ./images/service_b
    hostname: service_b
    restart: always
    environment:
      TZ: 'Europe/Warsaw'
    networks:
      default_network:
        ipv4_address: 172.16.238.21
        aliases:
          - service_b.lan

networks:
  default_network:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 172.16.238.0/24
</code>
I have tried to communicate between the above services (let's assume that I connected from service_b to service_a). When I was analysing network trafic on one of container (let's asume that it is service_a) I noticed that all incomming traffic has incorrect ip address (172.16.238.1 instead of 172.16.238.21). I would like to get IP of service_b (172.16.238.21). What can I do to achieve this goal?
Answer: Problem solved. The system has been restarted and it works.


Why k-nn classifier gives exactly the same accuracy with both Euclidean distance and Manhattan distance algorithm with my data?

Question: I am working on the breast cancer dataset  in Weka where the class variable is the target of classification. I ran the nearest neighbour classifier (lazy/IBk) with Euclidean distance with different values of k-nn for the k nearest neighbours, from 1 to 10 (with all the other features selected) and I got the following results:

Then I ran the same classifier with the same selected features but this time with Manhattan distance and with k from 1 to 10 and I got exactly the same result as before:

I wonder why the two result tables are literally the same?
Answer: Either or both of these conditions could exist:

They're the same because nearest neighbors ultimately only depends on what observations are nearest. In other words, each observation has the same ranked distances from the other observations, for these choices of $k$. (The ranks of the $k+1$ nearest observation, and all more distant observations, has not effect on the $k$-NN classification.)
The ranks could be different, but the distance to the nearest observation of like class (positive/negative) is not changed. So if changing the metric changed the ranked distances, this effect will be suppressed if the nearest neighbor in the Manhattan case is the same class as the nearest neighbor in the Euclidean case, for all cases, for all $k \in \{1,2,3,\dots,10\}$.

(Or there's a coding mistake somewhere. Coding mistakes sometimes happen.)
Comment: If you've found my answer helpful, please consider upvoting or accepting it. It seems that you have an outstanding question about how dimension and distance measurements are related. A large number of dimensions can mean that points tend to become uniformly far apart in a certain sense (see: https://stats.stackexchange.com/questions/99171/why-is-euclidean-distance-not-a-good-metric-in-high-dimensions/99191#99191), but that doesn't necessarily entail that you would observe the phenomenon that you outline in your question. If you wish, you can ask another question about this in particular.
Comment: Thanks for your answer. Besides what you have explained, can the dimensionality of data be one reason as well? The dataset on which I am working is not a big, one its shape is (286, 10)
Comment: As you are knowledgeable, could you please answer my other [question](https://stats.stackexchange.com/questions/499780/a-dataset-with-exactly-the-same-number-of-occurrences-of-each-attribute-value) as well? Thanks.
Comment: @Coder If you wish to draw attention to a question, you can place a bounty on it.


How to insert data from Textboxes into GridView on button click in ASP.NET

Question: I want to get the data from textboxes, and on button click I want that data to be inserted into GridView. On every click there should be a new row created, and old row must not be removed. Whenever I enter the new data and click on button, my old row is deleted and new row is stored in place of it. Here is my code:
DataTable dt1 = new DataTable();
bool flag = false;

private void gridVIEWData()
{
   dt1.Columns.Add("pName", typeof(string));
   dt1.Columns.Add("pCategory", typeof(string));
   dt1.Columns.Add("price", typeof(string));
   dt1.Columns.Add("pQuantity", typeof(string));
   dt1.Columns.Add("totalPrice", typeof(string));
}
protected void Button3_Click(object sender, EventArgs e)
{
    if (!flag)
    {
        gridVIEWData();
        flag = true;
        Int32 total = Convert.ToInt32(txt_quantity.Text) * Convert.ToInt32(txt_price.Text);
        DataRow dr = dt1.NewRow();
        dr["pName"] = DropDownList2.SelectedItem;
        dr["pCategory"] = DropDownList1.SelectedItem;
        dr["price"] = txt_price.Text;
        dr["pQuantity"] = txt_quantity.Text;
        dr["totalPrice"] = total;
        dt1.Rows.Add(dr);

        GridView1.DataSource = dt1;
        GridView1.DataBind();
    }
    else if (!IsPostBack)
    {
        Int32 total = Convert.ToInt32(txt_quantity.Text) * Convert.ToInt32(txt_price.Text);
        DataRow dr = dt1.NewRow();
        dr["pName"] = DropDownList2.SelectedItem;
        dr["pCategory"] = DropDownList1.SelectedItem;
        dr["price"] = txt_price.Text;
        dr["pQuantity"] = txt_quantity.Text;
        dr["totalPrice"] = total;
        dt1.Rows.Add(dr);

        GridView1.DataSource = dt1;
        GridView1.DataBind();
    }
}

Comment: What happens in `Page_Load`? Consider to rename your buttons. The purpose of `Button3` is not obvious.
Answer: The old data is removed as you bind it with new data. You have to keep the old data in the data source which data table in your case. Usually we have persistent medium for storing data like database of files.
For your understanding I will store datatable in Session but it is usually not practised, you should store in database or what ever medium you like.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        gridVIEWData();
        GridView1.DataSource = dt1;
        GridView1.DataBind();
    }
}

private void gridVIEWData() {
   dt1.Columns.Add("pName", typeof(string));
   dt1.Columns.Add("pCategory", typeof(string));
   dt1.Columns.Add("price", typeof(string));
   dt1.Columns.Add("pQuantity", typeof(string));
   dt1.Columns.Add("totalPrice", typeof(string));
   Session["dtInSession"] = dt1;     //Saving Datatable To Session
}

protected void Button3_Click(object sender, EventArgs e)
{
        if(Session["dtInSession"] != null)
             dt1 = (DataTable)Session["dtInSession"]; //Getting datatable from session

        Int32 total = Convert.ToInt32(txt_quantity.Text) * Convert.ToInt32(txt_price.Text);
        DataRow dr = dt1.NewRow();
        dr["pName"] = DropDownList2.SelectedItem;
        dr["pCategory"] = DropDownList1.SelectedItem;
        dr["price"] = txt_price.Text;
        dr["pQuantity"] = txt_quantity.Text;
        dr["totalPrice"] = total;
        dt1.Rows.Add(dr);

        Session["dtInSession"] = dt1;     //Saving Datatable To Session
        GridView1.DataSource = dt1;
        GridView1.DataBind();

    }
 }

Comment: You are welcome, but Session is not meant for this little about sessions http://msdn.microsoft.com/en-us/library/ms178581(v=vs.100).aspx
Comment: I don't think it's a good idea to store datatable in Session. Read the link http://stackoverflow.com/questions/12811932/using-session-to-store-datatable
Comment: @ Adil can u please help me in deleting a row from that gridview. after the data is inserted in that grid view. i have edited the code. kindly help. thanx
Answer: This is because you are calling gridVIEWData(); every time on postback that create table columns again.
Try this
DataTable dt1 = new DataTable();

private void gridVIEWData() {
    dt1.Columns.Add("pName", typeof(string));
    dt1.Columns.Add("pCategory", typeof(string));
    dt1.Columns.Add("price", typeof(string));
    dt1.Columns.Add("pQuantity", typeof(string));
    dt1.Columns.Add("totalPrice", typeof(string));
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        gridVIEWData();
        GridView1.DataSource = dt1;
        GridView1.DataBind();
        Session["dt1"]=dt1;
    }
}

protected void Button3_Click(object sender, EventArgs e)
{
    if(Session["dt1"]!=null) dt1 = (DataTable) Session["dt1"];
    Int32 total = Convert.ToInt32(txt_quantity.Text) * Convert.ToInt32(txt_price.Text);
    DataRow dr = dt1.NewRow();
    dr["pName"] = DropDownList2.SelectedItem.Text;
    dr["pCategory"] = DropDownList1.SelectedItem.Text;
    dr["price"] = txt_price.Text;
    dr["pQuantity"] = txt_quantity.Text;
    dr["totalPrice"] = total.ToString();
    dt1.Rows.Add(dr);

    GridView1.DataSource = dt1;
    GridView1.DataBind();
}

Comment: can u please correct it in my code. or where i shud call it.??
Comment: now i m getting error of column 'pName' does not belong to the table...:(


Fazer upload e download de imagem para pasta do projeto usando Spring Boot

Question: Estou desenvolvento um modulo web que preciso fazer um upload de uma imagem. Fazer salvar na pasta do projeto, estou usando a Commons Io do Apache:
public class FileUtil {

    public static void saveFile(String path, MultipartFile file){

        File saveFile = new File(path);
        try {
        FileUtils.writeByteArrayToFile(saveFile, file.getBytes());
        } catch (IOException e) {
        e.printStackTrace();
        }
    }
}

@Autowired
private ServletContext servletContext;

@RequestMapping(value = "/salvar", method = RequestMethod.POST)
public String salvar(Event evento, Model model, @RequestParam("file") MultipartFile file) {
    if (file != null && !file.isEmpty()) {
        String path = servletContext.getRealPath("/") + "resources/imagens/" + evento.getName() + ".png";
        FileUtil.saveFile(path, file);
    }
    service.salvar(evento);
    return "redirect:/evento/formulario";
}

Ate estou conseguindo salvar, mas como tonar esse caminho em que a imagem foi salva, em um link que possa baixar a imagem e adicionar como atributo da classe Evento?
Comment: Você quer esse link onde, numa página JSP? Qual seria essa classe `Event`? A imagem pode ser acessada de uma forma estática?
Comment: O link seria mostrado em uma coluna de uma tabela numa pagina html, mostrar o link nao e problema, a questao seria como recuperar esse aquivo que foi feito o upload e baixar ele. A classe evento deve possuir uma imagem, porem so estou guardando a referencia da imagem em um atributo da classe. Poderia ser acessada estaticamente sim.
Answer: Crie um método que receba o nome de uma imagem e faça o download dela, exemplo:
@Controller
@EnableAutoConfiguration
public class Main {

    @Autowired
    private ServletContext servletContext;

    //Lista as imagens dentro da pasta resources/imagem numa JSP
    @RequestMapping("imagens")
    public ModelAndView imagens() throws IOException {

        ModelAndView mv = new ModelAndView("image-list");
        Set<String> nomeDasImagens = servletContext.getResourcePaths("/resources/imagens/").stream()
                                                    .map(FilenameUtils::getBaseName)
                                                    .collect(Collectors.toSet());
        mv.addObject("imagens", nomeDasImagens);
        return mv;
    }

    //Faz o download da imagem com o nome informado
    @RequestMapping(value = "download/{nome}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<InputStreamResource> downloadImage(@PathVariable String nome) {
        InputStream is = servletContext.getResourceAsStream("/resources/imagens/" + nome + ".png");
        if(is == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }

        //Faça o que quiser aqui
        //Como criar um Event e atribuir o nome ou o caminho da imagem a ele

        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_PNG)
                .header("Content-disposition", "attachment; filename=" + nome + ".png")
                .body(new InputStreamResource(is));
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Main.class, args);
    }
}

Página JSP que lista todas as imagens:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Imagens</title>

        <c:forEach var="imagem" items="${imagens}">
            ${imagem}

        </c:forEach>

Edit:
Para apenas exibir a imagem, você pode remover o header da ResponseEntity ficando assim:
return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_PNG)
                .body(new InputStreamResource(is));

Outra opção é acessá-la de forma estática:
Para isso adicione o seguinte método:
@RequestMapping("imagens-estaticas")
public ModelAndView imagensEstaticas() throws IOException {

    ModelAndView mv = new ModelAndView("image-list");
    Map<String, String> nomeDasImagens = servletContext.getResourcePaths("/resources/imagens/").stream()
                                                .collect(Collectors.toMap(FilenameUtils::getBaseName, String::toString));
    mv.addObject("imagens", nomeDasImagens);
    return mv;
}

E altere o JSP para:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Imagens</title>

        <c:forEach var="imagem" items="${imagens}">
            ${imagem.key}

        </c:forEach>

Edit 2:
Para você poder fazer o download de imagens em qualquer formato:
@RequestMapping("imagens")
public ModelAndView imagens() throws IOException {

    ModelAndView mv = new ModelAndView("image-list");
    Set<String> nomeDasImagens = servletContext.getResourcePaths("/resources/imagens/").stream()
                                                .map(FilenameUtils::getName)
                                                .collect(Collectors.toSet());
    mv.addObject("imagens", nomeDasImagens);
    return mv;
}

@RequestMapping(value = "download/{nome:.+}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<InputStreamResource> downloadImage(@PathVariable String nome) throws FileNotFoundException {
    InputStream is = servletContext.getResourceAsStream("/resources/imagens/" + nome);
    if(is == null) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
    }
    return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType("image/" + FilenameUtils.getExtension(nome)))
            .header("Content-disposition", "attachment; filename=" + nome)
            .body(new InputStreamResource(is));
}

Comment: Nao realiza o download na requisicao. Teria uma forma de apenas exibir a imagem na pagina a partir da url?
Comment: @MarceloHenrique Estranho, nos meus testes, quando clico nos links das imagens, o download é realizado.Editei a resposta para apenas mostrar a imagem e não realizar o download dela.
Comment: Fiz um outro codigo e consegui realizar o download. Irei testar agora esse de apenas visualizacao..
Comment: Seu codigo esta correto, eu que fiz uma coisa errada. Obrigado! Nesse caso, o unico formato que eu poderia salvar na pasta seria o PNG, por casua do MediaType? Ou apenas trocar pela opcao ALL ja resolveria?
Comment: @MarceloHenrique No exemplo que dei, coloquei só no formato PNG porque foi o formato que você está salvando segundo o código na sua pergunta. Não seria necessário mudar para `MediaType.ALL`, porém você teria que passar extensão do arquivo junto ao nome e definir o `MediaType` de acordo com o formato do arquivo. Editei minha pergunta e coloquei um exemplo.


How to visualize a multilevel/mixed model with two fixed effects and one random effect?

Question: The model I want to visualize is this one:
BZ ~ 1 + SV_DMW + SV_DIFF (1 + SV_DMW| VPN)
Do you have any ideas how to do this best?
This is how I visualized the model, where just SV_DMW was included.

The single lines are 5 random chosen subjects (VPN).
Do you have any idea how to visualize the model shown above similarly, or do you maybe have entirely different recommendations how to visualize the relationship?
Further information:
SV_DMW and BZ are, in general, associated positively
SV_DIFF and BZ are, in general, associated negatively
Comment: Welcome to the site.  What are these variables? It helps to have context, but, in particular, are SV_Diff and SV_DMV continuous or categorical or integers or what? Are they always positive?
Comment: It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions.
Comment: @PeterFlom thanks for your questions. All variables are continuous. SV_Diff has a range from 1 to 6 and is associated negatively with BZ. SV_DMW has a range from 1 to 7 and is associted positively with BZ. BZ has a range from 1 to 9.
BZ = relationship satisfaction
SV_DMW = Jointly averaged level of sexual desire of a couple
SV_Diff = Difference of sexual desire of persons of a couple
Comment: Instead of plotting individuals, plot the predicted values.  Use two graphs. For graph 1, the x axis is SV_DIFF and the y axis is BZ. Make lines for different values of DMW (maybe the quartiles).  Graph 2, just the reverse.
Comment: Gelman's *Data Analysis Using Regression and Multilevel/Hierarchical Models* has many figures and visualizations wrt this class of models. Might be worth a look? https://www.google.com/books/edition/Data_Analysis_Using_Regression_and_Multi/lV3DIdV0F9AC?hl=en&gbpv=0
Answer: The sjPlot package can get you there. You can use the plot_model function.
library(lme4)
#> Loading required package: Matrix
library(sjPlot)
library(ggplot2)
library(patchwork)
theme_set(theme_sjplot())

# Data creation inspired by Ben Bolker's post at
# https://stackoverflow.com/a/38296264/7050882

set.seed(101)
SV_DMW = runif(6000, 1, 24)
SV_DIFF = runif(6000, 5, 15) * -SV_DMW
VPN = as.factor(rep(seq(1:60), each = 100))
testdata <- data.frame(SV_DMW, SV_DIFF, VPN)
testdata$BZ <- testdata$SV_DIFF * -testdata$SV_DMW/10 * rnorm(300, mean=30, sd=20)

# Model
fit = lmer(BZ ~ 1 + SV_DMW + SV_DIFF + (1|VPN),
           data = testdata, REML = TRUE)
#> boundary (singular) fit: see help('isSingular')

plot_model(fit, type = "pred", terms = c("SV_DMW")) +
  ggtitle(element_blank()) +
  plot_model(fit, type = "pred", terms = c("SV_DIFF")) +
  ggtitle(element_blank())
#> Warning: Ignoring unknown parameters: linewidth
#> Ignoring unknown parameters: linewidth

Created on 2023-06-27 with reprex v2.0.2
I simulated your data above. You can instead work directly on the plot_model part by replacing fit with the name of your model.


How can an event subscriber have access to the entity type?

Question: I'm using entity_print for PDF generation on two node types. I'd like each to have its own orientation configuration (or just have one override the default). There is an event in entity_print where configuration can be set at run-time, so I have a simple event subscriber, with a method to override the orientation, but I can't seem to get the last piece, which is the entity (bundle label) to switch on.
How can an event subscriber have access to the entity type?
Comment: You have an entity object in code? You should have a `bundle()` method to return the type. Node also has the convienient method `getType()` for node objects to get their node type.
Comment: @Kevin That's the problem, the event object is only storing the type of the print object, not the object being printed. I think upon further investigation, I may actually need to subscribe to a pre-send event to get this.
Answer: The event should have the entities its acting on. Have you tried the following?
<code>$entities = $event->getEntities();
</code>
To get the bundle:
<code>$bundle = $event->getEntities()[0]->bundle();
</code>


Laravel Query builder not fetch any response but same query work fine in MySql

Question: I am trying to Run This Query from laravel Query Builder But it returns an empty response
but when I get the query from the query log and run this in phpMyadmin it response with data.
<code> Project::join('project_assignation','projects.id','project_assignation.project_id')
        ->join('users','project_assignation.employee_id', 'users.id')
         ->join('eods', 'eods.user_id', 'users.id')
         ->select('projects.project_name', DB::Raw('SUM(eods.today_hours) as pr_time'))
         ->where('users.id', 210)
         ->whereMonth('eods.date', 9)
         ->whereYear('eods.date', 2019)
         ->where('eods.project_id', '=', 'projects.id')
         ->groupBy('projects.project_name')
         ->orderBy('projects.project_name')
         ->get();
</code>
Query Log:
<code> Array (
     [0] => Array
         (
             [query] => select `projects`.`project_name`, SUM(eods.today_hours) as pr_time from `projects` inner join
 `project_assignation` on `projects`.`id` =
 `project_assignation`.`project_id` inner join `users` on
 `project_assignation`.`employee_id` = `users`.`id` inner join `eods`
 on `eods`.`user_id` = `users`.`id` where `users`.`id` = ? and
 month(`eods`.`date`) = ? and year(`eods`.`date`) = ? and
 `eods`.`project_id` = ? group by `projects`.`project_name` order by
 `projects`.`project_name` asc
             [bindings] => Array
                 (
                     [0] => 210
                     [1] => 9
                     [2] => 2019
                     [3] => projects.id
                 )

             [time] => 0.98
         )

 )
</code>
In php myadmin this query execute fine and also return related data.
Comment: Well, the query seems to work fine. You have two different months in the queries, so maybe there are just no results to return?
Comment: No, the first one is a month and second year.
Comment: No, I meant you're using `month(\`eads\`.\`date\`) = 7` in the phpmyadmin query, and `month(\`eads\`.\`date\`) = 9` in your Laravel query. Try using the same month in both queries so that it should return the same data.
Answer: Just from first view I saw that in your SQL you didn't have comparison of "eods.project_id" with "project.id", which you had in Query Builder:
<code> ->where('eods.project_id', '=', 'projects.id')
</code>
So I think this answer can be useful for you
Comment: Actually, it is in the SQL, but you're right that this part of the query won't do what is expected.
Answer: With Laravel, the second/third parameter in a WHERE query is passed as a string, and would not be treated as a column name. Therefore, in a raw query,
<code> ->where('eods.project_id', '=', 'projects.id')
</code>
would look like
<code> WHERE `eods`.`project_id` = 'projects.id'
</code>
You need to pass it in as a RAW query so that it would compare column to column
<code>->whereRaw('eods.project_id = projects.id')
</code>


"New Mirrored Volume" is disabled for fixed size VHD disks

Question: I am doing a Windows Mirroring POC. I am using windows 10 Enterprise as my POC environment.
I created two fixed size VHD disks.
"New Mirrored Volume" is disabled per below screenshot:

Why are all the RAID options disabled?
Update 1:
Convert to Dynamic Disk is disabled too

Update 2:
It seems to be quite possible with Windows 7 Ultimate per blow post:
https://superuser.com/questions/116983/can-i-setup-a-software-raid-in-windows-7-using-virtual-hard-disks
Has anything changed with Windows 10?
Answer: You have to convert the disks from Basic to Dynamic.
Comment: please see my update 2. This is doable in Windows 7 ultimate. Do we know if it became more limited with windows 10?
Comment: Thank you for help. Please see my update. Convert to dynamic disk is disabled too.
Comment: Looking closer at your screenshot and re-reading your question, it looks like those are attached VHD files, right? I missed that in your question when I read it. I don't think you can convert attached VHD files from basic disks to dynamic disks.
Answer: I don't know if you got to solve it, Allan Xu.  My experience: in Windows 10 you have to use Storage Pools.  This can be launched from the Control Panel


Optimization of multple if condition in python

Question: I have a python condition statement like this
if 'small_cover' not in request.POST or 'medium_cover' not in request.POST or 'large_cover' not in request.POST:
    # do somethinf here.

Can there be the shortest way than this.
Comment: What framework provides the `request.POST` object? Is this Django, for example?
Comment: `if not all(thing in request.POST for thing in ('small_cover', ...)):`?
Comment: yes it is the dictionary of POST objects
Comment: @wrufesh: no, it is an *object that acts like a dictionary*. It depends *heavily* on what type of object it really is what answers I can give you.
Comment: If it *is* just a dictionary, this question is a duplicate. But the best way to do this with a true dictionary may not be the best way to do it with, say, a Werkzeug MultiDict object.
Comment: I've now dupe-hammered this to the canonical multiple-keys-in-dictionary post, as the answers here did not add anything new to the discussion.
Answer: if not all(x in request.POST for x in ('small_cover', 'medium_cover', 'large_cover')):

or even more concisely:
if not all(x+'_cover' in request.POST for x in ('small', 'medium', 'large')):

Answer: Just use any which will short circuit if we find any of the three items are not in  request.POST
if  any(x not in request.POST for x in ('small_cover',  'medium_cover','large_cover')):