Using proportional data with a binomial error structure in R... a worked example needing answers!

Question: I am trying to test if the proportion of herbivores in spider's diets is related to the proportion of herbivores in their grassland, but am struggling to understand if I should be using a binomial model.
Initially I was going to acrsine square root transform the response variable, but having done some further reading, discovered that this transformation is these days superseeded by using a binomial error structure in my model instead. I belive this is correct.... So,
I have 30 spiders per grassland and 5 grasslands.
My current binomial model looks like this:
glm (obs.herbs.in.diet.proportion ~ prop.herb.in.grassland, family=binomial)

The response variable (obs.herbs.in.diet.proportion) is structured by two columns of data along the lines of "successes,failures", using:
obs.herbs.in.diet.proportion<- cbind(proportion.herb.diet, proportion.NOT.herb.diet)

proportion.NOT.herb.diet is obviously not measured, I have just caluclated it to be the inverse of proportion.herb.diet (which I did measure) so that my response variable will work in this R model.
An example of my data is:
grassland proportion.herb.diet  proportion.NOT.herb.diet  prop.herb.in.grassland
    1             0.23                     0.77                 0.19
    1             0.27                     0.73                 0.19
    2             0.49                     0.51                 0.58
    2             0.49                     0.51                 0.58

As I understand it, I should be using a binomial model because my response variable is bounded by 0 at its lower limit and 1 at its upper limit.
1)  Does using a binomial model in this instance sound appropriate, and a better choice than a arcsine squareroot transforamtion?
2) Presumably, having proportional data for a second variable that is the explanatory variable (prop.herb.in.grassland) is not a problem, and does not require any transformation?
Additionally, when I run the model, I received the following warning:
Warning message:
In eval(expr, envir, enclos) : non-integer counts in a binomial glm!

3) Does anyone know if this means that my non-integer response variable values are inappropriate in a binomial model?
I used (summary) and get what looks to be a reasonable output and result, except I have large "under-dispersion".... I was worried about overdispersion!
Residual deviance:  5.8082  on 147  degrees of freedom

4) Is under-dispersion a concern and should I take action against it?
Comment: #3 is addressed here: http://stackoverflow.com/q/12953045
Comment: See also [Appropriate GLM when response variable is proportion, but not binomial](http://stats.stackexchange.com/questions/97907/appropriate-glm-when-response-variable-is-proportion-but-not-binomial). (Glen's comment there is a good enough answer.) The binomial model proper is for counting how many times something does happen out of the known number of times it can happen.
Comment: Thanks for these points. Each of my spiders is sampled once for the nitrogen in its tissues. So if it has a herb.proportion value of 0.35 that means 35% of its nitrogen is from herbivore sources. So, in this sense, could it be considered that the spider has undergone multiple trials (i.e. all the feeding events within the lifetime of the spider) and these total to 100%, and so we can view this as the spider having 0.35 successes to 65 failures? My apologies I'm unsure how to interpret if my data is actually binomial or not!! Its certainly proportional.
Answer: You can certainly use a binomial model when your response variable is a proportion. However, you then need to weight each observation by the number of trials that each observation represents, if you are to get an equivalent result to the formulation where you supply the positive and negative counts. In your case, you should weight by the number of spiders that are represented by the proportions in each observation.
Comment: @user2890989: Why not 10 or 1000 "food units"? It's just not a binomial model, though you could use a quasibinomial GLM: [What is Quasibinomial?](http://stats.stackexchange.com/questions/91724/what-is-quasibinomial). And consider robust standard error estimates.
Comment: (+1) It could be though, that each observation is a single spider, & there's no "number of trials" associated with the proportion of herbivores in its diet. Perhaps the OP will clarify.
Comment: Thanks for these comments. Yes, each observation is a single spider so there are no "number of trials" to weight each spider by. So if a single spider has a proportion of 0.35 then philosophically / biologically, this represents that of 100 food units 35 of these are herbivores. In this context, would 100 be the number by which i could weight each spider observation? And presumably when you mean weight each observation, this is where I weight "successes,failures", so in this instance 35,65 (=100).


Why did Fernando Torres win the Golden Boot at Euro 2012?

Question: Euro 2012 has now ended.
Why has Fernando Torres won the golden boot when the following players also had 3 goals?

Mario Gomez (Germany)
Alan Dzagoyev (Russia)
Mario Mandzukic (Croatia)
Mario Balotelli (Italy)
Cristiano Ronaldo (Portugal)
Answer: Torres won the Golden Boot because he was the most effective..
In the event of a tie, the Golden Boot will be awarded to the player with the most assists.
In a further tie, the winner will be the player spending the least time playing in the tournament(i.e On the pitch).
Fernando Torres secured one assist, the same as Mario Gomez, but spent a total of 189 minutes on the pitch compared to 281 minutes by Mario Gomez of Germany.
Over-all topscorer for Euro 2012 including qualification is Klaas-Jan Huntelaar (Netherlands) who scored 12 goals.


The probability to pick a spade and then a heart.

Question: From a standard deck of playing cards, you pick a card and without returning the card you pick a second card.  What is the probability that you picked a spade and then a heart?
Comment: @Jack I think you overcount. There are 13 cards of a suit.
Comment: The deck of cards has 52 cards: 14 are spades, 14 are hearts and 28 are the rest. I recommend, thinking about computing your probability in a simpler scenario supposing that you have 8 cards: 2 spades, 2 hearts and 4 the rest. Then try scaling your answer to the 52 cards. Try writing the cases by hand
Answer: There are 4 suits and each suit has 13 cards. In your first draw, you will get a spade with probability 1/4 (each suit is equally likely). Now that you have a spade, there are 51 cards (12 spades and 13 each of the other 3 suits). Now your probability of getting a heart is 13/51. So the probability of getting a spade followed by a heart is $1/4 \times 13/51$.


Wrapping C++ functionalities from std, is sometimes a bad idea?

Question: My question is about wrapping some containers or objects from the std library, and the cost of doing so.
Let's say I need to create a ThreadSafeStack class. I would wrap the std::stack container and use mutexes to make it thread safe. This would be totally ok because the functionalities of the new ThreadSafeStack would be worth the cost (function calls). But what if I want to wrap the std::mutex into a class MyMutex to add logging functionalities when debugging ? In your opinion, would it be worth it or not ?
And what if I do something like that only for convenience, to avoid writing std:: or using::std in all my files ? Do you think it is stupid ?
I have read a bit about function calls (like this for example) and I would say that it would not be a big overhead.
Comment: Your wrapper function calls most likely will be inlined on proper optimization level, resulting in *ZERO* overhead. For example check [this case](http://stackoverflow.com/a/15964113/1762344): pointer dereference wrapped into `operator*` results in identical assembler code to raw pointer dereference. Many levels of C++ abstractions can be evaporate during optimization.
Comment: I would also add that if you're doing IO (e.g. writing to a log file) then a function call is the least of your concerns.
Comment: You're right @selalerer.
Comment: Thanks for the example @Evgeny Panasyuk. Could we consider your quick answer as being an answer ?
Comment: this is the [decorator pattern](http://en.wikipedia.org/wiki/Decorator_pattern) which I find very useful when done correctly. Read about it.
Answer:
This would be totally ok because the functionalities of the new ThreadSafeStack would be worth the cost (function calls).

Your wrapper function calls most likely will be inlined on proper optimization level, resulting in ZERO overhead. For example check this case: pointer dereference wrapped into operator* results in identical assembler code to raw pointer dereference. Many levels of C++ abstractions can be evaporated during optimization.
Though, virtual function calls are very unlikely to be inlined. So use normal functions whenever it makes sense.

But what if I want to wrap the std::mutex into a class MyMutex to add logging functionalities when debugging ?

Logging may add some significant cost, but if you need it only during debugging - you can safely disable it on release builds via ifdefs or by any other means, like:
const bool do_logging = false; // somewhere
// ...
if(do_logging) // branching can be easily removed by optimizer,
               // because do_logging is constant
    // ...
else
    // ...

In your opinion, would it be worth it or not ?

Yes, of course. It is common practice to build more useful abstractions based on standard library facilities.

And what if I do something like that only for convenience, to avoid writing std:: or using::std in all my files ? Do you think it is stupid ?

It depends on your project - in some cases it is even OK to use using namespace std in header files. But note - someone who will include such header may face name clashes.
In most cases it is OK to use using namespace std at the head of .cpp files (after inlucdes). But even if that is not acceptable you can always use using directive at function level:
void foo()
{
     using namespace std;
     // ...
}


Saving a Form with Custom Button

Question: I am trying to create a custom button that modifies a field in a form then saves the form in the same way as the default save button. The following code creates the button but I am having trouble finding where/how to perform the operation that clicking the default save button executes, with validation and updating every field before executing my submit code.
function mymodule_form_alter(&$form, &$form_state, $form_id) {

     if ($form_id == 'submission_node_form') {
         $form['actions']['final_submit'] = array(
            '#type'   => 'submit',
            '#value'  => t('Submit'),
            '#submit' => array('mymodule_form_final_submit')
         );
     }

}

function mymodule_form_final_submit($form, &$form_state) {

}

Answer: A simple way is calling drupal_form_submit  in your custom module
function mymodule_form_final_submit($form, &$form_state) {

  drupal_form_submit('submission_node_form', $form_state);

}

Saving a Form with Custom Button


Access computer from both internet and internal network

Question: I work in a software development company and I have fairly common request from my boss that I need to execute. Setup the company's svn server to be accessible from both the internal network and the internet. Here's what the network looks like and what I've done so far:

Windows computers in local network all connected to a D-Link DIR615 router
Router connected to the internet
svn server installed on a computer in the local network
port forward on the router to redirect traffic on svn port to svn server

Now the svn server is accessible from the internal network using the internal IP address and from the internet using the router's public IP (which is static). But the problem is that it's not accessible from the internal network using the public IP. Is there any way I can get around this issue?
Answer: Yep. Tie the server to a fully-qualified DNS Name e.g. svn.yourcompany.com

On your external DNS, tie the DNS name to the SVN repo's public IP.
On your internal DNS, tie the DNS name to the SVN repo's private IP.
Comment: Thanks for your answers. I already have an FQDN tied to my external IP address, but how do I tie the internal IP to the FQDN in a D-Link DIR 612 router?
Answer: One simple solution is to not use an IP address to connect, use a DNS record (like svn.mydomain.com) and have it resolve to the correct IP address on the outside and the inside respectively.


A certain problem concerning a Hilbert class field

Question: Is the following proposition true? If yes, how would you prove this?
Proposition
Let $k$ be an algebraic number field.
Let $K$ be a finite abelian extension of $k$.
Suppose every principal prime ideal of $k$ splits completely in $K$.
Let $L$ be a finite extension of $k$.
Let $E = KL$.
Let $h'$ be the class number of $L$.
Then [$E : L$] | $h'$ and $E/L$ is unramified at every prime ideal of $L$.
Motivation
I thought I could use this proposition to prove the following result.
On the class number of a cyclotomic number field of an odd prime order
Effort
Let $\mathcal{I}$ be the group of fractional ideals of $L$.
Let $\mathcal{P}$ be the group of principal ideals of $L$.
Let $\mathcal{H}$ = {$I \in \mathcal{I}$; $N_{L/k}(I)$ is principal}.
Note that $\mathcal{H} \supset \mathcal{P}$.
Then use the following two links.
Related questions
On a certain criterion for unramification of an abelian extension of an algebraic number field
Complete splitting of a prime ideal in a certain abelian extension of an algebraic number field
Comment: I'm sorry, I down-voted this question as yet-another in a stream of these that strike me as not thought-through much. Only slightly facetiously, I'd wager I could write software to generate a huge number of not-trivial-to-answer questions in alg no th (akin to Gauss' disparagement of Fermat's "Last Theorem"). And, then, as a mathematician, my technical/aesthetic objection is that these questions "have no context", they are just shots-in-the-dark, disconnected. Each reasonable enough in isolation, but... consuming resources? A bit odd, actually.
Comment: @Makato Kato, Yes, indeed, I have noted your many questions of late, and only after these observations do I comment. I am not happy saying negative things, but, if you'll pardon my advice, greater "coherence", or "sense of purpose" would make a better impression on people able to answer your questions. The parallel is not entirely clear, but in English, and several other European languages, there is a fable of "The Boy Who Cried Wolf": it is worth looking up, if one has not ever seen it, and there is a point, that others' interest/care can be worn down... and real issues eventually lost.
Comment: What is the origin or background of this question? What have you done so far? Is it homework? How far have you got, and where are you stuck?
Comment: @paulgarett Dear Paul Garett, The motivation for the above question is to find a relation between the class number of a cyclotomic number field and that of its subfield. Please check to see the content of the link in the Motivation section. Regards
Comment: @paulgarett Dear Paul Garett, I added *Motivation* and *Effort* sections to explain my motivation and how the two links are related to the current question. Regards,
Comment: @OldJohn Dear John, The motivation came from desire to find a relation between the class number of $k$ and that of $L$. Regards,
Comment: @paulgarrett Dear Paul, have you checked the related questions above? Regards,
Comment: What's the reason for the downvotes? Unless you make it clear, I can't improve my question.
Comment: Please let me know the reason for the close flag. I'd like to avoid asking a question that you think should be closed.
Answer: This is a direct application of class field theory.  The assumption on $K$ implies that $K$ is contained in the Hilbert class field of $k$.  Thus $E$ is contained in the Hilbert class field of $L$, and so $E$ is unramified over $L$, and $[E:L]$ divides the class number of $L$.


A correct proof for this pumping lemma example?

Question: Given the language $L = \{0^{2^n} | n \geq 1\}$
So, the language contains all strings that have $2^n$ $0$s.
First of all I take $z = a^{2^p}$ where $p$ is the constant guaranteed by the pumping lemma.
Since $z$ is sufficiently long it can be split into the following string: $z = uvw.$
By the pumping lemma we can assume that $z=uv^2w ~~(uvvw)$ contains $2^n$ $0$s.
But $uv^2w = a^{2^p} + a^{|v|} = a^{{2^p+|v|}}$
So $uvvw$ = the original string + $|v|$ of the symbol $a$ represented as $a^{|v|}$.
This is a contradiction since this means that strings that do not have $2^n$ $0$s will be in the language.
End of proof
I hope I have made this easy enough to understand.
Comment: How do you know that $|v|$ is not the entire length of the string so that we have pumped length of $2(2^p) = 2^{p+1}$?
Comment: A good point, how would I go about fixing this proof?  Would this be a worthy conclusion to draw? a^{2^p+1}$ > a^{2^p}$ which is a contradiction.
Answer: Always use the exponent provided by the pumping lemma:
$2^p + |v|$ may accidentally happen to be a power of two, but $2^p + (i-1) |v|$ cannot be a power of two for every $i$, for example choose $i-1=2^{p+1}$.
Comment: did you mean p instead of i?
Comment: @user3130467 Where?


Mapeamento Eloquent?

Question: Existe alguma maneira de mapear uma chave estrangeira de uma database fora do meu default database no Laravel Eloquent?
Exemplo:
CREATE TABLE Banco1.Persons (
    PersonID int,
    LastName varchar(255),
    FirstName varchar(255),
    Address varchar(255),
    City int(11),

    CONSTRAINT FK_City FOREIGN KEY (City)
      REFERENCES Banco2.City (City)
      ON NO_ACTION
      ON NO_ACTION
    )
);

Comment: E ai deu certo??? a reposta!
Answer: Devem existir várias maneiras de se fazer isso, irei responder com uso que creio ser a melhor forma,
Adicione a segunda conexão no no seu config/database.php:
'mysql_secondary' => [
    'driver' => 'mysql',
    'host' => env('SECOND_DB_HOST', '127.0.0.1'),
    'port' => env('SECOND_DB_PORT', '3306'),
    'database' => env('SECOND_DB_DATABASE', 'database'),
    'username' => env('SECOND_DB_USERNAME', 'user'),
    'password' => env('SECOND_DB_PASSWORD', 'pass'),
    'unix_socket' => env('SECOND_DB_SOCKET', ''),
    'charset' => 'utf8',
    'collation' => 'utf8_general_ci',
    'prefix' => '',
    'strict' => false,
    'engine' => 'InnoDB',
],

Com isso você já consegue conectar a 2 bancos, o default e o mysql_secondary.

Para usar determinar a qual banco você está conectado basta usar o método estático: DB::connection('mysql_secondary');, passando como parâmetro o nome da conexão do banco configurado no database.php

Crie o migration e dentro da função up():
public function up()
    {
        Schema::create('Persons', function (Blueprint $table) {
            $table->increments('PersonID');
            $table->string('LastName', 255);
            $table->string('FirstName', 255);
            $table->string('Address', 255);
            $table->integer('City');
        });

        Schema::table('Persons', function($table) {
            $db = \DB::connection('mysql_secondary')->getDatabaseName();
            $table->foreign('City', 'FK_City')
            ->references('City')->on($db . '.City');
        });
    }

Essa função está criando a tabela e logo após definido a FK.

OBS.: é necessário que as tabelas estejam definida como InnoDB

Caso queria, agora basta você fazer os relacionamentos belongsTo dentro do seu model.
Esse procedimento foi testado no Laravel 5.7 com PHP 7.2 e Mysql 5.7.
Referencia 1, Referencia 2.

Mapeamento Eloquent?


Drupal 7 Views Contextual Links edit Nodes and Fields

Question: I created some Views with Drupal 7 and also installed the module Contextual Links. It helps me to edit Views and Blocks. But for non-admin users like Editors etc. it would be great to even edit Nodes or Fields with Contextual Links.
So I hover a Field there should appear a Edit Link.
I couldn't find any detailed settings for Contextual Links.
Please tell me how to set this up.
Comment: Try this solution: http://drupal.stackexchange.com/questions/58052/editing-fields-presented-in-a-view-in-drupal-7/58061#58061
Answer: At the moment, contextual links for the node are displayed only when you choose "Unformatted" as style and "Node" as row style. I already posted a feature request to allow adding contextual links when the row style is "Fields".


CSS make bottom container height 100% of visible space

Question: http://jsfiddle.net/n8YsM/
How do I make the div id blue take up the remaining visible space after the container div. Also this div should have no content.
Answer: Use this CSS:
<code>/*add this:*/
html, body
{
    height: 100%;
}

.clear
{clear:both;
display:block;
overflow:hidden;
visibility:hidden;
width:0;
height:0;

}
#blue
{width:100%;
background:blue;
/*and this*/height:100%;
}
</code>
Updated fiddle.
For the browser to detect that you want to expand the blue div 100%, you have to tell the HTML and the body of your page to be 100% as well, or the div has nothing to reference the percentage from.
Hope it helps you out.
Answer: Change the css to:
<code>#container{margin-left:auto;margin-right:auto;width:200px;}

html,body { height:100%; }

.clear{clear:both;display:block;overflow:hidden;visibility:hidden;width:0;height:0;}

#blue{width:100%;background:blue;height:100%;}
</code>
You had to extend the height of the page too.
Answer: something like this? http://jsbin.com/uxeda4
Comment: How about for something like on hobby.ellisberner.com/contact.html
?
Comment: you mean about the background?


Calculate the partial derivatives of $\sin(x^2+y^2) $ with the limit definition of the partial derivative.

Question: Here's what I have so far:
$$\frac{\partial f}{\partial y}|_{(a,b)} = \lim\limits_{t\to 0} \frac{\sin(a^2 + b^2 + 2tb + t^2) - \sin(a^2 + b^2)}{t} = \lim\limits_{t\to 0} \frac{\sin(a^2 + b^2)[\cos(2tb + t^2) - 1] + \cos(a^2 + b^2)\sin(2tb + t^2)}{t}$$
I can see that side left of the plus sign might go to $0$, and the side on the right would probably go to $\cos(a^2+b^2)$, but I'm missing a $2a$ multiplying my solution!
Answer: By definition
$$
\begin{gathered}
  \frac{{\partial f}}
{{\partial x}}\left( {x_0 ,y_0 } \right) = \mathop {\lim }\limits_{h \to 0} \frac{{f\left( {x_0  + h,y_0 } \right) - f\left( {x_0 ,y_0 } \right)}}
{h} \hfill \\
   \hfill \\
   = \mathop {\lim }\limits_{h \to 0} \frac{{\sin (a^2  + 2ah + h^2  + b^2 ) - \sin (a^2  + b^2 )}}
{h} =  \hfill \\
   \hfill \\
   = 2\mathop {\lim }\limits_{h \to 0} \frac{{\cos \left( {\frac{{2a^2  + 2ah + h^2  + 2b^2 }}
{2}} \right)\sin \left( {\frac{{2ah + h^2 }}
{2}} \right)}}
{h} \hfill \\
\end{gathered}
$$
where we used
$$
\sin p - \sin q = 2\cos \left( {\frac{{p + q}}
{2}} \right)\sin \left( {\frac{{p - q}}
{2}} \right)
$$
Now
$$
\mathop {\lim }\limits_{h \to 0} \cos \left( {\frac{{2a^2  + 2ah + h^2  + 2b^2 }}
{2}} \right) = \cos \left( {a^2  + b^2 } \right)
$$
by continuity of $\cos(t)$. On the other side
$$
\mathop {\lim }\limits_{h \to 0} \frac{{\sin \left( {\frac{{2ah + h^2 }}
{2}} \right)}}
{h} = \mathop {\lim }\limits_{h \to 0} \frac{{2ah + h^2 }}
{{2h}} = 2a
$$
since $\sin t \sim t$ as $t \to 0$. Therefore we have that
$$
\frac{{\partial f}}
{{\partial x}}\left. {\sin (x^2  + y^2 )} \right|_{\left( {a,b} \right)}  = 2a\cos \left( {a^2  + b^2 } \right)
$$
You can calculate the other partial derivative in the same way.
Answer: Just evaluate it as a derivative of a function of $t$.
$$\frac{d}{dt} \sin(a^2 + (b+t)^2)|_{t=0} = 2b\cos(a^2 + b^2)$$


Why does Brahms stand next to Bach and Beethoven?

Question: I've often heard the expression, "Bach, Beethoven, and Brahms" as sort of a summary of classical music, or something.  I feel that I understand why Bach and Beethoven should serve as pillars of classical music, but I haven't heard much about Brahms.
Can somebody give me a few pointers on why Brahms was chosen to stand next to Bach and Beethoven?  Also, in your opinion, is this still a helpful alliteration?
Comment: Vladimir Horowitz, in a radio interview with David Dubal, said that while Brahms may be one of the "Three Bs", he was a small B compared with Bach and Beethoven.
Comment: Related [question](https://music.stackexchange.com/q/63091/2600)
Answer: First, a history lesson:
Peter Cornelius originally claimed that these "Three Bs" were Bach, Beethoven, and Berlioz. It was Hans von Bülow that then replaced Berlioz with Brahms, and Bülow did it with a little pun: since a flat looks like a "B," he said that "My musical credo is in E♭ major, with three Bs in the key signature: Bach, Beethoven, and Brahms!" This automatically sets the stage that this statement isn't the most serious claim ever made.
Now, the actual answer:
Apart from the alliteration, the main reason it's these three composers is because they typify each of the three eras of tonal music.
Tonality was really codified in the Baroque era, which dates from (roughly) 1600 to 1750. Johann Sebastian Bach is a perfect figurehead for this era; in fact, most music historians choose 1750 as the end of the Baroque because that is the year of Bach's death.
After the Baroque came the Classical era, which lasts from around 1750 to approximately 1830. Beethoven, having died in 1827, is a solid figurehead for this era.
Then came the Romantic era, which lasts from around 1830 to around the turn of the 20th century. Brahms was chosen as the figurehead here. As for why Brahms should stand next to Beethoven, it might be important to note that von Bülow jokingly labeled Brahms's First Symphony "Beethoven's Tenth."
There are a few problems with this trio:

Beethoven is really best understood as a transitional figure between the Classical and Romantic. In short, this trio under-represents the Classical era; we need a Bozart!
Similarly, some (like Schoenberg) say that Brahms is better understood as a transitional figure between the Romantic and into the Modernist era. But this is less of a problem than it is for Beethoven, because Brahms was pretty firmly rooted in the Romantic.
Notice that the list is entirely Austro-German. This is a problem in much of music history: since the original music historians were German, our views of music history emphasize the German tradition. Missing in this trio are the masters of the French, Italian, Russian, etc., etc. traditions.
It privileges tonal music. There was something like tonality before the Baroque, but it was still being solidified; this list ignores everything before and including the Renaissance. Similarly, it ignores music after about 1900 (Brahms died in 1897).

As for whether it's helpful? I guess it's as helpful as anything would be that tries to summarize centuries of tonal music into three words :-)
Comment: A nice answer but I was surprised to read of Brahms as "a transitional figure between the Romantic and into the Modernist era". I question that judgement of this fairly conservative composer. Instead I would expect to read it of his progressive contemporaries and opponents, Liszt and Wagner.
Comment: @DavidRicherby to a German, _beaux arts_ sounds like _Bosart_ (malevolence), which is in fact the name of [a satire ensemble](https://de.wikipedia.org/wiki/BosArt_Trio).
Comment: @replete I was really referencing Schoenberg's famous "Brahms the Progressive" essay, but your point is well taken, and I'll edit accordingly.
Comment: If the quote is really about three B's in the key signature, it seems that this relates to the observation that a flat looks like a lowercase b more than the fact that B means B♭.
Comment: "Bozart" is particularly amusing, since it looks like a phonetic spelling of "beaux arts".
Comment: But did not Bozart compose 'March of the Clowns' from the opera 'Eine Nacht Mit Der Circus'? I could be wrong...
Comment: @Remy Thanks; I'm not sure how this lasted so long with that error!
Comment: I think you nailed it in the last sentence. Great as all three were, you just can't reduce 800+ years of musical culture to three names.
Answer: Brahms has written a whole lot of secular as well as some vocal works for sacred occasions (like Deutsches Requiem) with its own style and depth of tonality.  That's a corner very little covered by either Bach (who wrote a lot of formal religious vocal works, in cantata form, or arranged into larger works) or Beethoven (who was more into symphonic works in connection with vocals).  A lot of his "smaller" art is one of a kind.
Comment: I don't quite get what "the little corner" is. Beethoven wrote a lot of non-symphonic works. There are all his piano sonatas, his string quartets and many other chamber music works. The amount of chamber music from Beethoven is big. Bach wrote a lot for keyboard (harpsichord) and pieces for an instrument and keyboard, like violin and keyboard. Solo pieces for violin and more.


copy_to_user() and copy_from_user() for basic data type

Question: I'm writing a linux kernel driver and for every function that sends data up to userspace or reads data from userspace, I am using copy_to_user() and copy_from_user(). My question is: do I need to use these calls if I am just copying a basic data type such as a u32 or an int?
Comment: There's some confusion about just what you're asking. A sample function declaration, showing whether you're passing an `int` or a pointer to `int`, would be helpful. The two answers posted so far are based on two different interpretations of your question.
Answer: If the function receives a pointer to user-space data, you have to use copy_from_user() to copy the pointed-to data from user space into kernel space (and vice versa).
Note that the pointer value itself is passed by value (like all C parameters), so you don't have to do a copy_from_user() to obtain the pointer value before you can copy_from_user() the data it points to.
Numeric arguments work the same way as pointer arguments; in C terms, they're both scalars. You don't have to use copy_from_user() to copy the value of the parameter; that's already been copied. You only have to use it to copy data that's pointed to by a passed pointer.
So if you have a parameter of type int, you can use it directly. If your parameter points to an int, then the int object will be in user space, and you need to use copy_to_user to copy the value of that object into kernel space.
Comment: I disagree with you.  suppose a pointer in user space is not page aligned and you have to assemble both parts of the pointer to get it complete?  The only thing you receive from the user already as a parameter to the call is the user pointer, but if it points to another user pointer, that pointer must be acquired with user_copy.  In 64bit environments, a user pointer is 8 bytes wide, and can be split in a page boundary, so you'll need to acces the virtual page tables to translate it from user space to kernel.  Also, user space pages can be swapped out, so be careful with this also.
Comment: When you say the pointer is not page aligned, do you mean that the pointer object itself is misaligned, or the data it points to? Pointers are scalars and are always passed by value. If a system call has, say, a `void*` parameter, the kernel function that handles the system call receives a *copy* of the pointer; the alignment of the pointer object on the caller side is irrelevant.
Comment: For pointers of simple data types (like `int*`), `put_user` and `get_user` may also be used.
Comment: @holgac: Yes -- for the object pointed to by a pointer parameter, not for the pointer itself.it
Answer: When a user passes data to kernel space, this data can be split on several pages, and these pages can be even in swapped out memory.  In these cases, you'll have to wait for the kernel to swap in the page and get access to the page where the data is in.  In the case of elementary data types (like int or pointers) it is also true that some architectures (notably x86 intel) don't force the user to align the data so even an integer can be split around a page border.  You can have access to the first part of you integer, but to wait for the second to get swapped in by the memory manager before the whole thing is accessed.
You can save some roundtrips by putting all user data in a structure whose pointer is passed to the kernel.  You can copy_from_user it as a block and save accesses (and running into the risk of being blocked several times)
So, and as a conclusion, use the functions even for basic types, as there are plenty of them.  Don't assume anything about where the user data can be when running in kernel mode.  You have access to it, but the kernel virtual addresses of user data have nothing to do with the virtual addresses seen in user mode.
Comment: Luis: I think you have mis-interpreted the OP. All the OP is trying to do is pass a single value of a basic data type. The OP is really asking if it is possible to pass a basic data by value instead of by reference. As @Keith was pointing out, normally a pointer is passed in, and this pointer IS passed by value so it may be accessed directly. However if you want to dereference the user pointer, you must use the copy_from_user() or get_user() function when in the kernel.
Comment: Sorry, but as he says:  *if I am just copying a basic data type such as a u32 or an int*  meaning copying, so I supposed the int is passed by reference (to return some value, for example)  Of course that if he is passing a value only to the kernel (but not back to user space) he can do like this.  I am not thinking on ioctl's that is where this makes sense. Suppose he is trying to `int a; write(fc, &a, sizeof a);`...
Comment: Of course you can **use** the pointer passed to kernel space in a **write(2)** as data, but not much sense on making a driver like this.  He says *...and for every function...*
Answer: This is how I do it (works but I'm not sure if this is the right way):
First make an array of that datatype, then fill the array with the data, then pass the reference to that array, for example to pass only an integer:
    int *from_user = (int *)kmalloc(sizeof(int), GFP_KERNEL);
    if (copy_from_user(from_user, buff, count))
        return -EFAULT;
    printk(KERN_INFO "The value copied from user =   %d", *from_user);
    return sizeof(buff);

And the code for user space:
    int to_be_passed[1];
    to_be_passed[0] = 4; // 4 is just an example
    int fd = open(DEVICE_NAME, O_RDWR);
    write(fd, to_be_passed, sizeof(to_be_passed));


Storing files inside BASH scripts

Question: Is there a way to store binary data inside a BASH script so that it can be piped to a program later in that script?
At the moment (on Mac OS X) I'm doing
play sound.m4a
# do stuff

I'd like to be able to do something like:
SOUND <<< the m4a data, encoded somehow?
END
echo $SOUND | play
#do stuff

Is there a way to do this?
Answer: Base64 encode it. For example:
$ openssl base64 < sound.m4a

and then in the script:
S=<<SOUND
YOURBASE64GOESHERE
SOUND

echo $S | openssl base64 -d | play

Comment: Not really. `S=<<SOUND` might not do what you think it does (and in any case, the variable `S` will not contain the content of the here-doc).
Answer: I know this is like riding a dead horse since this post is rather old, but I'd like to improve Sionide21 answer as his solution stores the binary data in a variable which is not necessary.
openssl base64 -d <<SOUND | play
YOURBASE64DATAHERE
SOUND

Note: HereDoc Syntax requires that you don't indent the last 'SOUND'
  and base64 decoding sometimes failed on me when i indented that
  'YOURBASE64DATAHERE' section. So it's best practice to keep the Base64
  Data as well the end-token unindented.

I've found this looking for a more elegant way to store binary data in shell scripts, but i had already solved it like described here. Only difference is I'm transporting some tar-bzipped files this way. My platform knows a separate base64 binary so I don't have to use openssl.
base64 -d <<EOF | tar xj
BASE64ENCODEDTBZ
EOF

Answer: There is a Unix format called shar (shell archive) that allows you to store binary data in a shell script.  You create a shar file using the shar command.
Comment: This answer needs improvement with an example.
Answer: When I've done this I've used a shell here document piped through atob.
function emit_binary {
  cat << 'EOF' | atob
  --junk emitted by btoa here
  EOF
}

the single quotes around 'EOF' prevent parameter expansion in the body of the here document.
atob and btoa are very old programs, and for some reason they are often absent from modern Unix distributions.  A somewhat less efficient but more ubiquitous alternative is to use mimencode -b instead of btoa.  mimencode will encode into base64 ASCII.  The corresponding  decoding command is mimencode -b -u instead of atob.   The openssl command will also do base64 encoding.
Comment: @Sionide: Follow the link for source code, or you could use `mimencode`.
Answer: Here's some code I wrote a long time ago that packs a choice executable into a bash script.  I can't remember exactly how it works, but I suspect you could pretty easily modify it to do what you want.
#!/usr/bin/perl

use strict;

print "Stub Creator 1.0\n";

unless($#ARGV == 1)
{
    print "Invalid argument count, usage: ./makestub.pl InputExecutable OutputCompressedExecutable\n";
    exit;
}

unless(-r $ARGV[0])
{
    die "Unable to read input file $ARGV[0]: $!\n";
}

my $OUTFILE;
open(OUTFILE, ">$ARGV[1]") or die "Unable to create $ARGV[1]: $!\n";

print "\nCreating stub script...";

print OUTFILE "#!/bin/bash\n";
print OUTFILE "a=/tmp/\`date +%s%N\`;tail -n+3 \$0 | zcat > \$a;chmod 700 \$a;\$a \${*};rm -f \$a;exit;\n";

close(OUTFILE);

print "done.\nCompressing input executable and appending...";
`gzip $ARGV[0] -n --best -c >> $ARGV[1]`;
`chmod +x $ARGV[1]`;

my $OrigSize;
$OrigSize = -s $ARGV[0];

my $NewSize;
$NewSize = -s $ARGV[1];

my $Temp;

if($OrigSize == 0)
{
    $NewSize = 1;
}

$Temp = ($NewSize / $OrigSize) * 100;
$Temp *= 1000;
$Temp = int($Temp);
$Temp /= 1000;

print "done.\nStub successfully composed!\n\n";
print <<THEEND;
Original size: $OrigSize
New size:      $NewSize
Compression:   $Temp\%

THEEND

Answer: If it's a single block of data to use, the trick I've used is to put a "start of data" marker at the end of the file, then use sed in the script to filter out the leading stuff. For example, create the following as "play-sound.bash":
#!/bin/bash

sed '1,/^START OF DATA/d' $0 | play
exit 0
START OF DATA

Then, you can just append your data to the end of this file:
cat sound.m4a >> play-sound.bash

and now, executing the script should play the sound directly.
Answer: Since Python is available on OS X by default, you can do as below:
ENCODED=$(python -m base64 foo.m4a)

Then decode it as below:
echo $ENCODED | python -m base64 -d  | play

Storing files inside BASH scripts


Limit Apache 2 Memory Usage

Question: I am running a hobby webserver off of an ancient Blue & White G3/300 running Debian PPC Squeeze 2.6.30. The performance is okay for a while after a restart, but it eventually gets more and more bogged down. Right now it's at 76 days uptime, and the main culprit seems to be the memory usage of 10+ apache2 processes.
I think I need to lower the values for StartServers, MinSpareServers, and/or MaxSpareServers, but I'm not sure which one to adjust, and there are three sections for each depending on which mpm module is in use.
How do I tell which of the following sections I need to change, and what are some reasonable values given that the box has 448 MB physical memory (weird upgrade history of one each 64, 128, and 256 sticks)?
<IfModule mpm_prefork_module>
    StartServers          5
    MinSpareServers       5
    MaxSpareServers      10
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

<IfModule mpm_worker_module>
    StartServers          2
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

<IfModule mpm_event_module>
    StartServers          2
    MaxClients          150
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxRequestsPerChild   0
</IfModule>

There aren't any other instances of StartServers in my apache2.conf, but none of those mpm modules appear in mods-available or mods-enabled. Ideas?
Thanks!
Comment: I've gone on the assumption that your box is running low on memory (and your lousy performance is coming from swapping heavily).  If you're not swapping I'll bug you for more details :-)
Answer: 400MB isn't much for a web server these days -- you may want to consider replacing the box :)
That said, if your memory usage is ballooning you probably have a memory leak somewhere -- for a quick test look at the size of the httpd processes now, then stop/start Apache & see if they're a lot smaller.  If they are watch them for a few days and see if they grow.
If it is a memory leak the real solution for that is to find and fix the memory leak, but since that's usually a pain in the ass you can also adjust MaxRequestsPerChild to something other than 0 (unlimited). This will kill off the Apache workers when they've serviced a fixed number of requests (forcing them to give up their leaked memory in the process.
Start with larger values (in the thousands or so) and work your way down into the hundreds.  If you get below 100 requests per child your memory leak is big enough to warrant actually fixing it as the performance hit from constantly killing off and re-spawning apache workers will be significant.

Re: which mpm to adjust, the answer is almost certainly prefork.
You can run httpd -V and look for the Server MPM: line which will tell you for sure.
Comment: -V gave me the prefork info I needed (although it's apache2 -V in my case). Thanks!
Comment: If you're not handling a lot of requests you can also trim the Start & Spare server counts as you mentioned in your original post (on development systems I set them all to something between 2 & 5 to reduce RAM usage)
Comment: Seems to have done the trick. I think the problem was that I was running out of physical memory and swapping because too many child servers were up (each grabbing about 80 MB).

And yes, I know, the server is old. But it's barely handling any requests :oD.
Comment: I ended up dropping the min and max spares to 3 and 6 from 5 and 10, and that seems to leave enough RAM leftover to keep things from swapping. Thanks!
Answer: To nail down the memory use of the apache process you will want to adjust the MaxClients.
The common rule of thumb is:
(Max desired Memory) / (Memory Usage of 1 Apache Process) = # Max Clients
In the end you also need to adjust your to be MaxSpareServers <= Max Clients.
The memory usage of one process is strongly depended on the modules you have loaded (php and so on) so you may want to set the Max Clients a little lower.

Limit Apache 2 Memory Usage


Need to count field specific value in Views

Question: Need to count field specific value in Views.
I have 2 content types "project" and "task" In the task i have reference field for project (assign task to project) And another field "task_status" as a list: closed / open
I want to calculate the closed and total tasks so i can get the results in percentage:
closed_task / total_task * 100
How can i get the count for closed tasks value ?
Sorry for my bad English :)
Answer: You first create  a views to show the list of  open or closed task.
create a views with content type  "project" remove all field  then add a relation on task referenced field ,add title field with consider that you select relation field for it (because we want load task title instead of project title) then add  filter   "task_status" equal to close,then enable exaggeration and on title.and finally for better result you can get the title(or nid ) of project with contextual filter . it help you you can get only the list of tasks form specified  project.( and finally create another page in that views with only one change,  status=open ).
Comment: Thanks zhilevan ! I need to count the total and the closed task for that project.
How can you do Math expression from one view to another ?
Comment: not it is not need, you can use  `https://www.drupal.org/project/views_field_view`


Python sockets: TCP errors in linux, while same program works fine on Windows10

Question: I'm trying to communicate with a commercial power supply device via TCP/IP using python sockets.
I tried using both a virtual linux(centos8stream) and virtual windows10, both running at the same physical computer, on the same network interface. Both have python3.9.
I imagined the tcp/ip sockets would work same in both OS, but I got some communication issues ONLY in linux:

The delay between send and receive becomes much longer(2 sec instead of 0.14 sec) after few tries
Sometimes I hit the timeout and can't communicate with the device at all.

I got Wireshark running in both OS:

In windows there are no unusual messages (very rarely there is a TCP Retransmission)
In linux, after a while (or sometimes immediately) wireshark is flooded with TCP Dup Ack, TCP Fast Retransmission and TCP Spurious Retransmissions.

My question:

What could be the source of the difference? Are there any socket options I can experiment with?
Is there a way to compare network parameters in linux and windows10?

A sample program to continuously read device identification:
import socket
from time import sleep,time
HOST = '10.27.4.50'
PORT = 4444

#Create object and open the connection
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))

client.settimeout(5)

# Read identification
message=(b'*IDN?\r\n')

for i in range(5):
    start_time = time()
    client.sendall(message)
    rep=client.recv(1024)
    print("Trial {}, delay: {} seconds ".format(i,time() - start_time))
    sleep(1)

client.close()

windows:
Trial 0, delay: 0.17121100425720215 seconds
Trial 1, delay: 0.10957813262939453 seconds
Trial 2, delay: 0.17148327827453613 seconds
Trial 3, delay: 0.13976049423217773 seconds
Trial 4, delay: 0.14109373092651367 seconds

linux(See that last message took longer to receive response, this corresponds to start of TCP errors)
Trial 0, delay: 0.15080499649 seconds
Trial 1, delay: 0.143104076385 seconds
Trial 2, delay: 0.170531988144 seconds
Trial 3, delay: 0.183187961578 seconds
Trial 4, delay: 2.0480530262 seconds

Note: I also tried a physical linux machine, with same issues.
Comment: I don't think virtualization is the issue, the result is same if I use a physical computer to communicate the device. What bothers me is the difference between linux and windows.
Answer: I figured the problem was related to tcp timestamps. In linux, by default tcp_timestamp is enabled, in windows it's disabled.
Disabling tcp timestamps on linux, solves the problem:
sysctl -w net.ipv4.tcp_timestamps=0

Conversely, enabling timestamps on windows reproduces the same problem I observed on linux.
netsh int tcp set global timestamps=enabled

Digging a bit further, I saw that the tcp errors such as Dup Ack started occurring when device sends a packet, with a timestamp lower then of the previous packet. Probably there is a bug in the hardware/firmware of device and it creates faulty timestamps.


Eloquent: relacionamentos entre tabelas de um blog

Question: Alguém teria um exemplo prático de uso de relacionamentos no Eloquent da seguinte forma:
Tenho um blog com várias categorias, nessas categorias vou ter vários Posts, como eu faço para exibir uma categoria com vários Post na Views.
Já vi vários exemplos aqui, mas nenhum se encaixou no que eu quero acima.
Model Post:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category');
    }

    public function tags()
    {
        return $this->belongsToMany('App\Tag');

    }

    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

Model Category:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'categories';

    public function posts()
    {
        return $this->hasMany('App\Post');
    }
}

View index

    @foreach($posts as $post)

          image) }}" width="572" height="350" alt="" />{{--
          image) }}" width="572" height="350" alt="" />--}}

{{ $post->category->name }}

          id) }}">{{ $post->title }}

    @endforeach

Controller:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Post;
use Mail;
use Session;
use App\Category;

class PagesController extends Controller {

    public function getIndex() {

        $posts = category::find(1)->posts()->orderBy('created_at', 'desc');
        return view('v1.index')->withPosts($posts);
        // $posts = Post::orderBy('created_at', 'desc')->limit(3)->get();
        // $categorias = Category::find(1);
        // return view('v1.index')->withPosts($posts)->withCategorias($categorias);
    }

    public function getContact() {
        return view('v1.contato');
    }

    public function postContact(Request $request) {
        $this->validate($request, [
            'email' => 'required|email',
            'subject' => 'min:3',
            'message' => 'min:10']);

        $data = array(
            'email' => $request->email,
            'subject' => $request->subject,
            'bodyMessage' => $request->message
            );

        Mail::send('emails.contact', $data, function($message) use ($data){
            $message->from($data['email']);
            $message->to('firstname.lastname@example.com');
            $message->subject($data['subject']);
        });

        Session::flash('success', 'Your Email was Sent!');

        return redirect('/');
    }

}
laravel

Comment: Esse seu código tá funcionando? Os relacionamentos aparentemente estão corretos. Acho que depois do orderBy você precisa dar um ->get();
Comment: Eu estou querendo exibir na view os posts de apenas uma categoria...
Comment: E aparentemente você está fazendo corretamente: `$posts = Category::find(1)->posts()->orderBy('created_at', 'desc')->get();`. tenta ai.
Answer: Vamos lá, o Eloquent possui uma maneira de listar todos os dados de outras tabelas relacionadas com determinada model.
Usando o método hasMany();, que você pode colocar na model, segue esse exemplo prático:
Model:
class Categoria extends Model
{
    protected $fillable = ['id', 'nome', 'descricao'];

    protected $table = 'categoria';

    public function retornaTodosOsPostsDessaCategoria()
    {
        return $this->hasMany(Post::class);
    }

}

Certo, agora como você faz para acessar esse método? Simples, crie um objeto do tipo categoria, ou use diretamente a classe.
class CategoriaController extends Controller
{
    public function __construct()
    {
        $this->categoria = new Categoria();
    }

    public function listaTodosOsPostsNaViewIndex($idCategoria)
    {
        return view('categoria.index', [
            'categoria' =>  $this->categoria->find($idCategoria),
            'posts' => $this->categoria->find($idCategoria)->retornaTodosOsPostsDessaCategoria()
            //retornar esse posts é facultativo, pois voce tem acesso ao método na view;
        ]);
    }

}

Agora como manipular na view.
View
@extends('templates.app')
@section('content')

        Nome
        Título

      @foreach($posts [pode usar tambem o $categoria->retornaTodosOsPostsDessaCategoria] as $post)

        {{$post->titulo}}

      @endforeach

@endsection

Pronto, esse método retornaTodosOsPostsDessaCategoria() retorna uma coleção de objetos, onde você pode manipular da maneira que quiser.
Comment: Obrigado @Felipe Paetzold


prove that $f_n$ conerges uniformly in $X$"

Question: Please, help me to find a solution to this question:
"If a sequence of continuous functions $f_n:X \rightarrow \mathbb R$ converges uniformly in a dense set $D \subset X$, prove that $f_n$ conerges uniformly in $X$".
Obs:
Once $f_n$ converges uniformly in $D$, then $f_n$ is a Cauchy sequence, i.e., given $\varepsilon >0$, there exists $n_0 \in \mathbb N$, such that $m,n>n_0 \Rightarrow |f_m(d)-f_n(d)|<\varepsilon$, for every $d \in D$ Besides that, $f_n$ is continuous and every point of $X$ is the limit of a sequence of points pertaining to $D$. Then, $d_n \rightarrow x \Rightarrow |f(d_n) \rightarrow f(x)|$. How to conclude that there exists $n_0 \in \mathbb N$, such that $m,n>n_0 \Rightarrow |f_m(x)-f_n(x)|<\varepsilon$?
Answer: Fix $m$ and $n$, both greater than $n_0$, and let $x \in X$. You can pick $d \in D$ such that $|f_n(d) - f_n(x)| < \varepsilon$ and $|f_m(d) - f_m(x)| < \varepsilon$. Then you get $|f_m(x) - f_n(x)| \leq |f_m(x) - f_m(d)| + |f_m(d) - f_n(d)| + |f_n(d) - f_n(x)| < 3\varepsilon$.
Answer: Hint:  For $x\in X$, pick $d\in D$, and pick $n,m > N_{\epsilon/3}$, so large that
$$|f_m(x) - f_m(d)| < \frac{\epsilon}{3}$$ $$|f_n(x) - f_n(d)| < \frac{\epsilon}{3}$$
And also so that
$$|f_m(d) - f_n(d)| < \frac{\epsilon}{3}$$
(Why can we choose $d\in D$ so that this happens?)
Now, with these choices of $n$, $m$, and $x$, can you conclude that $|f_n(x) - f_m(x)| < \epsilon$?
Comment: Hi, Nicholas. $|f_m(d)-f_n(d)|<\frac{\varepsilon}{3}$ is true because $f_n$ converges uniformly on $D$. But why is true that exists $n_0 \in \mathbb N$ such that $m>n_0 \Rightarrow |f_m(x)-f_m(d)|<\frac{\varepsilon}{3}$?
Comment: Actually, we don't even need $m>n_0$ for this to be true.  What do you know about $f_m$?
Comment: In other words, the functions in the sequence $\{f_n\}$ have a certain property that tells us that, given $x\in X = \overline{D}$, there exists $d\in D$ so that $|f_m(x) - f_m(d)|< \frac{\epsilon}{3}$.  We will need to use this.
Comment: would you be speaking about continuity?
Comment: Exactly correct.
Comment: So, let me formalize. If $f_n(d)$ is continuous in $x \in X$, then given $\varepsilon>0$, there exists $\delta>0$, such that $|d-x|< \delta \Rightarrow |f_n(d)-f_n(x)|< \frac{\varepsilon}{3}$. But for each $n$ we have a different $\delta$.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/14110/discussion-between-walter-r-and-nicholas-stull)
Comment: But since you fix $n$, $m$, you can just pick the smallest of $\delta_n$, $\delta_m$ satisfying this, and then it will satisfy this for both.  And the formalization is: $f_n$ is continuous on $X = \overline{D}$, then given $\epsilon > 0$, $x\in X$, there exists $\delta_n > 0$ such that for any $d \in D$ such that $|x-d|<\delta_n$, $|f_n(x) - f_n(d)| < \frac{\epsilon}{3}$.
Answer: For $x \in X$, pick a sequence $d_k \in D$ satisfying $d_k \to x$. Then
$$
|f_n(x) - f(x)| = \left|f_n\left(\lim_{k \to \infty} d_k\right) - f\left(\lim_{k \to \infty} d_k\right)\right| \\
 = \left|\lim_{k \to \infty} f_n(d_k) - \lim_{k \to \infty}f(d_k)\right| \\
= \lim_{k \to \infty} |f_n(d_k) - f(d_k)| \\
\le \sup_{d \in D} |f_n(d) - f(d)| \\
= \|(f_n|_D) - (f|_D) \|_{\infty} \underset{n \to \infty}{\longrightarrow} 0.
$$
The uniform convergence of $f_n|_D$ to $f|_D$ implies the last statement, and since $\|(f_n|_D)-(f|_D)\|_{\infty}$ is a quantity that depends only on $n$ and not on $x$, this proves uniform convergence of $f_n$ to $f$.
In fact, you can even show a bit more. Since $h(x) \overset{def}= |f_n(x) - f(x)|$ is a continuous function on $X$ and $D$ is dense in $X$, we have
$$
\sup_{d \in D} h(d) = \sup_{x \in X} h(x)
$$
or in other words, $\|(f_n|_D)-(f|_D)\|_{\infty} = \|f_n-f\|_{\infty}$. Since uniform convergence is the same as convergence under the supremum norm, the fact that the statement you are asking about is true is no surprise anymore, since now the proof simplifies to
$$
\|f_n-f\|_{\infty} = \|(f_n|_D)-(f|_D)\|_{\infty} \to 0.
$$
Hope that helps,


What is the name for a group of five?

Question: The title seems off-topic, and I don't know what to tag. Could anyone edit it?
I see group of four is quartet, three is trio, two is duo (?) and one is solo. I see every number has different name. So:

What is the name for five?
Is there any language of this naming because a friend of mine said that "try Latin, I think it's the language".
Comment: As in Schubert's [Trout Quintet](https://en.wikipedia.org/wiki/Trout_Quintet)? It must be one of the best known, quite likely _the_ best known piece for any quintet.
Answer: The naming of groups does indeed come mostly from Latin, sometimes with Italian influence.
The etyomologies for the first nine are:

    Number    Group name     Latin      Italian      Meaning
      1         solo         solus       solo        "alone"
      2          duo           duo        due        "two" - this is the Latin word
      3         trio          tres        tre        "three" - tres, but on the pattern of duo
      4        quartet       quarto    quartetto     "fourth" (as opposed to "four")
      5        quintet       quintus    quinto       "fifth"
      6        sextet         sex        sei         "six" - from the Latin (old English: sestet)
      7        septet        septem     sette        "seven"
      8         octet         octo       otto        "eight"
      9         nonet        novem       nove        "nine"

It is odd how 4 and 5 have their root in the ordinal number ("fourth, fifth") while the others count directly (two, three, six, etc). Also - the "-et" ending can have the connotation of "a piece written for..." (e.g. "duet").
Comment: The Italian table is all mixed up: if you wanted to write the names of the numbers they are: *uno, due, tre, quattro, cinque, sei, sette, otto, nove*. If you wanted to write the names of the groups they are: *solo, duo, trio, quartetto, quintetto, sestetto, settetto, ottetto, nonetto*. If you wanted to write ordinal numbers then they would be: *primo, secondo, terzo, quarto, quinto, sesto, settimo, ottavo, nono*. Your table mixes all these three elements.
Comment: I believe it's "O sole mio" where sole = sun.
Comment: @Floris Well, I belive *trio* comes from Italian *trio* (see [here](http://dictionary.reference.com/browse/trio?s=t)) as *sextet* comes from *sestetto* (according to [this](http://dictionary.reference.com/browse/sestet), *not* from the latin number).
Comment: @James - yes you are right. I shouldn't write answers at 2 am. What was I thinking- error removed. Thanks for pointing it out.
Comment: @Bakuriu - I am writing the etymology of each of the group names - sometimes these are numbers, sometimes ordinals, sometimes (as in "solo") neither. I am showing that most of the names can be traced to Latin, and that where the etymology is from the Italian, it's not always from a number. I am sorry if I did not make that clear - I do know how to count in Italian, but my point was (intended to be) that that doesn't always explain the names of the groups. Maybe I should make an additional column in my table - but then the description falls off the edge...
Comment: Trio comes actually from the prefix tri- which is used in greek and latin for many words even in english (trident, triangle, tridimensional etc.).
Just to cause some more confusion, a vocal trio is often called a terzetto.
Answer: A quintet.
For example, the Miles Davis Quintet or the Charlie Parker Quintet with Dizzy Gillespie.
Johannes Brahms wrote a Piano Quintet in F minor, but no, it's not a piece for five pianos (it's for piano plus string quartet).
According to Merriam-Webster, the etymology of the word is Latin by way of Italian, from the Italian word "quintetto." First known use dates back to 1811.
Comment: Quint means five. Kwint is a fifth. Quintal harmonies are ones built on 5ths
Answer: It is a quintet.

A quintet is a group containing five members. It is commonly
  associated with musical groups, such as a string quintet, or a group
  of five singers, but can be applied to any situation where five
  similar or related objects are considered a single unit. In classical
  instrumental music, any additional instrument (such as a piano,
  clarinet, oboe, etc.) joined to the usual string quartet (two violins,
  a viola, and a cello), gives the resulting ensemble its name, such as
  "piano quintet", "clarinet quintet", etc. A piece of music written for
  such a group is similarly named.

What is the name for a group of five?


What are these arrows?

Question: I have played the guitar for 6 years now and have never seen this notation. What do these arrows mean?

EDIT: Bach Chaconne, arrangement by Edson Lopes, classical guitar (for electric guitar players: played with fingers, not a pick).
Comment: Just a guess so not a real answer: The advice to play both notes with a downstroke?
Comment: Need more info - composer, piece, violin or guitar, more of the page?
Comment: Your having never seen this notation before may well be because this music is not for guitar. Looks like it's for violin based on the name portion in the picture.
Comment: @Dekkadeci this is an arrangement for guitar specifically, that's why i'm curious
Comment: @Tim https://youtu.be/9AKC6e96pno video (didn't notice anything). Full sheet music in the description.
Comment: The first note in the next measure has two different fingerings offered.  That suggests to me that the arrows indicate that those are part of that same alternate fingering.
Comment: @Duston the first note in the next measure is a double-stop. That's not two different fingerings, it's the fret numbers for each note.
Comment: I've never seen this notation, but I would guess that the down arrow means to play the notes by hammering down on the frets, perhaps. Usually classical guitar transcriptions will indicate up or down strokes for the notes using the violin-style up and down bow markings, so I don't think it's that, although it might be given the idiosyncrasies of the notation.
Comment: @DonHosek good point.  I'm showing my piano player bias.
Answer: Thank you for including more information, it is very important to see and hear things in context, like knowing the key and time signatures in order to be able to give an accurate answer.
The notes happen at about 3:56 and are at the top of page 4. The arrows indicate shifting the positioning so the 1st finger extends towards the nut and playing the F and Eb with fingers 4 and 2. This allows the quick playing of the Bb of the double stop on the downbeat with the 1st finger.

What are these arrows?


Objective-C Moving Items Between Arrays (Memory Management)

Question: Is there any practical difference between the following two code snippets:
NSObject * obj = [[_mutableArrayOne objectAtIndex:i] retain];
[_mutableArrayOne removeObject:obj];
[_mutableArrayTwo addObject:obj];
[obj release];
and
NSObject * obj = [_mutableArrayOne objectAtIndex:i];
[_mutableArrayTwo addObject:obj];
[_mutableArrayOne removeObject:obj];

Answer: Only the extra retain/release cycle that you ask it to do.
It might have some performance impact inside a loop of time-sensitive processing?
Comment: Thanks. That's pretty much what I thought.
Comment: removeObject remove all occurrences - in second case you will not have the 'objec' in the mutable array any more .... see my answer...
Comment: This is blatantly not true.  In the second case, there is a small window of time when the object is in *both* arrays.  In a multithreaded environment, this may be a problem (conversely, having the object in no arrays might also be a problem).
Answer: Other than the need to call retain and release twice instead of once, no. The end result is the same.
Answer: If you want to own the object in the index 'i' then remove object from array and then you can add it back to the array in the later stage of the project.
I suggest option 2 should be careful : the object will not be in the array any more.
The result is different -- Option 1 you will have the 'object' in mutable array and in option 2 'object' will not be in array (removeObject remove all occurrences)
Comment: Not sure if I'm understanding you properly. Could you elaborate?
Comment: removeObject remove all occurrences

in your second case you add the occurrence of the 'obj' first then there will be duplicate entry in the array then you ask to remove the 'obj' occurrence using 'removeObject' which will remove all occurrence(apple apple documentation) of the 'obj' in the array so no more 'obj' is not present in the array

but in 1 case obj will be present in the end of the array.
Comment: sorry i missed some detail actually both are same
Answer: Both are same with respect to Memory Management and programming logic. Only in the first case you have to operate a pair of extra retain/release operation.


Equivalence bounded limit superior

Question: Suppose that $(x_n)_{n=1}^\infty$ is a real sequence such that $\limsup_n x_n$ exists. I wish to show that

$\limsup_n x_n\le\beta \iff \forall\varepsilon>0\ \ \exists N\ \ \forall n\ge N, x_n < \beta + \varepsilon$.

I do understand the quantifiers, and have two equivalent definitions of $\limsup_n x_n$:

$\lim_{n\to\infty}\left(\sup_{m\ge n} x_m\right)$;
the greatest number that any subsequence can converge to.

However, this proof looks quite finicky, and would like a suggestion for an effective approach.
Answer: Suppose the left hand side holds, and let $(x_{n_k})_k$ be a subsequence that converges to $p = \limsup_n x_n$, so that we have $p \le \beta$.
Suppose the right hand side does not hold, then there exists some $\varepsilon_0 > 0$ such that for all $N$ there exists some $n > N$ with $x_n \ge \beta + \varepsilon_0$ (using the negation rules for quantifiers).
This means that we can find a subsubsequence $(x_{n_{k_l}})_l$ such that all terms are $\ge \beta + \varepsilon_0$, but the limit of this subsubsequence, which is still $p$, is also $\ge \beta + \varepsilon_0$, which contradicts $p \le \beta$. So the right hand side does hold.
Suppose the right hand side holds, and again let $(x_{n_k})_k$ be a subsequence converging to $p = \limsup _n x_n$. Suppose $p > \beta$. Then take $\varepsilon_0 = \frac{(p - \beta)}{2} > 0$. Using the right hand side we find a $N_0$ such that for all $k \ge N_0$ all terms $x_{n_k}$ are $< \beta + \varepsilon_0$, so $p$, still the limit, obeys $p \le \beta + \varepsilon_0$. But by how $\varepsilon_0$ was defined, $p > \beta + \varepsilon_0$, so we have a contradiction. Hence $p \le \beta$.

Equivalence bounded limit superior


Criar nova base de dados a partir de valores aleatórios com loop ou outro método

Question: Eu tenho três dataframes com número diferente de linhas e eu gostaria de criar um novo dataframe com 100 valores aleatórios a partir desses dataframes e com base em três critérios:

A - Coluna a e b terá 100 valores aleatórios do 1 dataframe
B - As primeiras 50 linhas das colunas c1 e d1 em 50 valores aleatórios pareados, ou seja, que ocorrem na mesma linha do dataframe 2
C - As subsequentes 50 linhas de colunas (51-100) c2 e d2 em outros 50 valores aleatórios pareados, que ocorrem na mesma linha a partir do dataframe 3

Eu tentei com loop, mas não vai bem. Como eu poderia corrigir ou fazer isso de uma forma melhor?
Aqui estão os dados eo script, eo resultado esperado:
a <- c(4,6,7,3,2,5,6,9,6,5,8,6,7,8,9,7,6)
b <- c(40,60,70,30,20,NA,60,90,60,50,75,34,42,32,NA,45,29)

c1 <- c(1,2,3,4,5,6,7,8,9,10)
d1 <- c(10,9,8,7,6,5,4,3,2,1)

c2 <- c(11,12,13,14,15,16,17,18,19,20)
d2 <- c(20,19,18,17,16,15,14,13,12,11)

df1 <- data.frame(a,b)
df2 <- data.frame(c1,d1)
df3 <- data.frame(c2,d2)

#newdf (with 100 rows)

n <- 100
newdf <- data.frame(n=rep(1:n))
newdf$a <- NA
newdf$b <- NA
newdf$c <- NA
newdf$d<- NA

for (i in 1:50){
  newdf$a[i] <- sample(df1$a, 1, replace=T) # random value
  newdf$b[i] <- sample(df1$b, 1, replace=T) # random value
  newdf$c[i] <- sample[df2$c1,1, replace=T] # one criterion
  newdf$d[i] <- sample[df2$d1,1, replace=T] # one criterion
}

for (i in 51:100){
  newdf$a[i] <- sample(df1$a, 1, replace=T) # random value
  newdf$b[i] <- sample(df1$b, 1, replace=T) # random value
  newdf$c[i] <- sample[df3$c2,1, replace=T] # two criterion
  newdf$d[i] <- sample[df3$d2,1, replace=T] #two criterion
}

#Result

a      b     c    d
7     60     1    10 # linha 1
6     50     3    8
2     90     5    6  # linha 50
.
.
.
2     90     11    20  # linha 51
.
.
.

Answer: Creio que a melhor maneira para resolver este problema não seja através de um loop. Eu resolvi ele selecionando as linhas aleatoriamente, todas de uma vez. Guardei estes resultados dentro de vetores chamadas index_a, index_b, index_cd_50 e index_cd_100. Estes vetores armazenam, portanto, as 100 linhas sorteadas do df1, com as colunas a e b, e as 50 linhas sorteadas dos df2 e 50 linhas sorteadas do df3.
Estas linhas serão consideradas antes ou depois da posição 50 quando monto o newdf. Tente rodar o código linha a linha para identificar o que fiz.
a <- c(4,6,7,3,2,5,6,9,6,5,8,6,7,8,9,7,6)
b <- c(40,60,70,30,20,NA,60,90,60,50,75,34,42,32,NA,45,29)

c1 <- c(1,2,3,4,5,6,7,8,9,10)
d1 <- c(10,9,8,7,6,5,4,3,2,1)

c2 <- c(11,12,13,14,15,16,17,18,19,20)
d2 <- c(20,19,18,17,16,15,14,13,12,11)

df1 <- data.frame(a,b)
df2 <- data.frame(c1,d1)
df3 <- data.frame(c2,d2)

index_a <- sample(1:nrow(df1), 100, replace=TRUE)
index_b <- sample(1:nrow(df1), 100, replace=TRUE)

index_cd_50  <- sample(1:nrow(df2), 50, replace=TRUE)

index_cd_100 <- sample(1:nrow(df3), 50, replace=TRUE)

newdf <- data.frame(a=df1$a[index_a],
                    b=df1$b[index_b],
                    c=c(df2$c1[index_cd_50], df2$d1[index_cd_100]),
                    d=c(df3$c2[index_cd_50], df3$d2[index_cd_100]))


Add datestamp to a .txt file in an SSIS Package?

Question: I'm using Visual Studio 2005 to build a package that will deposit a flat file (.txt) into a specified location. The package will run every weekday.  Currently, the file that gets deposited is just called summary.txt, and the file is simply overwritten each day for new content.  What I'd like to do instead is change the name of the file to summarymmddyyy.txt, and just add a new file to the location everyday with the date of deposit.  So, today's would be summary12062010.txt, tomorrow's would be summary12072010.txt, etc.  Is there a way to do this within an SSIS package?  Really, all I'm doing is a simple data flow that does a select statement from a SQL DB source to this flat file - nothing too fancy.   Thanks!
Answer: You can use a variable that is evaluated as an expression to create the file name.
Add a new SSIS variable to your package.  Select the new variable in the Variables window and view properties (press F4).  Set the EvaluateAsExpression property to True and enter the following for the  Expression property value
<code>"summary" + RIGHT("0" + (DT_STR, 2, 1252) (DATEPART("mm", GETDATE())), 2) + RIGHT("0" + (DT_STR, 2, 1252) (DATEPART("dd", GETDATE())), 2) + (DT_STR, 4, 1252) (DATEPART("yyyy", GETDATE())) + ".txt"
</code>
This expression uses functions to extract the month, day and year values, and includes the values to create the name based on today's date.
Select the connection manager for your flat file.  View properties (press F4).  Select the Expressions property and click the elipsis (...) button.  In the Property Expression Editor select the ConnectionString property.  And enter the name of your new variable in the following format:
<code>@[User::MyVariable]
</code>
If you need to include the path, create the expression like this:
<code>"C:\MyFiles\" + @[User::MyVariable]
</code>
If you prefer, you can avoid the variable and put the entire expression in the ConnectionString property:
<code>"C:\MyFiles\" + "summary" + RIGHT("0" + (DT_STR, 2, 1252) (DATEPART("mm", GETDATE())), 2) + RIGHT("0" + (DT_STR, 2, 1252) (DATEPART("dd", GETDATE())), 2) + (DT_STR, 4, 1252) (DATEPART("yyyy", GETDATE())) + ".txt"
</code>
Comment: Awesome awesome awesome!  I chose the first option to create a variable.  Very simple and works like a charm.  Thanks!


Summation problems involving $k c^{-k}$

Question: I am trying to find a better way of solving problems involving summations of the form: $\sum_{k=0}^\infty k\cdot c^{-k}$ and $\sum_{k=0}^\infty k^2 \cdot c^{-k}$
For example, finding $\sum_{k=0}^\infty k\cdot 2^{-k}$, I used the following approach:
$S = \frac{1}{2} + 2 \cdot \frac{1}{2^2} + 3 \cdot \frac{1}{2^3} + ....$
$S = \frac{1}{2}[1+2 \cdot \frac{1}{2} + 3 \cdot \frac{1}{2^2} + .....]$
$S = \frac{1}{2}[1+\sum_{k=0}^\infty (k+1)\cdot 2^{-k}]$
$\sum_{k=0}^\infty (k+1)\cdot 2^{-k} = \sum_{k=0}^\infty k\cdot 2^{-k} + \sum_{k=0}^\infty 2^{-k} = S + \sum_{k=0}^\infty 2^{-k}$
Therefore, $S = 1 + \sum_{k=0}^\infty 2^{-k} = 1 + \frac{1}{1-\frac{1}{2}} = 3$
I may have made a few calculation mistakes (I would appreciate if you could point that out), but my main concern is a simpler way to approach this kind of problems. Can I use this method to evaluate problems of the form $\sum_{k=0}^\infty k^2 \cdot c^{-k}$ ? I tried, but failed.
I would appreciate if someone could point out the most efficient way to solve this
Comment: [This](http://math.stackexchange.com/questions/30732/how-can-i-evaluate-sum-n-0-infty-n1xn) may give you some ideas.
Comment: See http://math.stackexchange.com/questions/593996/how-to-prove-sum-n-0-infty-fracn22n-6
Comment: Your third identity $S=\cdots$ is wrong, it includes an extra term $1$.
Answer: Hint: Observe
\begin{align}
\frac{1}{1-x} = \sum^\infty_{n=0}x^n
\end{align}
when $|x|<1$. In particular, we have that
\begin{align}
\frac{1}{(1-x)^2}=\frac{d}{dx}\frac{1}{1-x} = \sum^\infty_{n=1} nx^{n-1} \ \ \Rightarrow \ \ \frac{x}{(1-x)^2} = \sum^\infty_{n=1}nx^n.
\end{align}
Comment: Note that the OP has $nx^{-n}$ and not $nx^n$
Comment: @BrevanEllefsen I use $x = \frac{1}{c} = c^{-1}$.
Comment: ah, I see. Alrighty. Looks good then :)
Answer: Note that we can start with the sum (where I replaced $c$ with $x$)
$$\frac{x}{x-1}=\sum_{k=0}^\infty x^{-k}$$
Differentiating and multiplying by $x$, we get that
$$\frac{x}{(x-1)^2 }= \sum_{k=0}^{\infty} kx^{-k}$$
Doing this again
$$\frac{(x+1)x}{(x-1)^3 }= \sum_{k=0}^{\infty} k^2x^{-k}$$
If you continue this process your denominator will not change, and your numerator will be an $n$th degree polynomial, where $n$ is the power of $k$ on the RHS
Answer: The short version:
$$S_2:=\sum_{k=0}^\infty k^2a^{-k}=\sum_{k=1}^\infty(k-1)^2a^{1-k}=a\left(\sum_{k=0}^\infty(k-1)^2a^{-k}-1\right)=a(S_2-2S_1+S_0-1)$$
and
$$S_2=a\frac{2S_1-S_0+1}{a-1}.$$

The full version:
We can solve this for any power, using
$$S_d:=\sum_{k=0}^\infty k^da^{-k}=\sum_{k=1}^\infty(k-1)^da^{1-k}=a\left(\sum_{k=0}^\infty(k-1)^da^{-k}-(-1)^d\right).$$
Then by the Binomial theorem,
$$(k-1)^d=\binom d0k^{d}-\binom d1k^{d-1}+\binom d2k^{d-2}\cdots+\binom dd(-1)^d,$$
and by subtraction we can cancel the powers $k^d$, giving
$$\left(1-\frac1a\right)S_d=\binom d1S_{d-1}-\binom d2S_{d-2}\cdots+\binom dd(-1)^{d-1}S_0+(-1)^d.$$
In particular
$$\left(1-\frac1a\right)S_0=1,\\
\left(1-\frac1a\right)S_1=S_0-1,\\
\left(1-\frac1a\right)S_2=2S_1-S_0+1,\\
\left(1-\frac1a\right)S_3=3S_2-3S_1+S_0-1,\\
\left(1-\frac1a\right)S_4=4S_3-6S_2+4S_1-S_0+1,\\
\cdots$$
With $a=2$, $$S_0=2,S_1=2,S_2=6,S_3=26,S_4=150,\cdots$$
Comment: Thanks for this alternative, but slightly more complicated solution.
Comment: @Jspake: it's actually simpler as it gives a regular formula to carry out the computation to arbitrary degree.

Summation problems involving $k c^{-k}$


Projection matrix: combining transition and fertility matrices for second stage group

Question: I would like to ask how to combine the following information into the projectio matrix. I do have data for transition (T) and fertility (F) matrices, so the projection matrix (A) is equal to the sum of these two matrices, i.e. A=T+F.
Concerning individuals in transition matrix, they may either move to unit time unit up (become one time unit "older") or down (vice versa) (i.e. entries in transition matrix are either subdiagonal or superdiagonal values).
The question would be how to combine T and F values in A for second stage group, where T and F entries overlap? That is, if probability to move from stage 2 to 3 is equal to e.g. 0.4, and from stage 2 to stage 1 = 0.1, it overlaps with the F value - 3 (which is not a probability, but a different unit). How to meaningully combine this information? Thank you in advance.
Please find below matrix to illustrate the problem. P(i) - probability of moving from one stage to another, and Z(i) - probability of moving from one stage to another backwards (time reversability); F(i) - fertility values.
A=
    [,1] [,2]           [,3]   [,4] [,5]
[1,] 0.0  F(i)???Z(i)   F(i)   F(i)  F(i)
[2,] P(i)  0.0          Z(i)   0.0   0.0
[3,] 0.0  P(i)          0.0    Z(i)  0.0
[4,] 0.0  0.0           P(i)   0.0   Z(i)
[5,] 0.0  0.0           0.0   P(i)   0.0

Comment: This question appears to be off-topic because it is about pure mathematics.
Comment: I think there may be confusion about what the matrix is really doing. It does not represent individuals but rather probabilities for transitions. The population at time `i` will be in a vector. If the probabilities change over time you should provide a better description than you have offered so far.
Answer: Since the expected number of individuals in stage 1 at time t+1 contributed by individuals in stage 2 at time t is indeed F(i)+Z(i) (i.e., individuals can both produce offspring and regress one stage, provided that they reproduce before they regress), the value of A[2,2] should indeed be F(i)+Z(i).


Find the factor groups of the $\mathbb{Z}/252\mathbb{Z}$ which are projective $\mathbb{Z}/252\mathbb{Z}$-modules

Question: I'm reading about projective modules and saw an algebra exam problem that and uses a bunch of concepts I am familiar with (question in the title) but I am not sure of the best method to solve it. Should I begin by considering some epimorphism from a $\mathbb{Z}252$-module to some factor group of $\mathbb{Z}252$ and see what orders the kernel of said epimorphism can take and still trivially intersect another subgroup with an order that divides 252? I am still new to modules so suspect I am missing some obvious points. I know there is also the definition of a projective module being the direct summands of free-modules but for some reason free-moduels are tougher for me to grasp than projective-modules (which are tough anyway).
Answer: The factor groups of $R=\mathbb{Z}/n\mathbb{Z}$ are the $\mathbb{Z}/d\mathbb{Z}$'s, $d\mid n$ (up to isomorphism)
Assume that $\mathbb{Z}/d\mathbb{Z}$ is projective, and consider the surjective $R$-linear map $f: \mathbb{Z}/n\mathbb{Z}\to\mathbb{Z}/d\mathbb{Z}$. The kernel of $f$ is isomorphic to $\mathbb{Z}/(n/d)\mathbb{Z}$, and we have an exact sequence  $ 0\to
\mathbb{Z}/(n/d)\mathbb{Z}\to \mathbb{Z}/n\mathbb{Z}\to\mathbb{Z}/d\mathbb{Z}\to 0$, which splits since $\mathbb{Z}/d\mathbb{Z}$ is projective.
Hence, we have $\mathbb{Z}/n\mathbb{Z} \times \mathbb{Z}/d\mathbb{Z} \times \mathbb{Z}/(n/d)\mathbb{Z}$ as $R$-modules and thus as abelian groups.
This will happen if and only if $d$ and $n/d$ are coprime (if they are not coprime, the product won't have  an element of order $n$, and if they are , this CRT).
Conversely, if $d$ and $n/d$ are coprime , then you can show easily that the isomorphism given by CRT is also an  isomorphism of $R$-modules, so that  $\mathbb{Z}/d\mathbb{Z}$ is a direct factor of the free $R$-module $R$, hence projective.
So we proved:
Thm. The projective factor groups of $\mathbb{Z}/n\mathbb{Z}$ are the $\mathbb{Z}/d\mathbb{Z}$'s, where $d\mid n$ and $d$ is coprime to $n/d$.
For $n=252$, this gives $d=1,4,9,7,28,36,63,252$.


Promise is resolved to undefined

Question: I am sorry if it is simple question, I'm new to javascript
So I have simple axios GET request. It is used three times in my code, so I thought that I could make it an external function, to avoid duplicating code, to making it cleaner and easy readable

The problem is when I call to that function, return value is undefined. And this is because code is working like synchronous. So I thought that I need to make the function return a Promise, and in function call I have to use async/await or then syntax to get the response in the right time. But after many tries code is still running as synchronous

I read a lot of theory on promises and how they work, got a solid understanding of when they change states, but something goes wrong when I try to implement them on my own

Here is the function that retrieves data
const getMessagesFromChat = async (JWT_header, chatId) => {

    if (JWT_header !== '') {
        //1 let messages
        //4 return
        axios.get(`${SECURED_API_PATH}/messages/chat/${chatId}`, {
            headers: {authorization: JWT_header},
            params: {size: 80, page: 0}
        })
            .then(response => {
                console.log('messages (fetch)', response.data)
                //1 messages = response.data
                //1 return messages
                return response.data  //2
                //3 return Promise.resolve(response.data)
            })
            .catch(error => {
                console.log(error, error.response)
            })
        //5 return Promise.resolve(messages)
    }
}

I marked comments with numbers based on what I've tried

make a variable and return it in then block
make function async so everything it returns is wrapped in promise
return explicit promise using Promise.resolve() in then block
return the whole request as a promise
return explicit promise using Promise.resolve() after the request

All responses except 4 were undefined. In 4 variant log statement shows the promise object itself instead of promise value. In other variants log statement shows first `undefined` response and then the actual response from request
I tried to implement second advice from
https://stackoverflow.com/questions/45620694/how-to-return-response-of-axios-in-return/45622080
 but it did not work.
This is the function I tried to use to get the result (onClick)##
const selectChat = () => {
        const JWT_header = getToken()
        if (JWT_header !== null) {
             try {
                 const messages = await getMessagesFromChat(JWT_header, chatId)
                 console.log('messages (after fetch)', messages)
                 //setMessages(messages)
             } catch (error) {
                 console.log(error)
             }
        } else {
            setIsLoggedIn(false)
        }

or
const selectChat = () => {
        const JWT_header = getToken()
        if (JWT_header !== null) {
             getMessagesFromChat(JWT_header, chatId)
             .then(response => {
                console.log(response)
                setMessages(response)
              })
             .catch (error =>console.log(error))
        } else {
            setIsLoggedIn(false)
        }

But none of them worked as expected

What am I doing wrong?
Comment: `getMessagesFromChat` doesn't return anything. You need `return axios.get/* ... */`
Answer: Your function doesn't return anything. A return statement in a then callback is not sufficient, you'd still have to return the promise chain itself from the outer function.
Use either .then() syntax:
function getMessagesFromChat(JWT_header, chatId) { // no `async` here
    if (JWT_header !== '') {
        return axios.get(`${SECURED_API_PATH}/messages/chat/${chatId}`, {
//      ^^^^^^
            headers: {authorization: JWT_header},
            params: {size: 80, page: 0}
        }).then(response => {
            console.log('messages (fetch)', response.data)
            return response.data
        })
    } else {
        return Promise.resolve(undefined)
//      ^^^^^^ important for chaining
    }
}

or async/await syntax:
async function getMessagesFromChat(JWT_header, chatId) {
    if (JWT_header !== '') {
        const respnse = await axios.get(`${SECURED_API_PATH}/messages/chat/${chatId}`, {
//                      ^^^^^
            headers: {authorization: JWT_header},
            params: {size: 80, page: 0}
        });
        console.log('messages (fetch)', response.data)
        return response.data
    }
    // else return undefined
}

Comment: Thank you, that was helpful, especially the .then syntax example
Guess I need to understand basics of promises before going to async/await

Promise is resolved to undefined


How best to compare two processes to know if they perform statistically the same?

Question: I have two processes, A and B.  I have tested A and B separately on different tasks, and each performed at a 90% level on their tasks (say, text classification).  Now, I pick a random set of 100 tasks to compare A and B, and on the random set, A did better on 60 of the tasks, and B did better on 40 of the tasks.  But the difference was only marginal on each.  Say, when A "won" it was only better by 1 or 2 "points" and likewise for B when it won.
Is there a way to "score" the results of the processes to know which one is statistically better than the other, or to know they are statistically the same, when they give slightly different results most of the tasks?
Comment: Maybe? I'm not sure how the equivalence bound would work.
Comment: This sounds a lot like [equivalence testing](https://en.wikipedia.org/wiki/Equivalence_test). Does that sound about right?
Answer: This sounds like a situation for paired testing. You have the performance of each technique on the first task, so take the difference in performance. Then do the same for the second task, third task…
This gives you $100$ differences that you can test for significance. If you want to show that the two techniques have equivalent performance, you must first define what you mean by equivalent, but once you do, various forms of equivalence testing could be appropriate, the easiest of which to understand is two one-sided testing (TOST).
In my view, if technique A is better $60$ out of $100$ times and by about the same magnitude as B when B outperforms A, that makes it seem like A is performing better, but you might have a different sense of what constitutes equivalence (which is fine).


Intent Data - How exactly are traceable urls used to track interest in b2b topics?

Question: I've been doing some research on intent data and I have some technical questions, especially about how two businesses might be collecting "contact level" i.e. personally identified web traffic details without using third-party cookies.
Some quick background: Most of the large providers of intent data (bombora, the big willow/aberdeen/Spiceworks Ziff Davis, Tech Target etc.) offer "account" based intent data - essentially when users visit websites in their network, they do a reverse IP addresses lookup, match them to know IP addresses of large companies (usually companies with at least 250 employees) and note what topics are "surging" - aka showing unusual traffic on a given week. This largely makes sense to me. I'm assuming that when a visitor shows up at your site, google analytics and similar tools can tell you what google search keywords were used to arrive at your site, and that's how they can say things like - we can "observe intent signals across an unlimited number of contextual keyword categories, allowing you to customize your keywords and layer these insights onto your campaigns for optimal performance." Third party cookies, and data from DSP's (demand side platform's enabling ad buyers to buy ads across many platforms) are also involved in providing data, those these will be less useful sources of data after google sunset's third party cookies on Chrome.
Two providers - intentdata.io, and intentflow.com are offering contact level intent data. You can imagine why that would be of interest - if the director of sales is interested in your sales SaaS tool, you have a better idea of how qualified that lead is and who to reach out to. Only one of the two providers is specific about what exactly they're collecting - i.e. what "intent" they are capturing and how they're collecting it.
Intentdata.io:
Intentdata.io looks like a tiny company (two employees on LinkedIn). The most specific statement I've found about what their data is was in an Impact+ podcast interview - Ed, the CRO at intentdata.io, mentions that the data is analogous to commenting on a Forbes article or a conversation on LinkedIn. But he's clear - "that's just an analogy." They also say elsewhere that the data they provide mentions specifically what action the contact took that landed them in the provided data.
Ed from intentdata.io is also asked about GDPR compliance in his Impact+ interview - he basically says, some lawyers will disagree but he believes their data to be GDPR compliant, and it is in use by some firms in the EU. He does mention though that some firms have asked them to exclude certain columns from the data, like email addresses.
Edit: Found a bit more on intentdata.io - looks like they build a custom setup to pull "intent" data for each customer - they don't have a database monitoring company interaction with content across social media and b2b sites, instead you provide them with "lists (names and URLs) of customers, competitors, influencers, events, target accounts and key terms that would indicate intent at different stages in the buying journey. Pull together important hashtags, details on your ideal buyer (job titles, functions, seniority) and firmographics (size, industry, location)" - then they create a custom "algorithm" from this info, and they iterate on that "algorithm" a little bit over time.
They also make this statement on their site: "IntentData.io's data is collected from observing public actions that users are taking around the web. That means that first, we observe action (not reading, searching, browsing, being shown an ad, etc.) which we believe is a more concrete manifestation of intent. Second, people are taking these actions publicly for the world to see. We do not use any cookies, bidstream data or reverse IP lookups."
Finally one piece of their sales collateral asks: What ad budget do you have for PPC nurturing ads? So their may be some targeted PPC ads involved in the "algorithm."
Edit 2: Their sales collateral also states that they use "a third-party intent data methodology that uses multi-variable linear regression analysis to correlate observed actions with a specific contact. This is the method that the LeadSift engine of IntentData.io data uses."
Intentflow.com:
Intentflow.com seems like the sketchier of the two providers if I'm honest. They provide a video walkthrough of how they get their data at intentflow.com/thesis - but I'm not following how using "traceable urls" with no cookies involved, could give you contact level information. They also say they lookup what the most popular articles/pages are for 5k to 40k unique keywords or phrases that are related to 10-50 keywords or phrases you give them to target. And they use "traceable urls" to track who visits those sites. Again - no cookies involved. Supposedly fully compliant at least with US laws. They don't provide data for the EU "by design" so presumably they're not GDPR compliant? They also claim they can identify the individuals who are visiting your website, again using "traceable urls" - it seems clear from the pitch that you're asked to reach out to your backlink providers around the web to use this traceable url.
I've seen an interview where a rep from Bombora says they tried for a while to do contact level intent data and it wasn't very useful - and it wasn't really doable in a compliant way. Ed seems to be aware they've said that publicly, and he says "that's just not true."
So what's going on here? How exactly are these two small firms getting contact level intent data? Do you think they're doing it in a compliant way?
Answer: Got more information:
Intentdata.io use public comments, likes, shares etc. on blogs, social posts via web crawling and scraping for events, influencers, hashtags, articles etc. that the customer deems worth tracking. They do some work to try and connect the commenters with an identifiable contact. They bill on a quarterly basis for this.
Intentflow.com doesn't seem to use "traceable urls" at all. They take bidstream data, and identify the individual visitors via an "identity graph." They provide a minimum of 5k contacts per month at $2 per contact, making their data very expensive ($120k+ per year). You can't get lower than however many contacts their system spits out per month so it seems like there's not a good firm limit on what you will be charged. They say they can identify ~70% of web traffic, and they only provide data on US site visitors. Each row of their output would include not just the contact, but the site that contact was shown an ad on. Definitely interesting data - but I'm guessing they will be very affected by upcoming changes to third party cookies, privacy laws, etc.


Can I use regression analysis for this type of research

Question: Can I use regression analysis when determining the impact of organizational change to job satisfaction and organizational commitment? my IV is organizational change and DV are job satisfaction and organizational commitment. I will use likert scale for my IV and DV
Answer: A simple linear regression model may not be appropriate because you have a dependent variable on a Likert scale.
If you have enough observations in your data, you could go for an Ordinal Logit Model. It would allow you to further estimate the marginal effects of the independent variable on the dependent variable. You can also predict the probabilities of each outcome of your Likert scale.
However, it won't give any reliable results if your dataset is too small.


Make pageViewController After NSURLSession is complete

Question: I'm a newbie on coding in objective-c.
I'm currently making an exercise application where I need to get some json-data from an API with a NSURLSession and send the date to a PageViewController.
So currently I'm getting my json-data in the method 'getWeer',which I call before making the pageViewController (in viewDidLoad). But because the NSURLSession runs async I think and isn't complete, the json-data always is null when I try to access it in my pageViewController.
How can I make the pageViewController after the NSURLSession is complete?
<code>@interface SecondViewController ()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) NSString *AppId;
@property (nonatomic, weak) NSDictionary *json;
@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.AppId = @"feda1f13263bb730deeb89fb3936a76e";
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    [[self locationManager] requestWhenInUseAuthorization];
    [[self locationManager] startUpdatingLocation];

    [self getWeer];

    // Create page view controller
    self.pageViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PageViewController"];
    self.pageViewController.dataSource = self;

    PageContentViewController *startingViewController = [self viewControllerAtIndex:0];
    NSArray *viewControllers = @[startingViewController];
    [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];

    // Change the size of page view controller
    self.pageViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 30);

    [self addChildViewController:_pageViewController];
    [self.view addSubview:_pageViewController.view];
    [self.pageViewController didMoveToParentViewController:self];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (PageContentViewController *)viewControllerAtIndex:(NSUInteger)index{

    // Create a new view controller and pass suitable data.
    PageContentViewController *pageContentViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PageContentViewController"];

    pageContentViewController.pageIndex = index;
    NSLog(@"%@",self.json);
    pageContentViewController.json = self.json;

    return pageContentViewController;
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController{

    NSUInteger index = ((PageContentViewController*) viewController).pageIndex;

    if ((index == 0) || (index == NSNotFound)) {
        return nil;
    }

    index--;
    return [self viewControllerAtIndex:index];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController{

    NSUInteger index = ((PageContentViewController*) viewController).pageIndex;

    if (index == NSNotFound) {
        return nil;
    }

    index++;
    if (index == 3) {
        return nil;
    }
    return [self viewControllerAtIndex:index];
}

- (NSInteger)presentationCountForPageViewController:(UIPageViewController *)pageViewController{
    return 3;
}

- (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController{
    return 0;
}

-(void)getWeer{
    NSString *dataUrl = [NSString stringWithFormat:@"http://api.openweathermap.org/data/2.5/forecast/daily?lat=%f&lon=%f&cnt=4&&APPID=%@&units=metric&lang=nl", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude, self.AppId];

    NSLog(@"%f",self.locationManager.location.coordinate.latitude);
    NSLog(@"%f",self.locationManager.location.coordinate.longitude);
    NSURL *url = [NSURL URLWithString:dataUrl];

    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        });
    }];
    [dataTask resume];
}

@end
</code>
Answer: Call this method after async finish.
<code>// Create page view controller
-(void)setupPageViewController {
        self.pageViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PageViewController"];
        self.pageViewController.dataSource = self;

    PageContentViewController *startingViewController = [self viewControllerAtIndex:0];
    NSArray *viewControllers = @[startingViewController];
    [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];

    // Change the size of page view controller
    self.pageViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 30);

    [self addChildViewController:_pageViewController];
    [self.view addSubview:_pageViewController.view];
    [self.pageViewController didMoveToParentViewController:self];
}
</code>