What inf means in the confidence intervals from a paired sample in t.test() ? R-related question

Question: I'm doing the t.test from a paired sample, only considering as alternative hypothesis that the mean is greater than 0. Why the confidence interval has a minimum value but not a maximum?
The only reason I can think of it is that the maximum value of the mean is not as important as the minimum value if your restriction is Ho>0, but seems strange.
This is the code:
healthy<- c(-0.9914, 1.471, 1.2459, 0.4024, 0.0325, -0.6396, 0.7246, 0.0604)
lame<-c(4.3541, 4.7865, 6.1945, 10.7383, 3.3007, 4.8678, 7.8965, 3.9338)

t.test(lame, healthy, paired = TRUE, alternative='greater')

And this is the outcome:
Paired t-test

data:  lame and healthy
t = 6.5639, df = 7, p-value = 0.0001574
alternative hypothesis: true mean difference is greater than 0
95 percent confidence interval:
 3.891736      Inf
sample estimates:
mean difference
         5.4708**

Answer: A 95% confidence interval doesn't have to be symmetric about the mean. It just needs to define an interval based on a calculation that would contain the true value 95% of the time in repeated experiments.
Your idea that "the maximum value of the mean is not as important as the minimum value if your restriction is" $H_\text{alt}>0$* is pretty much what's going on here. Your asking for a one-sided test has effectively ruled out the idea that the alternative could include $H_\text{alt}<0$. Any finding of a value below 0 would be attributed to random variation rather than a true negative value. So there's no need to consider the upper confidence limit for the mean; you just want to make sure that the lower 5% doesn't include the value of 0.
The result in practice is that the lower confidence limit in such a 1-sided t-test is farther away from 0 than it would be with a 2-sided t-test and its symmetric CI about the mean. For your data and a 2-sided test, the lower limit is at 3.50 instead of 3.89.
@BruceET has a nice illustration of the difference between 2-sided and 1-sided tests here.

*In standard terminology, $H_0$ stands for the null hypothesis, so I use $H_\text{alt}$ to represent the alternate hypothesis.


Matlab Chi^2 Goodness of fit test for specified mean

Question: I would like to perform a chi^2 goodness of fit test in Matlab and have found the function h = chi2gof(x) to do almost what I want. The only issue is that I want to perform the fit about a proposed mean and not the mean that chi2gof automatically estimates from the data.
Comment: I think that you may be able to do this if are able to specify more information than just your own mean estimate. You'd need to provide the CDF, and any parameters of the particular distribution, e.g., mean and std. dev. for a normal distribution. See [this example](https://www.mathworks.com/help/stats/chi2gof.html#expand_panel_heading_d124e174999).
Answer: I am going to answer starting with the point that seems to generate confusion:
The only issue is that I want to perform the fit about a proposed mean and not the mean that chi2gof automatically estimates from the data.
1.- chi2gof does not estimate a mean from data
chi2gof estimates how likely is the supplied data to be the pdf that you tell chi2gof it may be.
You supply the likely pdf therefore you supply the mean and other statistical moments that the data may or may not show.
2.- By default normal aka Gaussian
If you input just x the data
h=chi2gof(x)

chi2gof assumes it's a normal distribution with significance level p = 0.05
If the data is generated as normal with mean=100 and sigma=1 then chi2gof solves
is x normal with significance level aka p=0.05 ?
To change the significance level
h=chi2gof(x,'Alpha',.01)

The default significance level by default is 0.05 .
There has been some initiative to change such 0.05 default value down to 0.005 but it backfired, the experts casting further doubt on being able at all to pontificate around a bare threshold, details in article Moving to a world beyond p<0.05, authors:
R.L.Wasserstein,A.L.Schirm, N.A.Lazar Mar20th 2019 American Statistician .
3.- Alpha IS NOT mean(x)
Alpha is a threshold for significance level p.
Alpha=0.01 means the probability of errors or false positives being 1 in 100 samples, on average.
4.- To change the reference distribution in chi2gof use field CDF
First define the specific distribution with the particular mean you are aiming at, for instance
pd = fitdist(x,'Weibull');

and then use pd in chi2gof
h = chi2gof(x,'CDF',pd)

The complete chi2gof help file is available online here
https://www.mathworks.com/help/stats/chi2gof.html
Comment: When refering to "estimate of mean from data" I was referencing the matlab help page which you also linked:

"h = chi2gof(x) returns a test decision for the null hypothesis that the data in vector x comes from a normal distribution with a mean and variance estimated from x".

A proposed solution worked which was also found in the matlap help being h = chi2gof(x,'cdf',{@normcdf, mean, std}
Comment: yes, and in @normcdf you can put any other distribution, besides normal. Does the CDF field work and does it solve your question?


How to add a node field to a database table in a custom module

Question: When I am writing my own custom module, and designing a database table, if I want to use the  field nid to refer to a node, because I want my module to adding something to each node, how should I implement this in the module's mymodule.install file?
Answer: Most of the time you will probably want to use the field API (CCK module in D6) rather than adding custom tables or modifying node by yourself.
Adding custom tables was a very D5 way of doing thing.
If you want to do this you will need to define your tables using hook_schema() and then in your mymodule_install() hook you can call drupal_install_schema() this should create a new table which represents your module.
It is worth mentioning that your schema should always represent your current schema. If you add a column you should alter the schema so that someone who installs your module will get the correct schema, but also write an update function to alter the table so that existing users get the correct new schema.
It is possible to alter other modules' tables, but I think that should be covered in another question.
Comment: i only want to add two fields to the specific content type's node.if don't creat the table,which table should i add. someone tell me to use the node_revision table.what do you think?
Comment: If you only want to add two fields to a specific node type use the field api.
Comment: how to use the field api. could you make me an example.thank you.
Comment: I could, but it may be better to ask a separate question. As you are specifically asking about database tables in your question.


How to use CONCAT in join sql request in ZF2

Question: I am moving my zf1 app to zf2 and I am having a lot of problems to move my mappers.
Apparently, I can't just copy/past my query (too bad!)
I am trying to use CONCAT in a join like
$resultSet = $this->select(function (Select $select) use($userId, $filter, $status){

 $select->columns(array("id_project", "name", "current_to", "avancement"));
 $prj = "PRJ_";
 $select->join(array("ru" => "role_users"), "CONCAT( $prj , projects.id_project ) = ru.element", array())
                   ->where("ru.user_id = $userId");

If I print the $select->getSqlString(), I get :
    SELECT "projects"."id_project" AS "id_project", "projects"."name" AS "name",
    "projects"."current_to" AS "current_to", "projects"."avancement" AS "avancement" FROM
"projects" INNER JOIN "role_users" AS "ru" ON "CONCAT"( "PRJ_" "," "projects"."id_project"
 ) = "ru"."element" WHERE ru.user_id = 3

Apport for all the " ", this is correct (If I remove all the "" and execute it in phpmyadmin, it works.
But, if zf2 is executing it, I get an error :
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in
your SQL syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near '`projects`.`id_project` ) = `ru`.`element`
WHERE ru.user_id = 3' at line 1

It looks like there is a problem with the CONCAT() but I can't find where the problem is.
Answer: This I find not very elegant but it works:
$select->join(array("ru" => "role_users"),
new Expression("CONCAT( $prj , projects.id_project ) = ru.element"), array())
->where("ru.user_id = $userId"));


how separate Entity Reference in view?

Question: I have two content type, content type A and content type B , I used Entity Reference field in content type B to reference content type A.
I created view with field Entity Reference ,In Entity Reference there are more field included how can i separate this all field in view ?
Answer: Add a "Relationship" to your view:

And then select "Entity Reference" in the "Filters" select list. You can choose whether is a content entity that is referenced, or referencing.

how separate Entity Reference in view?


When are homotopy-equivalent 4-manifolds s-cobordant?

Question: Suppose $X$ and $Y$ are closed 4-manifolds, not necessarily simply connected.
Such manifolds are said to be s-cobordant if there is a 5-manifold $W$ with $\partial W = X \sqcup Y$ such that the inclusion maps $X, Y \hookrightarrow W$ are simple homotopy equivalences.
If $X$ and $Y$ are homotopy equivalent, are they s-cobordant? What if they are simply homotopy equivalent? I am interested in the smooth or PL categories.
Answer: Take two homotopy equivalent 3-dimensional lens spaces $L$ and $L'$ that are not homeomorphic.  Then $S^1 \times L$ and $S^1 \times L'$ are closed, smooth 4-manifolds that are simple homotopy equivalent but not $s$-cobordant.


Is it always better to analyze at the most granular level possible? What is the best unit of analysis in the context of hierarchically clustered data?

Question: Let's say that I have experimental data where the level of treatment is at a higher level of aggregation than the level of observation. For example, imagine some subset of schools adopted a new pedagogy for math class while the available data includes math test scores for all students across all schools.
Assuming that there is no spillage of the treatment effect and no interactions across schools, would using students or school-level aggregates maximize sensitivity with respect to detecting the treatment effect? Would there even be a meaningful difference?
My first instinct is to analyze at the lowest-level possible to maximize the sample size. However, I have been advised that the bottle-neck limiting the signal-to-noise ratio is at the level of treatment, and that if I were to use school-level aggregates (n=30) as opposed to students (n=10,000), there would be no real impact on the signal-to-noise ratio.
Can anyone please advise on the most desirable level of analysis for estimating the treatment effect in the context of hierarchically clustered data?
Answer: You don't have to choose! You can (and should) analyze the data at BOTH levels. This whole situation is one of the reasons that "multilevel modeling" (or "hierarchical modeling") was invented.
Your dependent variable is clearly at the student level, while the treatment is clearly at the school level, and students are "clustered" or "nested" within schools. So on one hand, if you try to "pretend" that your data is only at the student level you will be violating various assumptions about (for example) the independence of the error terms.
On the other hand you probably don't want to only analyze the treatment at the school level, since then you are no longer analyzing the treatment's effects on students, but instead just the effect it has on the average math score for all students at the school.
But this is what multilevel modeling is for. There are many ways to do this (and multiple ways to talk about or write the same kind of model) but I'll just give a simple example of a random intercept model that you might use to analyze these data. In this model "i" indexes students and "j" indexes schools
$TestScore_{ij} =\beta_0 + \zeta_j + \beta_1MathProgram_j+\epsilon_{ij}$
This is basically a linear regression model with math program (school level) as the independent variable and  test score (student level) as the dependent variable, but in addition to the normal intercept $\beta_0$ we also have a school level random effect $\zeta_j $. We assume these J "school level deviations" are normally distributed around  $\beta_0$. In other words we assume that students at the same school share an intercept and that these school level intercepts are normally distributed around some overall intercept. The model doesn't estimate the $\zeta_j $ values directly but it does use the data to estimate the variance of that normal distribution. This approach deals with the various violations of regression assumptions that come from having data at multiple levels. And unlike just adding a set of dummy variables for each school, it allows you to include other school level variables in the model (like the treatment variable). Of course, this model is still vulnerable to omitted variable bias at both the school and student level. So unless the treatment was randomly assigned to specific schools, you should consider adding other school level control variables to the model.
This is just a taste of the basic approach, but if you are interested in data like this you should read more about multilevel models, or hierarchical models (people use different terms to describe the same thing). What I've shown here is just a very simple example.
Answer: For a given data set, you don't actually have any choice about this - if you want to estimate a treatment effect, you can only analyze at the level that the treatment was applied. Analyzing at any other level fails to control alpha, so any standard errors and p-values you calculate would be meaningless.
Let's use your example, which seems to have a structure like this:
$$ Treatment -> Schools -> Students $$
This schematic reflects the reality of the structure of the data set, you can't decide to analyze it like this (or any other way):
$$ Schools -> Treatment -> Students $$
It's worth thinking about why the design of the experiment mandates a given analysis. Each school chooses to adopt the pedagogy at the school level, but there is likely random school-to-school variation in how the teachers are instructed to carry out the new lesson plans, etc. In fact, that's why we look at multiple schools - because there is random school-to-school variation in the implementation of the policy. However, every student at a given school experiences the same random error (so really, at the student level, any variation in treatment effect is really a systematic error), so you can't consider students to be IID samples. Another fairly obvious way to think about it is this - you would expect two students at the same school to be more similar than two students at different schools.
There is one thing to consider for this specific example, however. Let's say that you could somehow be sure that every school is implementing exactly the same strategy (so there is no school-to-school variation). You still could not choose to analyze at the level of students, however, because there's no way to ensure there is no classroom-to-classroom variation (after all, everyone in the same classroom is taught by the same teacher, who certainly plays a key role in pedagogy). So you could choose to analyze your data like this:
$$ Treatment -> Classrooms -> Students $$
This increases your effective sample size, which increases the precision of your estimate of treatment effect, but it relies on the assurance that there is no school-to-school variation in the treatment effect. As there is typically no way to ensure that, it's safer to stick with what you know - the treatment was applied to schools, so you have to perform an analysis that clusters at the "school" level.
The take-home message is this: the structure of your experiment justifies a specific analysis plan, you can't do something else without inflating the false positive rate or making strong (and typically unverifiable) assumptions.


Compute using the telescoping series $\sum_{n=1}^{\infty} \frac{n}{(n+1)(n+2)(n+3)} = \frac{1}{4}$

Question: This question is similarly found here, and I have been trying to break it down using partial fraction however I cannot seem to get the final result as in the thread linked. I would very much appreciate some advice on my solution!
$\sum_{n=1}^{\infty} \frac{n}{(n+1)(n+2)(n+3)} = \frac{1}{4}$
I have tried splitting this into Partial fractions:
$$n = \frac{A}{(n+2)(n+3)}+\frac{B}{(n+1)(n+3)}+\frac{C}{(n+1)(n+2)}$$
when n = 1 I find that A = $\frac{1}{12}$; When n = 2 then B = $\frac{2}{15}$; and when n = 3 then C = $\frac{3}{17}$
This then gets me:
$$\frac{(1/12)}{(n+1)}+\frac{(2/15)}{(n+2)}+\frac{(3/17)}{(n+3)}$$
However, I cannot seem to derive the solution $\frac{1}{4}$ from this.
Comment: Some of those coefficients should have been negative. Also, that's an odd way to set up the partial fractions, usually we put a single linear factor in each denominator, not two of them.
Answer: I think you may have computed the partial fractions incorrectly. If we write
$$\frac{n}{(n+1)(n+2)(n+3)} = \frac A{n+1} + \frac B{n+2} + \frac C{n+3}$$
then this rearranges as
$$n = A(n+2)(n+3) + B(n+1)(n+3) + C(n+1)(n+2)$$
and we need to plug in $n = -1, -2, -3$. Setting $n = -1$ gives us $A = -\frac12$, setting $n = -2$ gives us $B=2$, and setting $n = -3$ gives us $C = -\frac32$, so
\begin{align}
\frac{n}{(n+1)(n+2)(n+3)}
 & = -\frac{1/2}{n+1} + \frac{2}{n+2} - \frac{3/2}{n+3}\\
 & = -\frac{1/2}{n+1} + \frac{1/2}{n+2} + \frac{3/2}{n+2} - \frac{3/2}{n+3} \\
 & = \dfrac12\left(\dfrac{1}{n+2}-\dfrac{1}{n+1}\right)+\dfrac32\left(\dfrac{1}{n+2}-\dfrac{1}{n+3}\right)
\end{align}
and now the telescoping is more clear (this is the same form as in E.H.E.'s answer in the post you linked).
Comment: Hope you don't mind the edit.
Answer: I have solved the question and uploaded the picture of the solution.
Steps:
1.You need to write numerator as 2*(1/2)
2.Write 2 as (n+3)-(n+1)
3.Then separate it into partial fractions.
4. After that write the series and the club the terms which are common in both the partial fractions.
5. After that again decompose n/[(n+1)(n+2)] as 1/(n+1) - 1/(n+2).
6. Write the series and you are left with 1/(2*2), which is 1/4.
(https://i.stack.imgur.com/KbnX9.jpg)
Comment: Why do you write 2 as $(n+3)-(n+1)$?
Comment: Since many of the times in telescoping series, you need to express numerator in terms of denominator terms so that some of the terms will get canceled out.
Comment: Aha! I see the trick now, thanks!


How to autocomplete the options for a command in SLES 12?

Question: I have a service, say xyz. As of now, I can start, stop or restart that service using the command rcxyz start, rcxyz stop and rcxyz restart respectively. It is working fine.
All that I want to do is, if I type rcxyz and press <TAB>, I would like to have the three options (start, stop and restart) to be auto completed.
I referred the other bash_completion related questions in stackoverflow and tried writing a dummy script /etc/bash_completion.d/rcxyz.sh inside which I have written
complete -c rcxyz

I was expecting that when I type rcxyz and press <TAB>, I will get the list of available commands as argument. But it didn't work.
Am I missing something ?
Answer: You should write:
complete -W 'start stop restart' rcxyz

See bash's manual:

-W wordlist

The  wordlist  is  split using the characters in the IFS
                          special variable as delimiters, and each resultant  word
                          is  expanded.   The possible completions are the members
                          of the resultant list which match the  word  being  completed.
Comment: Works like a charm ! Thank you so much :)


Erro ao implementar método para tirar foto pela aplicação

Question: Estou querendo adicionar o método de tirar fotos pela aplicação só que ao rodar minha aplicação da erro:

abaixo está o meu código da classe do formulário:
Spinner option;
Button btnSend;
EditText Nome;
EditText Message;
EditText Endereco;
EditText Telefone;
EditText Email;
ImageView img;
private Bitmap bitmap;

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.reclame, container, false);

    img = (ImageView) view.findViewById(R.id.imageButton);
    img.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            abrirCamera();
        }
    });

    Nome = (EditText) view.findViewById(R.id.nome1);
    Message = (EditText) view.findViewById(R.id.msg);
    Endereco = (EditText) view.findViewById(R.id.endereco);
    Telefone = (EditText) view.findViewById(R.id.telefone);
    Email = (EditText) view.findViewById(R.id.email);
    btnSend = (Button) view.findViewById(R.id.send);
    option = (Spinner)view.findViewById(R.id.spinner);
    option.setOnItemSelectedListener(this);
    ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.option, android.R.layout.simple_spinner_item);
    option.setAdapter(adapter);

    btnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String nome = Nome.getText().toString();
            String message = Message.getText().toString();
            String matricula = Endereco.getText().toString();
            String telefone = Telefone.getText().toString();
            String assunto = option.getSelectedItem().toString();
            String ema = Email.getText().toString();
            Intent email = new Intent(Intent.ACTION_SEND);
            email.putExtra(Intent.EXTRA_EMAIL, new String[]{"firstname.lastname@example.com"});
            email.putExtra(Intent.EXTRA_SUBJECT, assunto);
            email.putExtra(Intent.EXTRA_TEXT, "Nome: " +nome +'\n'+  "Endereço: "+matricula + '\n'+ "Telefone: "+telefone + '\n'+ "E-mail: "+ema + '\n'+ '\n'+message);

            email.setType("message/rfc822");
            startActivity(Intent.createChooser(email, "Selecione o serviço de e-mail:"));
        }
    });
    return view;
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    TextView mtext = (TextView) view;
    //Toast.makeText(getActivity(), "Você selecionou: "+mtext.getText(), Toast.LENGTH_SHORT).show();
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}

public void abrirCamera(){
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, 0);
}

public void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    InputStream stream = null;
    if(requestCode == 0 && resultCode == RESULT_OK){
        try {
            if(bitmap != null){
                bitmap.recycle();
            }
            stream = getContentResolver().openInputStream(data.getData());
            bitmap = BitmapFactory.decodeStream(stream);
            img.setImageBitmap(resizeImage(getActivity(), bitmap, 700, 600));
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }finally {
            if (stream != null)
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}

private static Bitmap resizeImage (Context context, Bitmap bpmOriginal, float newWidth, float newHeight){
    Bitmap novoBpm = null;
    int w = bpmOriginal.getWidth();
    int h = bpmOriginal.getHeight();
    float densityFactor = context.getResources().getDisplayMetrics().density;
    float novoW = newWidth * densityFactor;
    float novoH = newHeight * densityFactor;

    float scalaW = novoW /w;
    float scalaH = novoH /h;
    Matrix matrix = new Matrix();
    matrix.postScale(scalaW, scalaH);
    novoBpm = Bitmap.createBitmap(bpmOriginal, 0, 0, w, h, matrix, true);
    return novoBpm;
}

O que está errado? e como enviar a imagem junto com as informações do formulário por email?
Answer: TLDR:
Use getActivity().getContentResolver() onde você tem getContentResolver().

O seu erro diz claramente:

error: cannot find symbol method getContentResolver()

Porque no método onActivityResult você declara:
stream = getContentResolver().openInputStream(data.getData());

e o método getContentResolver precisa de um Contexto, o qual você não tem. Simplemente forneça o contexto:
stream = getActivity().getContentResolver().openInputStream(data.getData());


What is the third number in subscription of Topic in Service Bus Explorer

Question: I am using Azure Service Bus Explorer,
What is the third number of Subscription in Service Bus Explorer,
For Example,
topicname
  - Subscriptions
   - SubscriptinName(12,13,0),
the first one(12) is the number of the messages
the second number(13) is the number of the messages in dead letter queue,
what is the third number 0?
Answer: Looks like the answer is here.
It looks like it displays the TransferDeadLetterMessageCount.


Retornar dados de uma classe para index

Question: Estou colocando em prática PHP Orientado à Objetos e estou desenvolvendo um CRUD de alunos.
Tenho uma classe para contar a quantidade de alunos no banco. E eu queria pegar o retorno da função que conta os alunos e mandar esse resultado para index, mas estou com dificuldade em fazer isso.
classe MostraAluno.php:
<?php

class MostraAluno
{
    protected $nome, $media;
    public $dns = 'mysql:host=localhost;dbname=alunos';
    public $user = 'root';
    public $pass = 'vertrigo';
    public $pdo;

    public function __construct()
    {
        try {
            $this->pdo = new PDO($this->dns, $this->user, $this->pass);
        } catch (PDOException $e) {
            die('Erro de conexao com o banco de dados: ' . $e->getMessage());
        }
    }

    public function contaAluno()
    {
        $count = "SELECT COUNT(*) AS total FROM usuarios ORDER BY nome ASC";

        $stmt_count = $this->pdo->prepare($count);
        $stmt_count->execute();
        $total = $stmt_count->fetchColumn();

        return $total;
    }
}

E o index.php:
<?php

require_once 'core/MostraAluno.php';

$mostraAluno = new MostraAluno();

$alunos = $mostraAluno->mostraAluno();
$totAlunos = $mostraAluno->contaAluno();

?>
<!DOCTYPE html>

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

<meta charset="utf-8">
<title>Notas - Alunos</title>

    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
      Toggle navigation

    </button>
    Sistema de notas

Cadastrar novo aluno

        Perfil

Sair

Total de alunos: <?php echo $totAlunos; ?>

Quando executado a index aparece somente o texto 'Total de alunos:' e nao aparece o retorno do método.
No arquivo MostraAluno eu retirei o método mostraAluno(), pois minha dúvida é somente com o método contaAluno().
Alguém poderia me dizer onde estou errando? Estou começando agora a colocar em prática PHP OO e estou com dificuldades em retornar os valores dos métodos para outros arquivos.
Comment: @Gabriel veja isto: https://pt.stackoverflow.com/help/editing se as pessoas melhoram sua pergunta você deveria aceitar a mudança. Algum motivo para ter rejeitado?
Comment: @Gabriel ele mudou bem mais do que italico, ele corrigiu acentuação e pontuação, o que é totalmente aceitável e útil e melhora sim a leitura. O Saul também editou outra pergunta sua que você rejeitou e era uma boa edição, ele removeu redundâncias (como no título) e "saudações" desnecessárias. Entenda mais sobre o assunto em https://pt.meta.stackoverflow.com/q/846/3635 ;)
Comment: sua tabela `usuarios` possui dados?
Comment: Porque eu testei seu codigo e funcionou
Comment: Sim. possui dois registros
Comment: coloca esse codigo no seu index e veja que erro mostra:  ` ini_set('display_errors',1);
ini_set('display_startup_erros',1);
error_reporting(E_ALL); `
Comment: Encontrei o erro... o nome da tabela no banco estava USUARIS

Sem a letra O de USUARIOS  -_-
Comment: pronto. Que bom que deu certo
Comment: Sim. Mudanças como alterar uma frase para itálico, ao meu ver, é irrelevante. Não mudará nada com relação ao entendimento do tópico e da questão levantada. E outra, as mudanças só começaram a serem feitas após o @adventistaam ja ter se manifestado em relação a minha dúvida, ou seja, ele entendeu o que foi questionado no tópico! Então não vi nenhum motivo para correção, principalmente correções de colocar frases em itálico.
Answer: Apesar de ja ter encontrado o erro. Tem um outro modo de fazer caso você queria usar um dia:
    $stmt_count = $this->pdo->prepare($count);
    $stmt_count->execute();
    $total = $stmt_count-> rowCount(); // aqui ele conta o total

O bom de fazer dessa forma, é que você pode fazer a seleção de todos os alunos(no caso) e apenas usar o rowCount(); para contar a quantidade total, sem a necessidade de fazer duas conexões.

Retornar dados de uma classe para index


If $[(p\rightarrow\ q)\land (\lnot p \rightarrow \lnot r)]\rightarrow (\lnot q \rightarrow r)$ is false how to find its equivalent in other words?

Question: The problem is as follows:
Assume the statement which is written below is false,
<code>If Gaston drinks milk then he takes his vitamins, and if he
doesn't drink milk then he doesn't eat; therefore if Gaston
doesn't take his vitamins, then he eats.
</code>
Find which of the statements in the alternatives is true.
$\begin{array}{ll}
1.&\textrm{Gaston drinks milk}\\
2.&\textrm{Gaston takes his vitamins}\\
3.&\textrm{Gaston eats}\\
4.&\textrm{Gaston eats or he doesn't drink milk}\\
\end{array}$
How exactly should I match the right one here?.
What I did in my attempt to solve this problem was to formulate the complex statement into terms of propositional logic as follows:
$\textrm{Gaston drinks milk = p}$
$\textrm{he takes his vitamins = q}$
$\textrm{he does eat = r}$
Then this is reformulated as follows:
$$[(p\rightarrow\ q)\land (\lnot p \rightarrow \lnot r)]\rightarrow (\lnot q \rightarrow r)$$
But what to do from here?. How exactly can this be simplified?. Is my intepretation correct?. Can someone help me here?. Please try to be the most detailed as possible so I can understand this part.
Comment: *Mathematica* gives this simplification $$(p\Rightarrow q)\land (\neg p\Rightarrow \neg s)\Rightarrow (\neg q\Rightarrow s)=p\lor q\lor s$$
Gaston does one or more of the action. Sounds wrong
Comment: Why did you use $p$ and $r$ to mean the same thing?
Comment: "If Gaston drinks milk then he takes his vitamins, *and* if he doesn't drink" This use of AND doesn't sound as a logical *conjunction*...
Comment: @Raffaele Sorry about that, I did my best in trying to fix the errors. The problem indicates that the whole statement is false. Then I believe it would have an equivalent. I don't know if what I did corrected would improve this question?
Answer: If you make a truth table, you'll find that the statement is false if and only if $p,q$, and $r$ are all false. In other words, that statement is false if and only if $\neg p\land\neg q\land\neg r$ is true. Your four choices of answer are $p$, $q$, $r$, and $r\lor\neg p$. The first three are clearly false, since they contradict $\neg p\land\neg q\land\neg r$. And $\neg p\land\neg q\land\neg r$ clearly implies $\neg p$, which implies $r\lor\neg p$, so $r\lor\neg p$ is true, and the correct answer is the fourth one.
If you want to proceed algebraically, note that saying that
$$\big((p\to q)\land(\neg p\to\neg r)\big)\to(\neg q\to r)$$
is false is the same as saying that
$$\big((p\to q)\land(\neg p\to\neg r)\big)\land\neg(\neg q\to r)$$
is true. And $\neg(\neg q\to r)\equiv\neg q\land\neg r$, so we're assuming that
$$(p\to q)\land(\neg p\to\neg r)\land\neg q\land\neg r\tag{1}$$
is true. Now $p\to q\equiv\neg p\lor q$, and
$$(\neg p\lor q)\land\neg q\equiv(\neg p\land\neg q)\lor(q\land\neg q)\equiv\neg p\land\neg q\,,$$
so $(1)$ is equivalent to
$$(\neg p\to\neg r)\land\neg p\land\neg q\land\neg r\,.\tag{2}$$
Finally, $\neg p\to\neg r\equiv p\lor\neg r$, and $(p\lor\neg r)\land\neg p\equiv\neg r\land\neg p$, so $(2)$ is equivalent to $\neg r\land\neg p\land\neg q\land\neg r$ and hence to $\neg p\land\neg q\land\neg r$.


Como recuperar o Resultado de uma tabela, em um Loop For

Question: Pessoal tenho uma tabela em javascript, ela esta sendo estruturado por um loop for, porem eu preciso calcular o resultado dela..segue o código..
for(i = 1; i<=30; i++) {
var maximo = 5;
var a = parseInt(Math.random()*maximo+1);
var b = parseInt(Math.random()*maximo+1);
var names = ["João", "Maria"];
var randomNames = (names[Math.random() < 0.5 ? 0 : 1]);

table += '
'+i+'	';
table += ''+ a +'	';
table += ''+ b +'	';
table += ''+ randomNames +'	';
table += ''+ f1 +'	';
table += ''+ f2 +'	';
table += ''+ f3 +'
';

}

table += '

';

nos campos f1, f2, f3, vai ser exibidos 2 valores diferentes.. ou é Maça ou Pera, o loop vai percorrer 30 linhas na tabela ao final preciso saber quantas Maças e quantas Peras apareceram no Total, quebrei a cuca aqui e não consegui resolver essa questão, agradeço!
Answer: olá, abaixo uma possível solução:
preencha um array com length = 30 das palavras que vc quer:
var names = ["João", "Maria"];
var array = [];
for(var i=0; i< 30; i++){
    array.push(names[Math.random() < 0.5 ? 0 : 1]);
}

preencha a tabela com os valores do array e depois recupere a quantidade de vezes que repetem por:
// para a posição 0, no caso, João
array.reduce((a,e)=>{ return e==names[0] ? a=a+1 : a }, 0)

// para a posição 1, no caso, Maria
array.reduce((a,e)=>{ return e==names[1] ? a=a+1 : a }, 0)


Is there a short hand in Julia for this list comprehension

Question: addresses = [
    "5412 N CLARK",
    "5148 N CLARK",
    "5800 E 58TH",
    "2122 N CLARK",
    "5645 N RAVENSWOOD",
    "1060 W ADDISON",
    "4801 N BROADWAY",
    "1039 W GRANVILLE",
]

counts = [0, 3, 10, 4, 1, 7, 6, 1]

more5 = [n > 5 for n in counts]
a = [addresses[i] for i in eachindex(more5) if true == more5[i]]
println(a)

For the line :
a = [addresses[i] for i in eachindex(more5) if true == more5[i]]

any short hand is possible in Julia, say with filter.
Answer: Try using filter in combination with array slicing:
julia> a = addresses[filter(i -> counts[i] > 5, 1:length(counts))]
3-element Vector{String}:
 "5800 E 58TH"
 "1060 W ADDISON"
 "4801 N BROADWAY"

Comment: `a = addresses[filter(i -> counts[i] > 5, eachindex(counts))]` also works
Answer: Since more5 is a boolean array, you can use it directly as a logical index:
julia> a = addresses[more5]
3-element Vector{String}:
 "5800 E 58TH"
 "1060 W ADDISON"
 "4801 N BROADWAY"

If you don't need more5 for some other purpose, you can also just avoid allocating that intermediate array by doing:
julia> [a for (a, c) in Iterators.zip(addresses, counts) if c > 5]
3-element Vector{String}:
 "5800 E 58TH"
 "1060 W ADDISON"
 "4801 N BROADWAY"

Answer: Perhaps the simplest solution is just:
julia> addresses[counts .> 5]
3-element Vector{String}:
 "5800 E 58TH"
 "1060 W ADDISON"
 "4801 N BROADWAY"

This calculation more5 = [n > 5 for n in counts] is really just the same as more5 = counts .> 5.


Notation on proving injectivity of a function $f:A^{B\;\cup\; C}\to A^B\times A^C$

Question: I'm trying to prove that for any cardinal numbers $a,b,c$, the following holds:
$a ^ {b + c} = a ^ b a ^ c$ i.e. that there exists a bijective function $ f : A ^ {B \:\: \cup \:\: C} \rightarrow A^B \times A^C $
This is only part of the proof sketch I have (proving $f$ is injective), and I'd like to know if is well written, since I believe it has flaws.

Let $f: \{ g \:\:\: | g:B \cup C \rightarrow A \} \rightarrow \{ \langle g,h\rangle  | \:\:\: g: B \rightarrow A \wedge h : C \rightarrow A \}$ such that
$f ( g_{b} \cup g_{c}) = \langle g_{b},g_{c}\rangle$.
Now,
$f( g_{b1} \cup g_{c1}) = f ( g_{b2} \cup g_{c2} ) \implies \langle g_{b1},g_{c1}\rangle = \langle g_{b2},g_{c2}\rangle$ and therefore $f$ is injective.

Questions:

Does that prove that $f$ is injective? I think it does not, since
$f ( g_{b} \cup g_{c} ) = f ( g_{c} \cup g_{b}) \implies \langle g_{b},g_{c}\rangle  = \langle g_{c},g_{b}\rangle (\bot)$
Is there an alternative way to define $f$? It's difficult for me to define it in terms of properties of elements of its domain.

Side note:
The title says "kinds" because the function domain and image sets are sets of sets, but I may be mistaken using that word, if so, please edit accordingly.
Comment: Is the union in $A^{B\cup C}$ meant to be disjoint union? Otherwise, the desired bijection need not exist.
Comment: What do you mean by $g_b\cup g_c$? Are you trying to say that $f:g\mapsto\langle g\upharpoonright B,g\upharpoonright C\rangle$? That function is indeed injective. It won't be surjective, however, unless $B\cap C=\varnothing$.
Comment: In ZF(C), the most common axiomatization of set theory, *all* sets are sets of sets, so I've just put a description of $f$ in the title.
Comment: Rather than $g_{b}\cup g_{c}$, I would write simply $g$, and map it to $\langle g|_B,g|_C\rangle$, where $g|_B$ is the restriction of $g$ to $B$, and $g|_C$ the restriction to $C$. To prove injectivity, your notation is not very nice, so instead you should us $f(g) = f(h)$ and note that this yields $g|_B=h|_B$ and $g|_C = h|_C$. Etc. P.S. Use `\langle` and `\rangle` for $\langle$ and $\rangle$ rather than `<` and `>`; the spacing is off for the latter.
Comment: For the argument to work as stated, we probably need to ask that $B$ and $C$ are disjoint. Why not define $\phi(g)$ as the ordered pair $(g_B,g_C)$? A lot fewer symbols. (The $\phi$ is because somehow $f$ sounds like something of the same family as $g$.) The injectivity should be easy. From $(g_B, g_C)$ we can reconstruct $g$.
Answer: I'm going to assume that I've guessed correctly that you want to define $$f:A^{B\;\cup\;C}\to A^B\times A^C:g\mapsto \langle g\upharpoonright B,g\upharpoonright C\rangle\;.$$ If you express it this way, it's easy to see that $f$ is injective. Suppose that $f(g_0)=f(g_1)$. Then $g_0\upharpoonright B=g_1\upharpoonright B$ and $g_0\upharpoonright C=g_1\upharpoonright C$. Now let $x\in B\cup C$ be arbitrary. If $x\in B$, then $$g_0(x)=(g_0\upharpoonright B)(x)=(g_1\upharpoonright B)(x)=g_1(x)\;,$$ and if $x\in C$, then $$g_0(x)=(g_0\upharpoonright C)(x)=(g_1\upharpoonright C)(x)=g_1(x)\;,$$ so $g_0(x)=g_1(x)$ for all $x\in B\cup C$, and hence $g_0=g_1$. It was the clumsy way in which you expressed an arbitrary element of $A^{B\;\cup\;C}$ that led you to doubt the injectivity of $f$.
Note that although this $f$ is injective, it is not surjective if $B\cap C\ne\varnothing$ and $A$ has at least two elements. To see this, suppose that $B\cap C\ne \varnothing$, and fix $x\in B\cap C$. Let $g_0\in A^B$ be arbitrary, and let $g_1\in A^C$ be any function such that $g_1(x)\ne g_0(x)$. Then $\langle g_0,g_1\rangle \ne f(h)$ for any $h\in A^{B\;\cup \;C}$.
To get bijectivity, you must assume that $B\cap C=\varnothing$. In that case $f$ as defined above is a bijection, and $$f^{-1}:A^B\times A^C\to A^{B\;\cup\;C}:\langle g,h\rangle\mapsto g\cup h\;.$$
Comment: Thanks for pasting the exact same argument as mine but adding $B \cap C = \varnothing$... you could've just ask me to complete my answer instead of making a new one though. (I am not arguing, I am thanking.)
Answer: You can think of $g : B \cup C \to A$ as a couple of functions $g_B : B \to A$ and $g_C : C \to A$ such that for all $x \in B \cap C$, $g_B(x) = g_C(x)$. Therefore, letting $f : \Gamma \to \Delta$ (with
$$
\Gamma = \{ g \,\, | \,\, g : B \cup C \to  A \}, \qquad \Delta = \{ \langle g_B, g_C\rangle \, \, | \, \, g_B : B \to A, \, \, g_C : C \to A \}
$$
obviously), you can see that a natural way to do this is to restrict the domain of $g : B \cup C \to A$ to just $B$ (or $C$), hence the map $f$ could naturally be defined by $g_B(x) = g(x)$ for all $x \in B$, $g_C(x) = g(x)$ for all $x \in C$ and $f(g) = \langle g_B, g_C \rangle$. In this manner the notation is more clear and more obviously well-defined.
This function $f$ is injective because of the following. Suppose that $f(g_1) = \langle g_B^1, g_C^1 \rangle = \langle g_B^2, g_C^2 \rangle =f(g_2)$. Thus for all $x \in B \cup C$, $x$ is either in $B$ or $C$, suppose $B$. Thus $g_1(x) = g_B^1(x) = g_B^2(x) = g_2(x)$. The case $x \in C$ is similar. Therefore $g_1 = g_2$.
I can't think of a natural way to define $ F : \Delta \to \Gamma$ right now, it'll require some thinking, I guess. I am not familiar with the usual rigor abusive context, but my problem is that I don't want to assume $B \cap C = \varnothing$. If we can assume that there is an obvious way back (i.e. you can show that this $f$ is bijective, easily). If someone could comment on this question I'm asking, I'd love to read.
Comment: Thank you Brian, Pattrick and yunome for your help, I really appreciate it.
Comment: There's not much reason to define an $F:\Delta\to\Gamma$ unless $B\cap C=\varnothing$, in which case the desired $F$ is simply $F:\Delta\to\Gamma:\langle g,h\rangle\mapsto g\cup h$.
Comment: Yeah... I know it would sound lame to do it if the intersection was non-empty, but ZFC theory usually scares me by its depth and generality, so I don't know if it is allowed sometimes in some contexts. I've never actually studied ZFC rigorously so I preferred to ask instead of babbling.
Comment: Perhaps because of this my notation seems more familiar to a mathematician that doesn't study logic or set theory because I've understood but never seen the notation $g \cup h$ for taking the "union" of two functions...
Comment: The functions $g$ and $h$ are just sets of ordered pairs, so their union is also a set of ordered pairs. As long as $g$ and $h$ don't contain two pairs $\langle b,a\rangle$ and $\langle c,a\rangle$ with $b\ne c$, their union will still be a function $-$ and if $B\cap C=\varnothing$, they won't contain such conflicting pairs.
Answer: I don't believe this proves $f$ is injective, for if $f(g_{b1}\cup g_{c1})=\langle g_{b1},g_{c1}\rangle$, then $f( g_{b1} \cup g_{c1}) = f ( g_{b2} \cup g_{c2} )$ and$\langle g_{b1},g_{c1}\rangle = \langle g_{b2},g_{c2}\rangle$ are really just the same statement so you haven't really proven anything.
I assume you also have the assumption that $B$ and $C$ are disjoint, for if not, surjectivity does not necessarily follow, and you want to show that $f$ is a bijection. I think the best way to go about proving injectivity is to first define $f$ by $f(g)=\langle g|_B,g|_C\rangle$, where $g|_B$ is the restriction of $g\colon B\cup C\to A$ to $B$, and likewise for $C$.
There are are two usual ways to show injectivity here. One is to show that $f(x)=f(y)\implies x=y$ or its contrapositive $x\neq y\implies f(x)\neq f(y)$.
One way to use it here is to suppose $g\neq h$ for $g,h\in A^{B\cup C}$, and then show $f(g)\neq f(h)$. Then for some $x\in B\cup C$, $g(x)\neq h(x)$. Let's also assume $x\in B$. Then $f(g)=\langle g|_B,g|_C\rangle$ and $f(h)=\langle h|_B,h|_C\rangle$. However, $g|_B\neq h|_B$ since $g(x)\neq h(x)$ for $x\in B$, so $f(g)\neq f(h)$, and $f$ is injective. The same idea works if you had chosen $x\in C$.


How is python assigning __module__?

Question: Our code has a logging decorator that prints a calling function's __module__. As it happens, someone recently added a unit test that verifies the argument logged, which has revealed that when our tests are run through poetry, __module__ takes on one value, while when they're run directly through python -m unittest the value is different.
Specifically:
A test in $REPO_ROOT/tests/unit/foo/bar/baz/test_module.py defines a test function.

When run in our CI environment (via poetry), that function's __module__ is identified as tests.unit.foo.bar.baz.test_module.
When run via python -m unittest, it's unit.foo.bar.baz.test_module

My own opinion is, we should nix the test that checks the particular module name, because it's just human visible text and the difference doesn't matter, but it made me wonder:
How is python actually setting that __module__ field?
Comment: I would nix the test, too, because it's an artifact of how the package is installed, not necessarily part of the code in the package.
Answer: poetry is somehow configured to treat test itself as a package, rather than a directory on the Python search path in which the unit package can be found. As such, unit is a subpackage in the package test, rather than a top-level package itself.

How is python assigning __module__?


$\frac{h(x)}{x} \to 0$ as $\lvert x \rvert \to \infty$ implies $\frac{h(y)}{x}$ being bounded when $\lvert x \rvert \geq \max\{1, \lvert y \rvert\}$?

Question: The question is as in the title. Let $h$ be a continuous function on $\mathbb{R}$ such that
If $\frac{h(x)}{x} \to 0$ as $\lvert x \rvert \to \infty$. Then, is it true that the two-varaible function
\begin{equation}
\frac{h(y)}{x}
\end{equation}
is bounded in the region $\{(x,y) \mid 1 \leq \lvert x \rvert \text{ and } \lvert y \rvert \leq \lvert x \rvert  \}$?
This is extremely confusing for me and I cannot figure out correctly.. Could anyone help me?
Answer:
On the region $|y|\le1\le|x|,$
$$\left|\frac{h(y)}x\right|\le|h(y)|
$$
is bounded since $h$ is continuous on $[-1,1].$
On the region $1\le|y|\le|x|,$
$$\left|\frac{h(y)}x\right|\le\left|\frac{h(y)}y\right|
$$
is bounded because $y\mapsto\frac{h(y)}y$ is continuous on $(-\infty,-1]\cup[1,+\infty)$ and has limit $0$ as $y\to\pm\infty.$

So: yes, $\frac{h(y)}x$ is bounded on the union $\lvert x \rvert \geq \max(1, \lvert y \rvert)$ of these two regions.


How can I avoid "missing dependency" in useEffect by useRef?

Question:   const increaseNumber = useRef({});
  increaseNumber.current = async () => {
    await setTimeout(() => {
      setNum(num + 1);
    });
  };
  useEffect(() => {
    increaseNumber.current();
  }, []);

Error at current():
(property) React.MutableRefObject<{}>.current: {}
This expression is not callable.
Type '{}' has no call signatures.ts(2349)
Comment: The error doesn't say "missing dependency" it says `{}` is not callable.
Answer: You are initializing increaseNumber to an empty object instead of a function.
const increaseNumber = useRef({});
Try:
  const increaseNumber = useRef(async () => {
    await setTimeout(() => {
      setNum(num + 1);
    });
  });


Output não esperado no ficheiro (loop infinito) CSV Python

Question: Boas, estou a tentar guardar a distancia e o tempo, resultado da diferença do tempo de envio/chegada do som ultra-sónico, isto através do sensor para Raspberry Pi 3 HC-SR04!
Após obter estes valores que elaborar gráficos com a biblioteca SeaBorn, para para isso preciso queria os dados sejam escritos num ficheiro CSV, mas tal não acontece, o Script fica num loop infinito e substitui sempre os valores na mesma linha, no primeiro segundo o ficheiro pesa 15 bytes no segundo próximo ja pesa 0 bytes, enfim não estou a conseguir fazer com que ele escreva numa nova linha! Sou novo em Python, por isso não sei muito sobre técnicas de loop nem quais metodos utilizar!
Requisitos:

Raspberry Pi 3
HC-SR04
Python 3

O codigo encontra-se aqui em baixo:
#Libraries
import os
import RPi.GPIO as GPIO
import time
import csv

#GPIO Mode (BOARD / BCM)
GPIO.setmode(GPIO.BCM)

#set GPIO Pins
GPIO_TRIGGER = 23
GPIO_ECHO = 24

#set GPIO direction (IN / OUT)
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)

#set CSV
currentPath = os.getcwd()
csv_files = currentPath + "/data_sensor.csv"
csv_columns = ['Time', 'Distance']

def WriteDictToCSV(csv_files, csv_columns, dict_data):
    new_file = False
    try:
        if not os.path.exists(csv_files):
            new_file = True

        with open(csv_files, 'a+') as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
            if new_file:
                writer.writeheader()
            for data in dict_data:
                writer.writerow(data)
    except IOError as err:
        print("I/O error({})".format(err))

def distance():
    # set Trigger to HIGH
    GPIO.output(GPIO_TRIGGER, True)

    # set Trigger after 0.01ms to LOW
    time.sleep(0.00001)
    GPIO.output(GPIO_TRIGGER, False)

    StartTime = time.time()
    StopTime = time.time()

    # save StartTime
    while GPIO.input(GPIO_ECHO) == 0:
        StartTime = time.time()

    # save time of arrival
    while GPIO.input(GPIO_ECHO) == 1:
        StopTime = time.time()

    # time difference between start and arrival
    TimeElapsed = StopTime - StartTime
    # multiply with the sonic speed (34300 cm/s)
    # and divide by 2, because there and back
    Distance = (TimeElapsed * 34300) / 2

    return Distance, TimeElapsed

    if __name__ == '__main__':
        try:
            while True:
                d, t = distance()
                dict_data = {t: d}
                WriteDictToCSV(csv_files, csv_columns, dict_data)
                print('Time Elapsed: {} ms | Distance: {} cm'.format(t,d))
                time.sleep(0.5)
        # Reset by pressing CTRL + C
        except KeyboardInterrupt:
            print("Measurement stopped by User")
            GPIO.cleanup()

Nota: O Script ainda não esta completo, mais dados serão exportados e formatados!
Para quem não possui uma Rpi ou o HC-SR04, aqui esta uma versão minificada do codigo:
import os
import csv

currentPath = os.getcwd()
csv_files = currentPath + "/data_sensor.csv"
csv_columns = ['Time', 'Distance']

def WriteDictToCSV(csv_files, csv_columns, dict_data):
    try:
        with open(csv_files, 'a') as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
            writer.writeheader()
            for data in dict_data:
                writer.writerow(data)
    except IOError as err:
        print("I/O error({})".format(err))
    return

if __name__ == '__main__':
    while True:
        # "d" respresenta a distancia de 12 cm e "t" representa o tempo em ms
        d, t = 12, 0.14732832
        dict_data = {t: d}
        WriteDictToCSV(csv_files, csv_columns, dict_data)
        #print('Time Elapsed: {} ms | Distance: {} cm'.format(t,d))

Output do erro é o seguinte:
Traceback (most recent call last):
  File "/home/pi/Documents/main1.py", line 70, in <module>
    WriteDictToCSV(csv_files, csv_columns, dict_data)
  File "/home/pi/Documents/main1.py", line 34, in WriteDictToCSV
    writer.writerow(data)
  File "/usr/lib/python3.5/csv.py", line 153, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "/usr/lib/python3.5/csv.py", line 146, in _dict_to_list
    wrong_fields = [k for k in rowdict if k not in self.fieldnames]
TypeError: 'float' object is not iterable

Comment: Sem analisar muito o resto, já digo que você está abrindo o arquivo no modo `w`. Neste modo, o ponteiro sempre é movido ao início do arquivo e o conteúdo atual é sobrescrito. Se quer apenas adicionar, abra o arquivo no modo `a`, pois assim manterá o ponteiro no final do mesmo.
Comment: Você tem bastante código aí que muita gente não vai conseguir reproduzir por não ter uma Raspberry Pi ou o sensor. Pode tentar criar um [exemplo Mínimo, Completo e Verificável](https://pt.stackoverflow.com/help/mcve) que isole o problema?
Comment: @PedrovonHertwig Acrescentei agora uma versão minificada do codigo!
Comment: @AdersonCarlosWoss , se passar o arquivo para o modo "a" ele ira rescrever o cabeção do ficheiro vezes sem conta!
Comment: @AndersonCarlosWoss Aqui esta, tal como sugerido!
Answer: Som - a cada meio segundo esse programa chama a função WriteDictToCSV que destrói o arquivo gerado meio segundo antes, e grava só os novos dados.
A linha
with open(csv_files, 'w') as csvfile:

Cria o arquivo novamente, com 0 bytes, cada vez que é executada.
Para um programa desses, você pode deixar o arquivo aberto, e ir gravando incrementalmente os dados, ou abrir o arquivo no modo "a" (e não "w"), que abre o arquivo para gravação a partir do final, sem destruir o conteúdo anterior.
Tente mudar a função de escrita do arquivo para esta:
def WriteDictToCSV(csv_files, csv_columns, dict_data):
    new_file = False
    try:
        if not os.path.exists(csv_files):
             new_file = True

        with open(csv_files, 'a+') as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
            if new_file:
                writer.writeheader()
            for data in dict_data:
                writer.writerow(data)
    except IOError as err:
        print("I/O error({})".format(err))

(A geração dos dados está incorreta também - você está fazendo bastante confusão com listas e dicionários, e eu recomendo fazer testes, criando listas e dicionários no modo interativo, adicionando valores, apagando valores, explorando os métodos - senão você provavelmente não vai conseguir fazer nada com sentido nesse programa)
Comment: Bom Dia, se me pode-se dar aqui uma ajudinha, ficaria-lhe agradecido! Obrigado
Comment: Oi Micael - a melhor forma de você ter ajuda é fazendo outras perguntas no site.
Answer: Sua função para escrever um dicionário não faz muito sentido.
def WriteDictToCSV(csv_files, csv_columns, dict_data):
    try:
        with open(csv_files, 'a') as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
            writer.writeheader()
            for data in dict_data:
                writer.writerow(data)
    except IOError as err:
        print("I/O error({})".format(err))
    return

Você utiliza como base o csv.DictWriter, definindo as colunas ['Time', 'Distance']. Desta forma, a função de escrita irá esperar um dicionário no seguinte formato:
{
    'Time': t,
    'Distance': d
}

Mas o que você está passando é {t: d}.
Além disso, não vejo porque iterar sobre o dicionário durante a escrita, tal como fez em:
for data in dict_data:
    writer.writerow(data)

Se dict_data for o dicionário como comentado acima, basta fazer writer.writerow(dict_data).


How prove a parabola is symmetric without coordinates?

Question: Some years ago a mathematician challenged a friend of mine to prove that a parabola is symmetric without using any coordinates. My friend got stumped, and challenged me to do this problem. I also got stumped.
I tried a couple of different ways. The first was to draw a picture of a parabola and simply notice that it was symmetric, but I think knowing how to draw the parabola in the first place might have assumed coordinates. The second approach I took was to parametrize by arc length and show reflective symmetry by a reflection in arc length, but then assuming (1) that there was a coordinate systems to parametrize the curve from and (2) that putting things in terms of arc length isn't its own kind of coordinates.
I am not sure I understand what a parabola is without some understanding of coordinates. The equation $y = ax^2$ to me entails a subset of a Cartesian product $Y \times A \times X$, or a permutation thereof, which is a space that the parabola sits within.
How do I show that a parabola is symmetric without the existence of any coordinates?
Comment: For any proof we need to define what is parabola. There is definition of parabola as locus, and from this definition it is almost obvious that parabola is symmetric.
Comment: How do you want to define a parabola for this question?
Comment: A [locus](https://en.wikipedia.org/wiki/Locus_(mathematics)) appears to be a set of points, which entails the existence of coordinates.
Comment: @Galen that's not true, points do not require you to introduce a coordinate system. These properties of the parabola were proved with compass and ruler centuries before algebra and coordinates were invented. They aren't required.
Comment: @CyclotomicField Doesn't positing a collection of lengths and angles induce an equivalence class of coordinate systems even if you don't introduce any of them?
Comment: @galen no it's not required. You can introduce a coordinate system if you choose to, but that's not the same. Typically introducing coordinates significantly complicates the problem so you'll find we often work very hard to avoid choosing one because the choice is arbitrary. This is motivated by physics as reality does not have a natural coordinate system. Tensor products are tailored for this purpose.
Comment: @Galen For more perspective on how unnecessary coordinates are these results on the symmetry of the parabola and other conic sections predates the invention of $0$. They didn't even know how to pick an origin. The analytic plane wasn't invented until the 1500s with the work of Fermat and Descartes, right before Calculus was discovered.
Comment: If you define the parabola as a section of a cone, then symmetry is obvious.
Answer: You'll need to refer to lengths, but not necessarily coordinates. By definition a parabola is the curve defined by all points equidistant from a single focal point and a line, the directrix. Let's call the focus A and the line L.
Drop a line from A to L that is perpendicular to L. Call this line M and the point of intersection Q. Suppose also we have a point P on a parabola on one side of M.
With Compass centered at A, construct a circle through P. With Compass centered at Q, also construct a circle through P. Call their point of intersection R.
Now construct line segments A to P, and P to Q. Combined with L, this creates triangle APQ. Then construct line segments A to R and R to Q. This is triangle ARQ. AQ is congruent to itself. AP is congruent to AR since both are a radius of the same circle. RQ and PQ are likewise congruent. These triangles are congruent by SSS.
Now construct a line between P and R and call the point of intersection with M point T. Now we have triangles ATP and ATR. AT is congruent to itself. Angle RAT is congruent to and PAT by the previous SSS argument and the definition of congruent triangles. AR and AP are also congruent. So ATP and ATR are congruent triangles by SAS. This implies TP is congruent to TR since corresponding sides of congruent triangles are congruent. We also have that angles ATP and ATR are congruent. This implies they are right angles.
QRT and QPT are then right triangles. Further, they are congruent by HL. From this it follows that R and P are the same height above the directrix and equal and opposite distances about line M. Thus we have established the expected symmetry.
This reasoning applies for any point P on the parabola and so applies to the parabola in general.
Comment: Or: After the second paragraph, note that reflection in $M$ fixes the focus $A$ and directrix $L$, so it fixes the parabola.


How to remove malware code from javascript file using sed

Question: I found the following two different pattern in some hacked javascript files.
  some code

/*2d3965*/ some code /*/2d3965*/

I am able to remove the first pattern from the file using this command:
sed -i 's/.*//g' javascript_file.js

but not able to remove the second pattern using similar command:
sed -i 's/\/\*2d3965\*\/.\+\/\*\/2d3965\*\///g' javascript_file.js

What's correct syntax to remove the second pattern?
Comment: Wouldn't it be easier to just revert to your backups that you have in your version control system?
Comment: Seriously?  You think the next compromise will look identical to the last one?  Wouldn't a better check be to calculate a cryptography hashs of the files, and watch for changes?   That combined with actually identifying and fixing the vulnerability so it can't happen again?
Comment: The hackers were nice enough to mark exactly where they injected code? And you trust those markers? The only reasonable course of action is to restore from backups.
Comment: This is a common attack, actually.
Comment: Yes, I have the backup. Just want to setup a monitor script to delete those code immediately when it find it.
Comment: @garconcn I hope you're also closing the hole the attacker is using to modify these files in the first place. After all, if someone walks into your house and steals your TV because you leve your door unlocked you wouldn't just buy a new TV every time, you'd start locking the door. (Right? I hope....)
Answer: The code I've used for this type of attack on .php, .js and .html files is:
perl -p -i.orig -0 -e 's/<\?\s*#([0-9a-z]{6})#.*#\/\1#\s*\?>//gs; s/<\!--([0-9a-z]{6})-->.*//gs;'

Annoying... You should figure out how the attacker got in and check the health of your backups as well. I had to run the above on 4 million files once because the backups were also tainted.
Comment: @garconcn Did this work?


Show that the genus of the projective curve $x^n_1 = x_2x^{n-1}_0 - x^n_2$ is $(n-1)(n-2)/2$.

Question: Suppose that we have a curve $X \subset \mathbb{P}^2$ given by $x^n_1 = x_2x^{n-1}_0 - x^n_2$ .  How do we show that the curve has genus $(n-1)(n-2)/2$ (whenever the curve is smooth).
I should use the fact that the sequence
$$
0 \to \mathcal{F}(X) \stackrel{\iota}{\to} \mathcal{F}(U_1) \oplus \mathcal{F}(U_2)  \stackrel{\delta}{\to} \mathcal{F}( U_1 \cap U_2)
$$
is exact. Where $\mathcal{F} =\mathcal{O}_X(D)$ for some divisor $D$  on $X$ and $\{ U_1, U_2\}$ an affine cover of $X$ (however, $X$ should be irreducible I think).  Moreover $\iota(f) =( f|_{U_1}, f|_{U_2})$  and $ \delta(f_1,f_2) = f_1|_{U_1 \cap U_2} - f_2|_{U_1 \cap U_2}$ .
There is a hint: compute the cokernel of $\delta$ using bases for the infinite-dimensional vector spaces $\mathcal{O}_X(X_1)$, $\mathcal{O}_X(X_2)$ and $\mathcal{O}_X(X_{12})$ that are as simple as possible. (As a sanity check on your computation: the kernel of $\delta$ should be one-dimensional!)
Any help on how to proceed or how to solve it would really be appreciated!
Comment: Well, what do you know about the two definitions of genus? This will let you connect the problem to the hint. As far as the computation, you have to sit down and do it - is there a point where you're getting stuck?
Comment: at this point  our definition of the genus is the cokernel of delta
Comment: Did you try computing the Hilbert polynomial?
Answer: First, considering the general open cover of $\mathbb{P}^{2}$ and setting $X_{i}=X\cap D(x_{i}) \ \ (i=0,1,2)$ it can be easily seen (by writing down the equation) that $X_{1}\subseteq X_{2}$ and so $\{X_{0},X_{2}\}$ is an open covering of $X$. Therefore, the genus of $X$ can be computed by the sheaf exact sequence
\begin{equation*}
    0\longrightarrow {\cal O}_{X}(0)(X)\longrightarrow {\cal O}_{X}(0)(X_{0})\oplus
{\cal O}_{X}(0)(X_{2})\longrightarrow {\cal O}_{X}(0)(X_{0}\cap X_{2}).
\end{equation*}
But there is a (natural) isomorphism of sheaves of ${\cal O}_{X}$-modules ${\cal O}_{X}(0)\xrightarrow{\sim}{\cal O}_{X}$ and so we may compute the genus of $X$ by computing the
dimension of the cokernel of the map $\delta$ in the following exact sequence:
\begin{equation*}
    0\longrightarrow {\cal O}_{X}(X)\longrightarrow {\cal O}_{X}(X_{0})\oplus
{\cal O}_{X}(X_{2})\overset{\delta}{\longrightarrow} {\cal O}_{X}(X_{02}),
\end{equation*}
where $X_{02}:=X_{0}\cap X_{2}$ and $\delta(f_{0},f_{2})=f_{0}|_{X_{02}}-f_{2}|_{X_{02}}$
for each $f_{0}\in{\cal O}(X_{0})$ and $f_{2}\in{\cal O}(X_{2})$.
We will compute
$\dim_{k}(\mathrm{coker}\delta)$ by precisely finding a basis of $\mathrm{coker}\delta$.
Note that by dehomogenization we  have that the isomorphisms of varieties
\begin{equation*}
    X_{0}\cong Z(f_{0}) \ \ \ \text{and} \ \ \ X_{2}\cong Z(f_{2}),
\end{equation*}
where $f_{0}=x_{01}^{n}-x_{02}+x_{02}^{n}\in k[x_{01},x_{02}]$ and
$f_{2}=x_{21}^{n}-x_{20}^{n-1}+1\in k[x_{20},x_{21}]$. Hence, we have that
\begin{equation*}
    {\cal O}_{X}(X_{0})\cong k[x_{01},x_{02}]/(f_{0}) \ \ \ \ \text{and} \ \ \ \
    {\cal O}_{X}(X_{2})\cong k[x_{20},x_{21}]/(f_{2}).
\end{equation*}
Before we start, observe that a system of generators for ${\cal O}_{X}(X_{0})$ is
\begin{equation*}
    T_{0}=\{x_{01}^{i}x_{02}^{j}:0\leq i<n,j\geq 0\}
\end{equation*}
and for ${\cal O}_{X}(X_{2})$ is
\begin{equation}
    T_{2}=\{x_{20}^{i}x_{21}^{j}:i\geq 0,0\leq j<n\}
\end{equation}
The above follows directly from the fact that in ${\cal O}_{X}(X_{0})$ we have the relation $x_{01}^{n}=x_{02}-x_{02}^{n}$ and in ${\cal O}_{X}(X_{2})$ the relation $x_{21}^{n}=x_{20}^{n-1}-1$. Hence, $\mathrm{im}\delta$ is generated by the image $T$ of
$T_{0}\cup T_{2}$ under the map $\delta$.
We now proceed with the construction of a basis for $\mathrm{coker}\delta$. We have that
\begin{equation*}
    {\cal O}_{X}(X_{02})\cong k[x_{01}.x_{02},x_{20}]/(f_{0},x_{02}x_{20}-1),
\end{equation*}
i.e. ${\cal O}_{X}(X_{02})$ results by inverting $x_{02}(=x_{2}/x_{0})$ in ${\cal O}_{X}(X_{0})$. Therefore, it can be readily seen that taking into consideration the relations in ${\cal O}_{X})(X_{02})$ and the generating set $T$ of $\mathrm{im}\delta$ the set
\begin{equation*}
    S=\{x_{01}^{i}x_{20}^{j}:0\leq i<n,j>0\}.
\end{equation*}
generates ${\cal O}_{X}(X_{02})$ and so also $\mathrm{coker}\delta$,
$S\cap T=\emptyset$ and is linearly independent in ${\cal O}_{X}(X_{02})$.
Now by considering the other relation $x_{21}=x_{01}x_{20}$ in ${\cal O}_{X}(X_{02})$
it can (again) be readily seen that we may further refine $S$ into
\begin{equation*}
    S'=\{x_{01}^{i}x_{20}^{j}:0\leq i<n,0<j<i\},
\end{equation*}
which has cardinality $|S'|=(n-1)(n-2)/2$ and its image forms a basis of $\mathrm{coker}\delta$.


getting a list of files from secure server

Question: i am trying to get a list of files from secure server to compare them (using diff) to the ones i modified on local version (unfortunately the company i work in is not using subversion nor git yet)
i get list of files easily with:
find . -mtime -20 | grep "\.php\|\.js\|\.css" > changedfiles.log

what i need is a script which would loop over this list and secure copy each of them (scp or rsync) to a local directory, preserving relative path name.
i tried:
for line in `cat changedfiles.log`
do
 DIRPATH=`dirname "$line"`
 `mkdir -p myfiles/$DIRPATH`
 scp user@host:/remotepath/$line myfiles/$line
done

but scp keeps asking me for the password (i dont want to setup key-based authentication to scp without password)
i am not allowed to ssh on remote server so i cannot just zip the list and download them in one command
is it possible to do something to input password only once?
Answer: Rather than set up a passphraseless key, create a passphrase-protected key and use ssh-agent to ensure you only need to enter it once per job.
After generating your keys, prefix your script with something like this:
# Start a new agent
eval `ssh-agent -s`

# add keys with a two-hour time limit
ssh-add -t 7200 ~/.ssh/id_rsa

At this point, you'll be prompted for your passphrase.  After your script is finished, you can have ssh-agent be killed automatically if you do not wish to let it continue to run:
# kill the agent
ssh-agent -k


How to replace a dynamic line in under 1 static line in pytho?

Question: I have the following text file:
This is a static line
This is a dynamic line
This is a dynamic line
This is a dynamic line
This is a dynamic line
This is a static line
This is a static line

I need to replace the first 4 lines under This is a static line with New line. Since the lines will always be dynamic how can I replace them? The text file obviously doesn't contact This is a dynamic line multiple times. This is what I have so far:
with open('textfile.txt') as f:
    f = f.readlines()
    f.remove('This is a static line')

The replace method doesn't appear to work here. What can I do?
Comment: using that `.remove()` will only affect the `f` variable, You have to actually write it back to file after removing
Comment: @Matiiss Yup I print it out later on but this doesn't remove the lines under it. Any ideas on what I can do?
Comment: use a loop, that should help
Answer: You can read the lines into a list, use list.index() to find index of first "This is a static line" and then replace 4 lines after it:
new_line = "New line"

with open("input_file.txt", "r") as f_in:
    lines = list(map(str.strip, f_in))

idx = lines.index("This is a static line")
lines[idx + 1 : idx + 5] = [new_line] * 4

with open("output_file.txt", "w") as f_out:
    print("\n".join(lines), file=f_out)


Warp Shadow - CSS

Question: estou tentando fazer um efeito de warp shadow em minha div mas não estou conseguindo, alguem pode me ajudar?
www.planow.com.br/nobre/empresa.php
Comment: poste o seu código, o que fez até agora, fica mais fácil de ajudar!
Comment: https://gist.github.com/anonymous/95bb3f2885cf8733090e
Comment: Coloque o código na pergunta, para que os OP possam ter o conteúdo necessário para responder na pergunta. Na dúvida veja [ask]
Answer: Acredito que o que esteja procurando seja isto
HTML

    Warp Shadow

CSS
.box {
    padding-top: 50px;
    padding-bottom: 50px;
    padding-left: 100px;
    width: 200px;
}

.boxColor {
    background: -webkit-gradient(linear, 0 0, 0 100%, from(#FFDB4D), to(#EABB00));
    background: -webkit-linear-gradient(#FFDB4D, #EABB00);
    background: -moz-linear-gradient(#FFDB4D, #EABB00);
    background: -o-linear-gradient(#FFDB4D, #EABB00);
    background: linear-gradient(#FFDB4D, #EABB00);
    filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFDB4D', endColorstr='#EABB00′);
}

.shadow_box {
    -moz-box-shadow: 0px 10px 5px #9C9C9C;
    -webkit-box-shadow: 0px 10px 5px #9C9C9C;
    box-shadow: 0px 10px 5px #9C9C9C;
    position: relative;
}

.shadow_box span.warp {
    width: 100%;
    height: 13px;
    position: absolute;
    bottom: -26px;
    right: 0px;
    box-shadow: 0px -10px 5px #fff;
    -moz-box-shadow: 0px -10px 5px #fff;
    -webkit-box-shadow: 0px -10px 5px #fff;
    border-radius: 50% / 20px;
    -moz-border-radius: 50% / 20px;
    -webkit-border-radius: 400px 20px;
}

Pode acompanhar o resultado nesta DEMO
Fonte: Wrap Shadow with CSS3
Comment: valew. isso mesmo

Warp Shadow - CSS


Why we do not accept the result of our simulation study as evidence of a limitation of one method

Question: I am doing a mixture model. I have established a new method using EM-algorithm. I have simulated data from a mixture model. Then, I applied my new method to the data. The result is very satisfying. Then, for comparison reason, the non-mixture model shows inaccurate results, as accepted. I have used this as evidence that the non-mixture model (for a specific area) is not able to deal with mixture dependency. Someone told me that is not surprising as the data is a mixture data. I already knew that but to make the reader aware of the importance of the mixture model and how the non-mixture fails in these cases. Then, he asked me to applied both non-mixture and mixture models on real data and see the results. The data I have used is general (I just would like to test the model on it and have no experiment information about it). I read that for real data, we should understand it or have a strong background on it, otherwise the comparison is not fair. For example, suppose that I fit a model on a data where I really do not know it very well. Suppose further that the first model (model A (non-mixture) fit different distribution (say arbitrary Gaussian models) to the data, while the mixture model (model B) fit only specific mixture Gaussian model. Then, it may possible that model A outperforms model B. However, if we have a great knowledge of our data, then fit the most appropriate mixture model, then, the possibility that model B fits the data better than model A is high.
My question is why we do not trust the simulation study to illustrates our problem (if we have not interested in specific data) or have data with no experiment knowledge? In other words, as I need to illustrate one point, then why do simulation data is not enough?
New edit
In other words,
My idea is, is it fair to compare model A with model B where I do not have enough information or knowledge of the data at hand? Which may make model A fits the data better than model B (due to poor knowledge of the data). I think, for this case, the fair comparison is can only hold if we have a great knowledge of the data and therefore fit the most appropriate model to it before the comparison. That is, to compare two models on real data, I should have enough knowledge about the data. Otherwise, if I fit wrong model, even if it mixture model, to the real mixture data, then, the non-mixture may fit the data better than the mixture model just because I fit the wrong mixture model? Is that correct? Therefore, the non-mixture model even shows a better model fit than the mixture model, still, give me wrong fits (because the data is a mixture). Hence, in this case, my simulation data is good to illustrate the limitation of the non-mixture model.
Comment: You cannot trust _one_ simulation experiment, but need _many_ repeated simulation experiments to show that the pattern persists across repetitions and variations of the parameters of the model you use to simulate.
Comment: @Xi'an Thank you so much for your comments. I always trust you. If you meant that I have to apply my model to a repeated simulated data set, then, yes that what I  have done. If you meant applied my model on different simulation scenario, then, yes I have done that. My question is, if I have a real data which I do not understand it very well, and fit wrong mixture model to it, with a fixed number of wrong components, then I will have a wrong result and hence, the non-mixture model may provide the better model fit. Is that possible?
Answer: Simulation studies that show that it is great when the data generating model and the analysis model are the same are very common. What people really want to see is more general:

Model performing well when the data generating merchanism has all the complexity of real life. There is a lot of judgement here, but some other aspect of the data generating mechanism may have a much bigger impact than others. Simulations are actually great for exploring that, but are too often poorly done.
Don't just knock down a strawman, but all the reasonable / frequently used methods. E.g. adjustment for covariates might make omitting a random effect less important.
The differences in performance need to be striking enough that it truly matters in practice. A good example can also help here to illustrate that one can get strikingly different conclusions.
Comment: I guess part of the problem is: why should anyone care that omitting a random effect on a model matters, if there is one in the data generating process, if they have no idea whether this can realistically occur in practice. Also, does the form of the random effect matter etc.
Comment: Thank you so much for your answer. I appreciate it. I have edited my question.


1, 4, 7 numeric collection

Question: Curious lay person here; my first post.
Background:
Years ago I was introduced to a numeric collection (sequence?) involving the numbers 1, 4, 7, and possibly beyond.  These numbers were used to control user access to computer files in the Primos operating system.  Users were allowed to either a) read a file, b) write to a file,  including creating a file, and c) executing the file. Read, write, and execute were represented by the numbers 1, 4, 7, respectively.  For example, if a user was assigned the ability to only read a file, the number 1 was assigned.  If the user could read and execute the file, the number 8 (1+7) was assigned.
As I recall, 1, 4, and 7 were used because no matter which read, write, execute status was assigned, the resulting 1-, 2-, or 3-way sum would be unique.
Question:
I'm trying to confirm that my memory is correct; does such a numeric pattern, where the sum of any combination of numbers in the (set?) results in a unique result, and if so, is there a generic term for such a pattern?  I spent a half-hour on searching the internet with no success.
Comment: In general, taking for such a collection the first $k$ powers of $2$ is an optimal choice – no two sums are the same, and the sum of values is the smallest possible.
Comment: [This](https://www.tutorialspoint.com/unix/unix-file-permission.htm) may be what you seek.
Comment: **If** the comment of @JohnDouma is on point, see also [this section of Wikipedia Unix File Permissions Article](https://en.wikipedia.org/wiki/File-system_permissions#Numeric_notation),
Answer: The general type of thing is called a bit field or a set of flags.
Each flag has a value that's a power of 2, so that in the binary representation of the number, each flag corresponds to a single bit, independent of the others.
Unix file permissions are a particular convention of a bit field defined as a combination of Read=4, Write=2, and Execute=1.  This allows 8 possible combinations of permissions:

0 = no permission
1 = Execute
2 = Write
3 = Write + Execute
4 = Read
5 = Read + Execute
6 = Read + Write
7 = Read + Write + Execute

Each 3-bit combination can be expressed as one octal digit.

1, 4, 7 numeric collection


Spring com DataBase (SQLServer) já criada

Question: Estou desenvolvendo uma aplicação Rest API utilizando Spring Boot.
Dúvida:
Se eu já tenho uma DataBase em produção com tabelas populadas é necessário criar mesmo assim a classe de Entidade com a anotação @Entity.
Se sim é precisa constar todos os campos dessa tabela nessa class ?
Comment: Sim Juliano, o @Entity é para que a classe que vai servir de modelo trabalhe com `javax.persistence.Entity`, sem isso ele não vai entender que aquele classe faz parte de algo, é para persistir, não tem haver com gerar o banco de dados (claro que você pode setar `hbm2ddl.auto` como "create" no hibernate, mas isso é outra história)
Answer: Sim Juliano, você deve mapear a classe com o @Entity para definir o objetos persistentes em sua base de dados, você pode mapear os nomes das tabelas e respectivos campos, para os campos que não deseja refletir na base você pode usar a anotação @Transient.
No arquivo de configuração de persistência (xml / properties do Spring Boot) você deve utilizar a estratégia de UPDATE no values hibernate.hbm2ddl.auto.
hibernate.hbm2ddl.auto=UPDATE
<property name="hibernate.hbm2ddl.auto" value="UPDATE"/>

Esse artigo da algaworks da umas boas dicas sobre JPA: https://blog.algaworks.com/tutorial-jpa/
Comment: Eu fiz essas configurações porém fica aparecendo um erro na criação da class entidade:
Comment: Error creating bean with name 'ifuncionario' defined in com.portalDigital7.repository.Ifuncionario defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create  [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Comment: Consegue compartilhar o Fonte?
Comment: Oi Paulo postei uma nova pergunta. e coloquei os fontes.
https://pt.stackoverflow.com/questions/479948/cannot-resolve-reference-to-bean-jpamappingcontext-while-setting-bean-property


Product (arbitrary) of open functions is open.

Question: Let $f_{\alpha}\colon X_{\alpha}\to Y_{\alpha}$ be open, for all $\alpha \in J$. Then $\prod_{\alpha} f_{\alpha}\colon \prod_{\alpha}X_{\alpha} \to \prod_{\alpha}Y_{\alpha}$ is open? Both $ \prod_{\alpha}X_{\alpha}$ and $ \prod_{\alpha}Y_{\alpha}$ have the product topology.
What if every $f_{\alpha}$ is also surjective?
Comment: You need to specify a topology on the product.
Answer:

2.3.29. Proposition. The Cartesian product $f=\prod_{s\in S} f_s$, where $f_s \colon X_s \to Y_s$ and $X_s\ne\emptyset$ for $s\in S$, is open if and only if all mappings $f_s$  are open and there exists a finite set $S_0\subset S$ such that $f_s(X_S)=Y_S$ for $s\in S\setminus S_0$.
Proof. From 1.4.14 and the equality $f(\prod_{s\in S}W_s)=\prod_{s\in S}f_s(W_s)$ it follows that if the mappings $f_s$ satisfy the above conditions, then $f$ is open.
Conversely, suppose that $f$ is an open mapping . Take an $s_0\in S$ and a non-empty open set $U\subset X_{s_0}$. the set $U\times \prod_{s\in S\setminus\{x_0\}} X_s$  is non-empty and open in $\prod_{s\in S} X_s$, so that the set
  $$p_{s_0} f(U\times\prod_{s\in S\setminus\{s_0\}} X_s)=f_{s_0}(U)$$
  is open in $Y_{s_0}$, because the projection $p_{s_0}$ is an open mapping. This implies that $f_{s_0}$ is open. As $\prod_{s\in S} X_s\ne\emptyset$, the set $f(\prod_{s\in S} X_s) = \prod_{s\in S} f_s(X_s)$ is a non-empty open subset of $\prod_{s\in SY_s}$, so that it contains a set of the form $\prod_{s\in S} W_s$, where $W_s\ne Y_s$ only for $s$ in a finite set $S_0\subset S$; then for $s\in S\setminus S_0$ we have $f_s(X_s)=Y_s$. $\square$

(cited from "General Topology" by Ryszard Engelking. )

1.4.14. Theorem. A continuous mapping $f\colon X\to Y$ is open if and only if there exists a base $\mathcal B$ for $X$ such that $f(U)$ is open in $Y$ for every $U\in\mathcal B$. $\square$


boxes and stacking them options

Question: If I have 5 different boxes, lets give them a letter A, B, C, D, E and I have to stack them. How many different ways are there to stack them. If I have to use them all it would be 5!, however if I do not have to use them all for a stacking. So A is a solution, B is a solution, etc.
Now to add to this question, if a stacking of AB is the same as stacking as BA what would be the total number of stacking possible?
Hope this is clear. Hope you can help! Thank you :)
I know that for 2 boxes, A and B the result would be: A, B, AB (AB=BA)
I know that for 3 boxes, A, B and C the result would be: A, B, C, AB, AC, BC, ABC
Now I don't know how to continue.....
Answer: It looks as if the order of stacking does not matter. So line up the boxes in order, and decide for each YES or NO, depending on whether we will use the box or not. There are $2^5$ ways to make the decisions. But one of the decisions we have just counted is the decision to use no boxes. That is presumably not allowed, so the answer to your problem is $2^5-1$.
If order does matter, then we can choose to make a stack of $1$ box, $2$ boxes, $3$ boxes, $4$ boxes, or $5$ boxes.
There are as you observed $5!$ ways to stack $5$ boxes.
If we will use $4$ boxes, the boxes we use can be chosen in $\binom{5}{4}$ ways and then for each such choice they can be stacked in $4!$ ways, for a total of $\binom{5}{4}\cdot 4!$.
Similarly, for $3$ boxes there are $\binom{5}{3}\cdot 3!$ ways to do the job. And so on. Now add up.
Comment: The order of the stacking does not matter in this case. Therefore your answer seems logical. If I understand correctly, if I were to have 500 boxes and wanted to stack them. the equation would be 2^500-1 different ways to place the boxes on top each other. Making sure that my ABC configuration is not also counted as BAC configuration. This isn't counted twice, as I see them as the same. Thank you for your answer.
Comment: Yes, if order does not matter it is $2^n-1$.  For your $n=5$ we could also argue (correctly) that the answer is $\binom{5}{1}+\binom{5}{2}+\cdots+\binom{5}{5}$. Of course this sum turns out to be $2^5-1$.
Comment: and this way when I have 500 boxes, I also consider the option of just stacking A being one stack? A AB ABC ............... right up to 500 boxes on top of each other.
Comment: Yes, but it considers $ABD$ as different from $ABC$, so it assumes the boxes are distinct (maybe distinct contents). If we only care about the *number* of boxes, then the answer is clearly $500$ (one box, two boxes, and so on). That would apply if we are stacking identical **bricks**.
Comment: no that is exactly what I was looking for. Thank you
Answer: This smells like homework. Is it?
$5Cx$ gives the total number of combinations of 5 boxes taken $x$ at a time without caring for order. $$nCx = \dfrac{n!}{(n-x)!x!}$$
(Notice 5C2 = 10)
$5Px$ gives the total number of combinations of 5 boxes taken $x$ at a time but caring for order. $$nPx = \dfrac{n!}{(n-x)!}$$
(Notice 5P2 = 20)
In this case,
$$5P2 = 2 \times 5C2$$
Helps?

boxes and stacking them options


Way to avoid predefining actions and states in reinforcement learning

Question: Recently, I have heard of the concept of the reinforcement learning and I have got interested in it. So I decided to start a project that uses this kind of machine learning for constructing algorithms from existing knowledge. My problem is that I really don't know all the possible states and actions in order to predefine them earlier. Is there any way of avoiding this and some kind of automatic algorithms that explore all of them?
Thank you for the patience.
Answer: When the set of states is not given or known it is used Fitted Value Iteration. http://cs229.stanford.edu/notes/cs229-notes12.pdf


What is wrong with this formula?

Question: I'm trying to make a formula that converts an ellipse in general form to one in standard. My steps to derive it are as follows:
$$ax^2+bx+cy^2+dx+e=0$$
Move e to the other side...
$$ax^2+bx+cy^2+dx=-e$$
"Complete the square" on both quadratics...
$$a(x+\frac{b}{2a}) + c(y+\frac{d}{2c})=\frac{b^2}{4a^2}+\frac{d^2}{4c^2}-e$$
I decided I only needed this much of the formula, as it was obvious that i would just divide the right side by the left to convert to the form
$$\frac{(x^2-h)}{a^2}+\frac{(y^2-k)}{b^2}=1$$
However, when I tested it with the equation $9x^2-54x+4y^2+8y+49 = 0$
I substituted in the variables, and the left side checked out:
$$9(x-3)^2 + 4(y+1)^2$$
However, when I tried to compute the right side, I got a result that neither nine nor four are factors of.
$$\frac{(-54)^2}{4(9)^2} + \frac{(8)^2}{4(4)^2} - 49$$
$$\frac{2916}{324} + \frac{64}{64} - 49$$
$$9 + 1 - 49 = -39$$
As this Wolfram|Alpha query shows, I should be getting 36 on the left, but I'm getting negative 39. I can't seem to find an error in either the formula or the math.
Comment: I think you completed the square wrong
Answer: You didn't complete the square right. Do the following for both $ x, y $,
$$
ax^2 + bx + c + ... = ... \\
a(x^2 + \frac{b}{a}x + \frac{b^2}{4a^2}) + c + ... = \frac{b^2}{4a^2} + ... \\
a(x + \frac{b}{2a})^2 + c + ... = \frac{b^2}{4a^2} + ...
$$
Do that for both x and y.
Answer: $$a(x^2+\frac{b}{2a}x +\frac{b^2}{4a^2}) + c(y^2+\frac{d}{2c}y + \frac{d^2}{4c^2})=\color{red}{a}\frac{b^2}{4a^2}+\color{red}{c}\frac{d^2}{4c^2}-e$$
There are errors when completing the square. First, it appears that you omitted the two red terms on the left hand side. More importantly, the terms you must add to the right hand side are missing the factors $a$ and $c$ respectively. Do you see where they came from?
Comment: And the x and y terms should be squared.
Comment: Oh whoops, the missing terms in completing the square were because of a typo in the question. The proper equation for that step is  $(x+\frac{b}{2a}) + c(y+\frac{d}{2c})=\frac{b^2}{4a^2}+\frac{d^2}{4c^2}-e$. I'll edit the question! The missing a and c factors are the mistake I was making, however! Thanks!
Comment: That's what I figured. I'll "un"-red them :)

What is wrong with this formula?


Putnam A-6: 1978: Upper bound on number of unit distances

Question: Let n distinct points in the plane be given.prove that fewer than $2n^\frac{3}{2}$ pairs of them are at unit distance apart
Comment: Discussion of past Putnam problems may be found at: http://www.artofproblemsolving.com/Forum/viewforum.php?f=80
Comment: The more interesting question is in $m$ dimensions instead of the plane.
Comment: @GEdgar-How am i able to find it if i don't know which problem it is?
Comment: @Victor: It is A-6, 1978.
Comment: Eric, in my view the planar question is the most interesting
Answer: There is a rich history for this problem.
Let $U(n)$ denote the number of times a given distance can occur for $n$ points in the plane.  In 1946 Erdos showed that $$n^{1+\frac{c}{\log \log n}}<U(n)<n^\frac{3}{2}.$$  (Notice the upper bound is what you want to prove) Erdos also conjectured that the upper bound should have the same form as the lower bound.
Szemeredi improved the upper bound to $o\left(n^\frac{3}{2}\right)$ in 1975, and in 1982 Beck and Spencer gave the upper bound of $n^{1.499}$.
The best known result is  $U(n)<cn^\frac{4}{3}$ which was done by Spencer Szemeredi and Trotter in 1984.
The link to Erdos paper contains a proof of the question you are asking.
Edit: Here is the more accessible (not JStor) link to Erdos Paper, provided by Aryabhata)
Comment: This link to the Erdos paper might be better: http://www.renyi.hu/~p_erdos/1946-03.pdf
Comment: A more recent result (I haven't read it, though): http://gilkalai.wordpress.com/2010/11/20/janos-pach-guth-and-katzs-solution-of-erdos-distinct-distances-problem/
Comment: A more relevant blog post with the bound n^{4/3} is here http://gilkalai.wordpress.com/2008/07/17/extermal-combinatorics-ii-some-geometry-and-number-theory/
Comment: @Aryabhata:  Thanks, I just wrote the wrong thing at the top (not sure why), all the references are correct.
Comment: @Aryabhata:  It does give the theorem two (on the next page).  I get the document through my University's subscription so I forget that JStor can be annoying.  Your link is definitely better, I'll edit the answer.


random() in python

Question: In python the function random() generates a random float uniformly in the semi-open range [0.0, 1.0). In principle can it ever generate 0.0 (i.e. zero) and 1.0 (i.e. unity)? What is the scenario in practicality?
Comment: @extraneon - what? Of course there's a float 1.0. It's '0011111111110000000000000000000000000000000000000000000000000000' (as a double, but the float value is basically the same). The only numbers that don't have an exact float representations are decimals that don't have exact representations with a power-of-two denominator. http://en.wikipedia.org/wiki/Floating_point#Representable_numbers.2C_conversion_and_rounding
Comment: Not 1.0 surely. Apart from the fact that the range does not include 1.0, there also does not exist a float 1.0 (it can't be represented binary).
Answer: 0.0 can be generated; 1.0 cannot (since it isn't within the range, hence the ) as opposed to [).
The probability of generating 0.0 is equal to the probability of generating any other number within that range, namely, 1/X where X is the number of different possible results. For a standard unsigned double-precision floating point, this usually means 53 bits of fractional component, for 2^53 possible combinations, leading to a 1/(2^53) chance of generating exactly 0.0.
So while it's possible for it to return exactly 0.0, it's unlikely that you'll see it any time soon - but it's just as unlikely that you'd see exactly any other particular value you might choose in advance.
Comment: @Dav: Just a nitpick for what's already a nice answer, but I think you mean 53, not 52.  With a perfect random source (which Mersenne Twister of course is not, but it's good enough for practical non-cryptographic purposes), random() generates a number of the form n/2^53 with n an integer uniformly and randomly chosen in the range [0, 2^53).  If you look at the source, it takes two 32-bit words generated by the MT algorithm and combines the top 27 bits of the first with the top 26 bits of the second to create n.

Incidentally, this means that most floats in [0.0, 1.0) can't ever be generated.
Comment: @Arkapravo: It looks like it, at least for not-too-old versions.  The release notes for MATLAB 7.4 (released March 2007) say: "rand Function Uses the Mersenne Twister Algorithm as Default".
Comment: Ah, right - probably because I was thinking of signed floating point, and random() probably uses an unsigned format given its range. I'll change it.
Comment: @Mark Dickinson : 2^52 is a troublesome number in MATLAB ! ..... does it also employ Mersenne Twister ?
Comment: @Mark Dickinson: I understand that Mersenne Twister is a significant improvement on Wichmann-Hill generator to generate random numbers ! ... anything more newer than the Twister ?
Comment: @Arkapravo: Sure; it's an area of active research.  There are recent PRNGs that claim to have better equidistribution properties, better bit-mixing, longer period, faster generation (e.g. by making good use of SIMD instructions), etc.  I don't think any of these PRNGs has established itself as an obvious successor to MT, though.
If you're not doing crypto, I'd be surprised if MT isn't good enough for your needs.
Comment: @Mark Dickinson: I am not into crypto ! ... just inquisitive ! :)
Answer: The [ indicates that 0.0 is included in the range of valid outputs. The ) indicates 1.0 is not in the range of valid outputs.

random() in python


VBA to multiply all cells in a range by looking up value

Question: i need to multiply all cells within a range. The number i need to multiply by is looked up in a different tab called initial machine prices. Within the range each line item has a quote date, this is what is required to be used for the lookup as i can lookup up the date against the annual % increase (in the initial machine prices tab). For example i need the vba to multiply all cells in the first row by 1.02% as the quote year is 2020, i then need it to go the the row below and multiply all cells by 1.0404% because the quote year is 2019.
The Top image shows the % table and then last table shows the values that are required to be changed
Below is what i have started with but only multiplies all cells by 1 number.
Sub Multiply_vals()

Dim ws As Worksheet
Dim rng As Range
Dim myVal As Range

Set ws = Worksheets("Epp mould")
Set rng = ws.Range("V4:AC46")

    For Each myVal In rng
    myVal = myVal.Value * 2
    Next myVal

End Sub

Comment: You know you do not need to **loop** all cells in row 1 range to multiply it by `1.02%`. There is a more efficient way which involves `.PasteSpecial Paste:=xlPasteValues, Operation:=xlMultiply`?
Comment: A screenshot of your data and one of the date/% table would be useful here. You should be able to use vlookup() or match/index to do the lookup of the % value.
Comment: Hi Tim, please see image that is embedded in the question.
Answer: Using the newer dynamic features (afaik versions 2019+ or MS365),
and assuming that the correct factor for the first row is
1.02% (cell EA2), the row below 1.0404% (cell EAB) etc. to the right in sheet `Initial Maching prices',
you can

use a (worksheet related) formula evaluation
referring to your source data in cells V4:AC43,
multiplied by the transposed factors (making them vertical) in sheet 'Initial Machine Prices' and
overwrite the originals by the recalculated array values

Note that this would overwrite existing data, so copy your source values to a backup sheet before!
Option Explicit         ' declaration head of code module

Sub Example()
'0) fully qualify data source sheet
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1")

'1) get data to array via formula evaluation
    '   (multiplying source values with factors in Initial Machine Prices)
    Dim data
    data = ws.Evaluate("V4:AC43*TRANSPOSE(OFFSET('Initial Machine Prices'!EA2,,,,ROWS(V4:AC43)))")

'2) overwrite existing data(!)
    ws.Range("V4").Resize(UBound(data, 1), UBound(data, 2)) = data
End Sub