ARIMA MODEL DEGREE OF FREEDOM PROOF

Question: According to arima(p,0,q) model if we have n data and our total parameter is p+q then it is said that degree of freedom is n-(p+q). Could you mathematically demonstrate it? No sufficient information on internet and books.
Regards;
Answer: The degrees of freedom in a model is the number of obervations minus the number of parameters to be estimated. So, there is nothing to be proven because it's a definition.
Comment: I do not think this is the definition of degrees of freedom. The notion of degrees of freedom is more complicated than that. There are models/techniques where this does not hold, e.g. k nearest neighbours (see James et al. "Introduction to Statistical Learning" and/or [nearest neighbors degrees of freedom](https://stats.stackexchange.com/questions/50379/nearest-neighbors-degrees-of-freedom)). If I remember correctly, ridge regression would be another example. @mertcan
Comment: But this situation can be explained mathematically in multilinear regression model using idempotent matrix. Are you sure that there is no proof that ARIMA(p,0,q) model has n-p-q degree of freedom?
Comment: I do not only want to memorize arıma model degree of freedom is n-p-q. Could you help me understand via mathematical proof?
Comment: Hi:IIRC,  the idempotentcy proof in multiple regression proves the unbiasedness of the estimate of sigma squared in multiple regression.  But that's  still defining the dof as number of samples - number of parameters estimated. In the arima case, the degrees of freedom is not used to prove unbiasedness so I'm not clear on what you're asking.
Comment: I believe there must be  analytical proof that ARIMA(P,0,Q) has n-p-q degree of freedom. Otherwise it has no meaning actually. I just would like to proofs. Could you help me?
Comment: Hiu: Unfortunately, there is no proof, whether it be regression or time series. The imdempotency result you are referring to ( which is used in the proof ) is used to prove that the formula for the estimate of $\sigma^2$
is unbiased. Look in any decent regression or time series book. There won't be a proof because the dof is DEFINED that way.
Comment: [in the link](https://stats.stackexchange.com/questions/24921/distribution-of-sum-of-squares-error-for-linear-regression/400261?noredirect=1#comment749409_400261) there is no proof related to unbiasedness instead using idempotent matrix sum of squared errors divided by $sigma^2$  is chi square dist. with n-p-1 degree of freedom. Actually there is a derivation of degree of freedom of chi square distribution using idempotency. What would you say about that?
Comment: Hi: That's a proof that, assuming normaility of the error term,  the SSE in a multiple regression is chi squared with  n-(p+1) degrees of freedom.. it's not proving that the degrees of freedom in a regression model  is n-(p+1). They ( the chi squared dof and a model's dof )  are two TOTALLY DIFFERENT THINGS. I honestly don't mean to be rude but if you take an upper level class in mathematical statistics, you will understand what that proof is used for and what the difference is. That's also where you will  prove the unbiasedness of the estimate of $\sigma^2$.
Comment: Hi Richard: What I described is how I learned it ? I'm definitely no expert with degrees of freedom ( I always found it confusing ) so I won't comment one way or the other except to say that there may be multiple definitions. Thanks for comment.
Comment: This showed up in review as low quality; I agree with @RichardHardy that degrees of freedom is deeper than "that's just how it's defined." There is a very readable article available as pdf by Helen Walker caleld simply "Degrees of Freedom" that goes into the reasons why degrees of freedom are as they are in linear models.
Comment: I'll check it out. I took the question from the OP to mean "how do I prove that the degrees of freedom is n - (p+q) in an arma(p, 0, q)". I don't think that it's possible to prove it but still her article could be enlightening.  thanks.

ARIMA MODEL DEGREE OF FREEDOM PROOF


Is there a module to hide URL path settings by content type?

Question: Eg. I'd like to let the client see the URL path settings fieldset for Page but not for Slide.
I'm happy to implement it myself, just wondered if someone else already had.
Answer: I don't believe there is anything out there at the moment (perhaps my search wasn't extensive enough either), but you can hide the URL path settings fieldset yourself easily with one line of code:
<code><?php $form['path']['#access'] = FALSE; ?>
</code>
Answer: Here's a sandbox module to automate Laxman13's answer for fieldsets in general (including URL path settings).
Comment: That might be a good feature to add to the [Override Node Options](http://drupal.org/project/override_node_options) module, as I don't believe it currently supports that.


Fixing datatype error in oracledb from Python ORA-01790

Question: I have the following code:
data = [1,2,None,4,5,6]
sql = """
SELECT :1 AS ID, :2 AS pkey, :3 AS issuenum FROM dual  UNION ALL
SELECT :4 AS ID, :5 AS pkey, :6 AS issuenum FROM dual
"""

cur = con.cursor()
cur.execute(sql, data)
data = cur.fetchall()

I gen an error DatabaseError: ORA-01790: expression must have same datatype as corresponding expression
If i run it with data = [1,2,3,4,5,6], it all passes.
From the error it seems, it doesn't like the missing value. My question is, how do I bid the statement so that I can select NULL value, where the None is in the list?
Comment: Does it help to use named placeholders, like in this insert problem: https://stackoverflow.com/questions/33080170/python-oracle-inserting-none-error ?
Answer: This is a SQL issue and nothing specific to the driver. You can fix this issue by issuing the following statement instead:
SELECT :1 AS ID, :2 AS pkey, to_number(:3) AS issuenum FROM dual
UNION ALL
SELECT :4 AS ID, :5 AS pkey, to_number(:6) AS issuenum FROM dual

This will ensure that the data type is number for both rows. In Python the value None has no type so the driver assumes the value is a string.
You can also work around this issue in the driver by issusing the following command prior to executing the SQL:
cur.setinputsizes(
    oracledb.DB_TYPE_NUMBER,
    oracledb.DB_TYPE_NUMBER,
    oracledb.DB_TYPE_NUMBER,
    oracledb.DB_TYPE_NUMBER,
    oracledb.DB_TYPE_NUMBER,
    oracledb.DB_TYPE_NUMBER,
)

This forces the driver to treat all of the bind values as number, including the value None.


2 axes scrolling tiled "map" view (TiledScrollView)

Question: I'm trying to create a tiled close-up map view that scrolls along both axes, with 3 zoom levels, similiar to the iOS CATiledLayer.  The map is for a very small space, with points of interest separated by feet rather than miles, so a google maps application wouldn't work.  Imagine a floorplan of an individual building.
I found this: https://github.com/ened/Android-Tiling-ScrollView, which initially looked like exactly what I wanted, but haven't had any success with it.  There are notes in the source that it's a "Library Project", which I've never used (I'm fairly new to Android development).  If I try to import it, Eclipse complains that it's not a project file.  If I build a new project from existing source, it is listed as a Library project but then many other errors appear (several errors complain about attributes - I can't remember the exact wording).
Has anyone had any success with the library linked above?  If not, are there any gotchas I should be aware of as regards Library projects in general?  Searching on Library projects yielded a little documentation, but none of the approaches I found worked with that particular library specifically.  Does a Libary project need to exist relative to the project using it in a specific way (e.g., does it need to be nested)?
TYIA
Answer:
Create a new Android project.
Copy all the java files from sample and library folders src to your new project src folder.
Similarly copy all other resources like assets, xml files etc to new project.
You are done!.
Comment: thanks - I actually figured this one out a while ago but forgot to close this question.


How to create popup for email link with major email provider links?

Question: Check out this new feature craigslist implemented. WHen you click on this button (like in the link below) that says "reply to this post", it pops up with this popup that shows the different email providers options (for web browsers, and local clients like Outlook).

How can this be done for Drupal?
Answer: First take a look here. Lots of JQuery plugins that integrate with Drupal.
I think Lightbox best fit here but check the rest. It provides a pop-up overlay similar to Craigslist's
I myself don't have any experience with these but since no one has answered thought I could try point you somewhere useful.
I did a quick search and also found these that could lead somewhere:
<code>http://www.lullabot.com/articles/announcing-beautytips-jquery-tooltip-plugin
http://www.jquerypopup.com/
</code>
Anyway, I hope those hints helps you in some way.
Answer: Please look in to this, it explains the same https://community.openatrium.com/documentation-en/node/2286


computed field with product variation and content type

Question: Using Commerce Kickstart 2 distribution :
Question 1: Where should the computed field go to access fields from both the Content Type and Product Variation? Does the computed field belong to the content type or to the product variation?
Question 2: How do you reference one from the other?
ie - I thought...
$field_my_gauge = field_get_items($entity_type, $entity, 'field_needle_guage');
$field_my_type = field_get_items($entity_type, $entity, 'field_needle_type');
$field_my_st = field_get_items($entity_type, $entity, 'field_needle_style');
$field_my_len = field_get_items($entity_type, $entity, 'field_needle_length');
$vari_l = taxonomy_term_load($field_my_len[0]['tid']);
$vari_g = taxonomy_term_load($field_my_gauge[0]['tid']);
$vari_t = taxonomy_term_load($field_my_type[0]['tid']);
$vari_s = taxonomy_term_load($field_my_st[0]['tid']);
$vari_result =  $vari_l->name . $vari_g->name . $vari_t->name . $vari_s->name;
$vari_result = preg_replace('/[\s,.]{1,}/', '', $vari_result);
$entity_field[0]['value'] = $vari_result;

buuuut...
Notice: Trying to get property of non-object in eval() (line 9 of /Users/Robert/Sites/devdesktop/country_yarns/modules/computed_field/computed_field.module(468) : eval()'d code).

$vari_g is, or should, be based on the field_needle_guage field. But this is in the product variation of Needle, and not in the content type of Needle. All other fields are in the content type and work correctly.
So what's the right way to access members of a product variation in the content type - or is that even the right way around? (See Q1)
[EDIT]
Ok, so looking at the objects available in the wrapper:
$wrapper = entity_metadata_wrapper($entity_type, $entity);
// field_product_node is documented as the automatically created backreference to the content type.
$product = $wrapper->field_product_node;

// DrupalCommerce Kickstart 2 documentation says the below should work, but it does not - 'error: can't find getProduct function'. (WHY?)
$wrapper->getProduct();

// This comes out as an EntityDrupalWrapper
dpm($wrapper);
// This comes out as an EntityListWrapper
dpm($product);

// but below fails - can't find getIterator on object (WHY??)
$plist = $product->getIterator();
// and below returns an empty array!
$plitems = $product->value();

So all these auto-back-reference class things in DrupalContrib are not accessible in this manner, it seems. If they work, I'd love to find out how!
Looking at how the tables are set up: field_revision_field_product is the link table between 'commerce_product' 'commerce_product_revision' and 'node', and any particular field_data_field_XXX field data table.
So I guess I need to use a sql query to get the field_data_field_XXX value through an inner join. I guess I'll need to put that into a custom module and then make a field of that type that allows you to configure what field to grab from the CT
Comment: When displaying content the product fields "push through" to the content type so that you can show variation-level product attributes. What purpose does the computed_field serve? What are you really wanting to do?
Comment: The code shows what I'm trying to do. I need to use a computed field to have a summary field to describe the product as a cumulation of the various components. You never see the product by the individual components. You would only see the product based on the computed summary value. So.... How do I access the product variation fields if they 'push through'?
Comment: The field in the variation is field_needle_guage. How do I fix this line to access the product variation? $field_my_gauge = field_get_items($entity_type, $entity, 'field_needle_guage');
Comment: I see some people mention entity_metadata_wrapper('commerce_product', YOUR-REQUIRED-PRODUCT-ID); - but how to get required product ID? Also tried $wrapper = entity_metadata_wrapper('node', $node);
dsm($wrapper->getPropertyInfo()); to see the properties, but it doesn't understand 'node'... Notice: Undefined variable: node in eval()  -- I'm just a bit green on this...obviously
Comment: It shows you're trying to build a string... but you aren't mentioning what your intention is for using that string. You have to remember that at it's core Commerce doesn't just do a single product to many product variations. You can have PVs that are related to several different products (content nodes). If you have information that is definitional to what a PV is and you want that to be shown as part of the product then that field should be on the PV. If you only care about displaying it, that information can be on the PV but you're better of using theming to display the appropriate values.
Comment: So then, with your logic (thank-you) I need to create the computed field in the variation. That makes more sense. In that case, from the product variation's point of view, how do I access the Content Type fields?
Comment: @nvahalik You're not being helpful and side-stepping the issue. It's doesn't matter what the intention is for using the string. I'm not going to explain my product to you. You said that it makes more sense to have the generated string in the PV, and I get that. So, if you don't know how to access CT fields from the PV, that's ok, but then don't pollute this thread. I'm asking a simple question and looking for a simple solution. I guess I have to look elsewhere.
Comment: That's fine. Just trying to help. Your question is a common one and there is no "simple solution". Your options are to properly model the data onto the PVs or just handle it in the theme layer.
Comment: That still doesn't answer the question - I am trying to access CT fields from PV - so how do I do that?
Answer: To clarify from the comment thread:

This is a question that is tough to answer on SE because it's just something you'll have to feel out. If you're doing 1:1 content types to product displays, it doesn't really matter where you put it (though it'd probably be easier to do it on the CT) in general I tend to put more on PV because it's data related to the product. If you're doing 1:N then you'll definitely want to put it on the PV and if you're doing M:N then you're going to have to do some customization.
You can put the computed field on the PV but you'll need something like Entity Backreference so that the PV has a link back to the content type so you can load it and grab it's fields.
Comment: Finding it hard to find an example of how to use that module...do you have a link?
Comment: have you ever used any back reference module? Do you have a code snippet you can share? I can't see how to use them
Comment: This is a dead end - I see no hope here as I can't find a single example


Implementar um botão de curtir em PHP e mysqli

Question: Estou tentando implementar um botão de curtir em um sistema que estou criando de teste. Ele já altera o valor da curtida no banco de dados, porém eu tenho que colocar o valor num campo input que coloquei. Então a cada número que eu coloco no input e clico em curtir ele faz o update no meu banco de dados. Gostaria de saber como faço para não precisar de inserir o valor no input e a cada vez que eu clicar ele somar mais um número no valor que já tem no banco de dados. Eis o código:
Index.php
<?php

  require_once "conecta.php";

  $resultado = mysqli_query($conexao, "select * from curtida");
  $curtida = mysqli_fetch_assoc($resultado);
?>

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>Curtir</title>
  <link rel="stylesheet" href="css/claudina.css" />

   <form action="envia_curtir.php" method="post">
   <input type="number" name="curtida" />
   <button class="icones icone-polegares-para-cima"></button>
   <?=$curtida['curtidas'];?>
    </form>

enviar_curtir.php
<?php

  require_once "conecta.php";
  require_once "funcoes.php";

  $curtida = $_POST['curtida'];

  curtir($conexao, $curtida);

  header("Location: index.php");

?>

funcoes.php

<?php

  function curtir($conexao, $curtida) {

    $query = "update curtida set curtidas= $curtida";

    return mysqli_query($conexao, $query);
  }

Answer: Você pode simplesmente alterar o update:
function curtir($conexao, $curtida) {

    $query = "update curtida set curtidas = curtidas + 1";

    return mysqli_query($conexao, $query);
  }

Comment: Muito obrigado!


How do I change the used PHP version?

Question: I am using Drush to update modules.
When I run the command php -v it correctly shows I am running version 5.5
I then use the command drush rf followed by drush up to perform any updates.
I am using the Schema.org Metatag module which requires php version 5.
The website is running php version 5.5.37
The default CLI version on Hostgator shared server is 5.4.45.
That is what I was originally using for drush. When I received the message below I found the path to use php 5.5 but I am still getting the same message.
So I can't figure out how it still sees php ver 5.4.45 and how to resolve this so it doesn't keep disabling that module.
When Drush runs an update I get the following message:
Schema.org Metatag requires at least PHP 5.5. (Currently using PHP   [warning]
5.4.45)
And then it disables the Schema Metatag module.
NOTE:
When I run command drush status:
PHP configuration: opt/php55/lib/php.ini
Drush version is 8.1.11
Thanks
Extra information
.bash_profile
PATH=$PATH:$HOME/bin
export PATH
alias composer="/opt/php55/bin/php ~/bin/composer.phar"
alias drush="/opt/php55/bin/php ~/.composer/vendor/bin/drush.php"

.bashrc
 alias php='/opt/php55/bin/php'
 alias composer='/opt/php55/bin/php ~/bin/composer'
 export DRUSH_PHP='/opt/php55/bin/php'

php -v returns PHP 5.5.37
which php doesn't return anything
drush status returns PHP configuration /opt/php55/lib/php.ini

But, when I use Drush to update a module I still get: Schema.org Metatag requires at least PHP 5.5. (Currently using PHP [warning] 5.4.45)
Answer:
Find the path to php 5.5's binary.
Find the path to drush.

Execute
/path/to/php_55/bin/php /path/to/drush status

Comment: @Jimmy Drush doesn't source .bash_profile or any other/equivalent when it executes. Anything you have in there is pretty much irrelevant to Drush.
Comment: My .bash_profile
PATH=$PATH:$HOME/bin
export PATH
alias composer="/opt/php55/bin/php ~/bin/composer.phar"
alias drush="/opt/php55/bin/php ~/.composer/vendor/bin/drush.php"

My .bashrc
alias php='/opt/php55/bin/php'
alias composer='/opt/php55/bin/php ~/bin/composer'
export DRUSH_PHP='/opt/php55/bin/php'

When I run following commands
php -v
PHP 5.5.37
which php
doesn't return anything
drush status
PHP configuration
/opt/php55/lib/php.ini

But, when I use Drush to update a module I still get: Schema.org Metatag requires at least PHP 5.5. (Currently using PHP [warning] 5.4.45)
Comment: @Jimmyk if you go to the status page, what php version does Drupal say it's using?
Comment: When you say status page you mean the command drush status? For PHP configuration: /opt/php55/lib/php.ini so that must mean PHP 5.5 But the version of Drush I am using is 8.1.11 Is that only 5.4? Does that mean I need to update Drush version?
Comment: Status page in your site. Log in then go to Reports > Status Page. Drush should be using 5.5 per your comment and the `DRUSH_PHP` var. I can only think that Drupal may be using a different one, 5.4.45. The drush and Drupal versions can be different.

How do I change the used PHP version?


Finding $[\mathbb{Q}(\sqrt{3}, i\sqrt{2}):\mathbb{Q}(\sqrt{3})]$

Question: I am very new to field extensions, so I am very sorry for this basic question.
I want to determine the degree of the field extension
$$[\mathbb{Q}(\sqrt{3}, i\sqrt{2}):\mathbb{Q}(\sqrt{3})]$$
So my problem now is that I dont know what the minimal polynomial could look like. I have only dealt with field extensions of a single element over a "normal" field such as $\mathbb{Q}$.
Help is very much appreciated!
Answer: The extension is generated by a single element $i\sqrt{2}$, so the extension degree is just the degree of the minimal polynomial of $i\sqrt{2}$ over $\mathbb{Q}(\sqrt{3})$. First of all note that $i\sqrt{2}\notin\mathbb{Q}(\sqrt{3})$ because $\mathbb{Q}(\sqrt{3})$ is a field which contains only real elements. So the extension degree can't be $1$, it is at least $2$. Also, it is easy to see that $i\sqrt{2}$ is the root of the polynomial $x^2+2\in\mathbb{Q}(\sqrt{3})[x]$, so the extension degree is also at most $2$. Hence it is exactly $2$.


Linked Lists and Trees - text book

Question: Does anyone know of a great book on Trees (binary, quad trees, etc...) in C++ that would start off nice and gentle, and then gets into serious code?
I need to improve my knowledge of advanced topics, like linked lists and trees...
Thank you,
Answer: Knuth's The Art of Computer Programming is the seminal book on many datastructures, but is in assembly and not C++. I still recommend it, though, as its coverage of the ideas themselves is beyond compare.
Answer:
Data Structures and Algorithms in C++
by Michael T. Goodrich, Roberto Tamassia, David M. Mount
C++ Plus Data Structures
by Nell Dale
C++, object-oriented data structures
by Saumyendra Sengupta, Carl Phillip Korobkin
Data Structures and Algorithm Analysis in C++
by Weiss, Weiss Mark Allen

You can buy any book of above. But I suggest the last one is good.

Linked Lists and Trees - text book


Question involving injective modules

Question: Let $A$ be an algebra such that every ideal is a direct summand of $A$. Show that every $A$ module is injective.
$\textbf {My attempt:}$
Let $I$ be an ideal of $A$, considere another ideal $J$, since $J$ is direct summand of $A$ there exists $N$ such that $A = J \oplus N$.
Now, if we have a morphism $v: J \to I$ then the inclusion $j: J \to A = J\oplus N$ defines a morphism $w:A \to I$ s.t $w$ restricted to $J$ is equal to $v$. By Baer's criterion, we have $I$ injective.
So far we've shown that every ideal of $A$ is injective. Now, let $M$ be a finitely generated module, that is, $M = \langle m_1,m_2, \dots, m_n \rangle$, then $\psi: A^n \to M$ given by $\psi(a_1,\dots,a_n) = m_1a_1+ \cdots+m_na_n$ is epimorphism. Since $I$ is injective the follow short exact sequence splits
$$0 \to I \to A^n \overset{\psi}{\longrightarrow} M \to 0.  $$
Therefore, $A^n \simeq I \oplus M \simeq I \times M$ and $A$ is injective, so $M$ is injective.
My question is, how can I  prove that if $M$ is not finitely generated???
Comment: Apply Baer's Criterion to an arbitrary module $M$, just like you did at the beginning to show that $I$ is injective.
Comment: Your $\psi$ needs to go from $A^n$, sending $(a_1,\ldots,a_n)$ to $m_1a_1+\cdots+m_na_n$.
Comment: You're right, but it doesn't change the solution. I fixed that...
Comment: Can you explain with more details?
Comment: It's been a while since I touched homological, but I guess you can do: Let $g: I \mapsto Q$, where $Q$ is some $A$-module. Now, you just need to provide a map $R\cong I \oplus N \mapsto Q$ such that the composition $I \mapsto I \oplus N \mapsto Q$ equals $g$. You can take $I \oplus N \mapsto Q$ to be the map $(i,n)\mapsto g(n)$, and now you should be done (By Baer's criterion you just need to check extension problems for all (left) ideals of A).
Answer: I'm guessing you were assuming commutativity, since you made no reference to sides. But really one can do this in noncommutative rings, and everything is symmetrical.
By Baer's criterion, if $M$ is a right $A$ module, you only need to check that every homomorphism $f:T\to M$ extends, where $T$ is a right ideal of $A$.
But it's always easy to extend to the complement of a summand, and $T$ is a summand by hypothesis.  This seems to be the part you are having a hard time seeing. If $T\oplus C=A$, you can use any homomorphism $g:C\to M$ at all (say the zero homomorphism) and then check $f\oplus g:T\oplus C\to M$.
What $f\oplus g$ means, in this case, is the map $t+c\mapsto f(t)+g(c)$. Since the sum is direct, this is well-defined, and really does produce an $A$ module homomorphism $A\to M$. Clearly it extends $f$ to all of $A$.
So, Baer's criterion is satisfied, and $M$ is injective.

Question involving injective modules


$S_7$ does not contain a subgroup of order 15

Question: $S_7$ does not contain a subgroup of order 15
This is an example of converse of Lagrange's Theorem not working.
I want to know how we can prove this.
Do you know which idea we should use?
Answer: A group of order $pq$ with $p=3$ not dividing $q-1 = 4$ is commutative and therefore cyclic of order 15.  Using the cycle decomposition of permutations, this cannot be done with actions on 7 elements.  In $S_8$ the product of a disjoint 3-cycle and 5-cycle is an element of order 15.


Key substitution in python

Question: I have two text files, one we'll call keys and it looks something like this:
S-84
S-72
S-73
S-83
32
S-73
S-83
32
S-65
32
S-84
S-69
S-83
S-84
S-49

The other file is sort of a dictionary of key-value pairs:
S-49 : "!"
S-65 : "a"
S-66 : "b"
S-67 : "c"
S-68 : "d"
S-69 : "e"
S-70 : "f"
S-71 : "g"
S-72 : "h"
S-73 : "i"
S-74 : "j"
S-75 : "k"
S-76 : "l"
S-77 : "m"
S-78 : "n"
S-79 : "o"
S-80 : "p"
S-81 : "q"
S-82 : "r"
S-83 : "s"
S-84 : "t"
S-85 : "u"
S-86 : "v"
S-87 : "w"
S-88 : "x"
S-89 : "y"
S-90 : "z"
32 : " "

I want to read in the first file and replace the keys therein with their values in the second file so that the output file looks like this:
this is a test!

I don't really know where to start with this.
I was trying to start with something like this manually, but my output is bleh
with open('newkey.log', 'r') as input_file, open('newkey.txt', 'w') as output_file:
    for line in input_file:
        if line.strip() == 'S-84':
            output_file.write('t\n')
        else:
            output_file.write('bleh\n')

I think I am going to have to read-in the second file as a dictionary as well, or I could hard-code it in? I would prefer to end up being able to change that file outside of the interpreter.
Comment: Once you have found an answer to your problem, please click the tick next to that answer to accept it. This lets others with your problem know which solution worked for you.
Answer: Yes, you must first read in the second file to create your dictionary.
import re

d['S-186'] = ':'  # To account for the delimiter per your comments below.
with open(key_values_filename, 'r') as f:
    for row in f:
        k, v = row.split(':')
        d[k.strip()] = re.sub('^"|"$', '', v.strip())

Then read the other file and get the value from the matched key.
missing_value = 'key missing'
with open(keys_filename, 'r') as fin, open(result_filename, 'w') as fout:
    for row in fin:
        fout.write(d.get(row.strip(), missing_value))

For an explanation of the regular expression re.sub('^"|"$', '', v.strip()), it removes double quotations found either at the start or end of each parsed string stripped of whitespace.

^" asserts position of the quotation at the start of the string.
"$ asserts position of the quotation at the end of the string.
| matches either assertion above.

The above solution works on your sample data.
Comment: I get and error:
'NameError: name 're' is not defined`
Comment: So I used `import re`, but I get another error now:

`Traceback (most recent call last):
  File "./try_parse.py", line 7, in
    k, v = row.split(':')
ValueError: too many values to unpack`
Comment: That means there is more than one `:` on a given row.  Have you confirmed *exactly* what that data looks like?
Comment: Yes! That was it! The actual dictionary file is a lot longer than I put here and one of the values was for a colon. I found it and deleted it, and it worked! But now, how do I account for that missing colon?
Comment: Change `d = {}` to  `d['S-186'] = ':'`
Comment: Yeah, just adding it in after the with loop worked. Thanks!
Answer: You can try this:
import re

keys = {a:b for a, b in [re.split("\s:\s", i.strip('\n')) for i in open('second_file.txt')]}

final_message = ''.join(keys[i] for i in [b.strip('\n') for b in open('first_file.txt')])

Key substitution in python


How to put two select attributes (which are in different forms) side by side using html & css

Question: I need to put two select types side by side which re in different forms
Float and span are not working, I have also tried position-property but of no use.
Below is the HTML code,

form.aui .field-group {
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  padding: 4px 0 4px 145px;
  position: fixed;
  left: 50%;
  margin: 1px 0;
  width: 100%
}

        <form class="xyz">

            Search Type
            <select name="searchType" class="select long-field" id="one-two-id">
              <option value="one">one</option>
              <option value="two">two</option>
            </select>

        </form>

        <form class="xyz">

            Search field
            <select class="select long-field" id="productName">
              <option value="one">one</option>
              <option value="two">two</option>
            </select>

        </form>

Comment: The `form` elements themselves are `block` by default, and the parent `div` presumably as well. You need to float the form or the parent div.
Answer: By using
.xyz-page-panel-content {
  display: flex;
}

It's important that you recognize the elements in your structure that are siblings. In your case it's

For display: flex to work, you must assign this rule to the parent element of those who are meant to be next to each other. If those are not siblings, you have to use some other strategy or change the HTML structure.
You could use float instead by floating the siblings. I don't like using float for layout purposes like these, so I don't show it in action.
.xyz-page-panel-content > * {
  float: left ;
}

form.aui .field-group {
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  padding: 4px 0 4px 145px;
  position: fixed;
  left: 50%;
  margin: 1px 0;
  width: 100%
}

.xyz-page-panel-content {
  display: flex;
}

        <form class="xyz">

            Search Type
            <select name="searchType" class="select long-field" id="one-two-id">
              <option value="one">one</option>
              <option value="two">two</option>
            </select>

        </form>

        <form class="xyz">

            Search field
            <select class="select long-field" id="productName">
              <option value="one">one</option>
              <option value="two">two</option>
            </select>

        </form>

Answer: Try to float the divs outside the form tags. This should work.
#searchType {
  float:left;
}

Like this


underscore template is not is not showing for popover function?

Question: // html.erb(template)

//script.js
//declaring variables for template
var _slicer=$('#temp').html();
//popover function
$(linkingmoduleobj).popover({
        container : 'body',
        html : 'true',
        content : "some content,
        title : "some title",
        template : '_.template(_slicer,{name: "praveen"})'
    })

inside _.template when directly use the html code instead of passing variable it is working when i pass reference variable  for template it is not working
Answer:

just change it the way you want to but the code to be changed is
_.template(_slicer)({name: "praveen"})

and


Isomorphism between [0,1] to (0,1)

Question: I need to find an isomorphism between [0,1] to (0,1) can you help me with this please?
thanks. benny
Comment: Possible duplicate: http://math.stackexchange.com/questions/418/construct-a-bijection-from-r-to-r-s-where-s-is-countable
Comment: Also let me know if the tag elementary-set-theory here is inappropriate.
Answer: The maps $(0,1) \to [0,1], x \mapsto x$ and $[0,1] \to (0,1), x \mapsto 1/4 + x/2$ are injective. The theorem of Cantor-Schröder-Bernstein implies that there is a bijection. It is actually possible to work out the proof of the theorem in these simple examples and get an explicit bijection, namely
$g : [0,1] \to (0,1), x \mapsto 1/2 \pm 1/2^{n+2}$ if $x = 1/2 \pm 1/2^{n+1}$ for some $n$, and $x \mapsto x$ else.
See also this article if you know german. ;)
Answer: You can identify a countably infinite collection of points starting with 0 and converging to some limit less than 1/2.  Just shift each point one down the line.  Now repeat from the top end.  All points not involved go to themselves.
Comment: Isn't this one of the tricks behind the Banach-Tarski decomposition? I seem to remember some discussion of this in a Mathematical Intelligencer article...
Comment: It is used.  In Wagon's excellent book, The Banach-Tarski Paradox, one of the first things proved is equivalent to this, a bijection between the unit circle and the unit circle missing a point.  He uses rotations that are multiples of 1 radian
Answer: What do you mean by "isomorphism"? Are you considering these sets with a given group or ring structure (if then, which one?), or as topological spaces (in which case you'd be looking for a "homeomorphism"), or just as sets?
I don't know of a canonical group structure on either set, but if you want your map between the two to be continuous you might have some luck by looking at the notion of compactness and how it behaves under continuous functions.
Comment: isomorphism in the category of sets = bijection, and this is meant here. sets are also algebraic structures (with empty signature).
Comment: sorry, I meant sets
Comment: @user3224: an Isomorphism is a special Homomorphism, which is a structure-preserving map between two algebraic structures.
so, *what* is the structure on those sets? or do you only want any bijective map?
Answer: If you just want a bijection there are many ways to do it. Here's a rather contrived one:
Let $\alpha$ be a limit ordinal of the same cardinality as $(0,1)$. By the Cantor-Bernstein-Schröder theorem there exists a bijective map $f: (0,1) \to \alpha$. Let $S$ denote the successor "function" (I know it's not a function - hence the quotes). Note that $\alpha$ does not have a maximal element, so it makes sense to define $\phi: [0,1] \to (0,1)$ by
$$\phi(x) = \begin{cases}
(f^{-1} \circ S \circ S \circ f)(x) & \text{ for $x \in (0,1)$}, \\
f^{-1}(1) & \text{ for $x = 1$}, \\
f^{-1}(0) & \text{ for $x = 0$}.
\end{cases}$$
Showing that $\phi$ is a bijection is an easy exercise. It's also completely useless and nonconstructive.
Comment: "It's also completely useless and nonconstructive. " Indeed ;)
Answer: The bijection 1/x turns (0,1) into (1,$\infty$) which you can chop up into countably many (]'s. Also you can split [] into [)(] and these can be divide countably many times to bisect with the (]'s but it flips the ordering around.
Answer: The easiest way (if you can apply Cantor-Bernstein-Schroder theorem) is to find a bijection from $[0,1]$ onto a subset, say $[1/4,3/4]$; that is easy to do. Since the identity map from $(0,1)$ to $[0,1]$ is a bijection, it follows from the theorem that the two sets are isomorphic.
Comment: This duplicates part of the answer by Martin Brandenburg posted 8 hours ago: http://math.stackexchange.com/questions/9274/isomorphism-between-0-1-to-0-1/9285#9285

Isomorphism between [0,1] to (0,1)


How to make Apache 2.4 redirect sub.example.com to a local server on the orgin?

Question: I've been trying to make a sub.example.com go to a local server at http://10.0.2.15:8080 to access my code-server https://github.com/cdr/code-server and cant seem to find the right config. This config I have
<VirtualHost *:80>
  ProxyPreserveHost On
    # Servers to proxy the connection, or;
    # List of application servers:
    # Usage:
    # ProxyPass / http://[IP Addr.]:[port]/
    # ProxyPassReverse / http://[IP Addr.]:[port]/
    # Example:
    ProxyPass / http://10.0.2.15:8080/
    ProxyPassReverse / http://10.0.2.15:8080/
    ServerName images.darksmp.com
</VirtualHost>

should have the server name and has the proxy connections. The website does display the login screen for code-server but when logged in, the content isn't loading either.
Is there a way someone can set up a CentOS 8 Server with GUI with http server on it and test it out for them self? That Would be great!
Comment: What is listening on 10.0.2.15:8080 ?
Comment: Gerard H.,
Please go to https://github.com/cdr/code-server as this is what is running on 8080
Comment: I read https://github.com/cdr/code-server/blob/main/docs/guide.md. Don't you need to provide websockets?
Answer: One option is to use redirect in vhosts config, which works fine in most cases
<VirtualHost 220.127.116.11:80>
ServerName images.darksmp.com
ServerAlias www.images.darksmp.com
Redirect 301 / http://10.0.2.15:8080/
</VirtualHost>

Just make sure you have routing working well within your network, and that your DNS is resolving also local names if you have defined them.
Comment: This could work bit its has to like CName to the ip instead as the redirect might not work I'll try this method real quick.
Comment: If CName is needed, then best to setup DNS on your local server to point to this internal comp, and should all work flawlessly.  Another option is to make a simple port forwarding like `iptables -t nat -I PREROUTING -p tcp -s outside/net -d server-ip --dport 80 -j DNAT --to 10.0.2.15:8080`, but this is not using apache then.
Comment: But what if i want to use the same port on the machiene and have a html site and a code server on the same ip? this is why im asking.
Comment: Then you need  or define your forwarding site on different port (ie 81) and then forward.  I'm not sure how individual pages (or login pages) would be forwarded via apache.  To have it working flawlessly, I presume the best option is really via port forward, as NAT server would translate every call


Shape operator of the unit sphere - The trace is the mean curvature

Question: I want to compute the shape operator $A$ of the unit sphere $\mathbb S^2$ which is given by $$A=-I^{-1 }II$$
where $I^{-1}$ is the inverse of the first fundamental form $I$ and $II$ being the second fundamental form.
From the parametrization $$X(\theta,\phi)=\bigl(\sin(\theta)\cos(\phi), \sin(\theta)\sin(\phi, \cos(\theta)\bigr)^T$$ one obtains the  first fundamental form and its inverse: $$I=\begin{pmatrix}1 & 0 \\ 0 & \sin^2(\theta)\end{pmatrix}\quad\quad I^{-1}=\frac{1}{sin^2{\theta}} \, \begin{pmatrix}\sin^2(\theta) & 0 \\ 0 & 1 \end{pmatrix}$$
and by the computation $N=X_{\theta} \times X_{\phi}$ the normal vector $N=\begin{pmatrix}\sin^2(\theta)\cos(\phi)\\ \sin^2(\theta)\sin(\phi)\\\cos(\theta)sin(\theta)\end{pmatrix}$.
The coefficients of $II$ are given by $II_{ij}=X_{ij} \cdot N$, thus , if I didn't miscalculate$$II=\begin{pmatrix}-\sin(\theta) & 0 \\0 &-sin^3(\theta) \end{pmatrix}.$$
Then finally the shape operator should be $$A=-I^{-1}II=\begin{pmatrix}\sin(\theta) & 0 \\ 0 & \sin(\theta)\end{pmatrix}.$$
The mean curvature $H$ of the sphere can then be calculated by $$H = tr(A)=2\sin(\theta).$$
But shouldn't the mean curvature of the unit sphere be $1$? Where did I miscalculate?
Answer: You need to take a normal vector with unit length. So the correct choice is
$$ N = \frac{X_\theta \times X_\phi}{|X_\theta \times X_\phi|},$$
then you should get
$$N = \bigl(\sin(\theta)\cos(\phi), \sin(\theta)\sin(\phi, \cos(\theta)\bigr)^T$$
and from there you find $H = 2$.
Comment: thanks, got it.

Now on wikipedia it says you can also calculate $H$ by
$H=-\nabla \cdot N$. Do you by chance know what in what sense $\nabla$ is meant here? In euclidean 3D-space I know $\nabla = (\partial / \partial x, \partial / \partial y, \partial / \partial z)^T$, but now $N$ depends on $\theta$ and $\phi$


Cox Regression: Testing for effect in subgroup

Question: I'm using a cox proportional hazard model in R to see if a treatment variable (treatment or placebo) has effect on the survivaltime of patients. I intend to test this for each of my grouping variables (e.g. Age <60 or Age > 60).
I could do this by making two different subgroups of my dataset, as follows:
c.example1 <- coxph(Surv(time, status)~factor(treatment), data=lung[ lung$age.ind==0 ,])
c.example2 <- coxph(Surv(time, status)~factor(treatment), data=lung[ lung$age.ind==1 ,])

Each cox model gives me a P value telling me if there is a significant treatment effect. So far so good.
Now someone working with me on this problem suggested to use an interaction term to test the same thing. He feels this also gives answer to the same question, but requires less work (instead of two models, we build one):
c2.2 <- coxph(s ~ age + treatment + age:treatment, data=lung)

His idea is that the p value for our interaction term now tells us that if there is a significant effect for treatment in both subgroups. I thought it would only give information if the effect of age on treatment is different in the two subgroups. Not test is the effect of treatment is significant.
Is his interaction term approach the right one? If not, what is a good approach (besides coding two seperate models)?
Answer: Your initial approach, breaking down the age variable into subgroups for separate analyses, loses a lot of potentially valuable information. See this page, or many others under the binning tag on this site, for why that isn't a good idea.
The single model that your colleague suggested accomplishes two things beyond your separate subgroup analysis.
First, and most important for your original question, consider the model s ~ age + treatment, without the interaction term. A significant coefficient for treatment in this case would mean significance regardless of age. So that part of your colleague's suggestion does directly test whether the effect of treatment is significant. That would be the case whether you persist in grouping by age or use age as a continuous variable.
Second, in the model suggested by your colleague, the added interaction term further evaluates whether there is a difference in treatment effects as age changes, as your initial question and the answer from @DWin recognize. That may be very important to know, although you typically need more data to identify a significant interaction term than you need for a main effect.
So your colleague's suggested approach simply and efficiently answers your original question and might gather more useful information.
You will, of course, have to check that the proportional hazards model adequately describes your data, or else none of these models will provide the answers you seek.
Answer: As far as R programming goes, the formula you offer is equivalent to:
s ~ age * treatment

The asterisk-operator is overloaded in R. When its arguments are numeric, it is multiplication, and when they are tokens or symbols in an R formula they are interactions that get expanded to all first order and second order ( and higher if there are more than two symbols.) Your representation of that model is also syntactically legal. We would have more to talk about if you had presented the output. I originally thought your were using the 'lung' dataset from pkg:survival, but it has no treatment variable.
It's true that SO tries to get interpretation and methodology questions shunted over to CrossValidated.com, but since that may happen anyway, I'll start that process. The interaction model gives you more information. Your question would be answered by a comparison of two models:
   s ~ age * treatment   # three coefficients
   s ~ age + treatment   # two effect coefficients

When there is no major difference in the "age effect" there will be no material change in the estimated coefficient for treatment across a comparison of those two models. The estimated "effect" in the "0"-groups will not be reflected in the treatment coefficients, since R uses treatment contrasts. The estimated effects in the older age group will be a combination of two or three coefficients depending on which treatment group is under consideration.
The question of whether there is a significant difference in the effect of treatment in the two age groups will be reflected in the magnitude of the age:treatment interaction and the associated p-value in the output from the first of those models. The results from the second of those models will return an treatment-estimate that is essentially a weighted average of the two models you were originally using. The mean of your two treatment estimates should be close to that estimate if the numbers of your cases in the age categories are similar.
You should consider looking at the possibility of modeling age as a continuous variable.
Comment: While this does cover the basics of how interactions work in R, this doesn't really answer @Rogier's questions about whether you can use interaction effects to test whether the treatment effect is significant in *both* age groups, which is a different question than whether there is a difference in effect size in the two groups.
Comment: In the younger group with the interaction model the p-value for the treatment coefficient should be the same as for the treatment coefficient in his younger-age-restricted model. The treatment coefficient plus the age:treatment coefficient should be the same as the treatment effect in older-age-restricted model. You should be able to make a linear contrast for the sum of the two coefficients being 0 if you want to test just the treatment effect in older group. The p-value for the age:treatment coefficient is the test of whether they are significantly different.


Converter variaveis numericas qualitativas em fatores no R

Question: Eu tenho o seguinte codigo ja PRONTO, que meu orientador passou para mim
fatores=c("Year","Month","DayofWeek","DayofMonth")

dadosFatores=apply(dados[,fatores],2,XXXX)

dados[,XXXX]=dadosFatores

No exercicio diz que eu devo trocar apenas os XXXX por algo que faça sentido e retorne o que a função pede, ou seja, converter as variaveis em questao em fatores.
Eu tentei substituir por as.factor, sem grande sucesso.
Alguem poderia ajudar ?
Comment: Você pode mostrar um pedaço da variável dados? É um data frame, uma matriz? Existem outras colunas além daquelas listadas no vetor fatores?
Answer: Alterando minha resposta, na verdade há um problema anterior, você teria que utilizar o lapply ao invés do apply, porque aparentemente o apply vai jogar tudo para uma matriz e converter para character antes de retornar para o data.frame (não tinha testado o código antes).
Gerando um dado fictício para ilustrar:
dados <- data.frame(x = 1:10)
dados[, fatores] <- rep(c("a", "b", "c", "d"),10)
str(dados)
data.frame':    10 obs. of  5 variables:
 $ x         : int  1 2 3 4 5 6 7 8 9 10
 $ Year      : chr  "a" "b" "c" "d" ...
 $ Month     : chr  "c" "d" "a" "b" ...
 $ DayofWeek : chr  "a" "b" "c" "d" ...
 $ DayofMonth: chr  "c" "d" "a" "b" ...

Com apply (não funciona):
dados[,fatores]= apply(dados[,fatores], 2, as.factor)
str(dados)
'data.frame':   10 obs. of  5 variables:
 $ x         : int  1 2 3 4 5 6 7 8 9 10
 $ Year      : chr  "a" "b" "c" "d" ...
 $ Month     : chr  "c" "d" "a" "b" ...
 $ DayofWeek : chr  "a" "b" "c" "d" ...
 $ DayofMonth: chr  "c" "d" "a" "b" ...

Com o lapply (funciona):
dados[,fatores]= lapply(dados[,fatores], as.factor)
str(dados)
'data.frame':   10 obs. of  5 variables:
 $ x         : int  1 2 3 4 5 6 7 8 9 10
 $ Year      : Factor w/ 4 levels "a","b","c","d": 1 2 3 4 1 2 3 4 1 2
 $ Month     : Factor w/ 4 levels "a","b","c","d": 3 4 1 2 3 4 1 2 3 4
 $ DayofWeek : Factor w/ 4 levels "a","b","c","d": 1 2 3 4 1 2 3 4 1 2
 $ DayofMonth: Factor w/ 4 levels "a","b","c","d": 3 4 1 2 3 4 1 2 3 4

Se aparece algum erro no código acima, coloque a mensagem de erro e um exemplo reproduzível para podermos entender qual é o problema e o resultado de head(dados) e str(dados) na sua pergunta para vermos como é o objeto
Comment: Retirando o primeiro XXXX e colocando as.factor aparece isso aqui:

Erro em dados[, fatores] : número incorreto de dimensões
Comment: @Felipe Isso quer dizer que seu objeto dados não tem colunas ou outra coisa desse tipo. Coloque o resultado de `head(dados)` e `str(dados)` na sua pergunta para vermos como é o objeto.


How to perform the same method on outlets that have similar names instead of writing out very similar lines 10s of times?

Question: I have these outlets...
@IBOutlet weak var pill1: UIImageView!
@IBOutlet weak var pill2: UIImageView!
@IBOutlet weak var pill3: UIImageView!
@IBOutlet weak var pill4: UIImageView!
@IBOutlet weak var pill5: UIImageView!
@IBOutlet weak var pill6: UIImageView!
@IBOutlet weak var pill7: UIImageView!
@IBOutlet weak var pill8: UIImageView!
@IBOutlet weak var pill9: UIImageView!
@IBOutlet weak var pill10: UIImageView!

I need to hide all of them in the 'viewDidLoad' function. For example...
self.pill1.isHidden = true
self.pill2.isHidden = true
self.pill3.isHidden = true
etc...
etc....all the way to...
self.pill10.isHidden = true

But instead of writing repetitive lines 10s of times that are very similar, how do I use a 'for loop', or whatever is needed, to make it more cleaner.
For example,
for index in 1...10 {

   pill(insert index here somehow).isHidden = true

}

I tried a few different ways, but I was getting errors with string types etc. I am new to this all. Any help appreciated. thank you
Comment: Use an outlet collection or arrays.
Answer: You can put the views into an array like this:
for pill in [pill1, pill2, pill3, pill4, pill5, pill6, pill7, pill8, pill9, pill10] {
    pill.isHidden = true
}

You could consider using an @IBOutlet collection.  In that case, all of your outlets would be wired to the same collection (array) variable:
@IBOutlet var pills: [UIImageView]!

for pill in pills {
    pill.isHidden = true
}

Comment: thanks. what about the word 'pill'? That is repetitive. Isn't there a way just to add different numbers to the end of it, and keep the 'pill' within the curly brackets?
Comment: as in getting rid of the repetitive 'pill' written over and over in the square brackets.
Comment: The names inside of the array literal `[ ]` have to match the names defined in your `@IBOutlet`s.  You could use an `@IBOutlet` collection which is just an array that holds the outlets. That works if you don't care about the order of the items in the array.


.htaccess 301 redirect remove [] from the URL

Question: I want to remove '[' and ']' from the URLs and redirect to correct link.
Here is a sample URL:
/forums/garage-150/cool-cars-sightings-[archived]-7610/index127.html

Needs to be redirected to:
/forums/garage-150/cool-cars-sightings-archived-7610/index127.html

Here is what I have composed so far, but still not working..
Options +FollowSymlinks
Options +Indexes
RewriteEngine on
RewriteRule ^/forums/(.*)/(.+)\[(.+)\](.+)/(.+)$ /forums/$1/$2$3$4/$5 [R=301]

Answer: Your directive looks OK, except if this is in .htaccess then you'll need to remove the slash prefix from the RewriteRule pattern. For example:
RewriteRule ^forums/(.+)/(.+)\[(.+)\](.+)/(.+)$ /forums/$1/$2$3$4/$5 [R=301,L]

RewriteRule directives in a directory context (which includes .htaccess) match against the URL-path less the directory-prefix. The directory-prefix always ends with a slash, so the URL-path that the RewriteRule pattern matches against never starts with a slash.
You may need to add the L flag if you (plan to) have more directives. (I also changed the first captured group from .* to .+, since a zero-width match here is impossible.

UPDATE:

The htaccess where I put this code is in / directory. There is also .htaccess in /forums directory

If there is an existing .htaccess file in the /forums subdirectory that also uses mod_rewrite, then (by default) this will completely override the directive above (in your root .htaccess file). The above directive will not even be processed.
The easiest way to resolve this is to move the above directive into the /forums/.htaccess file (near the top). Since this redirect is specific to the forum, that would also seem to be the most logical approach. However, you would also need to change the RewriteRule pattern to read:
RewriteRule ^(.+)/(.+)\[(.+)\](.+)/(.+)$ /forums/$1/$2$3$4/$5 [R=301,L]

Comment: it didn't work. it does not redirect..
Comment: Where is your `.htaccess` file? Do you have any other directives in your `.htaccess` file? If so, where have you placed this directive? (It would need to go near the top, before any other rewrites.) Do you have any other `.htaccess` files along the filesystem path?
Comment: The htaccess where I put this code is in / directory.
There is also .htaccess in /forums directory
Comment: If there is an additional `.htaccess` file in the `/forums` subdirectory that this is most likely overriding your redirect. I've updated my answer.


What is the proper name of the dash symbol over a note and how to play it

Question:
Sample score with this symbol:

Can anyone specify the name of the particular symbol above the crotchet in the top image and everything marked in red in the sample piece of music? According to Wikipedia it's called a Tenuto but my teacher said it's called a "dash". Which one is correct? Or are both names correct?
Second of all, how exactly do you play it? I read up on it in wikipedia and it was somewhat confusing. Could someone specify with examples exactly how notes with that kind of symbols should be treated? It would be helpful if you could explain in terms of the violin.
UPDATE:
This same symbol is called not just Tenuto in some places but also Détaché porté and Portato/louré when slurred. What is the explanation between this discrepancy?
Answer: That mark is known as a tenuto and when it's over the note it means to hold the note for the full duration and make the transition between notes more legato than normal. You can think of a tenuto as the opposite of a staccato where you play the note slightly shorter than the actual value.
Comment: @Sazid_violin When you go from playing one note to the next, you usually end the note you are playing slightly earlier than the duration to get to the next note. When the tenuto is used it is instructing you not to take that pause so the transition between notes is more legato.
Comment: @Dom - do you mean that in a phrase of ordinary notes, each has to be played so there is an audible gap between it and the next? That's more like marcato than legato. I don't believe a gap should be included in any legato playing.
Comment: The precise interpretation has more to do with the style of a piece than what is precisely marked. A tenuto marking suggests that the player should treat those notes differently than normal, or at least differently than the notes around it, but the player still has quite a bit of leeway in his or her interpretation.
Comment: Um, does that imply you do not hold other notes for their full duration? My teacher said that this note is to be played with a longer bow- giving the impression of a longer time.
Comment: Tenuto is one of the most disputed articulation marks, I believe, and its interpretation is just that: an interpretation.
Answer: I read tenuto ♩ as an accent where you put slight "pull" or "pressure" emphasis on the entire note; as opposed to normal accents ♩ where the initial attack is strongly emphasized but the remaining note rings out normally, or even marcato ♩ where the note decay is actively shortened.
Comment: Yes, agreed. I have always understood tenuto marks to have two meanings, and it isn't always clear which a composer means. It can mean that the notes have their full duration, but can also mean that there is a slight emphasis upon the note. Luckily, these two interpretations often go hand-in-hand; a note emphasised by being held for its full duration (all at the same volume as this answer points out) and by being played with slight emphasis of volume.
Comment: @Sazid_violin: I first wrote only pressure, but that doesn't quite catch it. There are multiple ways to execute tenuto with the bow; as you teacher says one of them is to use more bow (increasing the bow-speed and thus tone intensity, but not the attack). I think "pull" is a good description of how to do this. You may however amplify or replace this effect with some firm and steady extra pressure and perhaps move closer to the bridge, in particular if using much bow is not feasible for some reason (e.g. it's an upstroke and you're already close to the frog).
Comment: @leftaroundabout What do you mean by "pull" ? pressure I understand, or is the pull a means to execute that pressure? (as in moving your bow faster makes the note louder)
Answer: Tenuto (the correct name for the musical entity even if you may choose to call the typographic means to achieve that a dash) usually means an accent asking for emphasizing the note length instead of its start.
In bowed string music, this is often combined with slurs to indicate that you aren't expected to change bow direction between notes but aren't to play them staccato either while still keeping them detached.  So in the context of slurs, this is more like a portato indication.  Strictly speaking, a portato mark consists of both dash and dot, but this is not really used with string instruments: it's the normal expected articulation when changing bow direction, and otherwise you just combine a slur with tenuto marks.  The execution should sound as if you did change bow direction between notes without a pronounced pause (like it would be in staccato) but also not as connected as a straightforward slur.
Outside of slurs, this means normal tenuto: detached but stressing the whole length of the note.
On percussive instruments like a piano, tenuto execution is finicky and basically has to rely on not releasing the key early but also very slightly detaching and accenting the next note so as not to give a legato impression.
Answer: Tenuto is a notational device to make it easy to add selective legato within a phrase. The tenuto mark indicates that the note is to be sustained as long as possible before the next note is articulated, in whatever way is appropriate for that next note. Legato just means "do that same thing for every note for the entire length of this phrase".
As an example, if you had a tenuto quarter note followed by a staccato one, you'd sustain the first up to the start of the articulation of the second, which would be shortened (daah dat); if you had a quarter note slurred to a staccato one, you'd not articulate the second note but would cut it off short (daah-at). A subtle but definite distinction.
As far as portato goes, it's midway between staccato and legato; the individual notes are distinctly articulated, and none of them are attached to the following note, but they are not as short as staccato notes would be.


How to to check if user has changed the password?

Question: I wanted to send basic notification email to the user, after it has changed the password, to inform him of password change.
I am using Rules modules for that. But I am not finding any option there, to add condition if user has changed the password.
Is there any way I can check if user has changed his password using rules or pragmatically.
-- Many thanks for your time.
Comment: Check this may help you http://drupal.stackexchange.com/questions/68380/how-to-get-notified-when-a-user-is-blocked/68389?noredirect=1#68389
Answer: The easiest would be to do this using Rules. Following the next steps, should do the job.

Ensure you have enabled the "PHP filter" on the modules page. This is needed to be able to use PHP code inside Rules.
Create a rule that reacts on the user event "After saving a new user account".
Add a condition of type "Execute custom PHP code" and use the following snippet: return $account_unchanged->pass != $account->pass;
Add your action(s) to send an email notification to the user or anything else that fits your purpose.
Comment: have you tried it?
Comment: Yes, I tested this out just before I wrote the answer.
Comment: Thanks, simple and efficient solution. Works like charm!!
Answer: I haven't tried it in Rules before, but it would probably be a matter of comparing values on the $account and $account->original objects.
One way to do it in custom code is to implement hook_user_presave():
function MYMODULE_user_presave(&$edit, $account, $category) {
  // Don't show message for registering users.
  if (isset($account->is_new) && $account->is_new) {
    return;
  }

  if (!empty($edit['pass']) && $account->pass != $edit['pass']) {
    // Password has been changed.
  }
}

You could probably do the same in hook_user_update(), but I haven't tried that before. The above is taken from a live project and works perfectly.
Answer: Using Rules might be easier since you are already using it, but you need to enable PHP Filter module.
The instructions as follow:

Enable PHP Filter module admin/modules
Create a new Rule admin/config/workflow/rules
Make sure to select After updating an existing user account from React on event dropdow list.
Add a condition and choose Execute custom PHP code
Add the following PHP custom code in the value section
if(!empty($account->current_pass)) {
  return true;
}
Then add an action and select Send mail
In the value section add [account:mail] and fill subject field and message field.


What is the best practices to do LINQ query when it comes to the context of async, await, task with IEnumerable & IQueryable

Question: This is the IQueryable object that I wrote for one of my APIs. It just join with some of the schemas and returns company data. (I am using .net 6 for the project)
the query which return IQueryable object
<code>    private IQueryable<CompanyDto> FetchAllComnpay()
    {
        return from com in _context.Companies
               join cty in _context.Cities on com.CityId equals cty.Id
               join con in _context.Countries on cty.CountryId equals con.Id
               join lc in _context.Currencies on com.LocalCurrencyId equals lc.Id
               into slc
               from sublc in slc.DefaultIfEmpty()
               join ic in _context.Currencies on com.InterNationalCurrencyId equals ic.Id
               into sic
               from subic in sic.DefaultIfEmpty()

               select new CompanyDto
               {
                   Id = com.Id,
                   CompanyName = com.CompanyName,
                   CompanyCode = com.CompanyCode,
                   CountryId = cty.CountryId,
                   CountryName = con.CountryName,
                   CityId = cty.Id,
                   CityName = cty.CityName,
                   MobileNo = com.MobileNo,
                   PhoneNo = com.PhoneNo,
                   Email = com.Email,
                   Web = com.Web,
                   ZipCode = com.ZipCode,
                   Address = com.Address,
                   CreatedBy = com.CreatedBy,
                   CreatedDate = com.CreatedDate,
                   UpdatedBy = com.UpdatedBy,
                   LastUpdatedDate = com.LastUpdatedDate ?? null,
                   LocalCurrencyId = com.LocalCurrencyId ?? 0,
                   LocalCurrencyName = sublc.CurrencyName ?? "",
                   InterNationalCurrencyId = com.InterNationalCurrencyId ?? 0,
                   InterNationalCurrencyName = subic.CurrencyName ?? "",
               };
            }
</code>
Then I fetch a list of companies like this
<code>    public async Task<IEnumerable<CompanyDto>> GetAllCompanies()
    {
        return await FetchAllComnpay().AsNoTracking().ToListAsync();
    }
</code>
Then fetch a single company the like this
<code>    public async Task<CompanyDto> GetCompayByIdAsync(int id)
    {
        return await FetchAllComnpay().Where(e => e.Id == id).AsNoTracking().FirstAsync();
    }
</code>
Actually, I am forced to work with .Net core in my org. That's why I am asking this.
Here's the point that I wanted to know regarding this context

Am I on the right track
if I m not what are the best available best practices that I can apply in this type of query
Will you kindly provide me with any suggestions, please?
Comment: 1) Yes. 3) joins can be removed if you have navigation properties, `AsNoTracking` is not needed if you have `Select`.  EF Core do  not track custom entities.
Comment: 1. I didn't user navigation properties (although they're nice)  because I wanted to  Parent and Child to be two separate aggregate roots. I wanted them to be able to talk to each other via foreign key not through infrastructure-specific Entity Framework navigation properties.

2. according to the documentation of Microsoft (https://learn.microsoft.com/en-us/ef/core/querying/tracking) it is saying to use AsNotracking() when it comes to read-only scenario.
Comment: Do not use `AsNoTracking` if you project to DTO, it has no sense.
Comment: Using navigation properties does not preclude you from using aggregate roots, nor are they in any way infrastructure-specific.  What they would give you is much shorter, cleaner and easier-to-read Linq.
Answer:

Am I on the right track

Yes, you are.

If I m not what are the best available best practices that I can apply in this type of query?
Will you kindly provide me with any suggestions, please?

Here we deal with specific issues (there is an error, it takes too long, etc.).
For "any suggestion" https://codereview.stackexchange.com/ will be better.


applying two-sample t.test comparing multiple groups in two categories

Question: I want to do a two-sample t.test comparing values from two regions for several groups. I know it must be a simple trick, but I couldn't find an answer so far.
This is a short version of my table. Several species each from 2 regions (There are generally 6 specimens per species available for each region).
species region   N15
ARGAFF     EQ    9.85
ARGAFF     EQ   10.42
ARGAFF     EQ   10.43
ARGAFF    OMZ   10.28
ARGAFF    OMZ   10.30
ARGAFF    OMZ   10.41
BATABY     EQ   10.57
BATABY     EQ   10.60
BATABY     EQ   10.68
BATABY    OMZ    9.21
BATABY    OMZ    9.29
BATABY    OMZ    9.67

I tried
spp<-split(SIA,species,drop=FALSE)

followed by
lapply(spp,function (x) t.test(N15~region))

I further tried
by(SIA[,3], SIA[, "species"], function (x) t.test(N15~region))

but both versions compute the test for all values (N.138, not just for individual species (N:12).
On the other hand
 by(SIA[,3], SIA[, "species"], t.test)

results in a one-sample test but for individual species.
I'd appreciate advice.
Comment: Does this one help? http://stackoverflow.com/questions/37474672/looping-through-t-tests-for-data-frame-subsets-in-r/37479506#37479506
Comment: @AntoniosK, what if there is another column named N16, and I want to do a test on that too with a result formatted like: # species N15 N16 # 1 ARGAFF PVALUE PVALUE # 2 BATABY PVALUE PVALUE is this possible? I actually want to post this as a comment, but you know, no sufficient reputation to do that.
Answer: There are various ways to do that, but I'm using a combination of dplyr and broom packages. The advantage of this process is that you export the t-test information as a dataset:
library(dplyr)
library(broom)

set.seed(9)

# example dataset
dt = data.frame(species = c(rep("ARGAFF",6), rep("BATABY",6)),
                region = rep(c("EQ","OMZ"),6),
                N15 = rnorm(12,10,1))

dt_result = dt %>% group_by(species) %>% do(tidy(t.test(N15~region, data=.)))

dt_result

   #   species  estimate estimate1 estimate2 statistic   p.value parameter   conf.low conf.high
   # 1  ARGAFF 0.6029705  9.842659  9.239688  1.381967 0.2439265  3.732157 -0.6434982  1.849439
   # 2  BATABY 1.0238324 10.740491  9.716659  1.994738 0.1673019  2.300604 -0.9298488  2.977514

Hope it works for you.
Answer: First, in general it is a bad idea to attach a dataset. You can modify your lapply statement to do what you want I think.
set.seed(9)

# example dataset
SIA <- data.frame(species = as.factor(c(rep("ARGAFF",6), rep("BATABY",6))),
                region = as.factor(rep(c("EQ","OMZ"),6)),
                N15 = rnorm(12,10,1))

spp <- split(SIA, SIA$species,drop=FALSE)
out <- vector("list", length = length(spp))
out <- lapply(1:length(spp),function (x) out[[x]]<- t.test(spp[[x]]$N15 ~ spp[[x]]$region))

Then you can extract whatever features you want.
> out
[[1]]

    Welch Two Sample t-test

data:  spp[[x]]$N15 by spp[[x]]$region
t = -0.7566, df = 2.4628, p-value = 0.515
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -4.617903  3.018924
sample estimates:
 mean in group EQ mean in group OMZ
         9.982135         10.781625

[[2]]

    Welch Two Sample t-test

data:  spp[[x]]$N15 by spp[[x]]$region
t = 0.66769, df = 3.2858, p-value = 0.5483
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -1.564611  2.448523
sample estimates:
 mean in group EQ mean in group OMZ
        10.055578          9.613622

Answer: Rstatix::t_test() is a user-friendly wrapper of t.test() that returns a tibble.
library(tidyverse)
library(rstatix)

df <- tribble(~species, ~region,  ~N15,
              "ARGAFF",    "EQ",  9.85,
              "ARGAFF",    "EQ", 10.42,
              "ARGAFF",    "EQ", 10.43,
              "ARGAFF",   "OMZ", 10.28,
              "ARGAFF",   "OMZ", 10.30,
              "ARGAFF",   "OMZ", 10.41,
              "BATABY",    "EQ", 10.57,
              "BATABY",    "EQ", 10.60,
              "BATABY",    "EQ", 10.68,
              "BATABY",   "OMZ",  9.21,
              "BATABY",   "OMZ",  9.29,
              "BATABY",   "OMZ",  9.67)
df %>%
  group_by(species) %>%
  t_test(N15~region)


How to identify the middle of the first near-zero trough in a graph?

Question: I have audio files and timestamped fragment transcriptions that I have force-aligned with third party software.
Unfortunately the software places the end of each fragment right before the start of the next fragment, so if you try to play just one fragment from the audio file it will bleed over to the next fragment.
Here's a visualization of the waveform:

The red line is the automatically produced timestamp for the end of one fragment, and the start of another. The left and right sides are 2 seconds of audio on either end of that timestamp.  As you can see it's placed right up against the next time audio starts to output.
The blue and purple lines are two different algorithms I've used to try to identify the middle of the trough. In this case, the blue one worked, but in others it doesn't:

The data is a list of floating point numbers ranging from 0 to 1.  They represent a normalized and bucketed version of decoded 48Hz mp3 audio.  As you can see, in some cases there's a range of near zero values. In others there's varying degrees of "low volume", but always a visually-identifiable trough.
Can anyone recommend a method or algorithm for working backwards from the red line and finding the middle of the first trough? TIA!
Comment: This is a no-free-lunch problem. The only reliable answer is hand inputting the value. But if I were approaching it as a stat problem, I would define "silence" based on some bimodal modeling of the collapsed audio file. Then, having defined duration of tracks that are "silent", define long periods of silence as a track break, and take the midpoint as the time break.
Comment: It seems like taking the middle point between the purple and the red line would work well in these instances. Have you tried this on others?
Comment: @StephanKolassa I had not, yet. It works on some but not this one for instance: https://imgur.com/a/82E4JFA

I'm having better luck (but not 100%) using a method that looks for a grouping of 5 values where the median value is > 7x the minimum of the preceding set of values.  It worked on a bunch then failed on this: https://imgur.com/a/ubsWcC0 (the purple line is the updated alg in each)
Answer: Trough finding can be seen "peak finding" just with the feature being inverted. Peak finding is a common problem in digital signal processing, including in audio.
I would try computing the soundlevel (RMS or in dB), and try to use librosa.util.peak_pick. You can then try to snap to the closest peak forward in time (below a reasonable amount of time).


Equal parity of inversions and transpositions

Question: Let $\sigma $ be a permutation of the set $\{1,\ldots,n\}$  that is written as the product of $k$ transpositions. Let $\rm{inv}(\sigma)$ be the number of inversions of $\sigma$ - that is the number of pairs $(x,y)$ such that $x < y$ but $\sigma(x) > \sigma(y).$
How can I show that $\rm{sgn}(\sigma) \equiv k \pmod{2}$?
Answer: Let $\pi=\langle p_1,p_2,\ldots,p_n\rangle$ be a permutation of $[n]=\{1,\ldots,n\}$. If $\pi$ has no inversions, it's the identity permutation, which is even, so assume that $\pi$ has at least one inversion. Suppose that $1\le j<k\le n$, and $p_j>p_k$. Let $\rho=(p_j,p_k)\pi$ (where I apply the transposition first and then $\pi$); if $\rho=\langle r_1,\ldots,r_n\rangle$, then $r_j=p_k$, $r_k=p_j$, and $r_i=p_i$ if $i\in[n]\setminus\{j,k\}$. This swap obviously gets rid of the $\langle j,k\rangle$ inversion.
The only other inversions affected by this swap are those that involve position $j$ or $k$ and a position between $j$ and $k$. Suppose that $j<i<k$ and $\langle j,i\rangle$ is an inversion in $\pi$, i.e., $p_j>p_i$. Either $p_k>p_i$, in which case $\langle j,i\rangle$ is still an inversion in $\rho$, or $p_i>p_k$, in which case the swap gets rid of a $\langle j,i\rangle$ and an $\langle i,k\rangle$ inversion. Similarly, if the swap gets rid of an $\langle i,k\rangle$ inversion (instead of replacing it with a new one), it also gets rid of a $\langle j,i\rangle$ inversion. In all cases the number of inversions other than $\langle j,k\rangle$ that are affected by the swap is even. Thus, the total number of inversions affected by the swap is odd. Note also that the number of inversions is reduced by at least one.
Can you see how to finish it from here? I've left the conclusion of the argument in the spoiler-protected block below.

 Start with any non-identity permutation $\pi$. Repeatedly multiply by transpositions to remove inversions until no inversions remain. Say you multiplied by $m$ transpositions. Then $\pi$ has the same parity as $m$, and since each multiplication by a transposition removed an odd number of inversions, the number of inversions also has the same parity as $m$.
Comment: Hm.. In the first sentence of the second paragraph - given the permutation $\pi = (3 4 5 1 2)$ we have that $(2,4)$ and $(2,5)$ are its inversions. However, if we swap 2 and 4, $(2,5)$ is not an inversion anymore. Yet your argument says we need only consider inversions involving $p_j,p_k$ and an element in between. Am I missing something here?
Comment: @Jernej: $5$ **is** between $2$ and $4$. That's exactly one of the cases that I talked about in the answer.
Comment: Hm! Maybe my notation is confusing I meant the permutation $\begin{pmatrix} 1 & 2 & 3 & 4 & 5 \\ 3 & 4 & 5 & 1 & 2\end{pmatrix}$
Comment: @Jernej: So did I.
Comment: Hm.. Maybe I don't understand the proof then. If I apply the argument of the proof $j = 2, k = 4$ and the positions in between are $2,3,4.$ This should imply that the transposition of $(1,4)$ only possible inversions affect these positions, but affects only inversions at these positions, yet $(2,5)$ was a inversion  before and after applying the transposition its not anymore
Comment: @Jernej: The numbers in the positions between the $4$ and the $2$ are the $5$ and the $1$.
Comment: Yes that is correct. But the statement in the paragraph says to consider the values of $\rho(2),\rho(3),\rho(4)$. Shouldn't there be a $p_i,p_k$ in there? And also thanks for you quick and patient comments
Comment: @Jernej: I don't understand how you're reading that paragraph. In your example $j=2$ and $k=5$, so the values of $i$ that need to be considered are $3$ and $4$.
Comment: Hm.. Why isn't $k = 4$ since $\pi( 2) > \pi(4)$ hence $(2,4)$ is an inversion and the inversion $(2,5)$ now gets affected by the transposition $(1,4)$ even though $5$ is not between $2$ and $4$
Comment: @Jernej: This is hopelessly confused. Let's go back to the example of $\langle 3,4,5,1,2\rangle$. If we fix the $\langle 2,4\rangle$ inversion by premultiplying by $(4,1)$, we get $\langle 3,1,5,4,2\rangle$. It's true that this no longer has a $\langle 2,5\rangle$ inversion, but in compensation it **does** have a $\langle 4,5\rangle$ inversion. And this always happens when one of the positions is outside the $j$-to-$k$ interval. One of the **positions** of the inversion changes, but the **values** that are in the wrong order don't.
Comment: Yes yes, this is what I was trying to clarify. Thank you once again for your kind patience, I'll drop another 50 points in bounties to you.
Comment: @Jernej: Sorry about all the confusion. I'm not sure, but I think that for a while one of us was talking about indices and the other about the values, which of course meant that we were talking past each other. Anyway, I'm delighted to get it sorted out, and you're very welcome.


trouble getting the code to barplot or column plot these dataset

Question: data.frame(BADAGRY_CREEK_PUBLICATION_2)
       month station COPEPODA CYCLOPOIDA
1       MAY.       1       25          0
2       JUNE       1       10          5
3       JULY       1        4          0
4     AUGUST       1        5          5
5  SEPTEMBER       1       20          5
6       MAY.       2       20          0
7       JUNE       2       10         10
8       JULY       2        3          5
9     AUGUST       2       20          0
10 SEPTEMBER       2       40          0
11      MAY.       3       35          5
12      JULY       3        5          0
13      JUNE       3       25          5
14    AUGUST       3       35          5
15 SEPTEMBER       3       10          5
   JUVENILE.STAGES Number.of.Species..S.
1               15                     5
2               35                     6
3                0                     1
4               10                     4
5               15                     5
6               15                     5
7                5                     4
8                0                     2
9               10                     4
10              25                     6
11              20                     6
12               5                     2
13              30                     6
14               0                     3
15              30                     6
   Number.of.Individuals..N.
1                         40
2                         50
3                          4
4                         20
5                         40
6                         35
7                         25
8                          8
9                         30
10                        75
11                        60
12                        10
13                        60
14                        40
15                        50

was hoping tp plot stations on the x axis, with the count of each variable reflecting on the bars along the y axis. i tried this code
ggplot(BADAGRY_CREEK_PUBLICATION_2, aes(x=station)) + geom_bar() [this was the bar plotted which doesnot reflect the data gathered]
the result was not well plotted
Comment: Could you please share your data using `dput(BADAGRY_CREEK_PUBLICATION_2)` copy and paste from your console to your question?
Comment: What does "not well plotted" mean? What were you expecting, what did you get, and how did those two things differ?
Answer: It's difficult to tell what you are looking for here, since you also have month in your data. If you want to ignore month in your plot, you could do:
library(tidyverse)

BADAGRY_CREEK_PUBLICATION_2 %>%
  pivot_longer(-c(1:2)) %>%
  group_by(name) %>%
  summarise(value = sum(value), station = station) %>%
  ggplot(aes(x = factor(station), y = value, fill = name)) +
  geom_col(position = "dodge") +
  scale_fill_brewer(palette = "Set1") +
  theme_light() +
  labs(x = "Station", y = "Count")

To include month, you probably need facets:
BADAGRY_CREEK_PUBLICATION_2 %>%
  pivot_longer(-c(1:2)) %>%
  mutate(month = factor(sub("\\.", "", month), levels = c("MAY", "JUNE",
         "JULY", "AUGUST", "SEPTEMBER"))) %>%
  ggplot(aes(x = factor(station), y = value, fill = name)) +
  geom_col(position = "dodge") +
  facet_grid(month~.) +
  scale_fill_brewer(palette = "Set1") +
  theme_light() +
  labs(x = "Station", y = "Count")

Question data in reproducible format
BADAGRY_CREEK_PUBLICATION_2 <- structure(list(month = c("MAY.", "JUNE",
"JULY", "AUGUST", "SEPTEMBER",
"MAY.", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "MAY.", "JULY",
"JUNE", "AUGUST", "SEPTEMBER"), station = c(1L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L), COPEPODA = c(25L, 10L,
4L, 5L, 20L, 20L, 10L, 3L, 20L, 40L, 35L, 5L, 25L, 35L, 10L),
    CYCLOPOIDA = c(0L, 5L, 0L, 5L, 5L, 0L, 10L, 5L, 0L, 0L, 5L,
    0L, 5L, 5L, 5L), JUVENILE.STAGES = c(15L, 35L, 0L, 10L, 15L,
    15L, 5L, 0L, 10L, 25L, 20L, 5L, 30L, 0L, 30L), Number.of.Species..S. = c(5L,
    6L, 1L, 4L, 5L, 5L, 4L, 2L, 4L, 6L, 6L, 2L, 6L, 3L, 6L),
    Number.of.Individuals..N. = c(40L, 50L, 4L, 20L, 40L, 35L,
    25L, 8L, 30L, 75L, 60L, 10L, 60L, 40L, 50L)), class = "data.frame",
row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15"))

Comment: thanks alot! @Allan Cameron. got it. however, i like to change variable "name" to "species"
Comment: @KayAwo you can add the argument 'name =  "Species"` inside `scale_fill_brewer`
Comment: suppose i want to have the columns appear as a pattern fill so as to easily distinguish each variable list. not sure where to twitch. thanks
Comment: @KayAwo you would need to do `library(ggpattern)` and use `fill_pattern = name` instead of `fill = name`


spring.datasource.data picked up, but script never executed

Question: I am trying to set up in-memory H2 tables for a test class in my Spring boot application.
My config looks something like:
spring:
  jpa:
    show-sql: true
    generate-ddl: true
    properties:
      hibernate:
        dialect: org.hibernate.dialect.H2Dialect
  hibernate:
    ddl-auto: create-drop
  datasource:

    # not sure which one to use so added both just in case
    initialization-mode: always
    initialize: true

    platform: h2

    # casting a wide net here, but no cookie - completely ignored
    data: data-h2.sql,classpath*:data-h2.sql, classpath:data-h2.sql

    url: jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
    driver-class-name: org.h2.Driver
    username: sa
    password:

As you can see, I'm trying to load a data-h2.sql script upon db initialization.
Unfortunately, the property is ignored no matter the value.
I am certain the configuration file is being picked up properly (e.g. among others, I desperately added a @Value("${spring.datasource.data}" -annotated property in my test class and the value was indeed populated correctly).
As an alternative, I could annotate the test class with @Sql("classpath:data-h2.sql") which did run the script - however it did so for every test, while I wanted the script to be run once before any test execution.
I also tried removing that and using a blank schema.sql and moving the population to data.sql (as suggested here), but Spring would complain about the empty schema file - which is useless to me, because my schema is auto-generated and I certainly don't want to re-create it (NB: probably a conflict with a hibernate property if memory serves).
I've browsed some of the answers here, but the only one I could use, is not working.
The only solution I can see is to keep the @Sql annotation, but try and clear the tables after every test with another @Sql annotation launching another script on @After.
This seems insane to me - there must be a better solution.
Am I missing something more esoteric than it already is in my configuration?
Comment: side note: Shouldn't the `ddl-auto` property be configured under `spring.jpa.hibernate` instead of `spring.hibernate`?
Comment: @michalk looks like you're right - thanks for pointing that out
Answer: Simply put your file in the /main/resources directory (what you already did)
Spring Boot 2:
The correct property is:
spring.datasource.initialization-mode=always

Read more about this topic in the Spring Boot Documentation: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-initialize-a-database-using-spring-jdbc
Spring Boot 1
You only have to place data-h2.sql in the classpath
Read more about this topic in the Spring Boot Documentation:
https://docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/htmlsingle/#howto-initialize-a-database-using-spring-jdbc
Comment: Unfortunately the file *is* there, and as you can see from my configuration, the property is there too! But nope.
Comment: Elaborating on my comment above: "nope" means no script is executed with both file in place and property set in configuration. My version of spring boot is `1.5.8.RELEASE` is that's any relevant...
Comment: Yes this has changed from 1 to 2. I've added Spring Boot 1 to my answer
Comment: Sorry for the late reply. 1) seems so (no logs, properties are populated) 2) thanks for that - but it obviously still doesn't work for me no matter where the file is ...
Comment: Maybe you should try to create a minimal example. And if this works compare with your project
Comment: Sigh. You're probably right. Thought I might just have missed something obvious out there, but it's likely more relevant to something in the project itself. Will follow up when I have a chance. Thanks in the meantime.


Merge 2 columns of a CSV such as first+.+last to first.last with powershell

Question: The title is pretty badly written, so I will demonstrate what I would like to do. I have a csv with a list of first and last names, which relate to usernames in that all our domain usernames are first.last.
The csv has two columns that look like:
first  last
name1  name2
name3  name4

I have Import-Csv  -Path 'C:\blah\users.csv' | foreach { $($_.first) + "." + $($_.last) } but that doesn't work the way I need when I try to export-csv.
How can I get the above formatted in like name1.name2 and so on?
Thanks
Answer: You could do something like this:
Import-Csv -Path 'C:\blah\users.csv' |
  select @{n='FullName';e={"{0}.{1}" -f $_.first, $_.last}} |
  Export-Csv -Path 'C:\blah\fullname.csv' -NoType


Checking if the Product of n Integers is Divisible by Prime N

Question: Given $n$ integers, $x_1, ... , x_n$, is there some well-known procedure or algorithm that checks if the product $x_1 * ... * x_n$ is divisible by some arbitrary prime $N$ using minimal space?
Since the product and $N$ can be arbitrarily large, I don't think you can just simply use modular arithmetic to see if the remainder is $0$. I was thinking maybe convert the product to its prime factorization, and if $N$ isn't one of the primes used, then we know the product cannot be divisible by $N$, right? Does this seem like something that could work?
Comment: You don't need to do the multiplication, you can just check to see if $p$ divides any of $x_1,\cdots, x_n$.  Factoring is almost certainly a bad idea...that's very costly and unnecessary.
Comment: Just trial divide each $x_i$ by $p$. Then $N$ is divisible by $p$ if and only at least one $x_i$ is.
Comment: What about writing down the prime decomposition of $x_i$ first, hence deriving the prime decomposition of $x_1x_2\dotsm x_n$? Then proceed as you have written.
Answer: Note that primes are prime: that is, if $p \mid a b$ then $p \mid a$ or $p \mid b$. (This is Euclid's lemma.) Inductively, then, if $p \mid x_1 x_2 \dots x_n$ then $p$ divides some $x_i$. So just check each of the $x_i$ in turn. Modular arithmetic is fine for that.


View helper to sum line item amounts

Question: I have a view helper that totals the items inside line items.  Each order can have many line items.  Each line item has different sizes inside it (the fields).  For this below I'm curious how to sum up a certain field for multiple line items.
 def total_items(order)
        xxs = order.lineitems.xxs.sum
       return xxs
 end

This is what I have but doesn't work when there are multiple line items for an order, how can I properly write it?
Answer: It is not very obvious what you are asking, but I think what you want is something like this:
 def total_items(order)
    order.lineitems.inject(0) { |total, line_item| total + line_item.xxs }
 end

What this method does, is similar to this:
 def total_items(order)
    total = 0;
    order.lineitems.each do |line_item|
        total += line_item.xxs
    end
    total
 end

By the way, in Ruby the return keyword is optional.

View helper to sum line item amounts


php script can't access /tmp folder

Question: I have no open_basedir, php can access /etc /usr /proc /home etc… but not /tmp.
tmpfs is mount on /tmp (/tmp type tmpfs (rw))
That's also the reason I want to use the /tmp folder.
My files are owned by http (user for nginx and php) and readable by everyone.
sudo -u http cat /tmp/file is working but anything inside a php script does not (like file_exist() or file()).
edit : the error show in log :
PHP Warning:  file(/tmp/ydlw/pid): failed to open stream: No such file or directory in /srv/http/ydlw/status.php on line 267

edit2: I tested the issue the other way. I made
touch("/tmp/boo");
file_exist("/tmp/boo");

and file_exist return true so the file is created. Then I watched inside /tmp and no "boo" file can be found there. That's what I was afraid, php do not «see» the mount point. Why is that and how can I fix that ?
Comment: What is the error returned by those PHP functions? What does PHP error log show?
Comment: I added the error log
Comment: Does this file `/tmp/ydlw/pid` exist in `/tmp`? If not, then that is the reason for the error message.
Comment: -rw-r--r-- 1 http http 343 23 juil. 10:12 /tmp/ydlw/pid
Comment: What is your Linux distribution and PHP version and where did you get PHP from?
Comment: arch linux and PHP 5.5.11 (cli) (built: Apr  2 2014 06:08:28) (from the official arch repo)
Answer: I found off why, well, someone gave me the global hint.
It's neither the fault of php or tmpfs. The culprit was systemd and his security system PrivateTmp.
For those who get in the same issue that I did, the service php (and probably some others) have the PrivateTmp option to true in the systemd script (/usr/lib/systemd/system).
In that case, a new /tmp is created and isolated from the other one. All the data save inside are deleted once the service is stopped.
It's a security measure since /tmp can contain a lot a sensitive informations and php script are not always secure.
To deactivate this, simply copy the script inside /etc/systemd/system (to avoid overwriting of your changes after an update) and set PrivateTmp to false.
You can also set two or more services to share the same /tmp using JoinsNamespaceOf.
For more information > man systemd.exec
Comment: Thank you for that! I spent the whole day trying to figure that out. My brain is melting off my nose for trying so hard to figure that out.
Comment: I got confused on how exactly to do the steps but this has helped me:
https://www.maxoberberger.net/blog/2017/10/debian-9-private-tmp.html

php script can't access /tmp folder


Could i use Adaboost to solve the linear regression problem?

Question: Two months ago,i have learn the adaboost and I am surprised at it strength,so i have a question,could it can be used to solve the relationship between Tea polyphenols and spectrum? In many papers they use linear regression to predict tea polyphenols through spectral data.So can i use adaboost to solve this problem?
(I hope I made it clear)
Comment: You can use ```adaboostreggresor``` to solve your regression problems. For two machine learning tasks that is ```Classification``` and ```Regression``` ,there is ```adaboostclassifier``` and for regression there is ```adaboostregresor```. This link can help you how to implement it https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.AdaBoostRegressor.html
Answer: @think_maths already gave you a working practical solution, so let me give you a bit of intuition

If you look at the algorithm, It's pretty simple. The job of Adaboost is to give proper weights to the observations and classifiers/regressors so that the predictions for unusual observations become better. In the picture, function G(x) is any machine learning model of your choice, It could be Linear Regression as well.
You could read some paper if you want to learn deeper about it -
AdaBoost.RT: A boosting algorithm for regression problems.
also this thread -
Can AdaBoost be used for regression?

Could i use Adaboost to solve the linear regression problem？