Regression of the replicated measures (on pooled individuals) of an outcome variable on an individually measured predictor variable

Question: I keep running into the same kind of statistical/experimental problem and I still do not know how to deal with it properly.
In abstract terms my issue is to perform a regression of the replicated (not repeated) measures of an outcome variable on pooled individuals using an individually measured predictor variable, with a focus on accounting for the variance between the replicates of the group outcome and the variance between individual measurements in the predictor.
To describe it in more concrete terms, here is an experiment:
Let's imagine that we have 15 populations of flies and that we measure the mass of each of 50 individuals from each population.
We then want to see if this is a good predictor of the dry matter content of the pupae. Therefore, we grow larvae for each population in 8 trays. We then measure the dry matter content for 100 pupae from each population and each tray crushed together. (Due to technical reasons we can only measure dry matter on a pooled group of 100 pupae.)
My issue is how to account for the variance in the individual measurements and the variance between the trays.
This experiment is only an example because I run into this issue quite often and sometimes with slight variations:

An extension of this problem is if the 8 trays are separated into 4 with substrate A and 4 with substrate B and that we want to also account for possible interactions between the population and the substrate.
In a different experiment, if the individuals from the pools are the same as the individuals form the individual measurement but, for some reason, there is no way to know which individual was in which pool (i.e., each replicate).
Answer: Since the response is only measured at the group level, you need covariates at the group level also. So use the individual measurements for the group members to construct new variables, possibly

sum of individual values
standard deviation ...

That implies that your effective number of observations is the number of groups.
Comment: Thank you for your answer. Let say that I use the average of the individual values as a covariate, how do I still take into account the variance (or standard deviation) of the individual measurements? Maybe my understanding is wrong but a higher variance in the individual measurements should decrease my confidence in the estimations. And additionally, once I have averaged all my individual measures, how do I account for the variance in the response for each replication? Is it then correct to just re-use the same aggregated covariate value for each response replicate?
Comment: I do not understand what you mean by *re-use the same aggregated covariate value for each response replicate*. For each group you only have the aggregated values, so there is only one observation by group. So how do you reuse values?
Comment: Ok, maybe the description was not so clear but what I mean with "the replicated (not repeated) measures of an outcome variable on pooled individuals" is that there are separate pools (or trays) from the same group and therefore several observations per group on the response side.


If $a$ and $b$ are positive real numbers, then $a+ b \ge 2 \sqrt{ab}$

Question: If $a$ and $b$ are positive real numbers, then $a+ b \ge 2 \sqrt{ab}$.
Can you guys help me with this problem? I'm still trying to learn how to do proving and I don't really know how to start or complete this problem.
Comment: Other way round!
Comment: It should be $\geq,$ not $\leq.$
Answer: $$(a+b-2\sqrt {ab})=(\sqrt a-\sqrt b)^2 \ge 0$$
Thus $$ a+b \ge 2\sqrt  {ab}$$
Answer: $$a+b <= 2 \sqrt (ab) $$ is incorrect for positive a,b.
The equation is valid for negative a,b
Which, ofcourse is clearly visible 'a negative number is less than a positive number on number line.'
But for positive a,b we have the inequality
$$a+b>=2\sqrt{ab} $$
Hint: let $$\sqrt{a}= x $$ and $$\sqrt{b}=y $$, it is valid since a,b are positive.
Now you must be able figure out a whole term which is necessarily greater than equal to 0.
Answer: \begin{align}
0 & \le (a-b)^2\\
&=(a+b)^2 -4ab\\
4ab &\le (a+b)^2
\end{align}
Taking square root preserves inequality since both $a+b$ and $2\sqrt{ab}$ are positive


Google App Engine - Can't Update Budget

Question: I have billing enabled on my project, and have even issued a $10 payment just to test out the process (it works). But I am unable to change my daily budget on the google app engine dashboard.

I go to "Billing Status" section.
I am entering the new daily budget and I hit the "submit" button.
I am getting the not very informative error: "There was an error processing the request".

So I'm stuck without being able to update my budget, and my quota has exceeded for instance hours. My users are receiving errors and I am losing money, without any option of reaching out to Official Google Support (tried to email support - it can take up to a couple of days for them to get back to you, and the phone number requires a PIN that only premium customers get. becoming a premium customer also takes a couple of days...).
Any suggestions?
I have already tried:

making sure I have only one Google account signed in while changing the budget
replacing payment method
adding another user as a billing admin and changing the budget with that user

Nothing seems to work.
Answer: UPDATE: After reaching out to a developer advocate from Google, I found out that they are aware of this issue. They claim to have solved it last night, and for me the bug is now solved.

Google App Engine - Can't Update Budget


Can anybody develop their falsetto like Brian Mcknight?

Question: I practice singing a lot and exploring my voice--not that I'm very good at it, but I hope to be.
Lately I've been focusing on my falsetto because I want to have control over it like guys like Brian Mcknight, Usher, or even (dare I say it) Bieber. For the record I'm NOT a fan of Bieber, but I have to admit he has a good falsetto.
I've practiced a lot, but I haven't been able to find that smooth falsetto sound that those guys have. I found two falsetto sounds, one is kind of nasal-ish and I can do a good rock and roll high pitch vibrato with it--though it is not using my nasal cavity because if I cover my nose, I can still make the falsetto without any problem. The other falsetto voice I found is clearer and higher sounding than the nasal-ish one.
Both of them are falsetto's, just different in some way at the back of my throat. However, neither of them really give that smooth Usher or Brian Mcknight falsetto. Am I stuck with this rock n' rollish falsetto or is it possible that I can find/practice a falsetto that sounds like there's?
(Please don't give me any answers involving race.)
Answer: In case anybody else reads this question. I just wanted to let you know, the answer is YES!!!! I JUST found it!!!! Wow, this is a damn good feeling. I've been looking for that specific falsetto voice for so long and I've always wondered if it was genetic or anybody could learn it. So far I've discovered a few variations of the falsetto and a lot of it has to do with the throat (at least how it seems to feel for me). There is a kind of rock falsetto I can do that I described as nasally. There is a kind of pure falsetto that I can do that kind of reminds me of the falsetto intro to Celin Dion's "I will always love you". And there is the smooth Justin Timberlake and Brian Mcknight falsetto. Of course it's a little bit different, but I can definitely hear it and I recorded my self just to confirm. I'm amazed.
If you're also looking to find it, you have to play around a lot with your falsetto, but know this... YOU WILL FIND IT! It is NOT genetics, it is just practice.
As for the technique, I am still getting the muscle memory down so I can't really describe it accurately as I can't do it on command yet--takes me a while to find it again. But the jist of it seems like it's an inbetween voice between the rock voice and the clean voice. Also the throat must be really clear and open. The special adjustment that made me do it was in the throat. Hope this helps for anybody else looking to find this voice!
P.S. I also wanted to clarify, I started learning to sing when I was a teen and I was not particularly talented at this. Ok, I was really horrible. But, I am MUCH better and it just goes to show that anybody can do it if I did it. #Justsayin
Comment: Voice teachers will tell you that "special adjustment that made me do it was in the throat" sounds fishy: basically for a good singing voice, the feeling is to have a direct connection between diaphragm and your "mask", with the throat being wide open.  Of course, that is not really what happens physically, but if you find yourself doing anything with your throat, chances are that you are constricting it.  The larynx should stay relaxed and down (you can check by letting a finger rest there).
Comment: That's the best description I can give. I have been looking so long for this voice. I have watched countless Youtube videos about falsetto and nothing seemed to bring me to discover this voice. Voice teachers can say what they want, I've had one before (maybe not a great one), but all they did was bring me through vocal exercises--which I normally do on my own anyways. Not everybody is the same, but it is what it is. There is some kind of adjustment to my throat that made me find the smooth falsetto Brian Mcknight style voice I was looking for.
Comment: Of course, to each his own. I've tried the finger on the larynx thing before, but it did not seem to help me personally find the quality of falsetto I was looking for.
Comment: Uh, the finger on throat thing is not going to produce a "quality of falsetto".  It's just a check that helps with maintaining a consistent vowel quality and projection.  When your larynx bounces around, the sound quality goes all over the place for the listener.  When it's forced high, the sound quality is strained and unpleasant.  It's similar to hearing an oboe reed sound through the oboe, or sound without it.  There is no single "trick" to get a great sound from the voice, like there is no single trick to get a great sound from a violin.
Answer: It's possible that you may need to reapproach this question. You see, the playing field here is uneven. I don't know about Brian McKnight, but I can guarantee you that Justin Bieber and Usher have at least one leg up on you: The leg of technology and studio production.
Ever listened to some random singer in person and heard them switch into falsetto? Often times, if that singer is a man, you may find yourself thinking, "Wait a minute, that voice just got softer, but also a lot quieter". Especially for male singers singing in a fairly high range in their chest voice switching into the low-to-middle falsetto register, you might notice a significant volume drop.
Falsetto is quieter than chest voice, most of the time. Sure, the rare singer emerges who can deceive even fellow singers as to the register in which they're singing, but for the average guy, it's not as subtle of a shift.
So, the question is, how do the pros sound so smooth and connected and flawless? Are Usher and Bieber some kind of falsetto deities? And the answer to that, my friend, is no.
I'm not saying that they're not good singers; they've got to have at least some singing ability to have become so famous in the first place. I'm just saying that the whole recording industry is doing their best to make these guys sound good. For example, blending one's falsetto and chest voice is something that even professional singers struggle with (well, usually the men, anyway). Listen to male Broadway singers: there's usually a marked difference between the falsetto and chest voice, and those guys sing for a living live on stage with little to no studio trickery and usually no released album to point to as proof of their vocal skill. It's not as though the volume drop is because they're bad singers.
My somewhat educated guess is that one thing that studios do to recordings is to boost the volume of any notes in falsetto. That goes a long way in disguising the switch, since the only difference would be the timbre. Studios have access to the ability to change timbre in post (postproduction), but I'm not sure whether that's actual industry practice. I kind of doubt that. Plus, Autotune. I don't mean to jump on the "pitch-correction sucks" bandwagon, but falsetto is also a lot harder to control than the chest voice, and when you don't need to be as specialised or have as highly-developed of a falsetto to use it in a song, it's a lot easier.

(Here's the answer to your question as presented)
That doesn't mean that you need to use technology to "cheat" your way to a smooth falsetto. My best advice for that would be practice changing the timbre of your voice. You said that you can do the rock-style falsetto, right? Well, it's not really any harder to get the falsetto to sound less piercing. When you yawn, do you use falsetto? Some people do, and if you can sort of make that sound, that's pretty much the way you want to be making that more "classical", smoother falsetto. Once you get it, you should be able to change between the two falsettos very easily, as they're on opposite ends of a spectrum. The "whinier" one feels "closed", and the lighter one feels more "open" as you make it.
Volume will come with practice (So much of singing is practicing, it's unbelievable), but things that help are not putting big belted chest notes right before falsetto if it can be helped (few songs do that anyway, luckily), and singing higher notes than normal when in falsetto. The higher the falsetto note is, the louder it can be (usually).

(opinion part)
On the topic of Usher and Bieber: While Usher probably is indeed a very good singer with a pretty well-developed falsetto tone, I find it harder to believe the same about Justin Bieber. A former child singer in the late 2000's, Bieber was more well-known for his adoring fans than for singing talent, at least among musicians. Rarely do very popular teenage singers have the voices their albums do. Bieber, being so popular at such a young age, had a whole lot of production at his disposal in the studio, and as a performer, it likely was never a huge conern for him to develop a better voice. Not saying that he didn't try to become better, just saying that it really wouldn't have mattered that much to his audience whether he really was an amazing singer. As he matured, his more recent return to the popular music scene continued to be extremely well-produced, making me question his singing abilities behind the smoke and mirrors.
I may seem as though I'm just picking on Justin Bieber; I'm not. A lot of the same things I'm saying about production value and Justin Bieber's voice apply to just about every singer on Top 40 Radio today. Youtube videos exist of "Autotune vs. Real Voice" compilations for countless famous performers and the difference is staggering, especially in the relative lack of control displayed at live shows. If you ever get the opportunity to go see a famous singer live, and their vocals are sounding really good, try to see what sounds different from the recording, since a lot of modern singers do not really sing their songs during some live performances. This applies to just about everyone in the industry; it's simply how the industry works. That's not to say that they've all got not talent, it's just that they are not chosen specifically for having the best singing voices on the planet; it is the job of the singer and the postproduction team to create that illusion.
In a similar story, current teen singer/social media personality Jacob Sartorius is widely believed to be much, much worse than his released songs would let you believe. He really does not seem to be able to perform live anywhere near his recorded standards. In particular, his performance at the recent Teen Choice Awards (saw it on TV) did not impress me, to say the least.
Another obvious time that this is apparent is when famous actors "sing" in modern movies. One example that comes to mind is Disney's blockbuster film "Moana". Dwayne "The Rock" Johnson could not sing "You're Welcome" nearly as well as what audiences heard, I guarantee you that.

Ultimately, my point is that when singers try to compare their voices with those of contemporary pop musicians, they must take into account the fact that they are at an inherent disadvantage. Pop singers tend to be very good at certain things within the scope of singing, but no one expects them to sound as good as their songs do, and falsetto is no exception.
Keep in mind that pop singers are not reasonable standards to compare yourself to.


Confidence interval for sum of random variables

Question: Let $X_1, X_2$ be independent (not necessarily identically distributed) random variables. Assume we have estimates for the means $m_1, m_2$ and confidence internals $\left[a_1, b_1\right],\left[a_2, b_2\right]$
i.e. $\mathbb{E}\left[X_1\right]=m_1, \mathbb{E}\left[X_2\right]=m_2, \mathbb{P}\left(X_1 \in\left[a_1, b_1\right]\right) \geq 95 \%$ $\mathbb{P}\left(X_2 \in\left[a_2, b_2\right]\right) \geq 95 \%$. We are interested in the sum $Y:=X_1+X_2$. We know that the mean behaves nicely i. e. $\mathbb{E}[Y]=m_1+m_2$. What would be the best way to derive confidence intervals for $Y$ by computational means? What would be the statistical assumptions for each approach be?
On a side note. In my setting, I have many $X_1, \ldots, X_n$. The confidence intervals are symmetric around the mean.
I have thought about assuming gaussian $X_1, \ldots, X_n$ and then reverse-engineering the standard deviation for bootstrap or simply sum of standard deviation or something like that, but did not make it work.
Comment: What confidence intervals are those? A confidence interval provides probability statements about the parameter…
Comment: That's just a probability statement about the random variable.
Comment: Hi utobi, the probability statement would be $\mathbb{P}\left(X_1 \in\left[a_1, b_1\right]\right) \geq 95 \%$
Comment: The random variable is my parameter
Comment: utobi, How I understand it, a1 and b1 are values of the quantile function. E.g., if X ~ StdNorm, it means `qnorm(c(.025,.975))` (in R).

Daniel, what do you know about the distribution of Xs? Anything apart from the mean and these quantiles?
Comment: I only know that $X_1, \ldots, X_n$. For the sake of "making it work" I would be willing to introduce new assumptions on the distributions. However, I would like to avoid unnecessary assumptions.
Answer: We can't obtain similar intervals for $Y$ without additional information (or making additional assumptions) about the underlying distributions of the $X_i$. For example, consider the case where $\mathbb{P}(X_1\in[-1,1])=95\%$ and $\mathbb{P}(X_2 \in[-2,2])=95\%$. If we assume $X_1\sim N(0,\sigma_1)$ and $X_2\sim N(0,\sigma_2)$, then $X_1+X_2\sim N\Big(0,\sqrt{\sigma_1^2+\sigma_2^2}\Big)$. We can solve for $a_{12}$ and $b_{12}$ where $\mathbb{P}(X_1+X_2\in[a_{12},b_{12}])=95\%$:
<code>ci1 <- c(-1, 1)
ci2 <- c(-2, 2)
hl1 <- diff(ci1)/2
hl2 <- diff(ci2)/2
mu1 <- mean(ci1)
mu2 <- mean(ci2)
# gaussian model
sigma1 <- uniroot(function(sigma) qnorm(0.025, 0, sigma) + hl1, c(0.5, 0.6)*hl1, tol = sqrt(.Machine$double.eps))$root
sigma2 <- sigma1*hl2/hl1
setNames(qnorm(c(0.025, 0.975), mu1 + mu2, sqrt(sigma1^2 + sigma2^2)), c("a12", "b12"))
#>       a12       b12
#> -2.236068  2.236068
</code>
If we instead assume $X_1\sim\text{Cauchy}(0,\gamma_1)$ and $X_2\sim\text{Cauchy}(0,\gamma_2)$, then $X_1+X_2\sim\text{Cauchy}(0,\gamma_1+\gamma_2)$ and $a_{12}=a_1+a_2=-3$ and $b_{12}=b_1+b_2=3$, which are quite different from what was obtained using the Gaussian model.


PHP - select limited csv rows

Question: I am new to PHP and am trying to display some contents from CSV in a webpage. I am able to display the values successfully. I need to find the minimum and maximum of all the columns so that I can include a slider using which the user can select a range. This is the code I have to find the minimum and maximum values for all the columns.
<code>$total_columns = 0;
$handle1 = fopen('demo.csv', 'r');
while (false !== ($row = fgetcsv($handle1, 1000, ','))) {
    0 === $total_columns and $total_columns = count($row);
    $i = 1;
    while (++$i <= $total_columns) {
         $data1[$i][] = (int) $row[$i - 1];
     }
}

$i = 0;
while (++$i <= $total_columns) {
    $_SESSION["min-column-$i"] = min($data1[$i]);
    $_SESSION["max-column-$i"] = max($data1[$i]);
}
</code>
Using the above code, I have implemented a slider functionality for range selection.. After this range selection, I need to display only those rows that satisfy the range. For example,

a1 1 2 3
a2 3 4 5
a3 8 9 10

If I have a slider for column 1(min is 1 and max is 8) and if I choose the range value as 8, I need to display only the a3 row. My output should be,

a3 8 9 10

Is this possible with PHP?
Comment: Don't know if this would help, but: http://phpexcel.codeplex.com/
Answer: Keep in mind that PHP is all server side code so you'll have a few options here.

Process your data and create a div for each row hiding all of them. Store the ranges in javascript and write a method to check the user value against those ranges and hide/show the respective row.
On select of the range value, make an ajax call to a PHP script that would determine the row and return it. You'd then display it in a single results div.
Take a similar approach as #2, but post the data back to a script that did the same thing and displayed the results.

I'd look into #1 since you have to process all of the CSV data to determine ranges anyway. #2 and #3 both require you to reprocess the data a 2nd time to get the results.

PHP - select limited csv rows


How to use v-model inside select form?

Question: Is there any way to get the a selected options in vuejs in select tags form.
Like I've this tag i can get the
<input type="email" class="form-control" id="email" placeholder="firstname.lastname@example.com" autofocus v-model="email">

Like this I want to get the select dropdown element inside the data() in vue3.
My select element is follows

    <select class="form-select" >
        <option selected>Select your category</option>
        <option value="a">a</option>
        <option value="c">b-</option>
    </select>

and It is also inside form tag.
How can i also get data of it and stored in data in vuejs.
Thank you for your help.
Comment: You could do, ``
Answer: Add a v-model to a local reactive variable :
<template>

    <select class="form-select" v-model="selectedCategory">
        <option value="none">Select your category</option>
        <option value="a">a</option>
        <option value="c">b-</option>
    </select>

  selectedCategory: {{selectedCategory}}
</template>

Vue SFC Playground
Comment: Hello, Is it mandatory to use defineComponent  instead of just exporting defaults
Answer: <template>
<select class="form-select" v-model="item">
<option value="I">I</option>
<option value="J">J</option>
<option value="K">K</option>
</select>
</template>
export default{
...
data(){
return{
item: 'K'
}
}
}

Here , you can make option with value K selected with v-modal="item"

How to use v-model inside select form?


creating a view of a gallery of images

Question: I need to create a view of galleries of images.
The requirement is for a user to click on the menu item "albums". This then renders a view of a selected image from each of the galleries. Each gallery is made up of related images, each image is a content type which contains information about the image such as place taken description and category(this is the related field).
So the requirements are...

Albums: Grid view of galleries using a selected image from each
gallery.
Galleries: Grid view of images including meta data (from image
content type)

Clicking on each image in the gallery renders a colorbox.
When creating a gallery of images the user needs to be able to select which image is used as the displayed thumbnail in album view of galleries. This CANNOT be related to a date field or creation order. in other words a tickbox or something to be used to promote it to the gallery view. This image might be changed regularly so basing it on dates. etc is not feasable
We are talking a large number of images. they will initially be uploaded using the feeds importer + bulk media uploader (or ftp).
I have played with as many configurations as I can and cannot get the result I want.
The end users are not confident computer users so the system to add new images must be non complex. which is one of the reasons I am avoiding taxonomy as the category plus we could not get a taxonomy view to allow us to select an image as the promoted image. I also could not work out how to have taxonomy terms auto created as well. Which means I want people to be able to set the category by simply typing into the category field rather than first having to create a category and then select it from a drop down field.
One way I have considered is to make a gallery a content type and then embed into it a view of related images, The relationship would be on category. this of course is similar to pre-creating the taxonomy.
I hope this makes sense.
Answer: The Drupal Module Album Photos best suits your need.
Comment: One of the first modules we tried. Perhaps I didn't do it right but it appears to be do it our way or the highway. Layout appears to be fixed to a vertical list and as the image is not a content type I have no idea how I am meant to import the images? the first lot of images contains 2000 images in multiple categories. I also am unable to add custom fields to each image. you are restricted to title and description. so unfortunately it does not fit the bill. no gallery we have tried does.
Answer: How about Mediabox module the problem with this module is that it's in dev state but it have type with fields support where you can put Term reference field with auto completion for category creation also one Featured taxonomy field with a check box for which image to be featured in Album grid.
One problem with this module and large number of images is that it use quite annoying browser like interface for adding images which get cluttered quite fast also crop that I don't found a way to switch off.

creating a view of a gallery of images


Definition: Norm of a field

Question: The norm of a finite field extension $L|K $ is defined as $N:L\to K $, $a\mapsto N (a):=\det (m_a) $, where $m_a:L\to L, x\mapsto ax$.
It is easy to show for $a\in L $, that $N (a)=a^{[L:K]} $. Consider the field extension $\Bbb {C}|\Bbb {R} $ and $i \in \Bbb {C} $. By the foregoing section $N (i)=i^2=-1$. Now $B=(1,i)$ is an $\Bbb {R}$-basis of $\Bbb {C} $ and
$$M(m_i)=
  \left[ {\begin{array}{cc}
   0 & -1 \\
   1 & 0 \\
  \end{array} } \right]$$
is the matrix of $m_i $ with respect to $B $. But $N(M(m_i))=\det (M (m_i )) =1\neq -1$.
Why do I get different solutions for my calculations?
Answer: For $a\in K$ you have that $N(a)=a^{[L:K]}$, but it's not generally true for $a\in L$, as your example shows.
The reason it's true for $a\in K$ is that the matrix of $a$ is then just the $[L:K]\times [L:K]$ diagonal matrix with diagonal entries equal to $a$.

Definition: Norm of a field


Retorno de uma função JavaScript

Question: Quando executo o seguinte código os comandos que eram para ser retornados na real não são.

var a = 0;

main = function(_this){
  console.log('Está entrando em Main');
  return function(){
    console.log("Retorno"); //Não escreve o retorno
    a++; //Não incrementa a variável
  };
}(this);

console.log(a);
Answer: Está faltando chamar a função main(). main é uma variável que é uma função que retorna outra função, sem executá-la não fará nada:

var a = 0;
main = function(_this){
  console.log('Está entrando em Main');
  return function(){
    console.log("Retorno"); //Não escreve o retorno
    a++; //Não incrementa a variável
  };
}(this);
main();
console.log(a);

Coloquei no GitHub para referência futura.
Comment: Nem precisa do `this`, mas só não está retornando uma função, está executando uma direto.
Comment: Caramba achei que com (this) já chamaria kkkkkkkk Pois quando faço o seguinte funciona apenas com o  Self-Invoking
main = function(_this){ console.log('Assim vai apenas com a chamada abaixo'); }(this);
Answer: Ou se você preferir, não precisa chamar o main() depois da criação da função. No javascript no tempos a oportunidade de criar Self Invoking Functions, que são funções que se auto executam automaticamente. Basta apenas chamar (), no final da função.
var a = 0;
main = function(_this){
  console.log('Está entrando em Main');
  return function(){
    console.log("Retorno"); //Não escreve o retorno
    a++; //Não incrementa a variável
  };
}(this)();
console.log(a);

Comment: Obrigado. Mas eu só queria entender pq tem que chamar duas vezes. Uma com o this como parâmetro (mesmo que não seja usado) e outra sem...
Comment: Se você não usar ele dentro da função então nem precisava passar como parâmetro, geralmente usamos esse tipo de abordagem para dar o bind no this global. Isso significar dizer que dentro da função você vai ter ao acesso a todo o this global de fora dela, o que for default da linguagem não acontece
Comment: Então o código que estou estudando faz justamento isto o bind, muito obrigado :)

Retorno de uma função JavaScript


Arcwise connected components under a retraction on two points

Question:
Let $X$ be an Hausdorff space, and let $p,q$ two distinct points. Then if $X$ retracts on $\{ p,q\}$, establish if $X$ has at least two arcwise connected components, or if $X$ has at most two arcwise connected component.

My attemp:
A retraction is a continuous surjective map $$r:X\rightarrow \{p ,q\}$$
such that $r\circ i =\operatorname{id}_{ \{ p,q\}}$. Since $\{ p,q\}$ has the discrete topology, we know that, by continuity and surjectivity, $X$ has at least two connected components. On the other hand, we can't have three or more arcwise connected components, because the continuous image of a continous set is connected, hence there are exactly two connected components. What I don't see is why these connected components are indeed arcwise connected, maybe because I am not using the fact that $X$ is Hausdorff nor the fact that $i\circ r$ is omotopic to $\operatorname{id}_{X}$.
Comment: It most certainly can have 3 (or any number greater than two) components. Consider the discrete space. As for being arcwise connected: yes, Hausdorff space is arcwise connected if and only if it is path connected.
Answer:
On the other hand, we can't have three or more arcwise connected components, because the continuous image of a continous set is connected, hence there are exactly two connected components.

This gets it backwards - the pre-images of a connected set need not be connected, so we cannot conclude that the pre-images of $p$ and $q$ are connected.
As noted in the comments by freakish, the fact that a continuous image of a connected set is connected only tells you that $X$ is not connected, and therefore it has at least two connected components.
Next, as you have correctly observed, these components need not be arcwise connected, but that is no matter - since every arcwise component is connected, it is entirely contained in some connected component, and so there are at least two arcwise components.  There could of course be more than two, as the example of any discrete space shows.
Finally, the Hausdorff assumption is necessary because to even talk about arcwise components, we need for arc-connectedness to be an equivalence relation, and in general, it need not be (for example, in the line with a doubled origin, $0_1$ is arcwise connected to $1$, which in turn is arcwise connected to $0_2$, but $0_1$ and $0_2$ are not arcwise connected to each other). In the Hausdorff case, this issue is not a concern, since arcwise connectedness is the same as path connectedness, and the latter is always an equivalence relation.
Remark.
Regarding the retraction being homotopic to the identity, that is a stronger condition than simply being a retraction.  If the retraction were homotopic to the identity (a so-called "deformation retraction"), then you would then have precisely two arcwise components, since the homotopy would provide a path from each point to either $p$ or $q$.
Comment: It's clear, thanks! I have only one question left. If I have only a "weak" retraction, i.e. a map $r:X\rightarrow\{ p,q\}$ such that $r\circ i$ is only homotopic to the identity, then I can conclude again that there are at least two components? Or there can be strange cases where $r$ is constant?
Comment: @Dungessio if $r\circ i$ is homotopic to the identity, then $r\circ i$ is the identity, since the composition's domain and target are the discrete two point space $\{p,q\}$.  Maybe you instead wanted $i\circ r$ homotopic to the identity?  In that case, though, you would conclude the opposite, namely that there are *at most* two path components, and in fact there are either two path components that are both contractible, or a single path component that is contractible, depending on whether $r$ is surjective vs constant.


backdrop overlap my modal form using Bootstrap

Question: I have a problem in my modal form. When I clicked the login, my form will show but the backdrop overlap. Here's my JS before:
<code>$('#user-login').on('click', function(e) {
        e.preventDefault();
        $('#s-auth-login').modal({
            'backdrop': false, //if true the backdrop will overlap
            'show': true
        });
    });
</code>
I forced the backdrop to hide. But is there any alternative way to do this? I want to retain the background with an opacity color behind my form modal.
Comment: do u have it in jsfiddle? to test?
Answer: You can simply show the bootstrap modal without any additional configurations like
<code> $('#s-auth-login').modal('show');
</code>
This should handle all the things by default.


swagger-parser 1.0.57 provided additional responsesObject field to the parsed swagger definition

Question: I'm using swagger-parser 1.0.57 version and when I'm inputting swagger2 definition to the parser,the output of swagger after being parsed gives the following.
<code>/pets/{petId}:
get:
  summary: Info for a specific pet
  operationId: showPetById
  tags:
    - pets
  parameters:
    - name: petId
      in: path
      required: true
      description: The id of the pet to retrieve
      type: string
  responses:
    "200":
      description: Expected response to a valid request
      schema:
        $ref: '#/definitions/Pets'
    default:
      description: unexpected error
      schema:
        $ref: '#/definitions/Error'
  responsesObject:
    "200":
      description: Expected response to a valid request
      schema:
        $ref: '#/definitions/Pets'
    default:
      description: unexpected error
      schema:
        $ref: '#/definitions/Error'
</code>
Above content provides issue in swagger-editor since repsponsesObject.

To remove the reposesObject as a workaround I wrote following code with the swagger parser.
<code>SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(oasDefinition);
    if (CollectionUtils.isNotEmpty(parseAttemptForV2.getMessages())) {
        log.debug("Errors found when parsing OAS definition");
    }
    parseAttemptForV2.setSwagger(removeResponsesObject(parseAttemptForV2.getSwagger()));
    return parseAttemptForV2.getSwagger();

private Swagger removeResponsesObject(Swagger swagger) {
    Swagger modifiedSwagger = swagger;
    if (modifiedSwagger != null && modifiedSwagger.getPaths() != null) {
        Map<String, Path> pathMap = modifiedSwagger.getPaths();
        for (String pathKey : modifiedSwagger.getPaths().keySet()) {
            Path path = modifiedSwagger.getPath(pathKey);
            Map<HttpMethod, Operation> operationMap = path.getOperationMap();
            for (Map.Entry<HttpMethod, Operation> entry : operationMap.entrySet()) {
                Operation operation = entry.getValue();
                if (operation.getResponses() == null) {
                    operation.setResponses(operation.getResponsesObject());
                }
                if (operation.getResponsesObject() != null) {
                    operation.setResponsesObject(null);
                    path.set(entry.getKey().name(), operation);
                }

            }

            pathMap.put(pathKey, path);
        }
        modifiedSwagger.setPaths(pathMap);
        return modifiedSwagger;
    }
    return swagger;
}
</code>
When I debugging it  reponsesObject is setting as null, but after that it will again appears. I'm not sure this process is having a default multithread envorionment. Any suggetsions to imrprove the code to remove responsesObject?
Answer: Sound similar to the issues reported at

https://github.com/swagger-api/swagger-core/issues/2944

we solved it by applying in our code these mixins:
<code>        mapper.addMixIn(RefModel.class, IgnoreOriginalRefMixin.class);
        mapper.addMixIn(RefProperty.class, IgnoreOriginalRefMixin.class);
        mapper.addMixIn(RefPath.class, IgnoreOriginalRefMixin.class);
        mapper.addMixIn(RefParameter.class, IgnoreOriginalRefMixin.class);
        mapper.addMixIn(RefResponse.class, IgnoreOriginalRefMixin.class);
        mapper.addMixIn(Operation.class, OperationResponseMixin.class);
        mapper.addMixIn(Response.class, ResponseSchemaMixin.class);
</code>


Half-range Fourier transform of $e^{-ixt}$

Question: I'm reading a textbook that has the following sentence:

Making use of the formula $$\int_0^\infty dt e^{-i x t} = \pi \delta (x) - i \text{P}\frac{1}{x} , $$ where $\text{P}$ denotes the Cauchy principal value...

(Here is a link to the page on Google Books.)
Using the Fourier transform $\int_{-\infty}^{\infty}dt e^{-ixt} = 2\pi\delta(x)$, I can show that the real part of the integral is $$\text{Re}\int_0^\infty dt e^{-i x t} = \pi \delta (x) . $$ But how can I show that the imaginary part is $$ \text{Im}\int_0^\infty dt e^{-i x t} = -i\text{P}\frac{1}{x} , $$ and what does the Cauchy principal value mean in this context? (i.e., principal value of what?)
Comment: $\mathrm{P}\frac{1}{x}$ is a distribution defined by
$$\left< \mathrm{P}\frac{1}{x}, \phi(x) \right> = \lim_{\epsilon \to 0} \int_{|x|>\epsilon} \frac{1}{x} \phi(x) \, dx$$
Answer: First note that
$$\int_0^\infty e^{-ixt} \, dt = \int_{-\infty}^{\infty} H(t) \, e^{-ixt} \, dt$$
where $H$ is the Heaviside step function.
Now we multiply the above identity with $x$:
$$
x \int_0^\infty e^{-ixt} \, dt
= x \int_{-\infty}^{\infty} H(t) \, e^{-ixt} \, dt
= \int_{-\infty}^{\infty} H(t) \, x e^{-ixt} \, dt
= \int_{-\infty}^{\infty} H(t) \, i \frac{d}{dt} \left(e^{-ixt}\right) \, dt \\
= \{ \text{ partial integration } \}
= -i \int_{-\infty}^{\infty} H'(t) \, e^{-ixt} \, dt
= -i \int_{-\infty}^{\infty} \delta(t) \, e^{-ixt} \, dt
= -i
$$
The solutions to the distribution equation $x \, u(x) = 1$ are $u(x) = \mathrm{P} \frac{1}{x} + C \delta(x)$ where $C$ is some constant. Therefore we get
$$\int_0^\infty e^{-ixt} \, dt = -i \mathrm{P}\frac{1}{x} + C \, \delta(x)$$
By symmetry reasoning we find that
$$\int_{-\infty}^0 e^{-ixt} \, dt = i \mathrm{P}\frac{1}{x} + C \, \delta(x)$$
Thus
$$\int_{-\infty}^{\infty} e^{-ixt} \, dt = 2C \, \delta(x)$$
but it's well-known that
$$\int_{-\infty}^{\infty} e^{-ixt} \, dt = 2\pi \, \delta(x)$$
Hence we conclude that $C = \pi$ which gives
$$\int_0^\infty e^{-ixt} \, dt = -i \mathrm{P}\frac{1}{x} + \pi \, \delta(x)$$
Comment: Thank you. I'm a bit stuck on why $u(x) = \text{P}\frac{1}{x} + C\delta(x)$ is the solution to $xu(x) =1$, though. Could you tell me the reasoning behind that (or point me to a reference)?
Comment: There's some information on [Wikipedia](https://en.wikipedia.org/wiki/Cauchy_principal_value#Distribution_theory).
Comment: It's easy to show that $x \mathrm P \frac1x = 1:$
$$\langle x \mathrm P \frac1x, \phi(x) \rangle = \langle \mathrm P \frac1x, x \phi(x) \rangle = \lim_{\epsilon \to 0} \int_{|x|>\epsilon} \frac1x \cdot x \phi(x) \, dx \\ = \lim_{\epsilon \to 0} \int_{|x|>\epsilon} \phi(x) \, dx = \int \phi(x) \, dx = \langle 1, \phi \rangle$$
for all $\phi \in C_c^\infty(\mathbb R).$
Comment: Then, if $v$ is another distribution satisfying $x \, v(x) = 1$ then we have $x \, (u-v) = 0.$ The only distributions satisfying $x \, w(x) = 0$ are $w(x) = C \, \delta(x)$ so we must have $u-v = C \, \delta.$


jquery plugin Pace.js not working

Question: i am using jquery plugin pace.js, and i want that when the page is load then first the progress bar is loaded after that the content will shown,
this is my code

the jsfiddle will define the result of my work.
in my case the content and progress bar both will show simultaneously.
What i want: i want that first the progress bar will show and after the complition of progress bar the content will show like in this website.
Update:
This is what i try next but when the progress is complete then it will not show any contents...
<!doctype html>

      <meta charset="UTF-8">
      <title>bk</title>
      <link rel="stylesheet" href="css/pace-atom.css"/>

Comment: check this out http://www.useragentman.com/blog/2012/01/16/caching-images-with-javascript-and-html5-progress-bars/
Comment: thanks for the link, but i am looking only for pace.
Answer: If the progress bar stuck at 99%, and if you are using Visual Studio, you have to uncheck 'Enable Browser Link' option. This will solve the incomplete progress bar issue.
Comment: I assume this is because it creates a WebSocket connection, which is a request that doesn't really "complete", but remains active.
Comment: @NevilleKatila Happy coding :)
Answer: Okay so an easy way to implement this is to hide all your contents until pace is done loading (I assume there is a reasoning to pace's load screen but I'm not sure).
So your contents could have an id #contents and be default display: none. You can then show the contents after pace is done like so
$(function() {
    Pace.on("done", function(){
        $("#contents").fadeIn(1000);
    });
});

Here is a fiddle of it working http://jsfiddle.net/59caubpx/3/
Comment: @webydesigny where in your html are you putting the JS? It has to be after the pace.js JS insert and ideally at the end of the page. On the fiddle the JS is executed on page load so try my edited answer. Other than that remember all your contents should be wrapped in a div with `id='contents` which has css set to `display: none`.
Comment: can you please tell me that how to reduce the progress speed? mean progress time, by default it run faster..
Comment: yes, i want to decrease the progress sped, so that the user see the loading screen for long time
Comment: I'm not sure how to extend loading times. I advise you look at the documentation: http://github.hubspot.com/pace/
Answer: Please check that you add all the file properly, like jquery.js or theme.atom.css or pace.js etc...

jquery plugin Pace.js not working


W3 VALID cross browser css gradient,

Question: I am trying to find html conditional statement so that I can reference the required additional .css file. Opera, Ie8, Safari.
I am using:
background: -moz-linear-gradient(#ADD58A, #FFFFFF);

for Firefox which is great. But having other browser css properties causes W3 css validation to fail!
I believe with html conditional statements this can be done with valid code.
Before you reply, yes I have looked at pie, i do not have the 3 green ticks of validation when using pie, hence wanting to use html conditional rather than having the browser 'drop' styles.
Comment: It's fine to break validation *if you know what you're doing*. The vendor prefixed properties required for gradients are a perfect example of when breaking validation does not matter.
Comment: @thirtydot: I kept that phrase in italics in a special part of my mind while writing my answer... and I still neglected to mention it in the end. I guess I'm in too ranty a mood this morning (!).
Answer: The Jigsaw CSS3 validator should have an option for triggering warnings instead of errors on vendor extensions. Assuming you haven't used any other non-standard styles, your CSS should pass with a green, albeit with a few warnings, but nothing more.

As to why Daniel A. White says not to worry about validation, well, "W3C valid cross-browser CSS3" is an oxymoron. In 2011 you simply can't achieve such a thing with most CSS3 features yet.
Yes, validate your code for maximal cross-browser interoperability. But in the real world, that's only applicable to CSS2 stuff right now. When it comes to CSS3 features where the spec itself isn't yet finalized, let alone browsers' implementations (however they interpret the incomplete spec), validity doesn't make sense yet. Things like border-radius may work if you ignore less recent (I wouldn't say older) versions of most modern browsers, since the latest versions of every major browser now support the official property name, but nobody in the world has implemented the extensionless versions of any CSS gradients yet.
You can tell them to trigger only warnings in the validator, or if you're so anal that you don't even want warnings, perhaps wait until next year. Hopefully things will be stable enough and major browsers will have dropped their prefixes for CSS3 gradients.
Comment: Likewise for HTML validation: in the past 10 years (and possibly for another couple of years), the latest final version of HTML has been HTML 4; most browsers have had 10 years to stay as close to that standard as possible. HTML5 is a brand new, as yet half-finished spec, and browsers are just learning to implement it now. Validation for new technologies is not a real concern yet.
Answer: the -moz is a vendor specific prefix for Firefox. I wouldnt worry about the css validation.
Define the gradient with these too.

linear-gradient - the eventual standard
-o-linear-gradient - opera
-webkit-linear-gradient - safari/chrome
-ms-linear-gradient - ie
Comment: how come you say dont worry about css validation?
I thought W3 was important for standards.
I guess i have to safrice for fancy gradients.
Just really suprised you say don't worry about css validation.
What about HTML validation?
thanks anyway, going to use this way
Comment: @Renai - Vendor prefixes are valid markup and part of the spec. The validator, however, calls it out as an error. It is not invalid.
Comment: @Rob: Vendor extensions are part of the grammar (precisely why vendors can use them in the first place), but they're invalid as far as standard (i.e. official) CSS identifiers are concerned. http://www.w3.org/TR/css3-syntax/#vendor-specific
Comment: @Rob: Or to put it another way: vendor extensions are proposed as a "standard" way to indicate non-standard styles, but the property/selector names they're attached to invalidate in the same way `fb:like` invalidates XHTML.

W3 VALID cross browser css gradient,


Splunk File & Directory Data Inputs

Question: I've installed Splunk (4.1.5(85165) on windows) and have uploaded some logs without any issues.
I now want to monitor a linux server, but I'm having problems adding the datasource and always get the message:
Encountered the following error while trying to save: In handler 'monitor': Path must be absolute.
I'm using Splunk Web and have set the host field value to the two servers IP address and the full path on server to /var/log (and tried various other combinations).
On the Linux server I've added *.*@192.168.254.100 to syslog.conf.
I've read the manual, but it doesn't really help. and I'm finding a lack of tutorials. Pretty much thinking of abandoning the idea of Splunk now. I'm obviously missing some sort of basic information here. Can anyone help out? Being pointed in the direction of some decent tutorials would be good...
I'm having trouble understand how all this data gets sent to Splunk and how Splunk intercepts/retrieves it.
Answer: Splunk's "monitor" can only read files that are on the machine it's running on (or on drives mounted over the network that can be read from the machine it's running on).  The "host" field may make it look like it can read from another machine, but it's there to identify what computer the file came from, not to connect to a remote host. This page has various ideas for setting up Splunk on a network.  It looks like running Splunk on every machine and having them forward the logs to the central indexer is the "best practice", since it gives you access to log files not controlled by syslog (eg apache logs) and the local Splunk systems will hold the data if the main Splunk server goes down.  Otherwise, if you're going to use syslog, this page provides some instructions on how to setup syslog-ng in windows to receive the syslog messages, then set up Splunk to read from syslog-ng.
Comment: It should be noted that Splunk also provides the option of receiving syslog messages directly.
Comment: Thanks. How does it receive syslog messages directly? I've added the forwarder in the syslog.conf file and restarted the service... It is also listening on UDP:514 and is currently recieving syslog from vmware, but not from the linux boxes.
Comment: It looks as if you've configured your linux hosts to forward all syslog messages to 192.168.254.100, I guess this is your Splunk host? If so, try restarting syslog (or forcing it to re-read the config file).
Comment: yes, 100 is splunk host... I've restarted syslog, but not receiving anything... firewall ports are all open.... does *.*@192.168.254.100 automatically send data to UDP:514?
Comment: Do you have at least one space or tab after *.* and before @?  syslog.conf expects all of the settings to be two columns, the first column is what to log (eg "*.*") and the second column is where to log it to (eg "@192.168.254.100")

Splunk File & Directory Data Inputs


Geometry basic problem

Question: If I have a triangle with given: $b-c=3 \space\text{cm}$, $a=6\space \text{cm}$ and $\alpha$ is $30^\circ$, how do I draw this? Please help me by telling me where I can find this type of exercises online with explanations. Thank you!
Answer: Draw some generic triangle:

Then fill in what you know. $A=30\text{ degrees}$, $a=6\text{ cm}$ and $b-c=3\text{ cm}$. That means we can say $c=b-3\text{ cm}$

You can solve for $b$ using the Law of Cosines. Then from $b$ you can find $c$.
Comment: But how about if you were to just draw it without calculating anything?
Comment: Do you mean you are trying to draw an accurate to-scale diagram? And not just a diagram like the second picture?
Comment: Something like that. Basically without calculating anything, just drawing it with compass and a set square.
Comment: @user137794 See my delayed reply. Hope it satisfies your requirement because your question did not specifically say where the alpha is between which two lines.
Answer:
Step 1. Draw a line 3 units long (PQ).
Step 2. Draw another line 6 units long (PR) such that the angle between the two is 30 degrees.
(Hope that drawing a 30 degrees angle should not be a problem.)
Step 3. Join the endpoints of these two lines (QR).
Step 4. Produce the 3-unit line to certain extend (PQ... ).
Step 5. Draw MN, the perpendicular bisector of QR such that MN cuts the PQ produced at S.
Step 6. Join SR.
Triangle PRS is the required satisfying the given conditions (1) one side is 6; (2) one angle is 30 degrees (3) the difference between the other 2 sides is 3.

Geometry basic problem


Como fazer o padding de um item  oculpar 100% verticalmente do container?

Question: Consegui calculando o tamanho exato da barra e colocando o valor no padding, mas isso me causa problemas depois, como faço para ele ficar como na imagem abaixo?

                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>Document</title>

VM

Home

Sobre

Projetos

Fale Comigo

Answer: Coloque display: flex em tudo: nav, ul, li e a (é bom criar classes para esses elementos, senão irá afetar o site todo). Use a propriedade align-self: stretch; na ul. Essa propriedade fará com que o elemento ocupe toda a altura da nav. E com align-items: center você centraliza verticalmente os elementos:

* {
    padding: 0;
    margin: 0;
    font-family: 'Open Sans', sans-serif;
    box-sizing: border-box;
}

:root {
    --texto-branco: #f2f2f2;
    --fundo-preto:#222;
    --fundo-azul:#009DFF;
}

nav {
    background: var(--fundo-preto);
    height: 64px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;

}

.logo {
    color: var(--texto-branco);
    margin: 0 16px;
    cursor: pointer;
}

ul {
    list-style: none;
    display: flex;
    align-self: stretch;
}

li {
    display: flex;
    transition: .3s;
}

nav li:hover {
    background: var(--fundo-azul);
}

a {
    text-decoration: none;
    color: var(--texto-branco);
    padding: 0px 16px;
    display: flex;
    align-items: center;
}

VM

Home

Sobre

Projetos

Fale Comigo

Agora, o padding: 0px 16px deve ser colocado no a e não na li, caso contrário o link a não irá ocupar toda a área da li onde está.
E a logo você pode usar apenas margin: 0 16px;, pois ela será centralizada automaticamente no flexbox.
Comment: Para um site simples qual seria o mais adequado, calcular o tamanho do padding ou fazer desta maneira?
Comment: Calcular padding é gambiarra. O certo é usar desta maneira pq fica tudo automático.


Write keypresses to the DOM

Question: So, I am trying to run a function that grabs the key that was pressed and puts it in a variable.
I have tried doing:
let text = "";
function keys(){
    let key = KeyboardEvent.name;
    text = text + key;
    document.querySelector("#text").innerHTML = text;
}
while(1===1){
    document.onkeypress(keys());
}

But it hasn't thrown any errors at me and isn't doing what I want it to do. I would like to ask someone to explain to me how I can change and fix it.
let text = ""
function keys(){
    let key = KeyboardEvent.name
    text = text + key
    document.querySelector("#text").innerHTML = text
}
while(1===1){
    document.onkeypress(keys())
}

just doesn't work nicely.
Comment: Do you want to accumulate text to the screen (like in your example), or just write the latest keypress and delete everything else (like in the accepted answer)?
Answer: Your code has a few crucial errors:

document.onkeypress is a variable, not a function. You want to use .addEventListener() instead.
Don't put the event listener in a loop. You only need to register the event once.
KeyboardEvent is a class name, not the name of the actual event variable. Use e.key instead.

You also don't need a bunch of intermediate variables. Try this:

function keypress(e) {
    document.querySelector("#text").innerHTML += e.key;
}

document.addEventListener('keydown', keypress);

However, you should always consider a contentEditable element instead:

Enter text.

Answer: You can get the key pressed using event.key in the keypress event handler.

document.addEventListener('keypress', e => {
  document.getElementById('key').textContent = e.key;
});

Write keypresses to the DOM


How to understand and fixed this error?

Question: 2011-04-20 18:38:41.347 RIE[1683:607] -[UICGColor _shouldContinuePlaybackInBackground]: unrecognized selector sent to instance 0x28db10
2011-04-20 18:38:41.417 RIE[1683:607] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UICGColor _shouldContinuePlaybackInBackground]: unrecognized selector sent to instance 0x28db10'
*** Call stack at first throw:
(
    0   CoreFoundation                      0x342ed64f __exceptionPreprocess + 114
    1   libobjc.A.dylib                     0x35570c5d objc_exception_throw + 24
    2   CoreFoundation                      0x342f11bf -[NSObject(NSObject) doesNotRecognizeSelector:] + 102
    3   CoreFoundation                      0x342f0649 ___forwarding___ + 508
    4   CoreFoundation                      0x34267180 _CF_forwarding_prep_0 + 48
    5   MediaPlayer                         0x344628b7 -[MPMoviePlayerViewController _moviePlayerViewController_applicationDidEnterBackgroundNotification:] + 42
    6   Foundation                          0x333b5183 _nsnote_callback + 142
    7   CoreFoundation                      0x342bc20f __CFXNotificationPost_old + 402
    8   CoreFoundation                      0x34256eeb _CFXNotificationPostNotification + 118
    9   Foundation                          0x333b25d3 -[NSNotificationCenter postNotificationName:object:userInfo:] + 70
    10  UIKit                               0x36364d01 -[UIApplication _handleApplicationSuspend:eventInfo:] + 500
    11  UIKit                               0x362feaf9 -[UIApplication handleEvent:withNewEvent:] + 1916
    12  UIKit                               0x362fe215 -[UIApplication sendEvent:] + 44
    13  UIKit                               0x362fdc53 _UIApplicationHandleEvent + 5090
    14  GraphicsServices                    0x33e58e77 PurpleEventCallback + 666
    15  CoreFoundation                      0x342c4a97 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 26
    16  CoreFoundation                      0x342c683f __CFRunLoopDoSource1 + 166
    17  CoreFoundation                      0x342c760d __CFRunLoopRun + 520
    18  CoreFoundation                      0x34257ec3 CFRunLoopRunSpecific + 230
    19  CoreFoundation                      0x34257dcb CFRunLoopRunInMode + 58
    20  GraphicsServices                    0x33e5841f GSEventRunModal + 114
    21  GraphicsServices                    0x33e584cb GSEventRun + 62
    22  UIKit                               0x36328d69 -[UIApplication _run] + 404
    23  UIKit                               0x36326807 UIApplicationMain + 670
    24  Motor Show                          0x0000219b main + 70
    25  Motor Show                          0x00002150 start + 40
)
terminate called after throwing an instance of 'NSException'
Program received signal:  "SIGABRT".

Answer: Hard to say given just the stack trace, but I would suggest the following:

Implement applicationWillResignActive: in your UIApplicationDelegate to ensure that video playback is paused or stopped before the application enters the background.
Create a custom UIApplication subclass to use in your app, and override the _handleApplicationSuspend:eventInfo: method so that it returns without propagating the event to other classes further down the chain.
Figure out how to unregister your MPMoviePlayerViewController component from the notification center so that it does not receive the 'ApplicationDidEnterBackgroundNotification'.

How to understand and fixed this error?


$ \text{ Find } \lim_{n\rightarrow \infty} \frac{n}{a^n} $

Question: $\text{Find }$ $$ \\ \lim_{n\rightarrow \infty} \frac{n}{a^n} \\ \text{ where a > 0 is a number.} $$

$\text{To solve this problem we first realize that we need to use l'hopitals rule} \\ \text{because if we evaluate at infinity we get } \\ $
$$\lim_{n\rightarrow \infty} \frac{n}{a^n} = \frac{\infty}{\infty} \\ \text{using l'hopitals rule we get } \\ \lim_{n \rightarrow \infty}\frac{1}{n \cdot x^{n-1}} = 0 \\ \text{If we take lhopitals rule again we get } \\ \lim_{n \rightarrow \infty} \frac{0}{(n-1) \cdot n \cdot x^{n-2}} =0 \\ \text{Thus } \ \ \lim_{n\rightarrow \infty} \frac{n}{a^n} = 0 \\ \text{Is this the correct procedure that one uses in order to find the limit for this problem?}  \\  \text{Is there any mistakes in my solution?} $$
Comment: The function does not always satisfy L'Hopital's hypothesis.
Comment: And, as it's been correctly pointed out, $\frac{d}{dx}[a^x]\ne xa^{x-1}$.
Comment: Related: https://math.stackexchange.com/questions/55468/how-to-prove-that-exponential-grows-faster-than-polynomial. And please, only use MathJax for the *formulas*, not for all the text...
Answer: You are not differentiating $a^n$ (with respect to $n$) correctly.
$$
\frac{d}{dn}\left[a^n\right] = \text{ln}(a)a^n
$$
So using L'Hopital's Rule (first time) you should get
$$
\frac{1}{\text{ln}(a)a^n}
$$
Also note that if $0<a\leq 1$, then you will not be able to use L'hopital's Rule as
$$
\lim_{n\rightarrow\infty}\left[ \frac{n}{a^n}\right]=\frac{\infty}{0}
$$
for $0<a<1$, and
$$
\lim_{n\rightarrow\infty}\left[ \frac{n}{a^n}\right]=\frac{\infty}{1}
$$
for $a = 1$.
Comment: Is the limit then 0?
Comment: Depends on the value of $a$, will it converge for $a=\frac{1}{2}$?
Comment: It is 0 and $\infty $ that the limit can be depending on a.
Comment: Correct, you've proven the former with L'Hopital's rule - now you have to prove the latter, which is quite easy (*Hint*: $n\leq \frac{n}{a^n}$ if $a\leq 1$)
Answer: For $a \leq 1$ the denominator does not tend to $\infty$ so L'Hopital's Rule is not applicable. For $a>1$ one application of the rule gives $\lim \frac 1 {a^{n}\log\, a}$ and $a^{n}\log\, a \to \infty$ so there is no need to apply the rule again. For $a\leq 1$ the limit is $\infty$. Can you prove this?
Answer: By L'Hôpital's rule,  we get $\lim_{n\to\infty}\dfrac1{\ln a \cdot a^n}=0$, when $a\gt1$.
When $a\le1$, L'Hôpital isn't applicable.  But the limit is easy to calculate.  We get $\infty $.
Comment: Yes.  When $a\gt1$.
Comment: Right @SaucyO'Path.  I will try to clean it up.
Comment: So this limit can have two solutions correct depending on a?
Comment: That's right, Jon.
Comment: But after l'hopitals rule the limit can only be 0, so the limit is 0.
Comment: Since when $a \le 1$ $lim_{n\rightarrow \infty} \frac{1}{a^n \cdot ln(a)} = \frac{1}{0} =\text{   Does not Exist}.$
Comment: The numerator,  $n$, goes to $\infty $.  No L'Hôpital's rule when $a\le1$.
Answer: L'Hospital's rule is only applicable when you have a limit of the form
$$\frac{\infty}{\infty}$$
or
$$\frac{0}{0}$$
Thus we need to consider $3$ cases: (a) $0<a<1$, (b) $a=1$, and (c) $a>1$.
(a) For $a<1$ we have
$$\lim_{n\to\infty}\frac{n}{a^n}=\infty$$
because $\lim_{n\to\infty}a^n=0$ and $\lim_{n\to\infty}n=\infty$, so we have
$$\frac{\infty}{0}=\infty, \quad 0<a<1$$
(b) When $a=1$, we have
$$\lim_{n\to\infty}\frac{n}{a^n}=\lim_{n\to\infty}\frac{n}{1^n}=\lim_{n\to\infty}n=\infty, \quad a=1$$
(c) For $a>1$ we have
$$\lim_{n\to\infty}\frac{n}{a^n}=\frac{\infty}{\infty}$$
This is the only case where L'Hospital's rule is applicable. Here, write
$$\begin{align}\lim_{n\to\infty}\frac{n}{a^n}&=\lim_{n\to\infty}\frac{\text{d}}{\text{d}n}\left(\frac{n}{a^n}\right)\\
&=\lim_{n\to\infty}\frac{\text{d}}{\text{d}n}\left(\frac{n}{\exp(\ln(a^n))}\right)\\
&=\lim_{n\to\infty}\frac{\text{d}}{\text{d}n}\left(\frac{n}{\exp(n\ln(a))}\right)\\
&=\lim_{n\to\infty}\frac{\text{d}}{\text{d}n}\left(\frac{1}{\ln(a)\exp(n\ln(a))}\right)\\
&=\lim_{n\to\infty}\frac{\text{d}}{\text{d}n}\left(\frac{1}{\ln(a)a^n}\right)\\
&=\frac{1}{\infty}\\
\lim_{n\to\infty}\frac{n}{a^n}&=0, \quad a>1
\end{align}$$
I added extra steps to demonstrate how to perform the derivative of $a^n$.
Comment: @Jon correct. Consider $\lim_{n\to\infty}n$. The limit is clearly infinity. However, if we tried to apply L'Hospital's rule here, the limit would be come $\lim_{n\to\infty}1$, which is just $1$. L'Hospital's rule is only valid when we have one of those two forms, because in those cases, it is unclear what the answer is. Put another way, we do not apply L'Hospital's rule when we are already able to evaluate the limit. In those two cases, it is unclear if the denominator or numerator becomes smaller / larger faster, and L'Hospital's rule helps us to determine which one is.
Comment: So we only use lhopitals rule once because, we get a form that is not $\frac{0}{0}  , \frac{\infty}{ \infty}?$
Comment: Pardon me for asking but then case (c) would be the true limit solution posed by the original question.
Comment: @jon because $a>0$, (a), (b), and (c) together define the solution to the problem.
Answer: Most of the answers provided seem to be tackle the problem by applying l'Hopital's Rule, which is a perfectly valid method. However, it's important to have an intuition for the limits you're solving. Since this is a fairly simple one, I'll use the opportunity to explain how to think about them.
With these types of questions, it's important to think about the growth rates of the functions you're comparing. In this case, the two you're comparing a linear function, $y=n$, to an exponential one, $y=a^n$. First, we can look at the numerator, which fairly clearly goes to $\infty$ in a linear fashion. As the other answers suggested, the exponential function requires looking at three cases, $a<1$, $a=1$, and $a>1$. The second of these intuitively goes to $\infty$, as:
$$\lim_{n\rightarrow\infty}\frac{n}{1^n}=\lim_{n\rightarrow\infty}n=\infty$$
For the case where $a<1$, hopefully it is clear that, the more times you multiply $a$ by itself, the smaller it becomes. Hence, when your numerator is going to infinity and your denominator approaches $0$, this is an indication that your limit also goes to $\infty$.
When $a>1$, now you should consider how the two different functions grow. Looking at the case when $a=2$, we have this graph:

where the red graph is the line $y=x$ and the blue graph is $y=2^x$. Through graphing, you can clearly see the trends that the two functions have when increasing, and you can deduce that $y=2^x$ will "get to" $\infty$ "faster" than $y=x$ will. It's this kind of thinking that underlies the problem: which of these two functions that I'm comparing will reach infinity faster? If the one in the denominator does, then you should gain the intuition that your limit may go to $0$ (and $\infty$ if the numerator approaches it faster). There's nothing wrong with l'Hopital's Rule for more grueling limits where it's harder to have a feel about the problem, but I think it's important to have a conceptual grasp on how to think about these problems before you automatically apply it.


Check to see if AD Group is empty

Question: I am looking for a way to first check if the AD group is empty and if so, write to the CSV file something like "$GroupName + is empty." I imagine this will be in a IF-THEN construct, but note sure where to place it in my code below or the syntax. Thank you for your help.
#Script will export group members from the imported list of groups
#Import the AD Module necessary for the script to run
Import-Module ActiveDirectory
#specify the file that contains group names
$groups = Get-Content C:\temp\grouplist.txt
$UserProperties = 'GivenName', 'Surname', 'Name'

$resultsarray =@()

foreach ($group in $groups){

    $resultsarray += Get-ADGroupMember -Id $group -Server Server01.domain.com | Get-ADUser -Properties $UserProperties | select (@{n='FirstName';e={$_.GivenName}},
    @{n='LastName';e={$_.Surname}},'Name',@{e={$group};Label="GroupName"})

}
$resultsarray | Export-csv -path C:\temp\Groups_$(get-date -Format yyyy-MM-dd).csv -NTI

Comment: `Get-ADGroupMember` can return user, computer or group objects. With "_check if the AD group is empty_" you apparently mean there are no **users** in the group? What if there are groups in the group, but no direct user objects. Is that empty for you?
Comment: The groups could have either users or other groups. One group in particular typically has nothing in it, but could have users or groups added for short periods. So, each day this script runs and will report out the group membership. If the group is empty, which it usually is, I just want the script to report that. But, if the group has members, then report the members (but not recursive - I don't need the membership of the other groups).
Comment: Group and User objects have different properties. There is no `GivenName` on a group for instance.. Please edit your question and tell us what properties you want in the output for groups.
Comment: If the groups in the list have users, then list the user properties (GivenName, Surname, Name). If there is a nested group, I just want the Group name.
Comment: So you do want to recurse.. Maybe have a look at [this](https://gallery.technet.microsoft.com/scriptcenter/Get-nested-group-15f725f2)
Comment: No, not recursive.
Answer: I haven't tried this out but it could be something like
#Script will export group members from the imported list of groups
#Import the AD Module necessary for the script to run
Import-Module ActiveDirectory
#specify the file that contains group names
$groups = Get-Content C:\temp\grouplist.txt
$UserProperties = 'GivenName', 'Surname', 'Name'

$resultsarray =@()

foreach ($group in $groups){

    $result = Get-ADGroupMember -Id $group -Server Server01.domain.com | Get-ADUser -Properties $UserProperties | select (@{n='FirstName';e={$_.GivenName}},
    @{n='LastName';e={$_.Surname}},'Name',@{e={$group};Label="GroupName"})
    $resultsarray += if ($result) {$result} else {"$($group) is empty"}

}
$resultsarray | Export-csv -path C:\temp\Groups_$(get-date -Format yyyy-MM-dd).csv -NTI

Comment: Thanks for that. It prints a blank line in the CSV file where the group would have been.
Comment: Please could you try replacing this line:
    *$resultsarray += if ($result) {$result} else {"$($group) is empty"}*
first with
    *$resultsarray += if ($null -eq $result) {$result} else {"$($group) is empty"}*
and if that doesn't work, with
    *$resultsarray += if ($result -eq "") {$result} else {"$($group) is empty"}*
and finally with
    *$results\array += if ([string]::IsNullOrEmpty($result)) {$result} else {"$($group) is empty"}*
Comment: That last line should read
    *$resultsarray += if ([string]::IsNullOrEmpty($result)) {$result} else {"$($group) is empty"}*
Comment: Unfortunately, none of those work. It produces some interesting results though. I get a count of users I think. It literally exports a few lines with numbers in them. "length 39, 46, 45"
Answer: After some comments, I think I now understand the question as to when it should be empty or not.
Because the Get-ADGroupMember can return objects of type 'user', 'group' or 'computer', the code needs to handle that and output different results depending on the objectClass of each member.
However, since you want the result as CSV file, you need to take care all objects return the same structured object.
The following should do what you ask for:
Import-Module ActiveDirectory
#specify the file that contains group names
$groups = Get-Content C:\temp\grouplist.txt
$UserProperties = 'GivenName', 'Surname', 'Name'

# loop through the groups and collect group member info in a variable '$result'
$result = foreach ($group in $groups){
    # get all members of the group and force it to be an array
    $groupMembers = @(Get-ADGroupMember -Identity $group -Server 'Server01.domain.com')
    if ($groupMembers.Count) {
        foreach ($member in $groupMembers) {
            switch ($member.objectClass) {
                'user' {
                    # emit an object with the following user properties
                    $member | Get-ADUser -Properties $UserProperties |
                              Select-Object @{Name = 'FirstName'; Expression = {$_.GivenName}},
                                            @{Name = 'LastName'; Expression = {$_.Surname}},
                                            'Name',
                                            @{Name = 'MemberType'; Expression = {$member.objectClass}},
                                            @{Name = 'GroupName'; Expression = {$group}},
                                            @{Name = 'GroupIsEmpty'; Expression = {$false}}
                }
                default {
                    # for other objects like groups or computers, keep the same structure
                    # and only fill in the Name, MemberType and GroupName properties
                    '' | Select-Object 'FirstName','LastName',
                                        @{Name = 'Name'; Expression = {$member.Name}},
                                        @{Name = 'MemberType'; Expression = {$member.objectClass}},
                                        @{Name = 'GroupName'; Expression = {$group}},
                                        @{Name = 'GroupIsEmpty'; Expression = {$false}}
                }
            }
        }
    }
    else {
        # the group is empty. Again: keep the same structure as above
        '' | Select-Object 'FirstName','LastName','Name','MemberType',
                            @{Name = 'GroupName'; Expression = {$group}},
                            @{Name = 'GroupIsEmpty'; Expression = {$true}}
    }
}

$outFile = 'C:\temp\Groups_{0:yyyy-MM-dd}.csv' -f (Get-Date)
$result | Export-csv -path $outFile -NoTypeInformation -Force

Note: in this case you do not even need to use the -Properties parameter on the Get-ADUser cmdlet, since all the properties you want ($UserProperties = 'GivenName', 'Surname', 'Name') are returned by default
Comment: works nicely. thanks!! I see the logic now, so great help.

Check to see if AD Group is empty


insert advertisement block within views list

Question: I have a view that output the content nodes as grid. (instigram style). How to insert an advertisement block in a random location within the views list.
Node
Node
.
.
Advertisement
.
.
Node
Node
Comment: I think you must use the views hooks after generating result. then count the result's rows and select the random position between rows , finally you must load your advertisement block and insert it into the #markup nodes in the selected rows.
For this issue, module programming is needed buy maybe the other friends can help you to do it only with views definition.
Answer: You can override the format specific template like views-view-unformatted.tpl.php (you can find the right file based on your requirement) and then use some custom code like
  <?php if (($id % 2) == 0): ?>
    Do what-ever you want to do here.
  <?php endif; ?>

This module hosted on github https://github.com/pedroposada/custom_views_nthrow seems to do the same more modularly.
Instructions : http://www.pedroposada.com/blog/insert-whatever-every-nth-row-views.html-0
Comment: Thx !! Just what i needed !! i ended overriding "views-view-unformatted.tpl.php" and inserting the ad block in a random location wihin the loop.
Answer: If you want to have your custom code after first row then override your default views-view-unformatted.tpl.php with this code:
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

  <?php if ($id == 0 || $id == 5): ?>
Your custom adsense code
  <?php endif; ?>
<?php endforeach; ?>

Step-by-step tutorial for newbies on how to override default views-view-unformatted.tpl.php and achieve custom code after for example first and sixth row is here.


bootstrap-datepicker validates future dates with "can't be blank" - Ruby on Rails

Question: I don't know what's wrong but even I put a future date in my field :scheduled_date, rails validates it with can't be blank. Actually, the field validates only future dates and blank field but if I put a present date and past dates, there's no problem. Thanks!

UPDATED!
This is my model:
registration.rb
validates :scheduled_date, presence: true

html file:
<%=f .label :scheduled_date, 'Date of Appointment:', class: 'control-label' %>

    <%=f .text_field :scheduled_date, class: 'form-control', data: { format: "MM/dd/yyyy" } , placeholder: "Select date" %>

Comment: Can you post some related code? Your model `validations` and your input for `:scheduled_date` would be very helpful.
Comment: What are sample inputs you given to the `:scheduled_date` field?
Comment: just like 06/25/2014 (that's future date), if I submit, it will validate to can't be blank
Comment: Just a hunch,what happens when you change this line `format: "MM/dd/yyyy"` to `format: "mm/dd/yyyy"`?
Comment: nothing changes. I got the same error.
Answer: I got this thing. Actually, the error comes from the format: "MM/dd/yyyy" because MySQL only saves for data type date with this format yyyy/MM/dd. Thanks!


aggregate data by week using python

Question: I have a this data and I wont to aggregate it by week for two date periods given :
I do have this list of tuple that present the sales for each day from my transactions table
Metadate = [(Day, 'totalSales By dollars')]

--
data=[('2013-06-21', 14),
 ('2013-06-20', 19),
 ('2013-06-23', 11),
 ('2013-06-22', 13),
 ('2013-06-25', 6),
 ('2013-06-24', 22),
 ('2013-06-27', 22),
 ('2013-06-26', 3),
 ('2013-06-29', 10),
 ('2013-06-28', 15),
 ('2013-04-05', 20),
 ('2013-04-04', 33),
 ('2013-04-07', 20),
 ('2013-04-06', 15),
 ('2013-04-01', 23),
 ('2013-04-03', 5),
 ('2013-04-02', 8),
 ('2013-04-09', 10),
 ('2013-04-08', 24),
 ('2013-05-08', 1),
 ('2013-05-09', 29),
 ('2013-05-02', 17),
 ('2013-05-03', 18),
 ('2013-05-01', 4),
 ('2013-05-06', 16),
 ('2013-05-07', 10),
 ('2013-05-04', 9),
 ('2013-05-05', 12),
 ('2013-05-19', 21),
 ('2013-05-18', 26),
 ('2013-05-11', 8),
 ('2013-05-10', 12),
 ('2013-05-13', 24),
 ('2013-05-12', 9),
 ('2013-05-15', 5),
 ('2013-05-14', 7),
 ('2013-05-17', 20),
 ('2013-05-16', 36),
 ('2013-05-20', 24),
 ('2013-05-21', 5),
 ('2013-05-22', 3),
 ('2013-05-23', 18),
 ('2013-05-24', 8),
 ('2013-05-25', 11),
 ('2013-05-26', 9),
 ('2013-05-27', 13),
 ('2013-05-28', 4),
 ('2013-05-29', 7),
 ('2013-06-18', 9),
 ('2013-06-19', 2),
 ('2013-06-10', 20),
 ('2013-06-11', 4),
 ('2013-06-12', 3),
 ('2013-06-13', 25),
 ('2013-06-14', 16),
 ('2013-06-15', 10),
 ('2013-06-16', 11),
 ('2013-06-17', 17),
 ('2013-04-30', 12),
 ('2013-05-31', 13),
 ('2013-05-30', 29),
 ('2013-06-09', 12),
 ('2013-06-08', 20),
 ('2013-06-07', 47),
 ('2013-06-06', 5),
 ('2013-06-05', 2),
 ('2013-06-04', 3),
 ('2013-06-03', 32),
 ('2013-06-02', 13),
 ('2013-06-01', 9),
 ('2013-04-23', 3),
 ('2013-04-22', 33),
 ('2013-04-21', 14),
 ('2013-04-20', 20),
 ('2013-04-27', 15),
 ('2013-04-26', 17),
 ('2013-04-25', 21),
 ('2013-04-24', 1),
 ('2013-04-29', 34),
 ('2013-04-28', 11),
 ('2013-06-30', 13),
 ('2013-04-16', 5),
 ('2013-04-17', 3),
 ('2013-04-14', 10),
 ('2013-04-15', 22),
 ('2013-04-12', 23),
 ('2013-04-13', 19),
 ('2013-04-10', 1),
 ('2013-04-11', 31),
 ('2013-04-18', 27),
 ('2013-04-19', 14)]

I want to aggregate it by week for two dates given start and end date :
example of the output :
[(2013-05-07, 900), [(2013-05-14, 1800),....., (2013-08-01, 1000)]
Thanks in advance!
Comment: Is week here meaning a calendar week or a sequence of 7 days?
Comment: @leon : calendar week.
Answer: Try this:
from datetime import datetime
import itertools

sales = [
    ('2013-05-01', 100),
    ('2013-05-02', 200),
    ('2013-05-03', 150),
    ('2013-05-03', 120),
    ('2013-05-04', 200),
    ('2013-08-01', 250),
]

def toWeek(sale):
    '''(date,volume) -> date of the Sunday of that week'''
    sunday = datetime.strptime(sale[0], '%Y-%m-%d').strftime('%Y-%U-0')
    return datetime.strptime(sunday, '%Y-%U-%w').strftime('%Y-%m-%d')

grouped_sales = itertools.groupby(sales, toWeek)

aggregate_sales = (
    (week, sum(day_sales for date, day_sales in week_sales))
    for week, week_sales in grouped_sales)

print list(aggregate_sales)

Comment: This is the classic Python / itertools solution. Know that the list `sales` must be sorted by date for this to work.
Comment: @mongotop -   My solution presumed the input data set was sorted by date. Your new data set isn't. You could modify my solution thusly: `grouped_sales = itertools.groupby(sorted(sales), toWeek)`
Comment: This is a great solution! Thank you very much! I will go ahead and accept it as an answer! Can you please add some comments to your code so I can understand it more, I'm a bit newbie :) Thank you again!
Comment: @drewk : Thank you very much for chiming in!! I will go ahead and do some googling on itertools package!! :)
Comment: Hi, the code above works for a small data set, but when I feed it a big one line 90 elements, it pull the data for the same week twice with different value : I edited my question with bigger data set. Do you know why it's acting up with bigger data set? Thanks a lot!!
Answer: You can also use ISO 8601 week calculations and a deque to do this:
import datetime
from collections import deque

data=[
    ('2013-05-01', 100),
    ('2013-05-02', 200),
    ('2013-05-03', 150),
    ('2013-05-03', 120),
    ('2013-05-04', 200),
    ('2013-08-01', 250),
]
fmt='%Y-%m-%d'
data=deque((datetime.datetime.strptime(x,fmt),y)
              for x,y in sorted(data,key=lambda t:t[0]))
grouped={}
while data:
    week=data[0][0]-datetime.timedelta(days=(data[0][0].isocalendar()[2]-1))
    temp=[data.popleft()]
    while data and week.isocalendar()[:2]==data[0][0].isocalendar()[:2]:
        temp.append(data.popleft())

    key='ISO week {}-W{:02}'.format(*week.isocalendar()[:2])
    key+=' ({} - {})'.format(week.strftime(fmt),
                        (week+datetime.timedelta(days=6)).strftime(fmt))

    grouped[key]=sum(t[1] for t in temp)

for k in sorted(grouped):
    print '{}: {}'.format(k, grouped[k])

Prints:
ISO week 2013-W18 (2013-04-29 - 2013-05-05): 770
ISO week 2013-W31 (2013-07-29 - 2013-08-04): 250

Edit
I saw the code you posted and you can simplify with another deque:
D=deque()
fmt='%Y-%m-%d'
data=deque((datetime.datetime.strptime(x,fmt),y)
              for x,y in sorted(data,key=lambda t:t[0]))
while data:
    week=data[0][0]-datetime.timedelta(days=(data[0][0].isocalendar()[2]-1))
    temp=[data.popleft()]
    while data and week.isocalendar()[:2]==data[0][0].isocalendar()[:2]:
        temp.append(data.popleft())

    D.appendleft((week.strftime(fmt), sum(t[1] for t in temp)))

print list(D)

Prints
[('2013-06-24', 91), ('2013-06-17', 85), ('2013-06-10', 89), ('2013-06-03', 121), ('2013-05-27', 88), ('2013-05-20', 78), ('2013-05-13', 139), ('2013-05-06', 85), ('2013-04-29', 106), ('2013-04-22', 101), ('2013-04-15', 105), ('2013-04-08', 118), ('2013-04-01', 124)]

Comment: 1) Make sure there are only spaces -- no tabs (or vs vs); 2) Make sure the code is just as I posted it; 3) You probably will not be able to paste this directly into the Python interpreter -- you will need to use an editor.
Comment: Is the output as expected with the bigger data set?
Comment: it's always great to have another option to do the same thing! Thank you very much!!!
Comment: I tried the code, and it's giving me an error sayin : `while data and week.isocalendar()[:2]==data[0][0].isocalendar()[:2]:
    ^
IndentationError: unexpected indent`  I checked the code and I didn't find any spacing error. any idea why it might be trowing that error?  thanks a lot!!
Comment: You are right!!! I used python cm line, but when I used a text editor and I executed it it works like it should! Thank you very much again!!
Comment: sorry to bather you to mich, but is there's away to display that data on this format instead of `ISO week2013 Wnbr  (stardaytweek, leastdayweek ) : value`, can I display it as `[(leastdayweek, value1), (leastdayweek, value2)]` ? Thank you!
Comment: I played little bit with your code and I got the format I needed!! thank you!! http://jsfiddle.net/rHWEq/
Comment: much, much , much better solution that my hack solution! Thank you Drewk!

aggregate data by week using python


Are these two equation equal? $f(x)=\sin(4x)-\sin(3x)\cos(x)$ and $g(x)=\sin(x)\cos(3x)$

Question: I have been trying to get these equations into a sum or difference of sin formula but since the first equation has the $-\sin(3x)\cos(x)$ in it, I keep getting hung up on the multiplication.  I did set the two equations equal to each other but I am not seeing how these two equations are equal.  The back of the book says they are.
$$\sin(4x)-\sin(3x)\cos(x)= \cos(3x)\sin(x)$$
$$-\sin(3x)\cos(x)-\cos(3x)\sin(x) = -\sin(4x)$$
At this point the sum of sin formula looks possible if I multiply by $-1$
$$\sin(3x)\cos(x)+\cos(3x)\sin(x)=\sin(4x)$$
$$\sin(a+b)=\sin(3x)\cos(x)+\cos(3x)\sin(x)$$
But, I really do not think the $\sin(4x) = \sin(a+b)$.
Answer: The identity in question is
$$\sin(a+b) = \sin(a)\cos(b) + \sin(b)\cos(a)$$
and so
$$\sin(3x)\cos(x) + \sin(x)\cos(3x) = \sin(3x + x) = \sin(4x) \\ \implies \sin(4x)-\sin(3x)\cos(x) = \sin(x)\cos(3x)$$
so yes, $f(x)=g(x)$.
Comment: Thanks, I was having a hard time making that connection.  It must be similar to saying the $sin(\frac{5\pi}{12})=sin(\frac{\pi}{4}+\frac{\pi}{6})$


Expected Value Of Dice Rolling Game

Question: I am having trouble figuring out the expected value in situations were the examples are going to infinity.
Example:
I have a fair dice with 8 sides. I keep a counter ($k$) of the rounds I play. Each round I increase the counter by 1 and I roll the die. I keep doing this until I roll a 1 or an 8.
So I'll define a random variable $X$ to be the amount of rounds played. I know that the odds of rolling a 1 or a 8 on a 8 sided die is $\frac1 4$ otherwise it is $\frac3 4$. The way I am trying to solve the expected value is by using a geometric series. This is where I am getting stuck I think it should look like this:
$E(X)=X_1P_1+X_2P_2+X_3P_3+...+X_nP_n$
$E(X)=1*\frac1 4+2*\frac1 4+3*\frac1 4+...+n*\frac1 4$
I am unsure how to turn this into a sum.
Comment: Check out the geometric distribution https://en.m.wikipedia.org/wiki/Geometric_distribution
Comment: You would have to calculate the expected value of the random variable. If it goes to infinity or not doesn't matter, since it is a normal random distribution. The expected value is the sum of the product between the possible results and their probability. `E[X] = x1*p1 + [...] + xn*pn`
Comment: The probability $P_k$ that goes with $X_k$ in your sum should be the probability that the random variable $X$ takes on the value $k$. What you've got is the probability that you'll roll a $1$ or $8$, which is not the same thing at all. You should instead have the probability that the $k$th roll is $1$ or $8$ _and_ that none of the preceding rolls were.
Answer: There is an easy trick for this calculation, using the following fact, for a random variable $X$ and a specific value $x$:
$$
E(X)=P(X=x) \cdot E(X\mid X=x)+P(X\neq x)\cdot E(X\mid X\neq x)
$$
(where $E(X\mid X=x)=x$, of course).
We can let $X$ be the number of throws we do in total (including the last $1$ or $8$), and $x=1$. This gives
$$
E(X)=\frac14+\frac34E(X\mid X\neq 1)
$$
But $X\mid X\neq 1$ just means "we know we fail on the first throw, and then we keep going as normal", which means that
$$
E(X\mid X\neq1)=1+E(X)
$$
and this gives
$$
E(X)=\frac14 +\frac34(1+E(X))
$$which may be solved as a normal equation.
Comment: The way I am trying to solve this and the way I have seen similar question solved is using a geometric sequence.

Since X is the number of rounds played I think my expected value of X would look something like this:

$E(X) = X_1 P_1+X_2 P_2 + X_3 P_3 + ... + X_n P_n$ which would turn to $E(X)=1* \frac 1 4 + 2* \frac 1 4 + 3* \frac 1 4 +...+n* \frac 1 4$

Expected Value Of Dice Rolling Game


Storage Pools: Extending virtual disk after expanding Azure Disk

Question: We host our Windows Server 2016 Virtual Machines on Azure and I am having a problem to expand one Virtual Disk on the Storage Pool after having expanded the disk on Azure.
The Virtual Disk is a simple 300GB. The Physical disk is an Azure 300GB (Premium SSD), as you can see in the image below.

I expanded the Azure disk to 400GB, but this change was not reflected in the physical disk on Storage Spaces. Instead, it mounts my old disk just as it was before, and present another 400GB disk with 100GB free space.

How can I expand my Virtual Disk to 400GB? Is it actually possible or I would have to add another 300GB disk and expand in 300GB increments due to the column size? Am I misusing Storage Spaces on this scenario and instead it should be just a simple volume on windows?
Answer: If you have a look at the docs for expanding disks in storage spaces it has this warning:

Not supported: resizing the underlying storage used by Storage Spaces
  Direct. If you are running Storage Spaces Direct in a virtualized
  storage environment, including in Azure, resizing or changing the
  characteristics of the storage devices used by the virtual machines
  isn't supported and will cause data to become inaccessible. Instead,
  follow the instructions in the Add servers or drives section to add
  additional capacity before extending volumes.

Given that, you need to create a new disk in Azure and then extend the pool to use that, rather than trying to expand the existing disk
Comment: Thank you Sam! That's the confirmation I was looking for.


Inner join no entityframework

Question: Eu preciso fazer um inner join no entity frameworkm no banco, eu consigo fazer normalmente desta forma:
select * from Produtos inner join ProdutosEmpresas on ProdutoID = Produtos.Id

Porém no entity framework eu não consigo, ele não aparece a tabela para fazer o include.
Aqui é como está atualmente:
var produtos = db.Produtos.OrderBy(a => a.Codigo).Where(a => a.ControleEstoque == true).ToList();

Preciso fazer o inner join da tabela Produtos com a tabela ProdutosEmpresas. Tentei fazer com Include, porém ele não aparece a tabela para colocar. Não entendi o porque.
ProdutosEmpresas
 public class ProdutosEmpresas
{
    [Key]
    public int Id { get; set; }
    public Empresa EmpresaProduto { get; set; }
    public int EmpresaID { get; set; }
    public Produto ProdutoEmpresa { get; set; }
    public int ProdutoID { get; set; }
    public int Qtd { get; set; }
    public decimal PrecoCusto { get; set; }
    [DataType(DataType.Currency)]
    public decimal PrecoVenda { get; set; }
}

Produtos
 public class Produto
{

    [Key]
    public int Id { get; set; }
    [StringLength(100)]
    public string Codigo { get; set; }

    [StringLength(120)]
    public string nome { get; set; }
    public int QtdAtual { get; set; }
    public int QtdMinima { get; set; }
    public int QtdMaxima { get; set; }

    public decimal PrecoCusto { get; set; }
    [DataType(DataType.Currency)]
    public decimal PrecoVenda { get; set; }
    public decimal CustoMedio { get; set; }

    public float ICMS { get; set; }

    public float ISS { get; set; }

    public float IPI { get; set; }
    public float Margem { get; set; }
    public float Comissao { get; set; }
    public int CategoriaID { get; set; }
    public Categoria Categoria { get; set; }
    //public int EmpresaID { get; set; }
    //public Empresa Empresa { get; set; }

    [StringLength(500)]
    public string observacao { get; set; }
    [StringLength(8)]
    public string NCM { get; set; }

    public bool ControleEstoque { get; set; }
    public byte[] Foto { get; set; }

    public bool TipoProduto { get; set; }
    public bool TipoSoftware { get; set; }
}

Comment: Consegue postar o código das suas entidades Produtos e ProdutosEmpresas? Se você tiver feito o relacionamento entre elas talvez você nem precise do include.
Comment: Faltou a propriedade de referência em Produto de ProdutosEmpresa.
http://www.entityframeworktutorial.net/entity-relationships.aspx
Comment: @GeorgeWurthmann atualizei a pergunta com Produtos e ProdutosEmpresas.
Comment: https://docs.microsoft.com/pt-br/ef/ef6/fundamentals/relationships
Answer: O EF possui um método chamado Join.
Veja os docs
O seu código ficaria mais ou menos assim:
ObjectSet<Produto> produtos = db.Produto;
ObjectSet<SProdutosEmpresas> produtosEmpresas = db.ProdutosEmpresas;

var resultado = produtos
    .Join(produtosEmpresas, pe => pe.ProdutoID, (p, pe) => new { Produto = p, ProdutoEmpresa = pe })
    .Where(x => x.Produto.ControleEstoque)
    .OrderBy(x => x.Produto.Codigo)
    .ToList();

Comment: você está usando qual versão do Entity Framework?
Comment: Não deu certo, ele não aceitou esta parte `pe.ProdutoID`, então fiz assim: `var resultado = db.Produtos
    .Join(db.ProdutosEmpresas, pe => pe.Id, (p, pe) => new { Produto = p, ProdutoEmpresa = pe })
    .Where(x => x.Produto.ControleEstoque == true)
    .OrderBy(x => x.Produto.Codigo)
    .ToList();` porém também não deu certo, ele dá o seguinte erro:   Gravidade Código Descrição Projeto Arquivo Linha Estado de Supressão
Erro CS1501 Nenhuma sobrecarga para o método "Join" leva 3 argumentos
Comment: Versão 2.1.1 EntityFrameworkCore.
Answer: Você pode (ou até deve) especificar o relacionamento entre as entidades.
Você pode fazer isso adicionando a seguinte linha no ProdutosEmpresas:
[ForeignKey("Id")]
public Produtos Produtos { get; set; }

Ficaria assim:
public class ProdutosEmpresas
{
    [Key]
    public int Id { get; set; }
    public Empresa EmpresaProduto { get; set; }
    public int EmpresaID { get; set; }
    public Produto ProdutoEmpresa { get; set; }
    public int ProdutoID { get; set; }
    public int Qtd { get; set; }
    public decimal PrecoCusto { get; set; }
    [DataType(DataType.Currency)]
    public decimal PrecoVenda { get; set; }

    [ForeignKey("Id")]
    public Produtos Produtos { get; set; }
}

E na entidade Produto adicione a linha:
public virtual ICollection<ProdutosEmpresas> { get; set; }

Fazendo isso a Propriedade Produtos do ProdutosEmpresas seria carregado pelo Lazy Loading.
Comment: Deu certinho, obrigado, Era desta forma que eu queria mesmo.

Inner join no entityframework


Apache mod_rewrite behaves differently on SSL and non-SSL configs

Question: I have a system where I'm hosting a number of SSL sites on my server. I also need to setup OAuth for each domain, with Google and Yahoo in particular. They each require verification files be installed on the server, in order to validate ownership. There are so many of these files now that they're clogging my root directory. So I want to set up a rewrite rule to sends a request to a particular URL to a verification file directory, like so:
RewriteRule (^/googlew*.html$) /verifications$1

This sends a Google verification file request such as http://server/google27c81d94580e55dd.html to http://server/verifications/google27c81d94580e55dd.html, and without rewriting the URL it works fine.
But when the request goes to an SSL URL, it fails. Here's my configuration:
<VirtualHost *:80>
            ServerName <domain>
            DocumentRoot /www/public
            RewriteEngine On
            RewriteRule (^/googlew*.html$) /verifications$1 [R]
            RewriteRule (^.*--.html$) /verifications$1 [R]
</VirtualHost>

<VirtualHost <ipaddress>:443>
            SSLEngine On
            ServerName <domain>
            DocumentRoot /www/public
            RackEnv production
            RewriteEngine On
            RewriteRule (^/googlew*.html$) /verifications$1 [R]
            RewriteRule (^.*--.html$) /verifications$1
            SSLProtocol all
            SSLCipherSuite HIGH:MEDIUM
            SSLCertificateChainFile /usr/share/ssl/crt/intermediate.crt
            SSLCertificateFile /usr/share/ssl/crt/<domain>/<domain>.crt
            SSLCertificateKeyFile /usr/share/ssl/crt/<domain>/<domain>.key
</VirtualHost>

So when the request is non-secure HTTP, it works fine. When it's secure HTTPS, it fails. Any suggestions as to why?
UPDATE As requested, here's the output of the Rewrite Log at level 3:
init rewrite engine with requested uri /google27c81d94580e55dd.html
applying pattern '(^/googlew*.html$)' to uri '/google27c81d94580e55dd.html'
applying pattern '(^.*--.html$)' to uri '/google27c81d94580e55dd.html'
pass through /google27c81d94580e55dd.html

Now here's the funny thing: prior to making my original post, as I said the non-secure version was working fine. After I posted, the non-secure version stopped working as well! The log entry I've just pasted in is what I get when running the non-secure version. Face. Exploding.
Comment: What fails exactly - do you mean the request isn't redirected correctly, or do you mean that the Google verification fails? Also, if the only concern is that the files aren't clogging up your root directory, I wouldn't use the `[R]` flag at all - you might as well let the redirection happen entirely internally in your Apache, without clients knowing the file isn't in the root dir.
Comment: The request isn't redirected correctly. In mod_rewrite parlance, it "passes through", according to the log. Seems a clear case of not matching. I also removed the [R] flag later, but it snuck into my code above.
Comment: Odd. Can you post an excerpt of the rewrite_log at some useful `RewriteLogLevel`?
Comment: Added, as per request...
Comment: Hmm, that one looks like it's failing because it doesn't match the 'w's in `^/googlew*...`
Answer: A few things:

Parens shouldn't be around your ^ and $.
You probably meant \w*, instead of w*; that will match those characters.
Make sure you escape special characters

So, try this:
RewriteRule ^(/google\w*\.html)$ /verifications$1 [R]

I'm not following the intent of your second rule; can you clarify?
Comment: It "just works". Thank you so much. The mystifying thing about this problem was that I tried *many* variations, and found some that worked. And then didn't. It was very frustrating. But this is working for now, so I'm happy!
Comment: Oh, btw. The second rule is for a Yahoo verification file. Never had any problems with that, though I'll fix those parens and then be extra-good. :)