How to set node author based on a field's values?

Question: I have an entityreference field that references a redhen_contact entity. I want to set the node's author to be the user associated with the contact referenced in this field.
This is part of a (I think, rather basic) custom rendition of the node form via hook_menu() and drupal_get_form.
I can get the user from the entityreference field and I can print its name, uid, email etc. with drupal_set_message.  And when I print $node->uid with drupal_set_message it shows up as if I was successful, but it gets overridden apparently and I have no idea where. The saved nodes always show that I'm the author (as I'm the one submitting the form).
I first tried using hook_form_alter(), then I tried using hook_node_presave(), then hook_node_insert().  I don't know of any hooks that fire later. But maybe one of these hooks would work if I did it right?
Here's most of what I've tried:
<?php
function mymodule_register_existing_adult_submit($form, &$form_state) {
  $registrant_id = $form['#node']->field_registrant['und'][0]['target_id'];
//  $contact_wrapper = entity_metadata_wrapper('redhen_contact', $registrant_id);
//  $registrant_name = $contact_wrapper->label();
//  $registrant_email = $contact_wrapper->email->value();
//  $registrant_user = $contact_wrapper->user->value();
//  $registrant_url = $contact_wrapper->user->value();
//  drupal_set_message(t("Hey this works! " . "ID=" . $registrant_id . " " . $registrant_name . " " . $registrant_email . "
" . $registrant_user->uid));
//  sdpm($form);
  //$form['additional_settings']['group']['#groups']['additional_settings'][0]['name']['#value'] = $registrant_user->uid;
  //$form['additional_settings']['group']['#groups']['additional_settings'][0]['name']['#default_value'] = $registrant_user->uid;
  //$form['author']['name']['#default_value'] = $registrant_user->uid;
  //$form['author']['name']['#value'] = $registrant_user->uid;
  //$form_state['complete form']['uid']['#value'] = $registrant_user->uid;
  //$form_state['complete form']['uid']['#value'] = $registrant_email;
  //$form_state['values']['uid'] = $registrant_user->uid;
  //$form_state['build_info']['args'][0]->uid = $registrant_user->uid;
  //$form['uid'] = $registrant_user->uid;
//  $form['#node']->uid = $registrant_user->uid;
  //dpm($contact_wrapper->getPropertyInfo());
  $form_state['redirect'] = 'redhen/contact/' . $registrant_id . '/view/edit';
}
function mymodule_node_presave($node) {
  if ( $node->type == 'program_registration' ) {
    $registrant_id = $node->field_registrant['und'][0]['target_id'];
    $contact_wrapper = entity_metadata_wrapper('redhen_contact', $registrant_id);
    $registrant_user = $contact_wrapper->user->value();
    $node->author = $registrant_user->name;
    drupal_set_message('Hook implemented successfully.
User ID: ' . $registrant_user->uid);
    drupal_set_message($node->author);
    sdpm($registrant_user);
  }
}
function mymodule_node_insert($node) {
  $path = current_path();
  if ( $path == 'admin/register-existing-adult' ) {
    drupal_set_message('hook_node_insert author: ' . $node->author . '
Path: ' . $path);
    $registrant_id = $node->field_registrant['und'][0]['target_id'];
    $contact_wrapper = entity_metadata_wrapper('redhen_contact', $registrant_id);
    $registrant_user = $contact_wrapper->user->value();
    $node->author = $registrant_user->uid;
    $node->uid = $registrant_user->uid;
  }
}

Edit:
Where I'm at now is I've cleaned up the code to see more precisely what's going one:
<?php
function mymodule_node_presave($node) {
  if ( $node->type == 'program_registration' ) {
    $registrant_id = $node->field_registrant['und'][0]['target_id'];
    $contact_wrapper = entity_metadata_wrapper('redhen_contact', $registrant_id);
    $registrant_user = $contact_wrapper->user->value();
    $node->author = $registrant_user->name;
  }
}
function mymodule_node_insert($node) {
  $path = current_path();
  if ( $path == 'admin/register-existing-adult' ) {
    drupal_set_message('author: ' . $node->author);
  }

Here hook_node_insert() is successfully printing the email address for the user associated with the contact entity.  So it seems that the code in hook_node_presave() works, except that it must then be overwritten by Drupal afterwards? Or maybe the email address is not a valid value for the node author?
Answer: The hook depends on what you want to do and when. I don't think that you need to implement the code in hook_form_alter as will be executed every time you access that form. Try in your hook_node_insert to use field_attach_update('node', $node); in order to update your node. Also check https://www.drupal.org/node/2453099. In similar situation (I had to change the author after submit) I created a callback for the specific form where I was changing the author. Finally, keep in mind that when you altering a node you need to save/update it.
Comment: Yes @alec, I'm working on D8 but it's the same more or less. I think submit callback is the best option. Have a look at this link https://drupal.stackexchange.com/questions/219752/is-there-any-easy-way-to-set-the-default-author-for-a-node-being-edited-to-the-c I think is exactly what you need
Comment: Thanks but no success yet.  I simply added `field_attach_update('node', $node);` to the end of the `hook_node_insert()` function but that had no effect, not sure if there's more I should have done for that.  I looked around that post from d.o but calling `node_save()` yielded "duplicate entry" PDOException errors.

The callback you created when changing author after submit... that was a submit callback function that you added to the form via hook_form_alter?

I just added more information to the question.
Answer: Thanks to the link in the accepted answer by Ismini, I figured out how to do this in a form submit callback function.
<?php
/**
 * Implements hook_form_FORM_ID_alter().
 * Use this to call your submit function below.
 */
function roots_reg_form_program_registration_node_form_alter(&$form, $form_id, $form_state) {
  $path = current_path();
  if ($path == 'admin/register-new-adult/program') {
    $form['actions']['submit']['#submit'][] = 'mymodule_register_existing_adult_submit';
  }
}

function mymodule_register_existing_adult_submit($form, &$form_state) {
  $registrant_id = $form['#node']->field_registrant['und'][0]['target_id'];
  $contact_wrapper = entity_metadata_wrapper('redhen_contact', $registrant_id);
  $registrant_user = $contact_wrapper->user->value();
  // the following lines made the critical difference
  $nid = $form_state['values']['nid'];
  $node = node_load($nid);
  $node->uid = $registrant_user->uid;
  // calling node_save() is necessary but not at all obvious.
  node_save($node);
}

Answer: Another solution, alternate to doing it in the form submit callback, is to add $node->uid = $registrant_user->uid; to hook_node_presave().  In this case I had simply missed the needle in the haystack.  So the function could look like:
function mymodule_node_presave($node) {
  $path = current_path();
  if ( $path == 'admin/register-existing-adult' ) {
    $registrant_id = $node->field_registrant['und'][0]['target_id'];
    $contact_wrapper = entity_metadata_wrapper('redhen_contact', $registrant_id);
    $registrant_user = $contact_wrapper->user->value();
    // $node->author = $registrant_user->name;
    // doesn't seem to work
    // but...
    $node->uid = $registrant_user->uid;
    // does :)
  }
}


jQuery.browser.msie depreciated in 1.9 trying to fix in Drupal 7

Question: The design template I am using needs jQuery 1.9. But Drupal 7 doesn't seem to support 1.9. Please correct me if I'm wrong
The issue is that when in import jQuery 1.9 in Drupal 7 then here is the following error when in admin (overlay) trying to add content:
 Uncaught TypeError: Cannot read property 'msie' of undefined

This is coming from overlay-parent.js. It has the following code:
if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {

It's causing an error because I am importing jQuery 1.9 and Drupal 7 runs code that contains the deprecated and removed jQuery.browser method.
The problem is that, after updating the code in  modules/overlay/overlay-parent.js to:
if (navigator.userAgent.match(/msie/i) && navigator.userAgent.match(/7/)) {

These changes are not taking effect. Perhaps this has to be compiled into some minimized .js file but I am not sure. How to make these changes in Drupal 7? Any alternative ways to make jQuery 1.9 compatible Drupal 7?
Comment: If you have not turned on JS aggregation no need to minify js. To debug you can always print out `navagator.userAgent` to check if its working or not.

Also as David mentioned, there might be other code which are using deprecated code. To check that you can use [`jQuery.migrate plugin`](https://github.com/jquery/jquery-migrate/). It will indicate in console places where deprecated code are used.
Comment: Thank you 2-Stroker...the suggestion of JQuery.migrate worked very well
Answer: Drupal ships with a particular version of jQuery.
Using a different version of jQuery means refactoring various core javascript code.
If you want to use a more recent jQuery version, you can check the available versions provided by the jquery_update module which provides that refactored replacement javascript.
Answer: I had the same problem, I didn't want use lower Jquery version, so I resolve problem with  #2 tiny patch in this page


I can't induce a contradiction by assuming negation, what does that imply?

Question: Suppose I want to prove that $A \Rightarrow B$. So I assume $A$ and $\neg B$ and hope to arrive at a contradiction. But suppose $\neg B$ does not induce any contradiction - I don't mean "suppose I fail to spot any contradictions", I mean let's pretend I have proven that no contradictions arise (if that's even formally possible to do). Does this mean that I have proven $A \not \Rightarrow B$?
I mean, I have shown that $\neg B$ is consistent with $A$, or that $\neg B \not \Rightarrow \neg A$. But I'm no formal logic expert so I'm not convinced that this is equivalent to $A \not \Rightarrow B$. Help?
Comment: "So I assume $\neg B$ ..." - I assume you rather assume both $A$ and $\neg B$?
Comment: Yeah. Exactly. You've proven that $\neg B$ can co-occur with $A$. Then, $A$ does not necessarily imply $B$.
Comment: @HagenvonEitzen Yes. Good point.
Comment: @HagenvonEitzen Or rather, what I've done is to prove that $\neg B \not \Rightarrow \neg A$. I would guess that those statements are equivalent, but logic $\Leftrightarrow$ voodoo sometimes.
Answer: On way to prove $A \Rightarrow B$ is to assume $\neg B$ and arrive at (not a contradiction) but $\neg A$.
If you prove that no contradiction follows from $\neg B$, all that shows is that $\neg B$ is internally consistent. But it doesn't follow that it is consistent with $A$.
For example suppose $A = B$. Showing that $\neg B$ (i.e. $\neg A$) entails no contradiction doesn't show that $\neg B$ (i.e. $\neg A$) is consistent with $A$!
Comment: This is not clear to me. $A = B$? What does that mean? Same as $A \Leftrightarrow B$?
Comment: I mean... in your example, you're saying that $\neg B \Rightarrow \neg A$ because $A=B$. But surely that must imply that $A \Rightarrow B$!?
Answer: $(A \Rightarrow B) \Leftrightarrow (\neg B \Rightarrow  \neg A)$
The right statement is called the contrapositive.
What they are saying is that the satisfaction of $A$ results in a satisfaction of $B$.
If you happen to show that there are cases where $\neg B$ is satisfied but $\neg (\neg A)$ isn't then you have proved that $\neg B \not \Rightarrow \neg A$. At this point, this is telling us that there are cases where $\neg B $ and $A$ are simultaneously verified. What does this mean? it means that we can have $A$ satisfied and not be satisfied by $B$. Thus it does imply $A \not \Rightarrow B$ and your assumption is correct.
Comment: Ok let's clear this up. $\neg B \not \Rightarrow \neg A$ is the same thing as saying "it's not impossible that $\neg B$ and $A$ are both true", right? You're saying this is equivalent to "there are cases where both $\neg B$ and $A$ are true". This is not completely obvious to me - I guess this implicitly hinges on some assumption that "every true statement implies every other true statement" or something?
Comment: @BenjaminLindqvist "It's not impossible..." is not  a rigorous accepted reason to make a mathematical statement. All we can take from that kind of phrase is that we cannot declare the statement in question. It doesn't work like law "innocent until proven guilty".  $\neg B \not \Rightarrow \neg A$ isn't saying it's not impossible, it is actually saying there are cases where both $\neg B and A$ are satisfied.


Cabal update fails with unix package configure error

Question: I have a very old Cabal (1.16.0) installed from my distro's repo (Linux Mint). Today, I tried updating it and got:
cabal install cabal-install -v3
...
unix-220.127.116.11 failed during the configure step. The exception was:
ExitFailure 1
zlib-0.6.1.2 failed during the building phase. The exception was:
ExitFailure 1

I also see
checking for suffix of executables...
checking whether we are cross compiling... configure: error: in `/tmp/unix-220.127.116.11-2138/unix-184.108.40.206':
configure: error: cannot run C compiled programs.
If you meant to cross compile, use `--host'.
See `config.log' for more details
sh returned ExitFailure 1

After checking the config.log, I see some errors but I am not sure they are related and the configuration failed on them:
Thread model: posix
gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3)
configure:2738: $? = 0
configure:2727: gcc -V >&5
gcc: error: unrecognized command line option '-V'
gcc: fatal error: no input files
compilation terminated.
configure:2738: $? = 4
configure:2727: gcc -qversion >&5
gcc: error: unrecognized command line option '-qversion'
gcc: fatal error: no input files
compilation terminated.
configure:2738: $? = 4
configure:2758: checking whether the C compiler works
configure:2780: gcc -Wl,--hash-size=31 -Wl,--reduce-memory-overheads   conftest.c  >&5
configure:2784: $? = 0
configure:2832: result: yes
configure:2835: checking for C compiler default output file name
configure:2837: result: a.out
configure:2843: checking for suffix of executables
configure:2850: gcc -o conftest -Wl,--hash-size=31 -Wl,--reduce-memory-overheads   conftest.c  >&5
configure:2854: $? = 0
configure:2876: result:
configure:2898: checking whether we are cross compiling
configure:2906: gcc -o conftest -Wl,--hash-size=31 -Wl,--reduce-memory-overheads   conftest.c  >&5

This is weird (I tried running the gcc.. command and it was also fine). Any help with this error is welcome.
Comment: The errors are not necessarily in the end of config.log, you need to search for the string 'error'.
Comment: @Sibi this `stack` way of doing things looks quite cool, thanks.
Comment: You are right @n.m. I did the search and found some errors but I am not sure configuration failed on them. See the updated description above.
Comment: These errors are harmless, it's the configure script trying to figure out usable gcc options. There should be more error messages. You are probably interested in one that sits near "checking whether we are cross compiling" message.
Comment: @n.m. if you mean the config.log's messages near "checking we are...", then I copy-pasted everything into the post above. The log just suddently ends with "configure:2906: gcc -o conftest...".
Comment: Another alternative (better IMO) is to just use Stack: https://haskell-lang.org/get-started
Comment: @Sibi I would like to write a Haskell program that acts like a standalone script (with runhaskell) - I am not sure stack is an alternative for me (I would need new cabal's sandboxes).
Comment: @user1724641 You can use the scripting functionality for it: https://haskell-lang.org/tutorial/stack-script
Comment: @Sibi not bad! I mean I could use this. This way I will need to `stack new` etc. and add the needed package descriptor files (yaml, etc).
Comment: @user1724641 Note that you don't need `stack new` for the script interpreter feature. Also you don't need `yaml` files. It is an independent script with just one file. You can see the `script interpreter` section in that page to understand it better. All you need to do is `./http.hs` to execute it.
Answer: You can install the cabal-install binary for linux from the cabal homepage as well: https://www.haskell.org/cabal/download.html


How to measure changing dimensions of right scalene triangle as hypotenuse rotates?

Question: This is a high school level geometry question.
As shown in the top half of the image below, suppose we start with a right scalene triangle with hypotenuse = 5 and sides b and c = to 3 and 4, respectively.
Suppose we begin rotating the hypotenuse outward (rotated hypotenuse shown as dashed line "d" in bottom half of image). We rotate hypotenuse line "d" out by a unit of 1 from angle "B", denoted as dashed line "e" in the image. How do we measure lines f and g, formed in the new triangle as line d rotates outward?
It's obvious to me the new angle D formed as line "d" rotates will <> angle B. The little black square in the new triangle formed is my recollection of a 90 degree angle designation.
Answer: You have two equations for $f$ and $g$:
$$
f:(4+g)=1:3
$$
(from triangle similarity)
and
$$
f^2+1=g^2
$$
(from Pythagoras' theorem).
Comment: A reminder: solve using quadratic formula
Answer: Another solution is to solve for angle C when you know, for that new dashed-line triangle (the larger one), that hypotenuse ("a") = 5 and one side ("e") = 1. Then use those new angles that are formed from the shift of line "a", and the fact that "e" = 1, to solve for "f" and "g". In any event I end up with the same solution for "f" and "g" when I solve for the equations recommended by Intelligenti Pauca, using the quadratic formula.


Customizing search results page to use template.php and search-results.tpl.php

Question: I'm using Drupal 7, the basic Drupal search tool. I like what it returns as far as the actual node pages. However, I want to customize the main search results page that shows a list of results after a user enters a term to search by.
Right now it shows a list with a linked title to the node (fine), and then a 'summary' (if you can call it that) that's sort of a jumbled mess of the URL, part of the description field, and some other fields. I just want the description to show up there. I'd also like to add the date field and the associated image for the node in the search results. So I've discovered that I need to customize template.php mytheme_preprocess_search_results function and also search-results.tpl.php (results NOT result).
But I can't figure out how to parse out individual items from what the database is returning so I can make sure to only print those out in the tpl file. I did a var_dump on $search_results and see it returns a big 'ol chunk of HTML and database data...but how do I return just individual fields from the database and print those out?
Right now it just does a print $search_results.
I tried print $title and print $url but drupal complains it doesn't recognize those vars. So what are the vars and how can I use them to display what I want?
I'm also noticing it's showing the author and date for each node in the search results (although I hid this information in the content type)...so I'd also like to hide that information in the search results.
I've found a bunch of stuff online that led me to those two files I referenced, for changing the search results...but nothing that specifically addressed how to grab and use individual fields from the database. I also don't want to use a module, I want to do this with template.php and the tpl.php files if possible.
Thanks for your help in advance!
Answer: To change the snippet (that jumbled mess you mention), use theme_preprocess_search_result() (you want to override each search result, not the page of search results). Explicitly set $variables['snippet'] to the value you want to display.
A common tactic is to use the node's teaser view.
<code>function mytheme_preprocess_search_result($variables) {
  $teaser = node_view($variables['result']['node'],'teaser');
  $variables['snippet'] = drupal_render($teaser);
}
</code>
You can manage the node's teaser in Admin -> Structure -> Content Types -> Your content type -> Manage Display -> Teaser as always.
There's a no-code approach also. While you're managing displays, check out the expandable fieldset for 'Custom display settings' and check the one for 'Search results highlighting input'. Here you can control the fields you want to display, but Drupal will still show only a snippet, and it will highlight where in the node your search terms show up. Ditch the preprocess function in this case.
Here is one more example with the theme_preprocess_search_result() function that shows the first 160 characters of the body field: https://alastaira.wordpress.com/2011/01/07/customising-the-search-results-snippet-in-drupal-7/ (note that this one does not check for language).
Comment: FYI: I was able to add $variables['info'] = ''; to remove the author and date information too; sweet.
Comment: excellent; thanks for approving the answer even though I left something out


Como converter uma string em const char *?

Question: Estou tentando fazer um reprodutor de áudio(um mp3 player) usando a biblioteca SDL_mixer.
O problema é que tenho uma função que retorna uma string (um diretório de uma música) que preciso passar essa string como argumento para a função *Mix_LoadMUS(const char *file).
Sou iniciante em programação (1º período), serei grato se as respostas forem simplificadas.
Como faço para transformar uma string num tipo const char*?
Comment: Essa string é o tipo string do C++, ou é um tipo string de uma outra biblioteca? Se for o tipo do C++ padrão, acho que s.c_str() retorna um const char * compatível com C padrão.
Comment: Coloca o trecho do codigo por favor.
Comment: A especificação "const char *file" é só para garantir que a função não modificará o conteúdo apontado pelo ponteiro file.
Comment: Estou usando somente C, essa string vem de uma função escrita com a biblioteca GTK, essa função é um (File_chooser) Tela onde o usuário escolhe o arquivo que quer abrir . Consigo visualizar o conteúdo da string imprimindo ela em uma arquivo (fprintf). O problema é que quando tento passar essa string para a outra função, o programa fecha.
Comment: É do tipo GString?
Answer: Se for GString do GTK+, use
astringemquestao->str

que aponta diretamente para o buffer contendo a string. Ele é terminado em nulo e pode ser usado onde um const char * é esperado.
Lembrando que: qualquer modificação na GString, o valor do membro str pode mudar. Portanto este ponteiro não deve ser reutilizado. Se você precisar ter acesso a string durante um intervalo de tempo maior, durante o qual a GString talvez mude, faça uma cópia e use a cópia, não esquecendo de liberar depois.
Answer: Se você estiver usando uma string da std (std::string), chame a função c_str().
Por exemplo:
std::string str;

...

Mix_LoadMUS(str.c_str());

Comment: foi citado nos comentários que é usado apenas C.
Answer: O qualificador const apenas indica que a variável não pode ser alterada.
Assim o código abaixo significa que os dados apontados pelo ponteiro file não são alteráveis:

void Processa(const char * file)
{
      ....
}

O compilador se encarrega de gerar um alerta de erro caso o código na rotina tente alterar o conteúdo apontado pelo ponteiro.
Notar que const char *p ou char const *p tem o mesmo significado, ou seja os dados apontados não são modificáveis. Mas char * const p quer dizer o ponteiro é constante, não podendo ser modificado.
Portanto não deve ser problema, você passar uma variável string sem qualificador const para uma rotina como a mostrada em sua pergunta.
[EDIT]
Relendo sua pergunta percebi que seu problema é que o parâmetro que você está tentando passar para a rotina está gerando o erro na hora de compilar, correto?
Se sim, teste usar casting para adequar o parâmetro ao exigido pelo rotina chamada, por exemplo assim:

   char *p = Mix_LoadMUS ( (const char *) file )


Default value for Price field

Question: I'd like to know if there's a way to assign a default value in the Price field in Drupal Commerce. Currently, there are no field settings available.
Answer: It is not possible for the default price field, because Drupal locks down the field / widget settings for "locked" fields. This is a general Drupal issue, but you could work around it by using an alternate price field that you add custom to your product type paired with a product pricing rule that swaps that price in at the start of the pricing process. You'd have to do a form alter or something to hide the default price field from your product forms.
Comment: Thanks for the reply. So I can't unlock it? It seems that it's much more complicated that I expected it to be. I'm curious, do you know why this locking is done in the first place?
Comment: We had to lock it to prevent its deletion since so much of Drupal Commerce depends on that field being there. Unfortunately, Drupal 7 doesn't differentiate between a field that can't be deleted and a field that can't have its settings edited. Hopefully that's resolved in Drupal 8; I filed an issue for it but can't remember where it ended up.
Answer: You can temporarily unlock the field, set the default price and lock it again.  The PHP code is as follows:
$field = field_read_field('commerce_price');
$field['locked'] = 0;  // 0: unlock; 1: lock.
field_update_field($field);

You could run it using drush eval (use backslash to escape the $ and put it all on one line) or the php block from the devel module.  Credit: http://atlantic-canary.net/en/how-to-lockunlock-a-field-in-drupal.
Don't forget to lock it again after to make the field safe again.
Answer: Instill devel module
Enable the devel module either by drush en or from admin/build/modules.
It will generate several blocks and look for the one named 'Execute PHP' enable it by setting it to a preferred  region .
Write the code you want to check on the text area for example and then press execute to see the result.
so here we will use this code
$field_name = 'field_name';
$field = field_read_field($field_name);
$field['locked'] = 0; // 0: unlock; 1: lock.
field_update_field($field);
note: this line $field_name = 'field_name'; you have to add your filed name for example like this $field_name = commerce_price;
if you got any error such as displayed as messages "Notice: Undefined index" or "Notice: Undefined variable" and your logs will grow insanely…
the solution is to add in your settings.php the line
ini_set('error_reporting', 'E_ALL ^ E_NOTICE');

Default value for Price field


Help with Linear Algebra proof that an infinite set of polynomials is independent

Question: Let $\mu_k(t) = t^k$, for $k = 0,1,2, \dots,$ and $t$ is real. I want to show that the infinite set $S = \{\mu_0, \mu_1 , dots \}$ is independent. To do this, set up
(1) $\sum_{k=0}^n c_kt^k= 0$, for all real $t$.
Here's the part of the proof that I don't understand:
Putting $t=0$ in (1) we see that $c_0 = 0$. (Why? I don't see this, and it's my biggest stumbling block in the proof.) Now divide by $t$ in (1) and put $t=0$ again to find $c_1 = 0$. (So, I'm confused as to what is meant by $t$ in the proof. Is it all $t$? Also, why can we divide by $t$? Didn't we just say that $t=0$? Are there supposed to be subscripts?). Rinse and Repeat for the rest of the $c_k$.
I have one last question. The sum in (1) is finite. How does this prove that an infinite set is independent. Doesn't this show that only $n$ $\mu_i$'s are independent; rather than all $\mu_k$ for $k = 0, 1, \dots $ are independent.
Update 1: Why $t$ are we concerning ourselves with the case when $t=0$?
Comment: It means given the function $f(t)=t^k$, compute $f(0)$. For example, with $f(t) = t^2$, we have $f(0) = 0 \cdot 0 = 0$.
Comment: Because if you evaluate the function $t \mapsto t^k$ at $t=0$ the answer is $1$ for $k=0$ and $0$ for $k=1,...$.
Comment: No, $t$ is a specific $t \in \mathbb{R}$. It would be better to write $p(t) = \sum_k c_k t^k$. Then you want to show that if $p(t) = 0$ for **all** $t$, then $c_k = 0$. But note that $p(0) = \sum_k c_k 0^k = c_0$.
Comment: If a linear *dependence* relation holds among the infinitely many polynomials in your set, it only uses finitely many of them (dependence relations being finite sums to zero).  So if you show every finite subset is linearly independent, you prove the entire infinite set of polynomials is linearly independent.
Comment: An arbitrary set of elements is linearly independent **iff** any finite number of elements are linearly independent.
Comment: @copper.hat I'm confused by your first answer. What does it mean to evaluate $t \rightarrow t^k$ at $t=0$?
Comment: @copper.hat You're second comment is also confusing me. I'm not what I'm supposed to infer from it.
Comment: From my algebraic point of view the linear independence of the family $S$ is obvious, because each non-zero linear combination of its elements is a non-zero polynomial which cannot be a zero function, because it has only finitely many roots.
Answer: If $V$ is a vector space over a field $F$ then a subset $A\subset V$ is linearly independent if any finite subset $\{a_1,a_2,\ldots, a_n\}\subset A$, $\>n\in{\Bbb N}_{\geq1}$, is linearly independent. Note that, in algebraic terms, it wouldn't make sense to check under what circumstances an infinite sum $\sum_{k=1}^\infty \lambda_k a_k$ is $\>=0$, since such a sum would not be defined in the first place.
In your example $V$ is the space of all polynomials in an indeterminate $t$ with real coefficients. It is a matter of convention whether you consider a polynomial
(I) as an infinite coefficient sequence $(c_0,c_1,c_2,\ldots)$
with only finitely many nonzero entries $c_k\in{\Bbb R}$,
or (II) as a function
$$p:\ {\Bbb R}\to{\Bbb R},\qquad t\mapsto \sum_{k=0}^{n_p} c_k t^k\ .$$
Under both views the monomials $\mu_k$ form a linearly independent set: Under (I) we have
$$\sum_{k=0}^N\lambda _k\mu_k=(\lambda_0,\lambda_1,\ldots,\lambda_N,0,0,\ldots)=0$$
iff all $\lambda_k=0$. Under (II) we have to prove that $$p(t):=\sum_{k=0}^N\lambda_k\>t^k\equiv0\tag{1}$$
implies $\lambda_k=0$ for all $k$. A quick proof is
$$\lambda_k={1\over k!}\>p^{(k)}(0)=0\qquad(0\leq k\leq N)\ .$$
A more algebraic proof would set up an induction as follows: $(1)$ implies $\lambda_0=p(0)=0$ and therefore
$p(t)=t\>p_1(t)$ with
$$p_1(t)=\sum_{k=0}^{N-1}\lambda_{k+1}t^k\>\equiv0\ .$$
The induction hypothesis then guarantees $\lambda_1=\lambda_2=\ldots=\lambda_N=0$.
Answer: Let's give our polynomial a name: define $p(t)=\sum_{k=0}^nc_kt^k$. We are assuming $p(t)=0$ for all real $t$, and we want to show that $c_0=\ldots=c_n=0$. Now note that
$$p(t)=c_0+c_1t+c_2t^2+\ldots+c_nt^n$$
We know that the left hand side is zero for all real $t$. In particular, it must be true when $t=0$, so substituting $t=0$ into the right hand side we find
$$0=p(0)=c_0+c_1\cdot0+\ldots+c_n\cdot0^n=c_0$$
Hence our polynomial is now
$$0=p(t)=c_1t+c_2t^2+\ldots+c_nt^n=t(c_1+c_2t+\ldots+c_nt^{n-1})$$
So either $t=0$ or $c_1+c_2t+\ldots+c_nt^{n-1}=0$. This implies $c_1+c_2t+\ldots+c_nt^{n-1}=0$ for all $t\neq0$, but by taking the limit as $t\to0$, it must be true at $t=0$ too! This follows from the continuity of polynomials. Now we just repeat this procedure until we have shown every $c_i=0$. An induction proof would probably be more rigourous, but I think at this level "repeat until there are no $c_i$'s left" is sufficient.
But why does this show $S$ is independent? As you pointed out, $S$ is infinite whereas we only looked at the first $n$ terms. However addition is only really defined on finitely many terms; if you have some topology you can sometimes define infinite sums but in the general vector space case this is not possible. So, the only sensible definition of $S$ being independent is that every finite sum of $S$ is independent. If we have a finite subset $F\subset S$, then in particular there is a largest $n$ such that $\mu_n\in F$. Hence the above argument applied for that particular $n$ shows $F$ is independent, and thus by definition (and the fact $F$ was an arbitrary finite subset) we find that $S$ is independent.
Comment: I'm still a little confused about setting t = 0. All that seems to follow is that IF $t$= 0, then all $c_i$'s must = 0. Don't we need to show that for all $t$, $c_i$ = 0.
Comment: The $c_i$'s are constant - they do not depend on $t$! So for these *constant* values $c_0,\ldots,c_n$ it is true *for all* $t$ that $c_0+\ldots+c_nt^n=0$. In particular, this is true when $t=0$, so we MUST have $c_0=0$. The reason we evaluate at zero is to eliminate all terms but one.


How botmaster use Domain Generating Algorithms (DGA)?

Question:
Domain Generation Algorithms(DGAs) are used in malware to generate a large number of domain names that can be used in communications to the malware's command and control servers
For example, an infected computer could create thousands of domain names such as: www.(gibberish).com and would attempt to contact a portion of these with the purpose of receiving an update or commands. - Wikipedia

But my question is we need to buy and register a domain name before we want to use. Then how hacker can generate 10 Thousand of domain name ? and use them ?
Answer: A security administrator would need to block all domain names that are generated by the algorithm, wether they are registered or not.
The hacker on the other hand would only register and use a single or a few domain names out of the range that get generated by the algorithm.  Depending on wether or not the bot tries to connect to every domain the DGA provides, or just a random section of those generated domains (limiting the footprint of the bot and reducing the risk of getting detected),  the hacker can either control either a large number or only a small percentage of the infected machines.
Comment: Domains generated typically depend on the date or a part of it, so the bot has few to try and the master can register those needed few days before, and so on...
Comment: So you mean, attacker register a single or few domain name from registrar and create thousands of fake domain name using DGA algorithm.
and the infected machine will connect to the attacker's valid domain ?
If that happens then security admin can easily detect that only a single domain replys from all of those thousand domain. Then it wouldn't  be hard to catch that malicious domain. but I heard attacker use DGA algorithm for delaying detection purpose. can you explain me in details ? thanks


What test can i use for this hypothesis? It has a continous variable and a categorical variable

Question: I have two variables
Financial literacy- It's a continuous variable with high and low scores
Default(It means to Not pay their loan)- Yes or no (I can code this as 0 and 1)
What test can I use to test this hypothesis?

Customers with high scores in Financial Literacy default less as
compared to customers with low scores on Financial Literacy
Answer: You can fit a logistic regression and test whether the regression parameter of the Financial Literacy is zero.
https://en.wikipedia.org/wiki/Logistic_regression


Unable to find php8.0-fpm.sock in /run/php/php8.0-fpm.sock, Nginx Web Server

Question: I'm currently listening for TCP sockets in my Nginx Web Server, but for some reasons I'd like to listen to my UNIX-domain sockets. The issue is I'm unable to find php8.0-fpm.sock in both /var/run/php/php8.0-fpm.sock and /run/php/php8.0-fpm.sock paths. When I run ls /run/php, it shows only php8.0-fpm.pid.
systemctl status php8.0-fpm confirms that it is installed and running correctly:
php8.0-fpm.service - The PHP 8.0 FastCGI Process Manager

     Loaded: loaded (/lib/systemd/system/php8.0-fpm.service; enabled; vendor pr /php8.0-fpm.service; enabled; vendor preset: enabled)

     Active: active (running) since Sat 2021-10-30 03:03:54 EDT; 20min ago

       Docs: man:php-fpm8.0(8)

    Process: 282214 ExecStartPost=/usr/lib/php/php-fpm-socket-helper install /run/php/php-fpm.sock /etc/php/8.0/fpm/pool.d/www.conf 80 (code=exited, status=0/SUCCESS)

   Main PID: 282200 (php-fpm8.0)

     Status: "Processes active: 0, idle: 2, Requests: 7, slow: 0, Traffic: 0req/sec"

      Tasks: 3 (limit: 4621)

     Memory: 67.5M

     CGroup: /system.slice/php8.0-fpm.service
             ├─282200 php-fpm: master process (/etc/php/8.0/fpm/php-fpm.conf)

             ├─282212 php-fpm: pool www

             └─282213 php-fpm: pool www

Oct 30 03:03:54 127.0.0.1localhost systemd[1]: Starting The PHP 8.0 FastCGI Promd[1]: Starting The PHP 8.0 FastCGI Process Manager...

Oct 30 03:03:54 127.0.0.1localhost systemd[1]: Started The PHP 8.0 FastCGI Procmd[1]: Started The PHP 8.0 FastCGI Process Manager.

Answer: Try to find it with.
find / -name "*fpm.sock"

Comment: you can change the fpm socket location by changing the ```lesten``` file path in ```/etc/php/8.0/fpm/pool.d/www.conf```
By default the listen is set to ```lesten=/run/php/php8.0-fpm.sock```
Comment: Strangely they are on `/etc/alternatives/php-fpm.sock` and
`/var/lib/dpkg/alternatives/php-fpm.sock`? Should I use one of those?
Comment: Was there any dramatic change in PHP 8.0, that I'm missing?
Answer: You can choose it :

netstat -pluntx |grep php

Option -x in netstat is looking for all socket listen


LD_PRELOAD does not work as expected

Question: Consider the following library which can be preloaded before any program execution:
// g++ -std=c++11 -shared -fPIC preload.cpp -o preload.so
// LD_PRELOAD=./preload.so <command>
#include <iostream>

struct Goodbye {
    Goodbye() {std::cout << "Hello\n";}
    ~Goodbye() {std::cout << "Goodbye!\n";}
} goodbye;

The problem is that, while the constructor of the global variable goodbye is always called, the destructor is not called for some programs, like ls:
$ LD_PRELOAD=./preload.so ls
Hello

For some other programs, the destructor is called as expected:
$ LD_PRELOAD=./preload.so man
Hello
What manual page do you want?
Goodbye!

Can you explain why the destructor is not called in the first case?
EDIT: the above question has been already answered, that is a program might well use _exit(), abort() to exit.
However:
Is there a way to force a given function being called when a preloaded program exits?
Comment: Note that you are using fairly high-level functionality here: `std::cout` is a buffering stream that is synchronized with the stdio streams. It may well be that `ls` does something at exit that disrupts this mechanism. What happens if you use `::write(2, "Goodbye\n", 8);` instead?
Comment: R.. has answered your second question but *not* your first question.  It is *not* possible to force a function to be called no matter what, because of `_exit` and `abort` and various other "abnormal program termination" mechanisms whose contract includes that they *don't* execute any destructors, `atexit` functions, etc.  However, I find it implausible that `/bin/ls` would normally exit that way, so there is still a mystery as to why your preload module's destructor isn't getting run.
Comment: [This question](http://stackoverflow.com/questions/2204608) seems to indicate that the destructor should *always* be called. Can you do some more research to narrow down what types of programs end up calling the destructor and which ones do not?
Comment: What do you mean by "type"? I cannot seem to find a way to distinguish "good" programs from "evil" programs. Note that the problem happens also when the return code is 0 (no error, no abort())
Comment: Try writing a preload module in C, using GCC's `__attribute__((constructor))` to run a function on startup; have that function use `atexit` to register a function to run on teardown.  Does that behave differently?  (It *shouldn't*, but it might.)
Comment: Also, since we are in "potential implementation bug" territory here, it would be very helpful to know the OS, and the exact version of GCC and of the C library.
Comment: @Martin OK, in that case edit the output of `g++ --version` and of `/lib/ld-linux.so.2 $(find /lib -name libc.so.6 -print | head -1)` into the question.  DO NOT attempt to remove any apparently irrelevant information from the output of these commands.
Answer: ls has atexit (close_stdout); as its initialisation code. When it finishes, it closes stdout (i.e. close(1)), so your cout, printf or write(1, ... operations will not print anything. It doesn't mean destructor isn't called. You can verify this by e.g. creating a new file in your destructor.
http://git.savannah.gnu.org/cgit/coreutils.git/tree/src/ls.c#n1285 here is the line in GNU coreutils ls.
It is not just ls, most of coreutils do that. Unfortunately, I don't know exact reason why they prefer to close it.
Side note on how this could be found (or at least what I did) - may help next time or with program with no source code access:
Destructor message is printed with /bin/true (simplest program I could think of), but isn't printed with ls or df. I started with strace /bin/true and strace /bin/ls and compared latest system calls. It shown close(1) and close(2) for ls, but none for true. After that things started to make sense and I just had to verify that destructor is called.
Comment: I did a little more digging based on your results: it appears that this is done in order to detect write failures on `stdout` before it's too late to exit unsuccessfully.  Unfortunately, the definition of `close_stdout` is hiding over in gnulib, but the comments there are pretty clear: http://git.savannah.gnu.org/cgit/gnulib.git/tree/lib/closeout.c#n83
Comment: Oho!  Would you mind adding a link to the source repository so we can all see this for ourselves?
Answer: If the program exits via _exit (POSIX) or _Exit (C99) or abnormal program termination (abort, fatal signals, etc.) then there's no way destructors could be called. I don't see any way around this.
Comment: Why would `/bin/ls` do that?
Comment: That's a good guess, but http://lingrok.org/xref/coreutils/src/ls.c ends in `exit (exit_status);` (OP specified right now he's on linux)
Comment: @Zack, why would `/bin/ls` *not* do that? Unless there are external side-effects required for graceful shutdown (like on-disk data structures need updating or network messages sent to say "bye") why not just `_exit`? There is no need to `free()` the last few blocks if the whole heap is about to go away.
Comment: @Ben I know it looks like just one character of difference, but as a matter of idiom, `_exit` is *unusual*. It's a thing you only use if you have a specific reason you need it. `exit` / return from `main` are the normal way to end a program in C and it would be surprising for a basic utility like `ls` to be abnormal in this way.  Also, if `ls` used `_exit` it would need to manually flush `stdout`.
Comment: @Ben (Note that `exit` does *not* deallocate the `malloc` heap piece by piece.)
Comment: Note to editors: If you're editing an answer to add links to some of the interfaces mentioned, link to authoritative sources like the C standard or at least some sort of C documentation rather than a C++ site.
Answer: Like others said, a program might call via _exit(), _Exit() or abort() and your destructors won't even notice. To solve these cases you could override these functions by just writing a wrapper like the following the example below:
void
_exit(int status)
{
    void (*real__exit)(int) __attribute__((noreturn));
    const char *errmsg;

    /* Here you should call your "destructor" function. */
    destruct();

    (void)dlerror();
    real__exit = (void(*)(int))dlsym(RTLD_NEXT, "_exit");
    errmsg = dlerror();
    if (errmsg) {
        fprintf(stderr, "dlsym: _exit: %s\n", errmsg);
        abort();
    }

    real__exit(status);
}

But this wouldn't solve all the possibilities of a program escaping without your library's knowledge, because those are not the only exit points an application could have. It could also trigger the exit system call via the syscall() function and to avoid it you would have to wrap it too.
Another way a program could exit is by receiving an unhandled signal, so you should also handle (or wrap?) all signals that could trigger the death of a program. Read the signal(2) man page for more information but please be aware that signals like SIGKILL (9) cannot be handled and an application could destroy itself by calling kill(). With that being said and unless you don't expect to handle insane applications written by crazy monkeys you should wrap kill() too.
Another system call you'd have to wrap is execve().
Anyway, a system call (like _exit) could also be triggered directly via an assembly int 0x80 instruction or the obsolete _syscallX() macro. How'd you wrap it if not from outside the application (like strace or valgrind)? Well, if you expect this kind of behaviour in you programs I suggest you drop the LD_PRELOAD technique and start thinking about doing like strace and valgrind do (using ptrace() from another process) or creating a Linux kernel module to trace it.
Comment: This is clever, but when programs call `_exit` or `abort` they do it because there's some concrete and compelling reason why destructors, `atexit` functions, and so on *should not* be run.  For instance, on the child side of a `fork`, if `execve` fails, it's critical to use `_exit` so that I/O is not flushed twice.  A library should not be second-guessing the application about that sort of thing.
Comment: ... **no**, the lesson I wanted you to draw from my comment is *not* "you need to wrap `execve` as well", it was "this is the *bad* kind of clever."
Comment: ... **no**? What do you mean by that? Do you think I don't know this is a horrible hack? It's pretty obvious it is ugly. I added `execve` to the list just because I should, not because I didn't understood what you commented.
Comment: Downvoter: care to explain? I'm answering the last question of the OP **AND** giving a minimal and working example.

LD_PRELOAD does not work as expected


HTML list elements won't list horizontally?

Question: Basically I'm trying to make a web coding tutorial site (awesome that i cant do it myself right). For the life of me I can't figure out why my list items wont list horizontally instead of vertically.
See the jsFiddle.
Comment: +1 for posting a fiddle, -1 for the blind leading the blind.  Please develop more expertise before publishing tutorials.
Answer: It's because you have a width: 100px set on your #menu selector, which is crunching that box down to only allow for one element per line. Just remove it.
Comment: Thanks. cant believe it was so simple -_-
Answer: Fixed here jsfiddle
#menu {
    width: 600px;                   <-- changed from 100px to 400px
    height: 15px;
    position: relative;
    color: #999999;
    margin: 0px auto;
    float:left;                       <-- new
}

Answer was updated. The container element should be wide enough to accomodate all element horizontally.
Answer: change the menu width 100px in to 100% it's work
here my output:
  http://jsfiddle.net/srinivasan/XmhqW/


How to put multiple fields in an index operation on a GET HTTP request with services?

Question: I'm working with the module "services" everything's ok with a get request, note that i've create my own custom resource with CRUD operations, the "retrieve","update" are ok but the problem is with the index operation. With only one field it works and show all records with the default field I declared on resource. Now how to put an array of $fields ?
This is the resource declaration (the "fields" part of the code) :
array(
        'name' => 'fields',
        'optional' => TRUE,
        'type' => 'string',
        'description' => 'The fields to get.',
        'default value' => 'field_title_value',
        'source' => array('param' => 'fields'),
      ),

now here is the function index (callback) :
function _my_module_livre_index($page, $fields, $parameters, $page_size){

$query = db_select('field_data_field_title','t');

services_resource_build_index_query($query, $page, $fields, $parameters, $page_size, 'Livre');
$result = services_resource_execute_index_query($query);

$bien = services_resource_build_index_list($result, 'livre', 'field_title_value');
return array('code'=>'0', 'response'=>$bien);
}

The doc of services said that $fields is an array of fields i want to return, when i make :
$fields = array('field 1','field 2','field 3');
It return an error. If I make a "classic" :
$query = db_select('my table')
->fields('my table', array('field 1','field 2','field 3')

Same error.
Any help please ?
Thank you all.
Comment: "It return an error" - what error, exactly? And if you will edit your question, please try make your title a question, too.
Comment: God i'm confused It was an error that i've solved before what I wanted to ask is : how to make joins and display fields from different tables on an index operation (with tables that i've joined) this is my question. I think I'll answer this one, and re-answer another question. Thank you Molot and sorry again.
Comment: Nothing to be sorry about. And self-answers are good thing :)
Answer: The simple db_select with fields make it work easy as that :
function _my_module_livre_index($page, $fields, $parameters, $page_size){

$query = db_select('field_data_field_title','t')
->fields('t', array('field_title_value','entity_id','delta'));//<+++++ whatever you want

services_resource_build_index_query($query, $page, $fields, $parameters, $page_size, 'Livre');
$result = services_resource_execute_index_query($query);

$bien = services_resource_build_index_list($result, 'livre', 'field_title_value');
return array('code'=>'0', 'response'=>$bien);
}


"print()" não apresenta os elementos da lista inseridas

Question: Por que a instrução abaixo não funciona? Ele apresenta a última nota, e não a lista com todas as notas.
jnotas = int(input("quantas notas você já tem = "))

for c in range (0, jnotas):
    notas1 = []
    n = float(input("entre com sua nota = "))
    notas1.append(n)

print(notas1)

Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver pontuação suficiente).
Answer: Você está iniciando a lista dentro do laço, então toda vez que passa por ali a lista é zerada, só guarda o último elemento digitado.
quantidade = int(input("quantas notas você já tem = "))
notas = []
for c in range (0, quantidade):
    notas.append(float(input("entre com sua nota = ")))
print(notas)

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: muito obrigado ! tenho que prestar atenção a essas coisas !
Answer: Como já foi respondido anteriormente você está inicializando a lista dentro do laço for. Desta forma, a cada iteração do for os elementos da lista são sobrescritos. O correto é você implementa a lista fora do for, tal como no código abaixo...
jnotas = int(input("quantas notas você já tem = "))

notas1 = []
for c in range(0, jnotas):
    n = float(input("entre com sua nota = "))
    notas1.append(n)

print(notas1)

Agora, se você deseja dar mais legibilidade ao seu código, você pode implementar o seguinte código abaixo...
quant_notas = int(input('Desejas inserir quantas notas? '))

notas = list()
for c in range(1, quant_notas + 1):
    n = float(input(f'Entre com sua {c}ª nota: '))
    notas.append(n)

print(f'\033[32mAs notas digitadas são: {notas}\033[m')

Veja aqui o funcionamento do algoritmo.
Outra coisa, se você deseja exibir cada valor por linha e sem exibir os colchetes, você pode utilizar este código...
quant_notas = int(input('Desejas inserir quantas notas? '))

notas = list()
for c in range(1, quant_notas + 1):
    n = float(input(f'Entre com sua {c}ª nota: '))
    notas.append(n)

for nota in notas:
    print(f'\033[32m{nota}')

Veja aqui o funcionamento do algoritmo.
Se ao invés disso, você desejar exibir os elementos da lista em uma só linha, separados por vírgula e sem delimitadores colchetes, você pode utilizar o seguinte código...
quant_notas = int(input('Desejas inserir quantas notas? '))

notas = list()
for c in range(1, quant_notas + 1):
    n = float(input(f'Entre com sua {c}ª nota: '))
    notas.append(n)

print(f'\033[32mAs notas são:')
for nota in notas:
    print(f'{nota}', end='')
    print(', ' if nota < notas[-1] else '. ', end='')

Veja aqui o funcionamento do algoritmo.
Se for o caso, de você querer reduzir a quantidade de linhas de códigos, você pode utilizar o próximo algoritmo. Neste algoritmo, você terá que digitar todos os valores na mesma linha e separados por um espaço.
quant_notas = list(map(float, input('Insira aqui todas as notas separadas por um espaço: ').split()))
print(f'\033[32mAs notas são: {quant_notas}\033[m')

Se você deseja exibir os elementos da lista em uma só linha, sem vírgulas ou pontos e sem delimitadores colchetes, podes utilizar este algoritmo...
quant_notas = list(map(float, input('Insira aqui todas notas separadas por um espaço: ').split()))
print('A notas são: ', *quant_notas)

Agora, se desejas exibir cada valor por linha, com um determinado espaçamento temporal, podes implementar o seguinte algoritmo...
from time import sleep

quant_notas = int(input('Desejas inserir quantas notas? '))

notas = list()
for c in range(1, quant_notas + 1):
    n = float(input(f'Entre com sua {c}ª nota: '))
    notas.append(n)

cont = 0
for nota in notas:
    cont += 1
    sleep(0.4)
    print(f'\033[32mA {cont}ª nota é: {nota}')

Veja aqui o funcionamento deste algoritmo.


Exercício deveria mostrar um resultado mas mostra 3

Question: Um algoritmo que leia 3 valores inteiros, não repetidos, e mostre em ordem decrescente. Porém ele está mostrando 3 resultados, e deve ser só 1
package praticando;

import java.util.Scanner;

public class Exercicio2 {

    public static void main(String[] args) {

      Scanner valor = new Scanner(System.in);

        System.out.println("Digite o primeiro número: ");
        int A = valor.nextInt();

        System.out.println("Digite o segundo número: ");
        int B = valor.nextInt();

        System.out.println("Digite o terceiro número: ");
        int C = valor.nextInt();

        if (A == B || B == C || A== C) {
        System.out.println("Existem números repetidos!");
    }
         if (A > B & A > C) { //A é o maior
            } if(B > C){
              System.out.println(+A+" -> "+B+" -> "+C);
            } else {
              System.out.println(+A+" -> "+C+" -> "+B);
        }

          if (B > A & B > C) { //B é o maior
            }  if(A > C){
              System.out.println(+B+" -> "+A+" -> "+C);
            } else {
              System.out.println(+B+" -> "+C+" -> "+A);
        }

        if (C > A & C > B) { //C é o maior
        } if(A > B){
              System.out.println(+C+" -> "+A+" -> "+B);
         }else{
              System.out.println(+C+" -> "+B+" -> "+A);
        }

    }

}

Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: Tem algumas coisas esquisitas no código. Acho que queria usar && e não &. E não entendi porque faz um if que abre e fecha sem executar nada ali. Resolvido isto funciona perfeitamente. Se tivesse indentado corretamente perceberia que tem algo errado. Eu sempre falo que capricho ao escrever o código é importante, mas em geral muita gente ignora, acha que tem algum ganho escrever de qualquer jeito, quando é o oposto. Veja como caprichado fica mais fácil ver o erro, pegue o seu código e organize melhor.
import java.util.Scanner;

class Exercicio2 {
    public static void main(String[] args) {
        Scanner valor = new Scanner(System.in);
        System.out.println("Digite o primeiro número: ");
        int A = valor.nextInt();
        System.out.println("Digite o segundo número: ");
        int B = valor.nextInt();
        System.out.println("Digite o terceiro número: ");
        int C = valor.nextInt();
        if (A == B || B == C || A == C) {
            System.out.println("Existem números repetidos!");
        }
        if (A > B && A > C) { //A é o maior
            if (B > C) System.out.println(A + " -> " + B + " -> " + C);
            else System.out.println(A + " -> " + C + " -> " + B);
        }
        if (B > A && B > C) { //B é o maior
            if (A > C) System.out.println(B + " -> " + A + " -> " + C);
            else System.out.println(B + " -> " + C + " -> " + A);
        }
        if (C > A && C > B) { //C é o maior
            if (A > B) System.out.println(C + " -> " + A + " -> " + B);
            else System.out.println(C + " -> " + B + " -> " + A);
        }
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Tem como otimizar isto, mas não vou mexer nesta parte, é bem simples, fica de exercício.
Comment: Você deve abrir e fechar onde faz sentido para o que deseja. Eu respondi o que perguntou, se tem outros erros deveria estar na pergunta ou fazer nova pergunta, mostrando o erro, detalhando o problema.
Comment: Está retornando uma e eu demonstrei isso.
Comment: Olá, quanto a indentação, peço desculpas, estou aprendendo. Na questão do if, achei que era necessário fechar um if{} para abrir outro, obrigado por esclarecer isso. A questão principal é que
Comment: ...sim, ele está rodando. O problema é que está me mostrando 3 resultados. 2 incorretos
Comment: Pois foi exatamente o que eu perguntei da primeira vez, caro amigo. Porque está retornando 3, ao invés de uma resposta. A correta.
Comment: Obrigado por sua ajuda.


Create new column based on other columns from a different dataframe

Question: I have 2 dataframes:
df1
Time   Apples   Pears   Grapes   Peachs
10:00    3       5        5        2
11:00    1       0        2        9
12:00    20      2        7        3

df2
Class   Item   Factor
A       Apples   3
A       Peaches  2
A       Pears    5
B       NaN      4

I want to create a new column in df2 called Total which item at 10:00 in df1, multiplied by the Factor for that item - this should only be done if they are in Class A.
This is how the final df should look
df2
Class   Item   Factor   Total
A       Apples   3        9
A       Peaches  2        4
A       Pears    5        25
B       NaN      4

This is what I tried:
df2['Total'] = df1.setIndex().cols.isin((df2.Item) and (df2.Class==A)) * df2.Factor

Comment: Please break down the calculations, they are currently ambiguous
Comment: just like @mozway said. Like how is the total for apple 9
Comment: Apologies, have just corrected. Total for Apples should be 9 as it is = Apple (at 10:00 AM) x Factor = 3x3 = 9
Comment: Have also corrected the description
Answer: IIUC this will get you the desired output (This does not include the np.nan from df2 where it == b, but I don't think you wanted that)
df_melt = df1.melt(id_vars = ['Time'])
df_melt.columns = ['Time', 'Item', 'Count']
df2 = df2.loc[df2['Class'] == 'A']
df_merge = pd.merge(df2, df_melt)
df_merge['Total'] = df_merge['Factor'] * df_merge['Count']
df_merge

Answer: You could use df1 as a lookup table:
df2['Total'] = df2[df2['Class']=='A'].apply(
      lambda x, **kwd: df1.set_index('Time').loc[kwd['tgt_time'],x['Item']]*x['Factor'],
          axis=1, tgt_time='10:00')

  Class     Item  Factor  Total
0     A   Apples       3    9.0
1     A  Peaches       2    4.0
2     A    Pears       5   25.0
3     B      NaN       4    NaN

(To make this work I had to change the column name from Peachs to Peaches in df1)


Is there more to probability than Bayesianism?

Question: As a student in physics, I have experienced the "Why I am a Bayesian" lecture perhaps half a dozen times.  It is always the same -- the presenter smugly explains how the Bayesian interpretation is superior to the frequentist interpretation allegedly employed by the masses.  They mention Bayes rule, marginalization, priors and posteriors.
What is the real story?
Is there a legitimate domain of applicability for frequentist statistics? (Surely in sampling or rolling a die many times it must apply?)
Are there useful probabilistic philosophies beyond "bayesian" and "frequentist"?
Comment: I think this is a perfectly reasonable physics question.  Experimental physicists are obsessed with bayesian statistics and use them daily.  I want to know "what else is out there" and whether it is also useful to an (experimental) physicist.  P.S. What's up with this immediate, do-not-pass-go closure?  I thought there was "vote to close (N votes needed)".
Comment: @nibot: I agree with David, it's a stats question albeit one of interest to physicists. But also of interest to biologists, psychologists, and a great many other ists. The one-vote close is because David is a moderator (note the "♦").
Comment: Also see this previous question on the distinction between frequentist and bayesian reasoning http://stats.stackexchange.com/questions/22/bayesian-and-frequentist-reasoning-in-plain-english
Answer: The Bayesian interpretation of probability suffices for practical purposes.  But even given a Bayesian interpretation of probability, there is more to statistics than probability, because the foundation of statistics is decision theory and decision theory requires not only a class of probability models but also the specification of a optimality criteria for a decision rule.  Under Bayes criteria, the optimal decision rules can be obtained through Bayes' rule; but many frequentist methods are justified under minimax and other decision criteria.
Answer: "Bayesian" and "frequentist" aren't "probabilistic philosophies". They're schools of statistical thought and practice concerned mainly with quantifying uncertainty and making decisions, although they're often associated with particular interpretations of probability. Probably the most common perception, although it is incomplete, is that of probability as subjective quantification of belief versus probabilities as long-run frequencies. But even these aren't really mutually exclusive. And you may not be aware of this but there are avowed Bayesians who don't agree on particular philosophical issues about probability.
Bayesian statistics and frequentist statistics aren't orthogonal either. It seems like "frequentist" has come to mean "not Bayesian" but that's incorrect. For example, it's perfectly reasonable to ask questions about the properties of Bayesian estimators and confidence intervals under repeated sampling. It's a false dichotomy perpetuated at least in part by a lack of a common definition of the terms Bayesian and frequentist (we statisticians have no one to blame but ourselves for that).
For an amusing, pointed and thoughtful discussion I would suggest Gelman's "Objections to Bayesian Statistics", the comments, and the rejoinder, available here:
http://ba.stat.cmu.edu/vol03is03.php
There is even some discussion about confidence intervals in physics IIRC. For more in-depth discussions you could walk back through the references therein. If you want to understand the principles behind Bayesian inference, I would suggest Bernando & Smith's book but there are many, many other good references.
Answer: Take a look at this paper by Cosma Shalizi and Andrew Gelman about philosophy and Bayesianism. Gelman is a proeminent bayesian and Shalizi a frequentist!
Take a look also at this short criticism by Shalizi, where he points the necessity of model checking and mock the dutch book argument used by some Bayesians.
And last, but not least, I think that, since you are a physicist, you may like this text, where the author points to "computational learning theory" (which I frankly know nothing at all), which could be an alternative to Bayesianism, as far as I can understand it (not much).
ps.: If you follow the links, specially the last one and have an opinion about the text (and the discussions that followed the text at the blog of the author)
ps.2: My own take on this: Forget about the issue of objective vs subjective probability, the likelihood principle and the argument about the necessity of being coherent. Bayesian methods are good when they allow you to model your problem well (for instance, using a prior to induce unimodal posterior when there is a bimodal likelihood etc.) and the same is true for frequentist methods. Also, forget about the stuff about the problems with p-value. I mean, p-value sucks, but in the end they are a measure of uncertainty, in the spirit of how Fisher thought of it.
Comment: links 2 and 4 are dead, here are their cached versions (pretty funny read) https://web.archive.org/web/20100715084606/http://cscs.umich.edu/~crshalizi/weblog/664.html and https://web.archive.org/web/20100630162751/http://yolanda3.dynalias.org/tsm/ae_bayes.html
Answer: For me, the important thing about Bayesianism is that it regards probability as having the same meaning we apply intuitively in everyday life, namely the degree of plausibility of the truth of a proposition.  Very few of us really use probability to mean strictly a long run frequency in everyday use, if only because we are often interested in particular events that have no long run frequency, for example what is the probability that fossil fuel emissions are causing significant climate change?  For this reason, Bayesian statistics are much less prone to misinterpretation than frequentist statistics.
Bayesianism also has marginalisation, priors, maxent, transformation groups etc. that all have their uses, but for me the key benefit is that the definition of probability is more appropriate for the kinds of problems I want to address.
That doesn't make Bayesian statistcs better than frequentist statistics.  It seems to me that frequentist statistics are well suited to problems in quality control (where you do have repeated sampling from populations) or where you have designed experiments, rather than analysis of pre-collected data (although that lies rather beyond my expertise, so it is just intuition).
As an engineer, it is a matter of "horses for courses" and I have both sets of tools in my toolbox and I use both on a regular basis.
Answer: There are non-Bayesian systems or philosophies of probability -- Baconian & Pascalian, e.g. If you are into epistemology & philosophy of science you might enjoy the debates--otherwise, you'll shake your head & conclude that in fact the Bayesian interpretation is all there is.
For good discussions,

Cohen, L.J. An introduction to the philosophy of induction and probability, (Clarendon Press ;
Oxford University Press, Oxford
New York, 1989)
Schum, D.A. The evidential foundations of probabilistic reasoning, (Wiley, New York, 1994).


Is this code wrong to call the same constructor more than once

Question: The object that is created by the constructor in the following code can be called multiple times. Have I written the code badly by doing so I hope it is written to the proper conventions
import java.util.Scanner;
/**
 * this class uses the scanner to take input from the keyboard
 * test if the input is a variable of type double if it is store in a
 * variable called numOne then take next input test again for type double
 * store in variable numTwo, then add the two variables together in the form
 * of variable answer and return to the screen. The user then is asked for
 * continuation as Y/N then appropriate action is taken
 */

public class Calc {

    /**
     * this constructer does not throw InputMismatchException
     */

    public Calc() {
    Scanner in = new Scanner(System.in);  // create scanner object

        System.out.println("please enter 1st "
            + "number then press enter"
                + "\nthen enter 2nd number then "
            + "press enter again");

        /*test for a double returns true */
        boolean myBool = in.hasNextDouble();

        /*the actual test for a double*/
        if(myBool == false) {
                System.out.println("wrong format");

           /**
            * call constructer and instantiate as new object
            * by creating a new object i hope to have overwriten
            * the original object stored in memory there by getting
            * around the problem of hasNextDouble not allowing the
            * scanner to advance
            */

                Calc c = new Calc();

        } else {                   // 1st else
                double numOne = in.nextDouble();       // keyboard input

            /*test for a double returns true */
                boolean myBool2 = in.hasNextDouble();

        /*the actual test for a double*/
        if(myBool2 == false) {
                System.out.println("wrong format start again");

           /**
            * call constructer and instantiate as new object
            * there by removing need for InputMismatchException
            */

                Calc c = new Calc();

        } else {                   // 2nd else
                double numTwo = in.nextDouble();       // keyboard input

                double answer = numOne + numTwo;       // the maths

        for(int i = 0; i<35; i++) {            // print pattern
                System.out.print("*");
        }
        System.out.println("\n****  "
            + "Your 1st number is "
            + numOne + "   ****");

        System.out.println("****     "        // print operator
            + "                   " + "+"
            + "   ****");

        System.out.println("****  "
            + "Your 2nd number is "
            + numTwo + "   ****");

        System.out.println("****     "       // print line
            + "               ______  ****");

        System.out.println("****       "
            + "The answer is "
            + answer + "   ****");

        for(int i = 0; i<35; i++) {         //print pattern
                System.out.print("*");
        }
        System.out.println("\nDo you have "
            + "more calculations Y or N");

        String reply = in.next();                //keyboard input

        if(reply.equalsIgnoreCase("Y")) {
                Calc c = new Calc();
        } else {
                System.out.println("OK bye then");
                in.close();             //close scanner
        }               //end else
        }   // end 1st else
        }   // end 2nd else
        }   // end constructor

    public static void main(String[] args) {
        Calc c = new Calc();            // call constructor
    }  // end main
}    // end class

// just in case i do something wrong thanks in anticipation  Simon.

Comment: Please put more effort into formatting your code. It's all over the place at the moment... then put in some more effort to ask a question. You've included a *lot* of code, but only talked generically about "the object that is created by the constructor" - which object? Which constructor?
Comment: It seems like a pretty horrible idea.  I don't know that it's technically "wrong," but I think a lot of folks would call it wrong in production code.
Comment: If we ignore the infinite loop, the question is: Why the entire program is inside the constructor? WTF. The constructor should be used to create the object, not to execute the program.
Comment: Hi guys I am fairly new to any type of coding and I do appreciate the input from every one.Now @Jon Skeet could you be more specific in your comment as to all over the place as this would be of great help to me and others, also could you point out all the other constructors as I genuinely thought there was only one 'public Calc()' being called by 'new Calc()' first by the main method and 2 more times if and only if the user did not enter a double.
Comment: @Marco Acierno could you please point out the infinite loop as I do not honestly see one also could you elaborate on program execution as I thought this was done by the main method I put it in a constructor so I could call it from another class could you show me how to make it into a method please.
Comment: `Calc c = new Calc();` is potentially a infinite loop which will remains all the `Calc` objects uninitialized. And, your entire logic inside the constructor (BAD) Just move it in the main method and use constructor to initialize fields
Comment: @SimonRemington: Look at the indentation of the code - specifically, the first few lines of the constructor. `Scanner in...` isn't indented... whereas the next statement *is* indented, by 4 spaces. Elsewhere things are indented by 8 spaces. (If you're using tabs, please don't for SO - it doesn't work well.) Basically, it's up to you as the person asking the question to make the code as readable as possible... and ideally as *short* as possible to demonstrate the problem, while remaining complete.
Answer: Calling the constructor from within the same constructor, and without any parameters, looks like a sure way to get infinite loop and stack overflow. So, yes, it's wrong.
And since it doesn't look as if you are doing anything with all the instances of Calc that you create within the constructor, it's pointless.
Comment: Hi Eran the reason I recall public Calc(), if a user does not enter a double I could not get past .hasNextDouble as the scanner did not seem to advance the input. So I created a new object and started again please point out the possible loop.
Comment: @SimonRemington It doesn't make sense to put all this code in a constructor at all, since you are not really constructing an object, you are just getting inputs from the user and print some outputs. I'd put all this code in a static method. And instead of the recursive calls, put all the code in a while loop - `boolean needInput=true;while (needInput) {}`. Inside the loop, in any place you currently call the constructor, replace it with `continue`, which would proceed to the new iteration of the loop. set `needInput` to false when you which to quit the program.
Answer: It is usually seen as bad practice to do any work in a constructor that is not directly related to instantiating that object. Consider moving your logic into another method on the Calc. That way you can use a single instance of Calc, and using fields on that instance you might have better luck overwriting the values your comments mention that you want to overwrite.
As Eran mentioned, your current pattern uses recursive calls, which are prone to stack overflows if not done right. I wouldn't go so far as to say recursive calls are always a bad thing, but you should carefully consider whether that's the best pattern for what you're doing.
Comment: hello StriplingWarrior thank you for your input, in your opinion is the logic correct? and is there another way to make the scanner advance past .hasNextDouble. The reason behind the logic is that I read it is better to write code that does not throw errors than to rely on catching them.
Comment: @SimonRemington: developers will often use a loop to accomplish what you're describing: `while(true) { if(!in.hasNextDouble()){ outputNoNumberError(); break; } double numOne = in.nextDouble(); ... }`. As to whether the logic is correct, I'm not familiar with what your requirements are, and I don't feel like analyzing dozens of lines of code. That's not the purpose of this site.
Answer: Although you (probably) won't get an error, this is bad practice in many ways.
First of all, you should not do any of this in a constructor. A constructor is supposed to create an object or throw an Exception, that's it. If the constructor requires any input, read it in advance and pass it as an argument to the constructor. Constructors are not made for user interaction.
The next point is error handling. If the user makes an invalid input, there is absolutely no need to use recursion. Sure, you won't get a StackOverflowError (unless your user fails a few thousand times), but a loop is a better solution.
System.out.print("Enter a double please: ");
while(!scanner.hasNextDouble()) {
    System.out.print("Invalid input. Please try again: ");
    scanner.next(); //discard invalid input
}
double input = scanner.nextDouble();

Comment: J4v4 can you elaborate on your loop please, as when I compile the one that you have posted, it only produces an endless loop for me when I do not enter a double or is this a humorous way of creating a StackOverflowError. Please show me this loop so I do not get an InputMismatchException thank you
Comment: @Simon Remington I'm sorry, I'm not familiar with scanner so I didn't use the methods correctly. I looked it up now and fixed it.


chord voicing with arpeggiations and inversions

Question: This question is in two parts.
A) Assume the rules of 4-part harmony. Should the first note of an arpeggio be the one that is included in the chord for best sonority? For example, we are told, with regard to doublings, to double the root first.  In that case, would the following situation not be ideal (please see below)?

Or, because the listener must only wait one quarter note (see arpeggio in tenor) is this acceptable? In other words, technically speaking, should the arpeggio start with the most ideal chord tone (double the root first, then the fifth next. Try not to double the third)?
B) Regarding the voicing of chords in inversion, is the "root," third," and "fifth" the same as those if the chord were in root position? If a C major chord is in first position, when we are voicing the chord do we call the C the root? Or, because we've inverted the chord, is the E the root? Any information/tips on the voicing of chords in inversion is appreciated.
Comment: May I ask: Is this example a practical problem or a construction of a test situation? The "arpeggio" is in the tenor. So is it given, and are the other parts given or can you change them? So is the question: should the arpeggio begin with c or g or could it begin with e?
Comment: This is a test situation.  The other parts can change.  You are correct--the question is where do I begin the arpeggio
Comment: Are your A and B section the _actual_ wording of the test question? What is the test question?
Comment: My apologies—I thought you meant test situation as in "hypothetical". No, this is not a test. Just the questions I posed
Answer: A) Should the first note of an arpeggio be the one that is included in the chord for best sonority?
How you voice a chord is essentially up to your taste (unless your professor demands otherwise). If you are following a set of voice-leading rules/counterpoint/etc, then default to those as your guidelines. With regard to doublings, plenty of rules exist depending on the context (counterpoint, block chords, orchestration, etc). However in your specific example, doubling root between the bass and tenor is (in my estimation) more an issue of clarity. If you had put the 3rd of the chord (here, E) in the tenor's lower register, it could be considered a bit of a muddy voicing as it would be close to the bass's C in the lower register. Choosing the voicing that effectively outlines the harmony (or voice leading) you want for a specific passage is part of the craft. If you're writing an exercise, try to follow the rules. If you're writing your own music, try follow your ears, and always remember to listen carefully.
B) Regarding the voicing of chords in inversion, is the "root," third," and "fifth" the same as those if the chord were in root position?
Yes. A C major triad will always contain the notes C, E, and G, precisely because that it is how it is (essentially) defined[*]. What you mean to look for is the bass note, which is simply the lowest sounding note in the chord/sonority. So if you had (from bottom to top) the notes G E C E, it would still be a C major triad (because it contains the pitch classes C, E, and G and nothing else) but in second inversion (because the bass note is its fifth, G). In fact, both chords spelled G E C and G C E (spelling bottom to top) are in second inversion precisely because they have the G (again, C's fifth) in the bass. (An E in the bass is first inversion, meaning its third is in the bass). The spelling beyond that is a question of voicing as opposed to inversion.
[*] A major triad is, from root up, a major third to the next note followed by a minor third to the final note. Starting on C, this yields the notes C, E, and G together.
Comment: Thank you for the great response. Regarding part B, my question is specifically how to voice chords in inversion.  For example, should a C major chord with four voices in first inversion be spelled E-G-C-E (doubling the "root?") or E-C-G-C (doubling the "root?" I suppose the crux of my question is: is the bass tone the same as the root of the triad?
Comment: In your response to part A, you mention rules for block chords.  Where can I learn more about this?
Answer:
Should the first note of an arpeggio be the one that is included in the chord for best sonority?

Your wording  - "the one that is included in the chord" - is confusing to me. I sounds like you are asking about non-chord tones like a suspension, but I don't think that is your intent. I think you mean something like "should it be a tone that will complete the full voicing of all chord tones?"
The first beat of a bar is most important. I would say you want the chords on the first beat to be the essential harmony notes fulfilling good harmony.
With chord tones C E E given in the other voices the G is missing from a complete chord, it seems the question is "should the missing voice (which will sing the arpeggiated chord) start on G to provide the missing chord tone on the first beat and then the other arpeggiated tones can fall on less essential beats?"
If you want nice balance chord with full, sonorous chords: I think yes.
C would seem to be the next best starting choice - not ideal because then the chord will be incomplete on the first beat.
E would be a bad starting choice, because the chord will be poorly balanced with too much emphasis on the chord third.

Regarding the voicing of chords in inversion, is the "root," third," and "fifth" the same as those if the chord were in root position?

Yes.
Those chord tone identities are relative to the root as pitch classes above the root in close position.
Pitch class just means all C's like C3, C4, C5... are members of pitch class C.
That's kind of a wordy description. Basically, if you take all the given tones, rearrange them by octave transposition to be stacked up in thirds, the first tone is the root with 35d, 5th, etc above the root:
C E G = C root, E third, G fifth
...rearrange the tones to another inversion and spacing like E C G and it maintains the  same chord tone identities...
E C G = E third, C root, G fifth
Comment: Amazing response! You hit the nail on the head—thank you!!
Answer: If this question is just one of practice there would be 2 rules to consider:

sustaining the common tone of 2 chords = keeping in the same voice: e.g. the third in the soprano
the rule about doubling priority (root, 5th, 3rd)

So if this is not an exam task you can just ignore the point of doubling or like you say:

because the listener must only wait one quarter note (see arpeggio in tenor) is this acceptable?

yes, it is
(Even in a test situation you can ignore it - but you should  point this out to to tell them that you are aware of it. You can double the 5th aswell as the root and the third in the octave will be ok too.)
And if the soprano is not given you can handle it to fulfill the rules.)
Your second question concerning the root: yes the root note is the note on which the thirds are built and that gives the name to the chord.
That's why the other chord positions are called inversions: then the root tone isn't the bass note. As the third is in the bass it's a sixth chord (I6) because of the interval of 6th between bass tone and root (= 1. inversion). Look up: chord inversions.


linear regression is part of PCA but also an extention to it...(Truth or Bluff)

Question: The question I'd like to ask is what is the correlation of regression and PCA.
From my understanding the correlations of a factor and its constituent variables is a form of linear regression – multiplying the x-values with estimated coefficients* produces the factor's values**

are they called factor loadings?
are they called factor scores

And ,

my most important question is can you perform (not necessarily linear) regression by estimating coefficients for the factors that have their own now constant coefficients)
Answer: seems I found my answer at:
https://pdfs.semanticscholar.org/f7d6/bdbd63f784ef9badb087e9235f62fb74a5e9.pdf
After having understood that factor scores are a sumproduct of factor loadings(coefficients) and observations all you need to know to use FA or PCA in combination with linear Regression is on that paper...
except, maybe, if non-linear regression on the factors is possible(meaningful)


PHP-FPM Chroot jail corrupts timezone db?

Question: I'm trying to setup a PHP-FPM Chroot jail on a new CentOS 6.3 box. I can get the chroot to work fine, in the sense that I can get php scripts to respond and echo things out. But, every time I use the date function, I get an error saying the timezone db is corrupt.
All I've done is changed the value of the chroot directive in php-fpm conf, to be the document root as specified in nginx.
This is the test script:
https://gist.github.com/3199578
this is the nginx vhost
https://gist.github.com/3199552
Here's the output I get when I go to localhost
https://gist.github.com/3199602
Answer: do you have copy of TZ stuff inside the chroot folder ?
<code>/etc/localtime
</code>
-and-
<code>/usr/share/zoneinfo
</code>
to
<code>/chroot/path/etc/localtime
</code>
-and-
<code>/chroot/path/usr/share/zoneinfo
</code>
also maybe add
add TZ=CST  (or whatever your TZ is) in the nginx config
details here: http://wiki.nginx.org/CoreModule#env
Comment: Thanks! putting the /etc/localtime and zoneinfo worked..
Comment: copy? isn't a mount better?


Range of values of $k$ for which $\frac{x-2}{x^2-5x+k}$ is unrestricted

Question: Given that $$ f(x) = \frac{x-2}{x^2-5x+k}$$ and that $x$ is real, find: the range of values of $k$ such that the range of $f(x)$ is $\mathbb{R}$.
I attempted this question, by aiming to produce a sketch. Sketching the graph in it's current form doesn't seem very feasible. Therefore, I flipped the function. Examining $\frac{1}{f(x)}$. The reason for that is producing a sketch of a function is usually simple if you can sketch the reciprocal.
$$ \frac{1}{f(x)} = \frac{x^2-5x+k}{x-2} = (x-3)+\frac{k-6}{x-2} $$
From here, I noted that when $k = 6$, $\frac{1}{f(x)} = x-3$. Hence $f(x) = \frac{1}{x-3}$. Clearly in this case $f(x)$ is unrestricted.
However, I had trouble examining the cases of when $k > 6$ and when $k < 6$. I don't know how to produce sketches for those cases or an alternative way to go about solving for those cases. Would appreciate some guidance.
Comment: "The solution in my textbook includes $k=6$ as a solution" Then, the question your textbook asks is different from "Find the range of values of $k$ such that the range of $f(x)$ is $\mathbb{R}$".  Can you write the given solution in your textbook?
Comment: Think of the negative discriminant.
Comment: What do you mean by "the value of $f(x)$ is unrestricted"? That the image/range of $f$ is $\mathbb R$?
Comment: @hamam_Abdallah Thanks for the reply. I've seen some solutions to these types of problems that examine the discriminant. But I don't understand what the discriminant would suggest in such cases. My understanding of the discriminant is that it may be used to determine the number of solutions a quadratic equation will have. $b^2-4ac\geq0$ 2 solutions and $b^2-4ac<0$ means two complex solutions.
Comment: @themathandlanguagetutor Yes, that's correct
Comment: Then your conclusion is incorrect for $k = 6$ because $0$ is not in the range of $f$.
Comment: When $k=6$, you can't get 0.
Comment: The solution in my textbook includes $k=6$ as a solution. Perhaps there is another meaning for the term 'unrestricted'?
Comment: Could "unrestricted" mean "unbounded"?
Answer: First, let's handle a special case, when $k=6$, the denominator vanishes at $x=2$, $f$ can't take value $0$. We clearly have the condition that  $k \ne 6$.
For $r$ to be attainable, we need $x$ such that
$$\frac{x-2}{x^2-5x+k} = r$$
$$x-2=rx^2-5rx+kr$$
$$rx^2-(5r+1)x+kr+2=0$$
Hence using discriminant, we would want $$(5r+1)^2-4r(kr+2) \ge 0$$
That is we would want to pick $k$ such that the inequality holds for all $r$.
$$(25-4k)r^2+2r+1 \ge 0$$
For this to hold for all $r$, we need $25-4k > 0$ (for convexity) and $4-4(25-4k) \le 0$ (discriminant).
That is $k < \frac{25}4$ and $1 \le 25-4k$. Along with $k \ne 6$, we conclude that $k < 6$.
Comment: Hello. I follow your solution until fourth line, namely $(5r+1)^2-4r(kr+2) \ge 0$. My understanding of the discriminant is that it may be used to figure out for what range of values we can get our desired solutions. So in this case, solving the inequality would tell us when we have 2 real solutions to our quadratic equation in the third line. How does solving this inequality let us infer the values for which our function maps to the reals?
Comment: That is a quadratic inequality. If the leading terms is positive, then it is convex and not linear, and if the discriminant is non-positive, then the quadratic function is nonnegative.
Comment: I understand your reasoning for solving the quadratic inequality and arriving at $ k < 6$. But why did you use the discriminant in this case? That is $b^2-4ac \ge 0$ and how did it give us the correct range of values for which our function $f(x)$ maps to reals?
Comment: I use discriminat twice actually, for the first time where the variable is $x$, I obtain $(25-4k)r^2+2r+1 \ge 0$. For this to hold, I look at the quadratic inequality with $r$ being the variable, we want the discriminant to be non-positive, in that case, the convex quadratic in $r$ doesn't cut the horizontal axis twice, ensuring nonnegativity.
Answer: If you know how to analyse the behaviour of the graph of a rational function near roots and vertical asymptotes, you can use this to your advantage. First, note that $2$ is a single root of the function whenever $x - 2$ is not a factor of the denominator (i.e. whenever $k \neq 6$). Further, whenever the denominator has two distinct real roots, there are two vertical asymptotes. If $(2, 0)$ is between them, since $2$ is a single root, the function is positive on one side of $x = 2$ and negative on the other, and since there are vertical asymptotes on each side, you get a range of $\mathbb R$. There are still more cases left, but see if that can't get you started.
Comment: I'm not sure I follow you--the range can't be $\mathbb{R}$ due to the asymptotes, right? It's $\mathbb{R}$ minus $x = r, s$ where $r,s$ are the two roots of the denominator. Have I learned this/remembered this wrong?
Comment: The range is the set of *outputs*.
Comment: /facepalm. Yes, of course it is. I know that. My brain was not braining when I commented, apparently.


Sending an e-mail through MATLAB using Microsoft Outlook

Question: I am using the function found at the following blog: https://uk.mathworks.com/matlabcentral/answers/94446-can-i-send-e-mail-through-matlab-using-microsoft-outlook to send e-mails from my Outlook account from the MATLAB editor. It indeed works, and I can also include attachments or pictures etc.
My question is whether it is possible to send a result of another MATLAB function saved and run at the same directory. I tried calling the function like that :
<code>sendolmail('email_address','Subject included',result of a function);
</code>
When I run this, a mistake is returned. It seems as if only strings or attachments from my computer can be sent through the function. Any ideas on how results of functions can be added and sent?
Comment: @matlabgui you forgot to say "D'uh!" :p
Comment: save the results to a file and/or image.
Answer: No, it's all in HTML format, so you have to save the results to a file or convert the output to an HTML formatted output (could just be a string).


Understanding the relationship between R0, doubling time, and the epidemic curve

Question: New to infectious disease epidemiology here and am just trying to understand some basics. I've read basic texts on SIR esque compartmental models. However, I'm struggling to understand how to align that theory with the numbers I see on the news every day regarding COVID.

Firstly, I'm confused as to how the $R_0$ value relates to the doubling time. Is there a direct mathematical relationship between the two?
I see a lot of epidemic curves on the news, which plot the number of new cases over time. For these epidemic curve, in many countries like Germany, you've seen them reduce the number of new cases over time. Here is an example from the Robert Koch Institute:
 In these cases, if you see an decrease in the number of new cases day over day (but still non-zero new numbers of cases), can the $R_t$ still be $> 1$?
Answer: The basic reproduction number $R_0$, and effective reproduction $R_t$ are parameters in a simplified model. It represents how many other people are being infected by a person that it infected.
With a detail that $R_0$ is the case for reproduction in a population that is fully susceptible. If people become immune due to vaccinations, due to early encounters with the disease, or maybe they just don't get hit without those, then the effective reproduction will be less than the basic reproduction.

Firstly, I'm confused as to how the $R_0$ value relates to the doubling time. Is there a direct mathematical relationship between the two?

In the beginning, when nobody is immune, then the effective reproduction is equal to the basic reproduction. Say $R_0 = 2$ then the first sick person will infect 2 other people, those 2 will infect 4 other people, those 4 will infect 8 other people, those 8 will infect 16 other people and so on (this is an simplified model, in reality it is not so deterministic and the growth is less homogeneous).
So the infection grows with a factor $R$ each generation, but how fast it grows depends on how fast a generation passes on the virus. This will differ from disease to disease. With respiratory disease (influenza, common cold, SARS/Corona) this goes fast, but with a sexual transmittable disease this is much slower (because people do not have, on average, so many contacts during which the disease transfers).
When people are estimating the value $R_0$ then they use the growth rate, in combination with the time between generations (or a more complex combination of parameters, like incubation time, time of duration of infectious period, time between successive infection moments, etc.). An example computation is in the very similar question here https://stats.stackexchange.com/a/461251/164061
The $R_0$ is relevant, aside from the growth rate (or the doubling time which is just the inverse of growth rate), because it relates to the amount of people that need to be immune before the virus stops spreading/stabilized. The effective reproduction, $R_t$, number is the basic reproduction number multiplied with the fraction of people that are susceptible (not immune).
If this effective reproduction number is below 1 then the spread stabilized/reduces, because each next generation will be smaller than the previous generation. (This is actually not true in general, and only in the simplified model. In reality the reproduction is heterogeneous, and if the average basic reproduction, multiplied with fraction susceptible, is below 1 then there might still be a sub population where contact and spreading is still relatively high and increasing spread of the virus can still occur).

In these cases, if you see an decrease in the number of new cases day over day (but still non-zero new numbers of cases), can the Rt still be >1?

The growth rate is equal to
$$(R_t-1) \frac{1}{t_{generation}}$$
$R_t$ is for the number of people that get infected by a sick person, $-1$ is for the person that get's better after infections $R_t$ people (and so the net change is $R_t-1$), and $t_{generation}$ is for how long it takes between generations.
So in the simplistic view: yes, you get a decrease (negative growth rate) if $(R_t-1)$ is negative.
In reality the curves behave less ideal and relate to biased measurements (e.g. the one that you show has peaks every Sunday/Monday due to sampling variations, even when it is corrected from date of reporting to date of onset of symptoms).
So decreases might be due to that bias (changes in sampling and reporting). Also the virus may have spread to other parts in the society where sampling is done less actively (the $R_t$ and $R_0$ values assume homogeneous situation which is not realistic).
Also a decrease might be due to random irregularities. The spread goes in waves (due to inhomogeneous growth as function of time and space, effects of weather, population density and composition where the spread currently resides, and variations in timing of events that increase/decrease spreading).
The curve from the Robert Koch institute shows a strong decrease, so I would consider that the reproduction is below 1. But when it becomes above 1 then it takes a while before the numbers pick up. The getting sick, onset of symptoms, and date of reporting are not the same. So there is a delay. So that is a (theoretical case) that numbers are decreasing while the reproduction is above 1.
Also, theoretically you could have a reproduction above 1 but a change in the time between generations. In such a situation you can get a decreasing number while the reproduction is still above 1. This is however not very practical (it may occur when the virus evolves into something that stays longer).
It is not likely for respiratory diseases, but the case of sexual transmittable diseases could relate to this because people are infectious over a long period. Then say, a virus like AIDS may cause initially many cases because of people having lots of sexual contacts, and reduced contacts (in response to the disease) may decrease the cases, but it can be still that the reproduction is above 1. In this case of STD's you also have that generations overlap. A person that got a next person sick might still be sick and continue making other people sick.
Answer: I stated and proved a theorem that links Rt to the curve of infections. It's here:
https://www.medrxiv.org/content/10.1101/2021.01.24.21250405v2