Valores iniciais na função nls no R

Question: Olá, tenho o seguinte código em R
temp<-c(10,12,14,15,17,20,22,23,25,26,28,29,30)
taxa<-c(2,4.5,6.1,7.0,11,16,19,21,22,11,2,0.1,0.001)
taxa<-taxa/9
plot(temp,taxa)
df<- data.frame(temp,taxa)
x<- seq(1,45,length=100)
library(nlsMicrobio)
preview(taxa~(exp(p*temp)-exp(p*TL-(TL-temp)/delta)+z),data=df, start=list (p=0.2, TL=30, delta=4.9,z=-0.5))
fit<- nls (taxa~exp(p*temp)-exp(p*TL-(TL-temp)/delta)+z,data=df,
                start=list (p=0.2, TL=30, delta=4.9,z=-0.5),control=nls.control(maxiter = 1000))
summary(fit)

Ao executar fit está ocorrendo o seguinte erro:
Error in nls(taxa ~ exp(p * temp) - exp(p * TL - (TL - temp)/delta) +  :
  fator de passos 0.000488281 reduzido abaixo de 'minFactor' de 0.000976562

Alguém poderia me auxiliar com esse errro? Obrigado.
Answer: A função nls é utilizada para fazer uma regressão não-linear. Ela utiliza processos iterativos para obter as estimativas dos parâmetros do teu modelo. Em teoria estes processos iterativos vão pouco a pouco se aproximando do valor real do parâmetro da função que melhor se ajusta aos teus dados.
O problema com regressões não-lineares é que elas podem, em casos extremos, não ter solução. Isto é, pode ser que o algoritmo que esteja procurando as estimativas para os parâmetros do teu modelo não convirja nunca, principalmente se o modelo a ser ajustado aos dados estiver mal especificado. Para evitar isto, é necessário informar critérios de parada para o algoritmo. O teu código tem um deles, chamado maxiter = 1000. Ele quer dizer que, se a função nls não convergir em 1.000 iterações, o algoritmo deve parar.
O erro ocorrido no teu exemplo remete a outro critério de parada, chamado minFactor. Ele diz quão pequeno é o passo utilizado para atingir a convergência dos parâmetros (mais informações neste link). Por padrão, a função nls utiliza um passo igual a 1/1024 (ou seja, (1/2)^10).
Assim, basta brincar com os valores de maxiter e minFactor, dentro de nls.control, para fazer com que o teu algoritmo convirja. Veja abaixo a minha sugestão:
fit <- nls (taxa~exp(p*temp)-exp(p*TL-(TL-temp)/delta)+z,data=df,
  start=list (p=0.2, TL=30, delta=4.9,z=-0.5),
  control=nls.control(maxiter = 10000, minFactor=(1/2)^30))

summary(fit)

Formula: taxa ~ exp(p * temp) - exp(p * TL - (TL - temp)/delta) + z

Parameters:
      Estimate Std. Error t value Pr(>|t|)
p      0.09981    0.51807   0.193 0.851505
TL    31.04889    5.73290   5.416 0.000424 ***
delta  6.33825   18.63529   0.340 0.741569
z     -1.73670    7.20604  -0.241 0.814952
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.4274 on 9 degrees of freedom

Number of iterations to convergence: 1057
Achieved convergence tolerance: 9.783e-06

Eu diminuí o minFactorpara (1/2)^30 e aumentei o número máximo de iterações para 10.000. Perceba que o algoritmo precisou de 1057 iterações para convergir, mais do que as 1.000 definidas originalmente.
Note, inclusive, que visualmente o ajuste ficou bastante razoável. Perceba como a curva predita se aproxima muito bem dos dados originais:
plot(temp, taxa)
lines(temp, predict(fit, temp))

Comment: Considere aceitar a [resposta](https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta) já que ela foi útil para você resolver o seu problema.
Comment: Sua sugestões me auxiliaram e muito. Problema resolvido. Obrigado.

Valores iniciais na função nls no R


Chord A7 in piano

Question: I attach a picture with an A7 chord in piano splitted as shown un the picture. Now I know the regular A7 chord is A,C#,E,G. Why was splitted like that in picture (using in treble cleff B,C# and F and in bass cleff A,G)?
Here is the picture:
https://ibb.co/enEmzK
Thank you
Comment: Because someone is clueless?
Comment: The key sig. is so important in questions such as this. It could be anything, # or b.
Answer: Perhaps the person who chose the chord symbols didn't trouble to choose, for each moment, a symbol that would account for every note sounding at that moment. (Perhaps they might think that doing that would be over-analysing the music.) The little snippet of sheet music fails to show the all-important clefs and key signature. If we suppose that the upper chord is in the treble clef and the key signature has F#, then we have a dominant chord of D major (thus A), with added notes G, B and F#. "A7" accounts for the G. You could go further and say A9 to account for the B or A13 to account for the F#, but A7 is OK at indicating the chord's function as dominant of D major. Alternatively, if the key signature is blank, then the above applies, except that the chord has F, which is the minor 13th, suggesting the dominant of D minor. A7 is still OK as far as it goes.
Comment: We've been told it's F nat.
Answer: Yes, if you've told us the right notes (clefs and key signatures help a lot!)  it's actually A9(b13).
I wonder which came first, the chord symbol or the notes?  It's quite likely that  seeing 'A7' I'd feel justified in playing that.  In some musical contexts, anyway!
Alternatively, it's not unusual for a simplified set of chords to be printed to music that might be played by either a piano or an elementary guitar strummer, who might be scared off by  'A9(b13)'. Let's just hope they don't both try to play it at once, reading their notation literally!

Chord A7 in piano


How to specify — as an attribute value in JSF?

Question: When I tried the next code:
<o:weekSwitcher splitter="—"/>

I received error "unresolved entity reference mdash". How can I work around this issue?
Comment: Note that this is a XML error, not a JSF error. In other words, you're using Facelets and its parser is choking on a plain HTML entity. You need a XML entity instead, see McDowell. A HTML entity would have worked in JSP.
Comment: @BalusC: I'm trying to make work CDATA section but not very successfully yet. Do you have an example with CDATA?
Comment: @BalusC: ok, but what if I've got 10 lines of html which I want to past as an attribute value? using multiple < > is not very convenient..
Comment: If it's static, do it once and forget it. If it's dynamic, make it a bean property and escape XML entities using Java.
Answer: Try the Unicode character entity —


AWS set s3 bucket directory access with policy

Question: I'm trying to create a policy on AWS that allows access to specific folders in an s3 bucket. According to the documentation this can be done with the following policy
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowUserToSeeBucketListInTheConsole",
            "Action": [
                "s3:ListAllMyBuckets",
                "s3:GetBucketLocation"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::*"
            ]
        },
        {
            "Sid": "AllowRootAndHomeListingOfCompanyBucket",
            "Action": [
                "s3:ListBucket"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::my-policy-test"
            ],
            "Condition": {
                "StringEquals": {
                    "s3:prefix": [
                        "",
                        "home/",
                        "home/test-folder1"
                    ],
                    "s3:delimiter": [
                        "/"
                    ]
                }
            }
        },
        {
            "Sid": "AllowListingOfUserFolder",
            "Action": [
                "s3:ListBucket"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::my-policy-test"
            ],
            "Condition": {
                "StringLike": {
                    "s3:prefix": [
                        "home/test-folder1/*"
                    ]
                }
            }
        },
        {
            "Sid": "AllowAllS3ActionsInUserFolder",
            "Effect": "Allow",
            "Action": [
                "s3:*"
            ],
            "Resource": [
                "arn:aws:s3:::my-policy-test/home/test-folder1/*"
            ]
        }
    ]
}

I created a user to check if this policy works as intended, but unfortunately it doesn't. When I log in with the test user I am able to see the folders in the bucket, but I can't access the one that I want called "test-folder1".
Question: How do I change this policy so that allows access to test-folder1?
Answer: Do you have a home folder in your S3 bucket? You're referring to the home folder in your policy, but you don't mention it in your test with a test user.
Looking at the policy, I would expect the following S3 structure:
arn:aws:s3:::my-policy-test
- home
- home/test-folder1 (should have the rights here)
- other_folder

This should work given your policy.


Create a public profile page for specific roles only

Question: Here is what I am trying to do.
I used profile2 to create an employee profile type that only users with the user role of employee could fill out.
What I want to do with views ( which I am not even sure if its possible) is have views create a profile page for each employee with a path of about-us/[user:full-name] (a field I created for the employee profile) and only create it for employee user.
Any help would be appreciated, thanks.
Comment: You can achive it by create a new permission (employee profile type) using hook_permission(https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_permission/7). After creating the permisssion go to admin/people/permissions and give the permission "employee profile type" to the employee role. After creating the VIEWS, go to your VIEW + PAGE SETTINGS + Click Access and then click permission and select the the created permission "employee profile type".
Comment: Given the [comment posted for an answer](https://drupal.stackexchange.com/questions/72081/create-public-profile-page-for-specific-roles-only#comment79030_72098), and the fact there isn't any explicit question, this question is too broad. (_I know I will have to use view blocks and then state that the blocks should only appear on pages with the path about-us/*_.) It's not just a matter of creating a profile page for employee users, but also giving to the profile page a path alias, and associate blocks to the profile page.
Comment: Notice that for a profile page, you don't need any block, or a path alias. The Profile2 module allows to create profile pages that are used only for specific roles.
Answer: It seems that what you are looking for is to modify the URL structure. In my mind, View is for the layout. Since I assume you have a content type for Profile2 profiles, you can simply install PathAuto and configure it so your URLs have that structure.
Answer: You could easily do that with views too.. I think you will need to use argument handling in views.
But only issue is the query argument should have more qualifying filter like drupal user id or employee id (if you are maintaining them).
This could go along with users full name field to make your url about-us/[user:fullname]/[user:uniqueid]
Let me know if you need more details.
Comment: I think I need more details... let me explain exactly what I am looking for and where my confusions lay.   Have a very unique design in mind for the employee profile pages.  I know I will have to use view blocks and then state that the blocks should only appear on pages with the path about-us/* what I am not sure on is what filters or relationships do I need in the views to make the proper information fill in and if for the view page will threat of about-us/[user:full-name] create pages for all employees?


Rebuilding Nginx with Extra Modules Using PPA

Question: I am trying to install the RTMP module on Ubuntu 16.04.4 LTS. Here is what I've done...
add-apt-repository -y ppa:nginx/stable
vim /etc/apt/sources.list.d/nginx-ubuntu-stable-xenial.list
# Uncomment deb-src http://ppa.launchpad.net/nginx/stable/ubuntu xenial main
apt-get update

apt-get install dpkg-dev

mkdir /usr/src/nginx && cd /usr/src/nginx
apt-get source nginx
git clone https://github/arut/nginx-rtmp-module.git

cd nginx-1.12.2
vim debian/rules
# Added --add-module=/usr/src/nginx/nginx-rtmp-module to the full install flags

apt-get build-dep nginx
dpkg-buildpackage -b
cd ../
dpkg --install nginx-common_1.12.2-0+xenial0_all.deb nginx-full_1.12.2-0+xenial0_amd64.deb

However, when trying to run the install command I get the following error...
(Reading database ... 100580 files and directories currently installed.)
Preparing to unpack nginx-common_1.12.2-0+xenial0_all.deb ...
Unpacking nginx-common (1.12.2-0+xenial0) over (1.12.2-0+xenial0) ...
Preparing to unpack nginx-full_1.12.2-0+xenial0_amd64.deb ...
Unpacking nginx-full (1.12.2-0+xenial0) over (1.12.2-0+xenial0) ...
Setting up nginx-common (1.12.2-0+xenial0) ...
dpkg: dependency problems prevent configuration of nginx-full:
 nginx-full depends on libnginx-mod-http-auth-pam (= 1.12.2-0+xenial0); however:
  Package libnginx-mod-http-auth-pam is not installed.
 nginx-full depends on libnginx-mod-http-dav-ext (= 1.12.2-0+xenial0); however:
  Package libnginx-mod-http-dav-ext is not installed.
 nginx-full depends on libnginx-mod-http-echo (= 1.12.2-0+xenial0); however:
  Package libnginx-mod-http-echo is not installed.
 nginx-full depends on libnginx-mod-http-geoip (= 1.12.2-0+xenial0); however:
  Package libnginx-mod-http-geoip is not installed.
 nginx-full depends on libnginx-mod-http-image-filter (= 1.12.2-0+xenial0); however:
  Package libnginx-mod-http-image-filter is not installed.
 nginx-full depends on libnginx-mod-http-subs-filter (= 1.12.2-0+xenial0); however:
  Package libnginx-mod-http-subs-filter is not installed.
 nginx-full depends on libnginx-mod-http-upstream-fair (= 1.12.2-0+xenial0); however:
  Package libnginx-mod-http-upstream-fair is not installed.
 nginx
dpkg: error processing package nginx-full (--install):
 dependency problems - leaving unconfigured
Processing triggers for systemd (229-4ubuntu21.2) ...
Processing triggers for ureadahead (0.100.0-19) ...
Processing triggers for ufw (0.35-0ubuntu2) ...
Processing triggers for man-db (2.7.5-1) ...
Errors were encountered while processing:
 nginx-full

Comment: Sorry, forgot that part... updated the question to include it, @anx
Answer: This is whats supposed to happen if you use packages from the artful (17.10) release. The Packages from the /usr/lib/nginx/modules/*.so modules were split out, so you could install them one by one. This has the nice side-effect that you will have a higher degree of freedom choosing what to recompile and install.
Two options:

Use your Ubuntu versions supported version of nginx (remove the PPA version and follow the instructions of the module author as you did, in that version the modules should be all inside the nginx-full package)
Use a newer nginx package, but do install its the split-out dependencies aswell (add them to you dpkg -i commands - you probably already produced the required packages - check the folder containing nginx-common_1.12*.deb)
Comment: How do I get the sources for Option 1 to add the module to? I'd prefer that method as it sets everything up nicely with sites-available/sites-enabled anyway.
Comment: I ended up using `dpkg --install libnginx-mod-* nginx-common_*_all.deb nginx-full_*_amd64.deb` and it worked well for me. Thanks :)


How many 5-man starting line-ups are possible?

Question:
In an alternate universe, LA Lakers decided to gather the 5 best guards and 10 best forward/centers in their history. One of the guards is Kobe, and one of the forward/centers is Shaq. How many 5-man starting lineups are possible consists of 2 guards and 3 forward/centers if Kobe and Shaq refuse to be starters at the same time?

Why is $504$ wrong?
I solved both of them using: $\dfrac{n!}{r!(n - r)!}$
And got $6 × 84 = 504$
I $n - 1$ both of them due to the condition of the problem. Is there something wrong with my solution which makes $504$ wrong?
Comment: You seem to have done ${4 \choose 2}{9 \choose 3}$ which is the number if neither Kobe nor Shaq start.  But what happens if one of them starts?
Comment: You have to find the number of line-ups where neither is included plus the number of line-ups where only one of the two is included (since they refuse to play together). It might be easier to find the total number of line-ups with no restrictions and then subtract the number of line-ups where both are included.
Comment: Do I have to find the permutation where they are both included? Sorry I am very confuse
Comment: I got 504 + 840 +  720, is this right?
Answer: You should find the number of all line-ups and then subtract the number of those where both of them are starters at the same time: $$C_5^2 \cdot C_{10}^3-C_4^1\cdot C_9^2=1200-144=1056$$  Where $C_n^k=\frac{n!}{k!\cdot(n-k)!}$
Comment: They said that 2256 is incorrect,  I am so confuse
Comment: What is the source of this problem?
Comment: It was just a problem given by our teacher,  I am really confuse and he won't give any guide on how to solve this
Comment: I think your calculations are wrong, shuold it be 1200 instead of 2400?
Comment: @XX Oh yeah, you're right. Is it correct now?


Changing  background color on button click

Question: On a button click I am creating a draggable div with the help of jquery ui. Each div created has text appended from a textarea input field. The text is placed in bulleted list tags. I am running into this problem: I want to set the background color dynamically for everything inside the
 tag. I am using SPECTRUM as the color picker. On the button click instead of changing the
 tag background it changes the whole div. How can I only change the
 background and not the div? JSFIDDLE
$('#button').click(function (e) {
    $('
', {
        class: 'draggable ui-widget-content',
        text: $('textarea').val(),
        html:  '
'+
                '
'+
                ''+
                ''+
                '
'+$('textarea').val()+'
'+
                '
',
        appendTo: '.middle-side',
        draggable: {
            containment: 'parent'
        }
    })
    .css('background-color' , color)
    .addClass('placement');
});

Comment: You can use any of the answers, but are you sure you want to put the textarea value inside 2 closing `` tags?
Comment: @TomSarduy good call will change that. Thanks
Comment: I'm sure you're looking for something like this:
`html:'' +$('textarea').val()+ ''`
Answer: You can use like this:
$('#button').click(function (e) {
    $('
', {
        class: 'draggable ui-widget-content',
        text: $('textarea').val(),
        html:  '
'+
                '
'+
                ''+
                ''+
                '
'+$('textarea').val()+'
'+
                '
',
        appendTo: '.middle-side',
        draggable: {
            containment: 'parent'
        }
    })
    .find('ul') //find ul then apply css
        .css('background-color' , color)
        .end() // to go back to select the previous div and apply addClass
    .addClass('placement');
});

Comment: **`+1`** I love the `end` method ;)
Answer: Add a style attribute to the ul element, and remove .css('background-color' , color). Updated Fiddle.
$('#button').click(function (e) {
    $('
', {
        class: 'draggable ui-widget-content',
        text: $('textarea').val(),
        html:  '
'+
                '
'+
                ''+
                ''+
                '
'+$('textarea').val()+'
'+
                '
',
        appendTo: '.middle-side',
        draggable: {
            containment: 'parent'
        }
    })
    .addClass('placement');
});

Answer: You should apply background-color to your ul, not the whole div:
$('#button').click(function (e) {
    $('
', {
        class: 'draggable ui-widget-content',
        text: $('textarea').val(),
        html:  '
'+
                '
'+
                ''+
                ''+
                '
'+$('textarea').val()+'
'+
                '
',
        appendTo: '.middle-side',
        draggable: {
            containment: 'parent'
        }
    })
    .addClass('placement')
    .find('ul').css('background-color' , color);
});

jsFiddle Demo.


Closure of a set under a certain operation

Question: How can I prove that the set $A=\left\{x\in \mathbb{R}\mid x>0\right\}$ is closed under the operation $\oplus$ defined by $x\oplus y=\frac{1}{x}+\frac{1}{y}$? Thanks in advance.
Comment: Firstly, do you know the definition of closure?
Comment: Is $\frac{1}{x}+\frac{1}{y}>0$ if $x,y>0$?
Comment: Mathematician 42: yes, x,y > 0
Comment: That doesn't answer my question.
Answer: We want to show $A$ is closed under $\oplus$.
That is for all $x,y \in A$ we have $(x \oplus y)\in A$.
So let us take arbitrary $x,y \in A$ since $x,y \in A$ then we have $x,y \in \mathbb{R}$ and $x,y >0$.
Because of this we have $\frac{1}{x}, \frac{1}{y} >0$ and of course they are real.
Thus we must have that $x \oplus y= \frac{1}{x}+\frac{1}{y} > 0$ and is real so $(x \oplus y) \in A$ as required.


Equivalent to produce field glow in other browsers?

Question: I was long using this to add a glow to focused fields, I accessed my page from Firefox for the first time and realized it doesn't work on it, and most likely not on explorer either.
<code>border: 1px solid #E68D29;
outline-color: -webkit-focus-ring-color;
outline-offset: -2px;
outline-style: auto;
outline-width: 5px;
</code>
I had copy pasted it from another page so I'm not quite sure how it works. What is the equivalent for Firefox or Explorer? I mean how do I make a similar glow in other browsers? Thanks
Comment: http://stackoverflow.com/questions/3798919/how-to-simulate-chrome-safari-border-around-active-input-or-textarea-on-other-ele
Answer: Webkit treats "outline-style: auto;" differently than other browsers. If you want to get behavior that's more similar across browsers I'd recommend you use box-shadow instead. It won't apply to older browsers (IE8 and earlier, or FF3.0 and earlier) but otherwise should be the same.
Using this code
<code>  input {
    border: 1px solid #E68D29;
  }
  input.focus {
    border-color: #439ADC;
    box-shadow: 0 0 5px #439ADC; /* IE9, Chrome 10+, FF4.0+, Opera 10.9+ */
    -webkit-box-shadow: 0 0 5px #439ADC; /* Saf3.0+, Chrome */
    -moz-box-shadow: 0 0 5px #439ADC; /* FF3.5+ */
  }
</code>
I was able to produce a result that shows cross-browser glow in IE9+, FF4+, Chrome 10+, and Safari 5+.
Option 2) You could experiment with using some combination of outline (which will show in Webkit) and box-shadow (for other browsers).
Option 3) Use a library like Formalize CSS to take care of the cross-platform input styling for you. The results are pretty impressive.


SQL query in one table in 2 columns

Question: I have for example this database table:
CREATE TABLE IF NOT EXISTS `docs`
(
    `refid` int(6) unsigned NOT NULL,
    `myrefid` int(3) unsigned NOT NULL,
    `user` varchar(200) NOT NULL,
    PRIMARY KEY (`refid`,`myrefid`)
) DEFAULT CHARSET=utf8;

INSERT INTO `docs` (`refid`, `myrefid`, `user`)
VALUES ('1', '5', 'user1'),
       ('2', '1', 'user2'),
       ('9', '3', 'user3'),
       ('8', '3', 'user4');
       ('4', '3', 'user5');
       ('4', '8', 'user6');

I want to write a query where I get user2 and user6 because from user2 is the myrefid (value) same like from user1 refid (value) and from user6 is the myrefid (value) same like from user4 refid (value)
How can I write this query ?
Answer: You can use EXISTS and check you condition

SELECT
    `user`
FROM `docs` d WHERE EXISTS ( SELECT 1 FROM `docs` WHERE `refid` = d.`myrefid`)

| user  |
| :---- |
| user2 |
| user6 |

db<>fiddle here

SQL query in one table in 2 columns


How To Center Child Divs In Flex Parent Div?

Question: I have an html page called presets page. This page contains different (child) divs and I am having a hard time on how I could center all these divs within the container (parent) div. These preset divs are currently in flexbox. Apologies if this question has been answered already, I really suck in centering elements in html/css.
It currently looks like this.
And I want it to look somewhat like this.
I tried using justify-content: center but how can I make the last line align to the left/right to look like this?
Here is the HTML:

  {% for presets in presets_list %}

{{ presets.preset_name|hide_preset_suffix }}

LOAD

DELETE

{% endfor %}

Here is the CSS for the presets container:
.presets-container{
  background-color: pink;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

Comment: To center horizontally `justify-content: center` and vertically `align-items: center`, Default value for `flex-direction` is `row` so you don't need to specify
Comment: please add your code to question
Comment: Hello, After seeing your screenshot your requirement is to add equal margins around the content so use `justify-content: space-around`
Answer: Add justify-content: center and align-items: center to the parent div
.presets-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  background-color: pink;
  justify-content: center;
}

Answer: You can use justify-content: center
Comment: How do I make the last line align to the left and not make it center? Check last edit :)
Comment: Unfortunately that's an unsolved problem ;-) , i.e. not easily possible. You'd have to use a container within the container which is only wide enough for the three columns and which you center inside its parent (using the default `justify-content: flex-start`) inside it - usually rather too complicated...
Answer: Just add a div under presets-container and then use justify-content: center in presets-container


Expectation of an average (law of large numbers)

Question: Let $X$ be some random variable; we will take different measurements of this same variable $(X_1, X_2, ... X_N)$; distribution of each random variable then is identical, but variables are not independent; I am now trying to show that:
$$\mathbb{V}[\bar{X}] = \frac{1}{N^2}\sum_{n,m=1}^N Cov (X_n,X_m)$$
The above is the result from the book, whereas I have:
$$\mathbb{E}[\bar{X}^2]-\mathbb{E}[\bar{X}]^2 = \frac{1}{N^2} \left[ \mathbb{E}\left[ \sum_{i=1}^N X_i^2 \right] +2\mathbb{E}\left[ \sum_{i=1}^{N-1} \sum_{i<m} X_i X_m \right] - \mathbb{E} \left[\sum_{i=1}^N X_i\right]^2 \right]$$
Answer: Note that
$$\mbox{Var}[\overline{X}] = \frac{1}{N^2} \mbox{Var}\left[\sum_{i=1}^{N} X_i \right] = \frac{1}{N^2} \mbox{Cov}\left(\sum_{i=1}^{N} X_i, \sum_{j=1}^{N} X_j\right).$$
Comment: Yeap. It is the variance with itself...
Comment: I mean covariance
Comment: Yes, applying some basic rules from the covariance (covariance of a sum = sum of covariances) you immediately obtain the desired result.


Views Contextual filter for matching taxonomy names

Question: I have a view of content type slideshow items. Each item has a taxonomy term fromslideshow_category vocabulary. I also have another content type: articles, which has it's own taxonomy article_categories.
I'd like to create a view that will match the names of those taxonomies and display the slideshow items accordingly.
For example on articles taxonomy page news the only slideshow items displayed are those which marked news .
What I'm doing right now:
I have created a contextual filter on the slideshow items view
When is NOT available

Content: field_slideshow_category
Provide Default value > Raw value from URL
Path component > 2
Use Path alias > checked

When IS available

Specify validation criteria > checked
Selected the slideshow_category
Filter value type > Term name converted to Term ID

PROBLEM
This works fine on page like /articles/news/ (using my previous example ), but obviously because I pass RAW value this view also appear on /articles/news/news-item (which is the actual article page). What I need is for this view to show up only on taxonomy pages. Is there a way to limit "Raw value"? should I be using a different "Provide Default value" ?
Thanks in advance :)
Answer: Yes try different "Provide default value" for this case "Taxonomy term ID from URL"
When it's available specify "Taxonomy name converted to ID"
Comment: Thank you, I just tried that, but this isn't working. Now the view doesn't display items on any pages, taxonomy or not. Weird...


AVAssetExport setting a constant frame rate

Question: I am using AVAssetExport to export a composition of asset tracks. But the problem is I can't get the Frame rate mode to be constant, the meta data for the video being exported is as follows:
Video
ID : 1
Format : AVC
Format/Info : Advanced Video Codec
Format profile : firstname.lastname@example.com
Format settings, CABAC : Yes
Format settings, ReFrames : 2 frames
Codec ID : avc1
Codec ID/Info : Advanced Video Coding
Duration : 3s 502ms
Bit rate : 684 Kbps
Width : 480 pixels
Height : 480 pixels
Display aspect ratio : 1.000
Frame rate mode : Variable
Frame rate : 30.000 fps
Minimum frame rate : 28.571 fps
Maximum frame rate : 30.000 fps
Color space : YUV
Chroma subsampling : 4:2:0
Bit depth : 8 bits
Scan type : Progressive
Bits/(Pixel*Frame) : 0.099
Stream size : 292 KiB (90%)
Title : Core Media Video
Encoded date : UTC 2013-11-22 00:27:28
Tagged date : UTC 2013-11-22 00:27:32
Color primaries : BT.709
Transfer characteristics : BT.709
Matrix coefficients : BT.601
My code being used for the export is as follows:
<code>AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetPassthrough];
session.outputURL = [NSURL fileURLWithPath:finalVideoPath];
session.outputFileType = AVFileTypeMPEG4;
[session exportAsynchronouslyWithCompletionHandler:^{
    switch ([session status]) {
        case AVAssetExportSessionStatusFailed:
            LogError(@"Export failed: %@", [session error]);
            break;
        case AVAssetExportSessionStatusCancelled:
            Log(@"Export canceled");
            break;
        case AVAssetExportSessionStatusCompleted:
            Log(@"Export successfully");
            break;
        default:
            Log(@"Export session status unknown");
            break;
    }
}];
</code>
Answer: This means the asset being export has frame durations which are not constant. If the frames all have exactly the same duration, then you'll see the "Frame rate mode" reported as "Constant".


Exportar um dicionário para arquivo .txt

Question: Olá.
Eu gostaria de saber como eu faço pra exportar um dicinário para um arquivo .txt.
e como importar os dados que estão no arquivo.txt para o dicionário, no programa. Quando eu importo, o dicionário fica todo bugado, como eu importo corretamente?
Answer: Se você está trabalhando somente com os tipos de dados padrão da linguagem, isto é, "int", "float", "str" e "bool" você pode exportar e importar o dicionário como um arquivo JSON:
<code>#!/usr/bin/env python
from __future__ import print_function
import json

dicionario = {
    'nome': 'Fulano de Tal',
    'idade': 30,
    'saldo': 520.37,
    'online': True,
}

open('dicionario.json','w').write(json.dumps(dicionario))

with open('dicionario.json', 'r') as file_json:
    dicionario_2 = json.loads(file_json.read())

print(dicionario_2)
</code>
Porém, se você tem outros tipos de dados você pode usar o pickle.
<code>#!/usr/bin/env python
from __future__ import print_function
import pickle
from datetime import datetime

dicionario = {
    'nome': 'Fulano de Tal',
    'online': False,
    'ultimo_login': datetime.now()
}

open('dicionario.pickle','w').write(pickle.dumps(dicionario))

with open('dicionario.pickle', 'r') as file_pickle:
    dicionario_2 = pickle.loads(file_pickle.read())

print(dicionario_2)
</code>
Comment: Tu também podes usar sem o read(), json.load(file_json), também quando escreves no ficheiro. https://docs.python.org/3.3/tutorial/inputoutput.html#saving-structured-data-with-json, https://docs.python.org/3/library/json.html#json.load


Integration Limits on Functions of Two Random Variables

Question: I am working on the following problem and am struggling with how to come up with the particular limits of integration. I've done some maths voodoo to get part of the same argument as the solution, but I cannot explain why it works or defend that it is correct. I've always had problems with constraints.

Suppose that $X_1$ and $X_2$ are iid random variables and that each
  has a uniform distribution on the interval $[0,1]$. Find the p.d.f. of
  $Y = X_1 + X_2$.

I let $Z = X_1 \implies X_1 = Z$ and thus $X_2 = Y - Z$. To the the PDF of $Y$, I then use the following form an integrate out $Z$ since I want a function of $Y$.
\begin{align}
\int_{-\infty}^\infty f(z, y - z) \,dz &= \int_{-\infty}^\infty f(z) f(y-z)\,dz \\
&= \int_{-\infty}^\infty\,dz
\end{align}
Since $X_1$ and $X_2$ are both from $U[0,1$, I know that
(1) $0 \lt x_1 \lt 1$
(2) $0 \lt x_2 \lt 1$ and thus,
(3) $0 \lt z \lt 1$ and
(4) $0 \lt y \lt 2$.
This is where I get stuck. I can assume based by subtracting (3) from (4) that
(5) $0 \lt y - z \lt 1$.

The solution says I need to consider two cases: one where $0 \lt y \le 1$ and the other $1 \lt y \lt 2$. First off, I don't understand why.
(1) For $0 \lt y \le 1$, I surmise the integrand is positive if $0 < z < y$ by taking (5) and adding $z$ to both sides of the equation and applying the lower bound from (3). Is this legal?
(2) For $1 \lt y \le 2$, the solution says that the integrand is positive if $y - 1 < z < 1$. I don't know where this comes from.
I need help applying these constraints to get the limits of integration for the two cases.
Comment: What is the purpose of downvoting this question. Do you just not like it?
Answer: The density of a Uniform $\cal{U}(0,1)$ is not one (1), it is
$$f(x)=\mathbb{I}_{(0,1)}(x)$$
Therefore,
$$f(z)f(x-z)=\mathbb{I}_{(0,1)}(z)\mathbb{I}_{(0,1)}(x-z)=\mathbb{I}_{(0,1)}(z)\mathbb{I}_{(1-x,x)}(z)=\mathbb{I}_{(0\vee x-1,1\wedge x)}(z)$$
which is also $$\mathbb{I}_{(0,x)}(z)$$when $0\le x\le 1$. And $$\mathbb{I}_{(x-1,1)}(z)$$when $1\le x\le 2$. This leads to
$$\int f(z)f(x-z)\text{d}z=\begin{cases}\displaystyle\int_{0}^x \text{d}z=x&\text{ when }0\le x\le 1\\
\displaystyle\int_{x-1}^1 \text{d}z=2-x&\text{ when }1\le x\le 2\\
\end{cases}$$


Use of MaxDegreeOfParallelism in TPL

Question: We are implementing TPL (C#) in one of our applications where we are uploading files to server in parallel. When we try to upload 15 files in parallel with MaxdegreeOfParallism set to 4 only 12 files are uploaded and three files are not uploaded. We changed the MaxDegreeOfParallelism to 2 then 14 files are uploaded. I am not sure how does MaxDegreeOfParallelism work. Could any one clarify the use of MaxDegreeOfParallelism and what could be the reason of non processing the files.
My code
<code>Parallel.ForEach(fileCollection,new ParallelOptions{ MaxDegreeOfParallelism = 2 },
            number => { fileNumber = UploadFile(file, response); });
</code>
Upload function will upload files to AmazonS3.
When we upload the files with MaxDegreeOfParallelism =1 then all files are uploaded properly whereas when we change the MaxDegreeOfParallelism to 2 only 14 files got uploaded out of 15 and if we change to 4 only 12 files got uploaded.
My Development system is quad core window 10.
Comment: It would be awesome if you could share a [mcve].
Comment: Possible duplicate of [What does MaxDegreeOfParallelism do?](https://stackoverflow.com/questions/9538452/what-does-maxdegreeofparallelism-do)
Answer: Hard to know what you need help with unless you provide some code to put it in context, but in general, the MaxDegreeOfParallelism is summed up on the MSDN documentation.
My understanding is that it is used to limit the number of concurrent Tasks to something less than the default, which is the number of available threads.  That may not necessarily correspond to the number of Web Requests which I presume is what you're concerned with if you're looking at file uploads.
https://msdn.microsoft.com/en-us/library/system.threading.tasks.paralleloptions.maxdegreeofparallelism(v=vs.110).aspx

The MaxDegreeOfParallelism property affects the number of concurrent
  operations run by Parallel method calls that are passed this
  ParallelOptions instance. A positive property value limits the number
  of concurrent operations to the set value. If it is -1, there is no
  limit on the number of concurrently running operations.
By default, For and ForEach will utilize however many threads the
  underlying scheduler provides, so changing MaxDegreeOfParallelism from
  the default only limits how many concurrent tasks will be used.

Use of MaxDegreeOfParallelism in TPL


Two $C^\infty$ functions which agree on a set containing an accumulation point, but do not agree on *any* neighborhood?

Question: As I understand it, two analytic functions defined on $\mathbb{R}^k$ which agree on a set with an accumulation point must agree on a neighborhood; however, the same is not true of $C^\infty$ functions. What is an example of two $C^\infty$ functions which agree on a set containing an accumulation point, but do not agree on any neighborhood?
(The functions $f\equiv 0$ and $g(x) = \begin{cases} 0 &\text{ if $x\leq0$}\\ e^{\frac{-1}{x}}&\text{ if $x > 0$}\end{cases}$ agree on a set which has zero as an accumulation point, but do not agree in a neighborhood of zero. However, they do agree on some open set.)
Comment: Consider $0$ and $e^{-1/x^2}\sin\dfrac1x$.
Comment: The two analytic functions agreeing on a set having an accumulation point only implies they agree on a neighbourhood of that point when $k = 1$. For $k > 1$, consider $f(x) = x_1$.
Answer: njguliyev's example: $0$ and $e^{-1/x^2} \sin\frac{1}{x}$ is probably the best that one can give. But I'll mention a somewhat related result (due to Whitney, I guess): for every closet subset $A\subset \mathbb R$ there is a $C^\infty$ function $f:\mathbb R\to\mathbb R$ such that $f^{-1}(0)=A$. For example, you can choose $A$ to be the Cantor set and get a  $C^\infty$ function that agrees with $0$ on the Cantor set and only there.


Adding extra info to each Node -> Taxonomy Term relationship

Question: We have a basic site with a pages that have a taxonomy term content type associated with a number of terms.
What we would like to is to add more information to each of the node -> taxonomy relationship.
For example, the details of the author that tagged the term(different authors can tag a term to a node), the date the particular tag was added and so on.
I have looked at the Entity API, the Relation module and various other solutions in between.
From what I can tell, Entity Reference along with the Entity API seems to be the simplest way forward.
While I am not loathe to get my hands dirty and start coding this out, my knowledge of how each of these things fit together is limited.
Can someone point me in the right direction and point out any potential pitfalls along the way with regards to getting this done?
Answer: Imho, the simpliest way to achieve associations of data with field value without coding is to use Field Collection.

Provides a field-collection field, to which any number of fields can be attached.
A field collection is internally represented as an entity, which is
embedded in the host entity. Thus, if desired field collections may be
viewed and edited separately too.

You will then be able to set, each time you tag one or more terms, additional informations in other fields of your field collection. Plus, you can have multiple field collections of the same type on your content.
Comment: I had looked at this as well. However in trying to use it, it seems to simply associate an x number of fields to a node. I didn't find a way to use this field to represent an existing entity for example..
Comment: You can also use it to add x number of fields to a field : imagine you add a field collection to your content type, which is "term association". In that field collection, you set a term reference field, and other fields that you need for additional info. Then you'll do your trick, don't you ?
Comment: IF that worked, I would need to select each term manually - right? instead of using the taxonomy widgets? It would not make it easy / possible to add additional information to the relationship automatically created by the taxonomy -> node relationship - it would be creating a new relationship with the additional info - correct?
Comment: Every term relationship widget will be available, with all optinos : several terms at once, etc.
Comment: I've just tried and it *almost* works. The one thing I don't seem to be able to do is let the term selection be multi-select and have a new field collection to be created for each selected term. If the additional fields within the collection can be automatically generated (without user input), is there a way to get a new field collection created for each term from a multi-select?
Comment: I don't see how you could do it _without_ coding a custom ajaxified field collection... :(


Strange results when applying Wilcoxon test in R

Question: I am interested in whether the mean of one sample is statistically greater than the mean of the other one. The samples are not independent in that if the ith observation in sample A is positive, than the ith observation in sample B is "-1" and vice versa.
To answer this question I used Wilcoxon test in r and performed the analysis for different samples. In each pair of samples I have larger mean for the first sample than for the second one. However, the test sometimes shows p-value of one, whereas the same test with alternative = "less" rejects the null hypothesis. I find this counterintuitive. Is there smth wrong?
The files to run the code are here:
http://www.filehosting.org/file/details/747619/doc1.csv
http://www.filehosting.org/file/details/747620/doc2.csv
http://www.filehosting.org/file/details/747621/doc3.csv
http://www.filehosting.org/file/details/747622/doc4.csv .
And the code is below:
aa <- read.csv("doc1.csv")
bb <- read.csv("doc2.csv")
cc <- read.csv("doc3.csv")
dd <- read.csv("doc4.csv")

aa1 <- aa[,2]
aa2 <- aa[,3]
bb1 <- bb[,2]
bb2 <- bb[,3]
cc1 <- cc[,2]
cc2 <- cc[,3]
dd1 <- dd[,2]
dd2 <- dd[,3]

mean(aa1)
mean(aa2)
mean(bb1)
mean(bb2)
mean(cc1)
mean(cc2)
mean(dd1)
mean(dd2)

wilcox.test(aa1,aa2, alternative = "greater", paired = TRUE)
wilcox.test(bb1,bb2, alternative = "greater", paired = TRUE)
wilcox.test(cc1,cc2, alternative = "greater", paired = TRUE)
wilcox.test(dd1,dd2, alternative = "greater", paired = TRUE)

wilcox.test(aa1,aa2, alternative = "l", paired = TRUE)
wilcox.test(bb1,bb2, alternative = "l", paired = TRUE)
wilcox.test(cc1,cc2, alternative = "l", paired = TRUE)
wilcox.test(dd1,dd2, alternative = "l", paired = TRUE)

Comment: I have no idea.  I can't imagine what you'd be trying to find out from such a data set, or how such a data set would come to be... I would reassess how this data is being generated: What does a negative 1 mean?  Could it be some other value?  Can you discard all negative 1's?
Comment: Given your condition: `The samples are not independent in that if the ith observation in sample A is positive, than the ith observation in sample B is "-1" and vice versa.`, I don't know how you would use a (paired) Wilcoxon test.  I suspect you would want to change the process that is arranging the data in this way...  Also, the Wilcoxon signed rank test may not be a test of means in your case.
Comment: Thank you very much for your answer! Which test would you then recommend for comparing the means in my case?
Comment: Thanks again! The data cannot be reassessed or modified. These numbers are simply the returns to betting strategies for two-outcomes games: in every game if one result happens, then you loose the bet from the other outcome (that's how -1's come into play) and the bet on the realized outcome delivers a positive value.
Comment: The way the data are arranged doesn't make any sense because you are using one variable to hold two types of data: if the bet was lost, and the return value (?).  You might want to look at these separately.  1) which stategy was more likely to win, and 2) which strategy had the higher return.
Comment: In these datasets I simulate two strategies: one is betting on favorites and the other one is betting on outsiders. The question is whether the mean returns of these two strategies are statistically different. The returns from the strategies are paired by games.
Comment: Does A represent only the return?  Or does it sometimes represent the return, and other times represent this flag, -1, which is not a return?
Comment: All the observations are always returns.
Comment: Okay. I think your data are clear to me now.  Essentially, the bet is always $1, so a loss is always -1, but a win can be different amounts, which are recorded as positive.
Comment: Exactly! In fact these numbers are relative returns, i.e. they are independent of the bet size (assuming the bet size is identical for two strategies). For example, -1 means the return of -100% (full loss of the invested capital) and 0.62 means the return of 62% on the invested amount (bet size). But you are right, the example with a bet of size 1 is just another way to understand the data.
Comment: What do you mean by "sometimes" in the post?
Answer: This is an interesting problem.  Probably someone will have a better solution, but I will keep with the paired Wilcoxon signed-rank test for now.  Edit: I don't really like using the Wilcoxon in this context. See ending comments.
I think the first thing to realize is that the Wilcoxon test isn't a test of means, so it's possible that the Wilcoxon test is calling the group with the lower mean, "larger".
With the distributions of data, I don't know if there is a test of means that will be satisfactory.
That being said, the mean is probably the best estimator of the expected return, so that may be what you want to go with in the end.
### Install the packages
if(!require(lattice)){install.packages("lattice")}

### Read in the data
aa <- read.csv("C:/Users/Salma/Desktop/doc1.csv")
aa1 <- aa[,2]
aa2 <- aa[,3]

### Make it a data frame for convenience
Return = c(aa1, aa2)
Strategy = c(rep("Strategy1", length(aa1)), rep("Strategy2", length(aa2)))
Data = data.frame(Strategy, Return)

Looking at the histograms of the data will give of some sense of what we're dealing with.
It's clear that Strategy2 has a higher percentage of losses (about 60%), but that when it wins, its winnings tend to be higher than those of Strategy1.
library(lattice)

histogram(~ Return | Strategy,
          data=Data,
          layout=c(1,2))

But the paired test doesn't look at these independent distributions.  What it does is take the difference between the two paired observations, and then see if these differences are statistically different from zero.
For intuition here, imagine balancing the histogram of differences on a fulcrum at zero.  Which way does it tip?  (But the test uses ranks at this point, so the white space may matter less to the test than in the plot.) The way I did the math, if it tips right (positive), that would mean aa2 (Strategy2) is "larger".
Difference = aa2 - aa1   #### Positive means aa2 is higher

hist(Difference, col="darkgray")

The Wilcoxon paired test comes out significant.  But with a large sample size, there aren't too many conclusions we can draw from the p-value.
(I'm also worried about how you would interpret the conclusion given the distribution here.  We can conclude that the ranks are not symmetric around zero, but how to explain why?...)
wilcox.test(aa1,aa2, paired = TRUE)

   ### Wilcoxon signed rank test with continuity correction
   ###
   ### V = 242560, p-value < 2.2e-16

In order to determine the direction of the weight of the ranks, probably the easiest way is to look at the median of the difference.  I'm not sure if this is fool-proof for this test.
median(Difference)

   ### [1] -1.5

This suggests that aa1 (Strategy1) is "larger".

Finally, how do we square this with using the alternative option in the function? I don't know.  It's not making sense to me.
Big   = c(5,6,7,8,9,10)
Small = c(1,3,2,4,3,5)

wilcox.test(Big,Small, alternative = "greater", paired = TRUE)

   ### Wilcoxon signed rank test with continuity correction
   ### V = 21, p-value = 0.01751
   ### alternative hypothesis: true location shift is greater than 0

wilcox.test(aa1,aa2, alternative = "greater", paired = TRUE)

   ### Wilcoxon signed rank test with continuity correction
   ### V = 242560, p-value = 1
   ### alternative hypothesis: true location shift is greater than 0

Overall, I'm not very happy with this approach.  I think if we're looking at expected return, we should be looking at the mean value.  The ranks based approach, I think, is too likely to discount rarer and higher returns.

Edit: I'll offer one other approach.
It might be possible to use a confidence interval for the mean of the differences, or alternatively for the mean of the returns for each strategy.
Here, I'll just get the 95% confidence intervals for the mean of the differences.  The mean of the differences is about -0.05, suggesting aa1 (Strategy1) is larger, the way I did the math above.  The confidence intervals for the mean of the difference contain zero, suggesting this mean is not statistically different from zero.  I'm not sure about this approach for data with a distribution as shown above.
if(!require(boot)){install.packages("boot")}

library(boot)

Mboot = boot(Difference,
             function(x,i) mean(x[i]),
             R=10000)

mean(Mboot$t[,1])

   ### [1] -0.04991604

hist(Mboot$t[,1], col="darkgray")

boot.ci(Mboot,
        conf = 0.95,
        type = c("norm", "basic" ,"perc", "bca")
        )

   ### Intervals :
   ### Level      Normal              Basic
   ### 95%   (-0.1605,  0.0631 )   (-0.1590,  0.0637 )
   ###
   ### Level     Percentile            BCa
   ### 95%   (-0.1623,  0.0604 )   (-0.1627,  0.0603 )

Comment: Thanks! Actually the functions I used claim to test paired-samples hypothesis for the difference between two population means and build confidence intervals. They also provide p-values. But, I am still a bit skeptical about the overall approach and its implementation.
Comment: Thanks a lot for your efforts! I posted this question quite a few days ago, so since then I also reconsidered the original idea of using Wilcoxon test. And, I also does not like it at all. In fact this is one of the ways I saw in academic literature, dealing with the problem of different returns from betting on favorites and outsiders, so called favorite-longshot bias. Another approach is to perform no statistical tests at all, but simply compare the actual means.
Comment: What I tried as a potentially better approach is bootstrapping using wBoot package in R. For example, with this functions:
boot.paired.bca(x, y, null.hyp = 0, alternative = "greater")
boot.paired.bca(x, y, null.hyp = 0)

boot.paired.per(x, y, null.hyp = 0, alternative = "greater", R = 100000)
boot.paired.per(x, y, null.hyp = 0)
However, I am not sure if this is the best approach.
Comment: No problem.  I'm really not sure what is a good approach here.  Interesting, tho.
 I added some to my answer using bootstrapped confidence intervals for the mean of the differences.  Maybe your functions do a similar thing in a more legitimate manner.


How to deal with DjangoCMS i18n URLs (/en/my_page, /fr/my_page...) and AngularJS?

Question: I'm trying to learn AngularJS and DjangoCMS so I created a new project using them together.
Status
By default, DjangoCMS uses the first URL segment to determine the language of the site (/en/, /fr/). Every URL that doesn't contain a language segment will get redirected to /en/ by default.
That means, all my AngularJS ajax calls need to be addressed to either /en/api/ or /fr/api/.
Questions

I'd like to use this first segment to determine the language in Angular for internationalization.
And also set that first segment globally to my AngularJS app so I don't need to specify it on each ajax call.

Probable Solution
One solution I found is to use a different template for each language on Django side.

The english template would have <base href="/en/"> in the  tag.
The french template would have <base href="/fr/"> in the  tag and I could either use a pre-bundled rule set or simply add the local script to the script list (https://docs.angularjs.org/guide/i18n).

I guess that would work for more languages too, but that means I have to create a specific template and code for each language.
Best solution ?
I think the best would be to have a logic defined in the Angular app to load the language script depending on the first url segment, and determine that first segment globally in the app. We would avoid having to code things for each language. Is that solution possible ? I searched on setting a base url dynamically on Angular, but I didn't find any interesting results.
I'm not sure that question should be on StackOverflow, but I don't really know about other stack exchange forums.
Thanks !
Answer: I would do something like this:

Load i18n template tags: {% load i18n %} And set <base href=""> like this:

{% get_current_language as LANGUAGE_CODE %}
<base href="/{{ LANGUAGE_CODE }}/" />

When You have base set like above, You can use $provide in to get href value and expose it to services and directives. For example:

angular.module("myapp.services", [])
    .config(["$provide", function ($provide) {
        $provide.value("base", $("base").attr("href"));
    }]);

And inject it to a service which makes ajax calls:

angular.module("myapp.services").factory("myService", ["base", function (base) {
    var uri = base + "api/some_url";
    ...

Comment: Thanks for the answer. Actually, when setting ``, that base is automatically set for every call the app will do. So there's no need to add it manually. Your solution is almost what I did to my app though, and that's working properly :)


are these repeated measures?

Question: I have a set of 30 patients. Each patient has a variable number of observations over a variable length of time(ranging from 4 to 10 data points per patient).
My outcome variable is whether they have gained or loss/stabilised their weight at any given point in time. I calculate this weight gain/loss by taking their weight on a given observation and compare it to the previous observation. Creating a dichotomous nominal Loss / Gained Weight variable.
I have a few continuous explanatory variables. some are normally distributed and others non-normal.
Can i treat my outcome variable as "independent observations" and use logistic regression modeling? Otherwise, is there any suggestion for which model to use?
Answer:
Yes, this is a repeated measures situation.

It would probably be better to model the weight directly and not the change between points. But even if the change is what you are interested in, you should definitely not just turn it into a binary gained/lost variable.

The distribution of your predictors is not relevant. The distribution of the model residuals is generally important.

Overall, this is not a lot of data to deal with the complexities you are after (30 patients, 4-10 time points, many predictors).

are these repeated measures?


inserting input filed as an arry and its value to table

Question: i am having a simple query that is creating trouble for me..
i need to insert my form containing basically 2 input field
<input type="text" name="slottiming[]" value="" ></input>
<input type="text" name="slottname[]" value=""></input>

.
.
.
..

Like the same i am creating 48 input fields (pairs) to store in 2 fields in my table
|id | Timing | Slotname
| 1 | 00:00  | 4
|   |        |

here is my controller ::
$slotname=$this->input->post('slotname');
        $slot=$this->input->post('slot');

            print_r($slotname);

        foreach($slotname as $key =>$slot)
        {
                $form_data=array(
                'slottime'=>$slotname,
                'seat' =>$key,
                'assocviva' => 'Cycle1'
                );
            $this->load->model('modelquery');
            $this->modelquery->common_add($table_name,$form_data);

        }

how to write the correct query to insert into common_add method as $form_data parameter arry with field
Answer: are you looking for the following answer?
function common_add($table_name, $form_data)
{
 $this->db->insert($table_name, $form_data);
}
have a look at the database inserting documentation in http://ellislab.com/codeigniter/user-guide/database/active_record.html
Hope it is helpful
Answer: If I'm understanding correctly, $slotname is the array you want to store?
One quick fix would be to serialize the array before you insert it to the DB and unserialize when you retrieve it from the DB.
$form_data=array(
    'slottime' => serialize($slotname),
    'seat' => $key,
    'assocviva' => 'Cycle1'
);

Then when you get it from the DB
$slotname = unserialize($row->slotname);

Comment: firstly thanks for the intrest, but i need to add without serializing. so that changes can be made from backend if needed..
Comment: Then I would recommend storing the items from the array in a separate table, with a field to reference which entry in the main table they belong to. Or make all 48 fields in the main table.
Answer: I wouldn't use a foreach here. Since they are pairs, you should use a for loop to sincronize the same result.
$this->load->model('modelquery');
$slotname = $this->input->post('slotname');
$slot     = $this->input->post('slot');

for ($i=0; $i < count($slotname); $i++){
 $form_data = array(
  'slottime' => $slotname[$i],
  'seat'     => $slot[$i],
  'assocviva'=> 'Cycle1'
 );
 $this->modelquery->common_add($table_name, $form_data);
}

never put a model loading line inside a loop.
Comment: yes but i would like to make little correction in your code.
'slottime' => $slotname[$i],
  'seat'     => $slot[$i],


Migration to localhost causes 404 errors

Question: I'm trying to copy my site on my computer.
I've successfully downloaded and setup all the things. My site localhost URL is http://localhost/rich/ and when I run this URL, it opens my site homepage perfectly; after this, any clickable link gives me a 404 error page.
When I run this URL http://localhost/rich/user on my localhost, it gives me the following error:

Not Found
The requested URL /index.php was not found on this server.

Can anyone tell me what is wrong? What should I do it to fix it?
Comment: Make sure you have the `.htaccess` file in root. If yes try reading the section `# Various rewrite rules.`
Answer: Recently had simmilar issue. If your Drupal site were set up with clean url-s , you might want to change
#   RewriteBase /

in .htaccess file

Try comment it out.
If commented, try to uncomment it.
Try to add subdirectory in that declaration, if drupal is installed
under any

Of course, check mod_rewrite as was suggested by optimusprime619
Answer: I had the same problem recently and I checked the following to make it work:

Make sure rewrite module is enabled
Make sure in apache you have override all in order that your .htaccess works.
Look for any modifications in your .htaccess that might been conflicting with your new environment, especially those one related to force https. What I ended doing it is to copy the .htaccess from a new drupal project.
Make sure that in settings.php your base_url is commented or properly set it to your current environment
if you are using a mac, verify that in /etc/apache2/users/nameuser.conf you change AllowOverride none to AllowOverride all

I had that problem recently and suggestion number 5 is what it worked for me
Answer: You may need to turn off clean URLs. To access the clean URLs settings page (when clean URLs aren't working) go to yoursite/?q=admin/config/search/clean-urls. Turn off clean URLs here.
Once you can click on the links in your site, you can then figure out what you need to do on your local machine to get clean URLs working.
Answer: Please check if there's been any modification done to the .htaccess file in your drupal to suit the Dev environment. Also i'd suggest checking to ensure the rewrite module / mod_rewrite is enabled in your local web server.


My quicksort is sorting just marks instead of marks and student ids

Question: When I print the stu[] struct array in my main function it sorts only the marks but the ids stay the same. So for example stuid abc has mark 23 and def has mark 12, it swaps the mark so abc has 12 and def has 23. How do i make it so that the mark is swapped with the id.
struct student
{
    char id[20];
    int mark;
};

typedef struct student Student;
Student stu[5];

void swap(int* a, int* b)
{
    int t = *a;
    *a = *b;
    *b = t;
}

int partition (Student stu[], int low, int high)
{
    int pivot = stu[high].mark;
    int i = (low - 1);

    for (int j = low; j <= high- 1; j++)
    {
        if (stu[j].mark < pivot)
        {
            i++;
            swap(&stu[i].mark, &stu[j].mark);
        }
    }
    swap(&stu[i + 1].mark, &stu[high].mark);
    return (i + 1);
}

void quickSort(Student stu[], int low, int high)
{
    if (low < high)
    {
        int pi = partition(student, low, high);
        quickSort(student, low, pi - 1);
        quickSort(student, pi + 1, high);
    }
}

Comment: You need to swap the `Student`s, not the `mark`s.
Answer: The original code is only swapping the key fields, but it needs to swap entire records.
Change the swap function to swap Students instead of ints:
void swap(Student* a, Student* b)
{
    Student t = *a;
    *a = *b;
    *b = t;
}

Change the calls to swap to pass pointers to the Students instead of pointers to the Student.mark values:
    swap(&stu[a], &stu[b]);

Comment: Ah i see. I tried that before and it didn't work because I forgot to change the pointers from student.mark. Thanks for the help!!


Model for longitunal data with different interactions

Question: I've now spent quite a bit of time doing research on linear mixed models in R using lme4 and lmer. However, I still read conflicting advice on how to best fit the model.
This is my data: Longitudinal clinical data (0-10 years, fixed observation intervals) with clinical and laboratory values from each observation point.
The question I'm trying to answer is how certain laboratory values (numerical) or conditions (categorical) affect others.
So my random effect is my patient id.
The model I use is:
outcome ~ fixed_effect1 * fixed_effect2 * age + (1 | patient_id)
However, there are some questions that come to my mind and that I couldn't answer:
1) The effects I'm looking at might also lead to a more accelerated decline of outcome, so i'd need to do a slope analysis, right? Would this mean that I use (age | patient_id), for example?
2) I have two similar fixed effects, age and observation_time (years after study started). How should I consider this?
Any help is highly appreciated, thank you!
Best
Edit 1
Thank you very much for your kind introduction and reply. So, to get it straight. I have an outcome, and I suspect different other data to have an impact on it:
Obviously, it is a longitudinal data set, so I put Age/Observation_Time as fixed effect
- There is some baseline grouping (i.e. diseased, not diseased), which I suspect to accelerate or decelerate the developement of my outcome variable by time/Age/etc (this variable is the same in every table line of my results table for every subject). I put this grouping variable as slope effect, right?
- There are some other variables which might influence my outcome over time, so I put them as other fixed effects?
The model I get is then:
outcome ~ fixed_effect1 * fixed_effect2 * age + (1 + baseline_grouping | patient_id)

Edit 2
So I took some time to construct my model. I have scaled all relevant fixed_effects as proposed by Schilzeth et al. 2010 (using as.numeric(scale(.)))
The model now goes:
lmer(outcome ~ fixed_effect1 * age + fixed_effect2 * age + baseline_grouping + (1 + age | patient_id)

So for the fixed_effectN * age combinations, this reads like: I allow the  effect of age/time/whatever to vary between different levels of fixed_effectN, right? And I like your explanation for (1 + age | patient_id): This allows the effect of age to vary between patients (as patient_id), right?
Do I actually need the "1+age" or would "age" be the same?
(It should be, according to https://bbolker.github.io/mixedmodels-misc/glmmFAQ.html#model-specification)
Answer: Welcome to the site! You seem to have a pretty good handle on things. Let me try to address your two questions.

1) The effects I'm looking at might also lead to a more accelerated
  decline of outcome, so i'd need to do a slope analysis, right? Would
  this mean that I use (age | patient_id), for example?

That is a a possibility, and one that your subject matter expertise can speak to. If you add (age|patient) to your random effects structure, this allows for the linear effect of age on the outcome to vary for each person. You will get both an age slope variance and a covariance between the age slope and the intercept. The covariance is centered at age==0, so you may want to make sure that an age value of 0 is meaningful.

2) I have two similar fixed effects, age and observation_time (years
  after study started). How should I consider this?

This is a good question and again, should be guided more by your subject matter expertise. The advantage of modeling observation_time is that you could code the first year in the study as 0, so that will help in interpreting the age-slope random effect covariance. However, that takes away any information about age. Perhaps older people have steeper slopes. That would be masked with using observation_time. It seems that people start the trial at different ages. You could possibly add a covariate for age of the patient at first measurement and then interact that with observation_time to see if the effect of time in study is different for people of different ages.
Edit based on additional information
Variables that do not vary within subjects (i.e., variables that have the same value for all rows in a given subject) cannot be included in the random part of your model. These variables can only be considered as fixed predictors that are time invariant. Only time-varying predictors (such as age) can be included in the random part of the model as a slope. So in your case, you may want a model such as the following, if you are interested in allowing the effect of age on the outcome to vary across persons:
lmer(outcome ~ fixed_effect1 * fixed_effect2 * age + baseline_grouping (1 + age | patient_id)
You could interact age and baseline_grouping (age:baseline_grouping in the fixed effects portion of your model) to allow a person's age effect to vary based on their baseline_grouping value.
Comment: Thank you @Erik Ruzek for your help, I'm now very happy with the analysis and effects plots!
Comment: Thank you for your kind reply. I updated my question....
Comment: @user9551890, I updated my response.
Comment: thank you  again, I edited some information.
Comment: @user9551890, your edit looks good to me. One thing - I would not suggest scaling the age variable. You may want to center age around some fixed constant such that a 0 value is meaningful, but you do not want to z-score it. Also, I suggest you graph the interactions to help you understand what is going on. You can use `ggeffects()` for this.  See https://cran.r-project.org/web/packages/ggeffects/vignettes/introduction_randomeffects.html


How to build a small size react-native production application

Question: I have recently started working with react-native (earlier i was working with ionic). My question is related to building the react-native app.
My main concern is regarding the size of the application. As far as i know, running the "react-native run-android" command runs the application in development mode with live-reload and checking the size of the installed app,it turns out to be almost 52MB.
Checking with the some answers from stackoverflow , i was told to use the following commands for the building an apk:
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
cd android/  && ./gradlew assembleDebug
or
cd android/  && ./gradlew assembleRelease
But these commands still create an application of around 30MB, that too for a starter application. If i compare it with ionic framework the "ionic cordova run android" directly builds an install-able application (without the need of signing it) of reasonable size.
Please tell me if i am doing anything wrong.
Answer: try adding
ndk {
    abiFilters "armeabi-v7a", "armeabi" // includes ARM SO files only, so no x86 SO file
}

inside
buildTypes {
    release {

of your app/build.gradle and see how much size will change
Comment: Tried it. But there was no effect in the app size.
Comment: in that case you may want to use Analyze APK inside Android Studio to see what is the culprit of the app size.
Answer: React native will always be far bigger than an Cordova app of the same complexity.  Cordova runs in a web browser.  React Native doesn't, so it has to come with its own javascript interpreter.  That's a large .so file. You may be able to make it a bit smaller, but you're not going to get a huge decrease from there.
Comment: So a size of 30mb for a starter app is normal in react-native?


Polynomial representation of $\sum\limits_{n=m+1}^N \binom {n-1} m$

Question: Background: I am looking for a polynomial representation of
$$
\sum_{n=m+1}^N \binom {n-1} m \tag{1}
$$
where $m\in\mathbb{Z^+}$ is a positive integer $2,3,4,\ldots $ that is greater than or equal to $2$. I know how to write polynomials for small values of $m$ and am curious if the general case also produces a polynomial that can be written down by hand. Below I complete the analysis where $m=2$ and $m=3$.
Case 1: m=2. Equation $(1)$ becomes
\begin{equation}
\sum_{n=3}^N \binom {n-1} 2 = \sum_{n=3}^N \frac{(n-1)(n-2)}{2} = \sum_{n=3}^N \frac{n^2-3n+2}{2}.
\end{equation}
Since
\begin{align}
\sum_{n=3}^N n^2 &= \sum_{n=1}^N n^2 - \sum_{n=1}^2 n^2 = \frac{N(N+1)(2N+1)}{6}-5 = \frac{1}{6}\left(2N^3+3N^2+N-30\right), \\\\
3\sum_{n=3}^N n &= 3\sum_{n=1}^N n - 3\sum_{n=1}^2 n=\frac{3N(N+1)}{2} - 9 = \frac{3}{2}\left(N^2+N-6\right), \\\\
\sum_{n=3}^N 2  &= 2\sum_{n=1}^N 1 - 2\sum_{n=1}^2 1 = 2(N-2),
\end{align}
we have
\begin{align}
\sum_{n=3}^N \binom {n-1} 2 &= \frac{1}{12}\left(2N^3+3N^2+N-30\right) - \frac{3}{4}\left(N^2+N-6\right) + (N-2) \notag\\\\&=
\boxed{\frac{N^3}{6} - \frac{N^2}{2} + \frac{N}{3}}. \tag{2}
\end{align}
Case 2: m=3. Equation $(1)$ becomes
\begin{equation}
\sum_{n=4}^N \binom {n-1} 3 = \sum_{n=4}^N \frac{(n-1)(n-2)(n-3)}{6} = \sum_{n=4}^N \frac{n^3-6n^2+11n-6}{6}.
\end{equation}
Because
\begin{align*}
\sum_{n=4}^N n^3 &= \sum_{n=1}^N n^3 - \sum_{n=1}^3 n^3 = \frac{N^2(N+1)^2}{4} - 36 = \frac{1}{4}\left(N^4 + 2N^3 + N^2 - 144\right), \\\\
6\sum_{n=4}^N n^2 &= 6\sum_{n=1}^N n^2 - 6\sum_{n=1}^3 n^2 = N(N+1)(2N+1)-84 = 2N^3+3N^2+N-84, \\\\
11\sum_{n=4}^N n &= 11\sum_{n=1}^N n - 11\sum_{n=1}^3 n= \frac{11N(N+1)}{2} - 66 = \frac{11}{2}\left(N^2+N-12\right), \\\\
\sum_{n=4}^N 6  &= 6\sum_{n=1}^N 1 - 6\sum_{n=1}^3 1 = 6(N-3),
\end{align*}
we see that
\begin{align*}
\sum_{n=4}^N \binom {n-1} 3  &= \notag \frac{1}{24}\left(N^4 + 2N^3 + N^2 - 144\right) - \frac{1}{6}\left(2N^3+3N^2+N-84\right) \\\\
& + \frac{11}{12}\left(N^2+N-12\right) - (N-3) \notag \\\\&=
\boxed{\frac{N^4}{24} - \frac{N^3}{4} + \frac{11N^2}{24} - \frac{N}{4}}. \tag{3}
\end{align*}
Next, I move onto the general case where $m$ is greater than $3$.
Case 3: m=m. Equation $(1)$ is
$$
\sum_{n=m+1}^N \binom {n-1} m = \sum_{n=m+1}^N\frac{(n-1)(n-2)\ldots(n-m)}{m!}=? \tag{4}.
$$
Through a computer algebraic system (such as Mathematica), I found that
$$
\sum_{n=m+1}^N \binom {n-1} m  = \frac{\binom N m(N-m)}{m+1}=\boxed{\frac{(N-m)N!}{m!(N-m)!(m+1)}}\tag{5}.
$$
Equation $(5)$ follows from induction. For the inductive step, I assume
$$
\sum_{n=m+1}^N \binom {n-1} m  = \frac{\binom N m(N-m)}{m+1}.
$$
Adding $\binom{N}{m}$ to both sides to gives
$$ \begin{align*}
\sum_{n=m+1}^{N+1} \binom {n-1} m &= \frac{\binom N m(N-m)}{m+1} + \binom{N}{m} \\&=
\frac{(N+1)!}{(m+1)!(N-m)!} \\&=
\frac{(N+1)!(N+1-m)}{(m+1)!(N+1-m)!} \\&=
\frac{\binom {N+1} m (N+1-m)}{m+1}
\end{align*}$$
which validates $(5)$.
Question: Is $(5)$ the most general polynomial representation of the general case (similar to $(2)$ and $(3)$ when $m=2$ and $m=3$)? Would it be better to instead apply Stirling numbers of the first kind?
Comment: Your identity (5) is called the https://en.wikipedia.org/wiki/Hockey-stick_identity
Comment: Since you have the expression, have you tried proving it via induction?
Comment: @ChrisLewis: Yes, induction works for verifying $(5)$.
Answer: Yes, what you found in (5) is the Hockey stick identity, yours can be written more simply as
$$
\sum_{n=m+1}^N \dbinom {n-1} m=\binom{N}{m+1}.
$$
If you wanted it as a polynomial in $N$, i.e. expressing its coefficients, then again yes Stirling numbers of the first kind are the answer. By definition $(x)_n=\sum_{k=0}^{n}s(n,k)x^k$ and so
$$
\sum_{n=m+1}^N \dbinom {n-1} m=\sum_{k=0}^{m+1}\frac{s(m+1,k)}{(m+1)!}N^k.
$$
Comment: Not sure what you mean by "need", this is just rewritten definition of Stirling numbers, note that $\binom{N}{m+1}=\frac{(N)_{m+1}}{(m+1)!}$. Also I would not necessarily call $\frac{N(N-1)\cdots(N-m)}{(m+1)!}$ simpler than $\binom N {m+1}$.
Comment: The expression simplifies to

$$
 \binom M {m+1}= \frac{N(N-1)\cdots(N-m)}{(m+1)!}.
$$
Do you need the $\color{blue}{\text{additional summation term}}$ in the falling factorial polynomial?

$$\sum_{n=m+1}^N \dbinom {n-1} m=\sum_{k=0}^{\color{blue}{m+1}}\frac{s(m+1,k)}{(m+1)!}N^k$$

This may be because the falling factoral polynomial has $(m+1)$ factors

$$N_{(m+1)} = N(N-1)\cdots(N-m).$$


Maximum number of Fourier terms in forecast package

Question: I am using the forecast package in R to get some Fourier components - namely, function fourier(ts, K, ..). For a time series ts, K controls the maximum number of the Fourier terms one gets (sines + cosines of with different frequencies).
However, if the period of the time series is specified as 7, K is automatically capped at 3 maximum, or for other periods, $\#\textrm{terms} = \frac{\textrm{Period}}{2}$.
Why is that? I thought Fourier series can be represented by an infinite number of components. Is there some practical issue?
Answer: You are observing a discrete series. With a period of $k$ and a constant term already fitted, there are only $k-1$ degrees of freedom for the seasonal terms (there's only $k$ different means you can have in a period with $k$ times, but one is accounted for by the constant). This is the same df you get if you used seasonal dummies.
Because you have both $\sin$ and $\cos$ terms, you normally get two terms each harmonic. So with $k=7$, you get $(k-1)/2=3\,$ $\sin$ terms and $(k-1)/2=3\,$ $\cos$ terms. (With even $k$, you get one term at the end rather than two, because one - the highest order $\sin$ term - doesn't contribute anything.)
Any higher order periodicities would consist of wiggles between the data points. You don't observe those.
Comment: Essentially, yes; being on a discrete set of points you can only determine as many coefficients as points - and because the points are on a lattice, higher harmonics couldn't do anything anyway.
Comment: Ah, so it is due to the function being discrete? So, as I understood, the first 7 terms approximate all 7 points of the period, while higher order terms try to approximate something which is in-between points, so it makes no sense (since the ts is discrete), and they are simply discarded. Did I get it correctly?


Generating IMA(1,1) series

Question: I'd like to generate a series that follows an IMA(1,1) process, where $θ$ is the moving average parameter. I generated the series based on different representations and I got different results, I'm wondering which one is correct?
$$
\begin{aligned}
d_1 &=μ+e_1  \\
d_t &=d_{t−1}−θ\cdot e_{t−1}+e_t  \\  \\
\text{or}  \\  \\
d_1 &=e_1  \\
d_t &=μ+d_{t−1}−θ\cdot e_{t−1}+e_t
\end{aligned}
$$
Comment: 2)  d1=e(1); dt=μ+d(t−1)−θ*e1(t−1)+e1(t) is correct for simulation purpose.
Answer: It is depending on which series you are actually looking at. Assuming $ \{ e_t\}$ is white noise.
In your first series,$d_1=\mu +e_1; d_t=d_{t−1} − \theta*e_{t−1} + e_t$, the series $d_t$ will have shift
and
in the second series, $d_1=e_1; d_t=\mu+d_{t−1}−\theta* e_{t−1} +e_t$, the series $d_t$ will have drift.
Both are IMA(1,1) series (for simulation purpose)
Comment: Actually if we suppose we have n periods, in the first one the constant part is equal to μ while in the second one equals to nμ
Comment: You are right. But still 1) and 2) are IMA series. The second series will have drift (you could find the term 'drift' in random walk literature).
Comment: Which one is more appropriate in practice? I don't knwo which one I should use for demand process simulation.
Comment: I guess the first one (I assume the periods are not very long and no linear growth in demand.)
Comment: Is it the same for the other process like MA(1), AR(1) , ARMA(1,1)?
Comment: I didn't get the question. Are you asking about the constants? MA(1) AR(1) ARMA(1,1) are stationary series.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/7155/discussion-between-vinux-and-roji)

Generating IMA(1,1) series


May I use a root user to expose the python bottle application to the Internet?

Question: I made a WEB application using Bottle and want to publish it. I decided to use paste for the web server because official document said it's the easiest way.
In order to let the web server process listen on the port 80, the process must be launched by the root user. I'm not a security expert and can not judge that it's safe to use the root user for launching an application that is exposed to the internet directly.
Shall I avoid using root user in such a situation ?
Answer: No.
Do not run your web server as root.

Shall I avoid using root user in such a situation?

Yes, avoid running as root.

In order to let the web server process listen on the port 80

Your web server does not need to listen on port 80. One common way to structure this is to put a proxy (like a load balancer) in front of your web server. Your server listens on a non-privileged port (e.g. 8000); the load balancer (which is listening on port 80) forwards all requests to your server.
The accepted answer (which does not actually answer your question) merely mentions chroot, but I suggest that you not worry about that. Running as a non-privileged user is a much more important safeguard than using chroot. I would consider chroot to be secondary to your initial, quite legitimate, concerns over running as root.
Comment: You're welcome! Good question. A proxy is not running your code; it's running purpose-built, hardened code that does only one thing. Your web server, on the other hand, can do anything it wants, which includes inadvertently creating security holes.
Comment: Thank you. Let me ask one more question. To my understanding, the proxy should be launched by root (because it should listen on port 80). What's the difference between launching web server and proxy as root ?
Answer: It is recommended to create an chrooted environment with an restricted user.
Over here you can find a howto on how to create a chrooted environment www.howtogeek.com/441534/how-to-use-the-chroot-command-on-linux/amp/


Como alinhar os itens  de uma lista  embaixo?

Question: A ideia e criar um chat semelhante ao skype, whatsApp, etc... Onde as mensagens começam a aparecer de baixo para cima ate atingirem a altura da ul para dai aparecer a barra de rolagem.

    ul {
        list-style: none;
        height:380px;
        width:500px;
        overflow-y:auto;
        padding:5px;
        background-color:#ccc;
    }
    ul>li {
        height:80px;
        margin-bottom:5px;
        width:100%;
        background-color:#888;
    }

111111111111

222222222222

Comment: Você precisa que o li que representa a mensagem de um usuário fique com margem a esquerda do usuário atual com margem a direita? Assim como no whatsapp? Que tipo de alinhamento exatamente?
Comment: Ola @GuilhermeNascimento ! Oque preciso e apenas alinhar os blocos de mensagem embaixo, para que quando a primeira mensagem do chat aparecer, aparece-rá em baixo e depois vai subindo conforme novas mensagens surgirem. Quanto a questão de alinhar as mensagens a direita e esquerda, não tem problema.
Comment: você quer que `222222222222` apareça acima de `111111111111`?
Answer: Faço assim usando as propriedades display:table e display:table-cell e vertical-align:bottom
display:table - Elemento Pai DIV
display:table-cell - Elemento Filho UL com vertical-align:bottom

div {
  display: table;
  width: 100%;
}
ul {
  list-style: none;
  height: 340px;
  width: 100%;
  padding: 5px;
  background-color: #ccc;
  display: table-cell;
  vertical-align: bottom;
}
ul>li {
  height: 80px;
  width: 100%;
  background-color: #888;
}

111111111111

222222222222

Comment: Bom exemplo de uso do stacksnippet []s
Answer: Faça isto, acaso necessite que o container do ul tenha o tamanho exato de 380px como no exemplo, terá que ter uma div por fora com essa medida para ele:

ul {
    list-style: none;
   max-height:380px;
    width:500px;
    overflow-y:auto;
    padding:5px;
    background-color:#ccc;

     position: absolute;
    bottom:0;
}
ul>li {
    height:80px;
    margin-bottom:5px;
    width:100%;
    background-color:#888;
}

111111111111

222222222222

Comment: Editado o poste pois links podem quebrar
Answer: Tu cria um JavaScript assim:
function updateScroll() {
    var element = document.getElementById("teste");
    element.scrollTop = element.scrollHeight;
}
updateScroll();

var timerId = window.setInterval(1, 1000);

setTimeout(function () {
    clearInterval(timerId)
}, 10000);

No CSS não é preciso alterar nada, mas pode usar o seguinte para esconder a barra (porém ela continuará funcionando)
ul::-webkit-scrollbar{
    display: none;

}

É só colocar um id na ul e colocar o nome dessa id no Javascript no lugar de teste.
Link JSFiddle

function updateScroll() {
    var element = document.getElementById("teste");
    element.scrollTop = element.scrollHeight;
}
updateScroll();

var timerId = window.setInterval(1, 1000);

setTimeout(function () {
    clearInterval(timerId)
}, 10000);
ul {
    list-style: none;
   max-height:380px;
    width:500px;
    overflow-y:auto;
    padding:5px;
    background-color:#ccc;

     position: absolute;
    bottom:0;
}
ul>li {
    height:80px;
    margin-bottom:5px;
    width:100%;
    background-color:#888;
}

ul::-webkit-scrollbar{
    display: none;

}

111111111111

222222222222

222222222222

222222222222

222222222222

222222222222

222222222222

222222222222

222222222222

222222sasa222222

222222222222

222222222222

22asa

222222sasa222222

222222sasa222222

222222sasa222222

222222sasa222222

222222sasa222222

FINAL

Comment: Ola @LeonardoVIlarinho ! Muito bom, funcionou como esperado... valeu
Answer: Alexander, para vc fazer este chat vc tem que trabalhar com linguagem do tipo PHP e banco de dado como MYSQL, pois eles serão responsável por armazenar e mostrar na tela a resposta da outra pessoa.
Mas a parte funcional onde vc envia fica mais ou menos assim:

function sendMsg(){
  var send = $('.send_msg').val();
  if(send){
    $('.display_msg').append('
' + send + '
');
     $('.send_msg').val('');
     $('.display_msg').scrollTop($('.display_msg').height()); // FALTOU ESTE TRECHO
  }
}
ul {
        list-style: none;
        height:380px;
        width:500px;
        overflow-x:auto;
        padding:5px;
        border: 1px solid #333;
    }
    ul>li {
        margin-bottom:5px;
        background-color:#888;
        padding: 10px;
    }
    ul>li.receive{
        background-color:#ddd;
    }
    .send_msg{
        border: 1px solid #333;
        height: 50px;
        width: 500px;
    }

111111111111

222222222222

<textarea class='send_msg'></textarea>

<button type="button" onclick="sendMsg()">Enviar</button>
Comment: Isso faz funcionar, mas não resolve o que ele perguntou: como alinhar os itens na base do ``
Comment: Com certeza não iria.... já que eu esqueci de colocar um trecho do código, valeu  bfavaretto. Será que agora é isto que vc precisa Alexander???
Comment: curti bastante isso, eu coloquei um mais simples (sou novato na linguagem), tem algum site/canal pra recomendar pra aprender mais sobre a linguagem?
Comment: EU usei apenas CSS, HTML e Jquery... isto tem na net ao montes.. no youtube mais ainda... mas se precisar de alguma junda só chamar...
Comment: Ola @ValentimAraújo ! Muito obrigado pelo seu post... A linguagem que estou utilizando e ASP.NET C#, mas isso não importa. Oque importa e o empenho de todos para ajudar na comunidade... valeu pela ajuda


Compact, continuous embeddings of $H^s := W^{s,2} \leftrightarrow C^{(\alpha)}$

Question: The sobolev-space $H^s([-\pi,\pi])$ can be embedded into $C^{(\alpha)}([-\pi,\pi])$ (space of $\alpha$-Hölder-continuous functions) and vice-versa.
My question is for which exponents $s, \alpha$ can we reach those embeddings and for which exponents $s, \alpha$ are these embeddings compact?
$H^s \subset C^{(\alpha)} $ continuous for $s > \alpha + [?]$
$H^s \subset C^{(\alpha)} $ compact for $s > \alpha + [?]$
$C^{(\alpha)} \subset H^s $ continuous for $s < \alpha - [?]$
$C^{(\alpha)} \subset H^s $ compact for $s < \alpha - [?]$
What I have found so far:
$C^{(\alpha)} \subset H^s $ continuous for $1 > \alpha > s \geq 0$ (Bernstein's theorem)
Answer: Sobolev spaces normally have integrability exponent $s\ge 1$, just as Lebesgue spaces do. Indeed, otherwise they would not qualify as normed spaces.
Also, in much Sobolev space literature $H^s$ stands for $W^{s,2}$, not $W^{1,s}$. This makes sense if we think that $H$ stands for Hilbert.  For this reason, I write $W^{1,s}$ below.

$W^{1,1}$ continuously embeds into $C^0$ (by the Fundamental Theorem of Calculus), but not into any $C^\alpha$ with $\alpha>0$. Indeed, it contains $|x|^\epsilon$ for every $\epsilon>0$.
For $s> 1$, $W^{1,s}$ continuously embeds into $C^\alpha$ with $\alpha=1-1/s$, by Morrey's inequality. The constant $1-1/s$ cannot be improved. The embedding is not compact. To verify both of the above, consider a sequence of triangles with base $n^{-2}$ and height $n^{2/s-2}$. Putting them next to each other on the real line, you get a sequence of functions which is bounded in $W^{1,s}$ and has no convergent subsequence in $C^{\alpha}$ with $\alpha=1-1/s$.
When $0<\alpha<\beta <1$, the space $C^\beta$ compactly embeds into $C^\alpha$. See
Is there a reference for compact imbedding of Hölder space? This and item 2 imply that  $W^{1,s}$ compactly embeds into $C^\alpha$ when $0<\alpha<1-1/s$.

I think you are mistaken about the embedding of $C^\alpha$ into $W^{1,s}$. For any $\alpha\in (0,1)$, there exist $C^\alpha$ functions that are not of bounded variation, and therefore do not belong to any Sobolev  space. You can build them from a chain of triangles similar to item 2 above: if the total height of triangles is infinite, the function does not have bounded variation.
The space of Lipschitz functions ($\alpha=1$) is the same as $W^{1,\infty}$. See relation between $W^{1,\infty}$ and $C^{0,1}$. This embedding is not compact because it's an invertible operator.
As you can see, going from Hölder to Sobolev scale is not as easy as the other way around: you get  nothing when $\alpha<1$, and then suddenly get everything when $\alpha=1$.
Comment: A very good explanation, in my opinion. A tiny quibble: various other bits of information make the origin of the "H" for the $L^2$ version of "W" spaces hazy... Nevertheless, the _mnemonic_ that it is "Hilbert (-space)" is very good. :)
Comment: Sorry, I assumed the common notation $W^{1,p}$ would refer to those. I meant the $W^{s,2}$-spaces as you correctly noticed. Thank you neverteless for the clarifications.
As I have found the necessary constants for $W^{s,2}$ already (Sobolev's theorem, Berstein's theorem and a generalisation of Sobolev's theorem), I marked the question as solved.
Do you know, whether the embedding $H^s \subset C^{(\alpha)}$ for the "actual" $H^s$ and $0 < \alpha < s-\frac{1}{2}$ is continuous or compact?
Comment: @AlexR: It is compact.
Comment: @timur Thank you very much.


How to set color in graphics in C#

Question: How to set color in graphics in c#?
SetColor method not working.
How do I convert the following Java code to C#?
private Graphics g1;

g1.setColor(Color.getHSBColor(h, 0.8f, b));
Color col = Color.getHSBColor(h, 0.8f, b);
int red = col.getRed();
int green = col.getGreen();
int blue = col.getBlue();

Comment: Those function names on `Color` and `Graphics` look like they are from a java class but your question is tagged C#, which language is it?
Comment: It's c# code are you sure?
Comment: I think you are using `java.awt.Graphics` from j++ ;).
Comment: He may be asking about converting that Java code in to equivalent C# code.
Comment: I'm sorry. This is a java code.
Comment: And yes i'm trying to convert into c# code.
Comment: My sincere apology. Thank you.
Answer: The drawing model in C# is slightly different.  Instead of setting resources, like color, on a graphic object, you create resources, such as Pen, or Brush that have properties on them, like Color.  You then use those objects to draw on an image.
Graphics g = Graphics.FromImage(someBitMap); //create a graphics object for an existing BitMap
Color c = new Color(255,0,0); //a "red" color
Pen p = new Pen(c); //create a Pen using the Red color from earlier
p.Width = 5; //Pen is 5 pixels wide

g.DrawLine(p, 0,0,100,100); //draw a diagonal line

//Get rbg values.
int r = c.R;
int g = c.G;
int b = c.B;

//It is VERY important to call `.Dispose()` on GDI objects.  They contain unmanaged system resources that can, and will, leak if you don't.
g.Dispose()
p.Dispose()

It looks like you might be trying to convert a color from the HSB color-space to RGB.  Unfortunately, that isn't natively supported in .NET.  The following blog post has some code that can do that for you: https://blogs.msdn.microsoft.com/cjacks/2006/04/12/converting-from-hsb-to-rgb-in-net/
Comment: Thank you very much Bradley.

How to set color in graphics in C#


open sphere around $x=14$ with radius $r=3$ for closed set $[10,16] \cup [17,25]$, is $16$ an interior point?

Question: Let $ S=[10,16] \cup [17,25] \subseteq \mathbb{R}$ and
$ d: \mathbb{R}^n \times \mathbb{R}^n \rightarrow \mathbb{R} $ with $ \mathbb{R}: d(x, y)=|x-y| $.
I need to find the open sphere around $x=14$ with radius $r=3$
$B_3(14)=\{y \in S| |14-y|<3\} =(11,16)$ or is $16$ an interior point?
Comment: Are you familiar with the subspace topology?
Comment: No, we haven't had the topic of topologies yet
Comment: Yes.  For any metric space:  every point in an open sphere is an interior point of that sphere.  In particular, $16$ is an interior point of $B_3(14)$ in the metric space $S$.
Answer: Recall the definition of the subspace topology (https://en.wikipedia.org/wiki/Subspace_topology).
Definition Let $(X,\tau)$ be a topological space and let $S \subseteq X$ be a subset. Then we define the subspace topology as
$$\tau_S = \{S\cap U\: |\: U \in \tau\}.$$
That is, a subset of $S$ is open if it is the intersection of $S$ with an open subset of $X$.
In your question we have $X = \mathbb{R}$ equipped with the standard topology, that is the topology generated by open balls. Let's denote the open ball of radius $3$ centered at $14$ in $\mathbb{R}$ by $B_3(14)=\{x\in \mathbb{R} \: | \: |x-14| <3\}$.
Then the ball of radius $3$ centered at $14$ in $S$, which we denote by $B_3^S(14)$, is the intersection of $S$ and $B_3(14)$, that is $$B_3^S(14) = B_3(14) \cap S = \{x\in S \: | \: |x-14| <3\} = (11,16].$$
Notice that this set is open by definition of subspace topology, being the intersection of $S$ with an open set.
Answer: Here is an answer without (explicitly using) the subspace topology.
Recall that in a metric space $M$, a subspace $C$ is closed if and only if every convergent sequence inside of $C$ has its limit in $C$. A subspace $U$ is open if and only if $M \setminus U$ is closed.
So to show that $B_3(14)$ is open in $S$, we should show that $S \setminus B_3(14)$ is closed. To see this, let $(x_n)$ have a limit $x$ in $S$, so that each $x_n \notin B_3(14)$. Then $|x_n-14| \geq 3$ for each $n \geq 1$. As distance is continuous, it follows that $|x-14| \geq 3$, so $x \notin B_3(14)$, thus $S \setminus B_3(14)$ is closed, hence $B_3(14)$ is open.


Why is Normal Distribution required to perform an independent t-test?

Question: I've been told many times that, when carrying an independent t-test, I have to determine whether my dependent variable (DP) is normally distributed on boths levels of my independent variable (IV).
On the other hand, I know that the independent t-test (and many other statistic test) is based on the General Linear Model (GLM):
<code>Y = b0 + b1*X + e
</code>
Where Y is my DV (continuous) and X my IV (coded for example has -1 and +1). As far as I know, the GLM requires, among other things, that the errors are normally distributed. It doesn't say anything about the distribution of the IV or DV.
If my assumptions are correct, then why are we asked to check if our variables are normally distributed?
Also, assume I have a large sample.
Comment: See also [Normality of residuals vs sample data; what about t-tests?](http://stats.stackexchange.com/q/45671/17230) & [If the t-test and the ANOVA for two groups are equivalent, why aren't their assumptions equivalent?](http://stats.stackexchange.com/q/1637/17230)
Answer: Both conditions are equivalent. Let us look at your equation
$$
Y = b_0 + b_1X + \epsilon
$$ with $\epsilon$ being normally distributed with mean zero.
Then samples in one group (indicated by $X=0$) are normally distributed with mean $b_0$ and samples in the other group (indicated by $X=1$) are normally distributed with mean $b_0 + b_1$. This is the same as the requirement for the t-test you cite above. What distribution $X$ has, or if it even has a distribution, is not relevant.
A normally distribured random variable plus some number is still normally distributed.


Can't bind nested JSON in Knockout

Question: I am trying to pass a JSON to knockout and display it, and I have managed to do so for the first few elements. However I am having trouble with the nested objects. What I am trying to achieve is to display the desc and value fields for each of the A1,A2,A3 / B1,B2,B3 ..
I've looked through a million examples and tried various versions, but still can't figure out how mapping works.
Many Thanks for your help.
JS:
function jsonSubsetModel (desc,value){
    var self = this;
    self.desc = ko.observable(desc);
    self.value = ko.observable(value);
    }

    var myModel = function(){
        var jsonUrl = '/myjson.json';
        var self = this;
        var mapped = {};

        //Data
        self.date = ko.observable();
        self.time = ko.observable();

        self.set1 = ko.observableArray([]);
        self.set2 = ko.observableArray([]);

    $.getJSON(jsonUrl,function (data) {
    self.date(data.Date);
    self.time(data.Time);
    self.img(data.ImgURL);

    mapped = ko.mapping.fromJS(data);
    self.set1(mapped.SET1);
    self.set2(mapped.SET2);
    });

    };

    ko.applyBindings(new myModel());

HTML:

JSON:
{
"Date":"21/02/2013",
"Time":"13:55",
"SET1": {
            "A1":{
            "desc":"descA1",
            "value":"30",
            },
            "A2":{
            "desc":"descA2",
            "value":"30",
            },
            "A3":{
            "desc":"descA3",
            "value":"30",
            }
    },

    "SET2": {
            "B1":{
            "desc":"descA1",
            "value":"30",
            },
            "B2":{
            "desc":"descA1",
            "value":"30",
            },
            "B3":{
            "desc":"descA1",
            "value":"30",
            }
    }
}

Comment: Are you sure that your JSON is correct? Because "SET1" and "SET2" **are not arrays** but objects holding 3 object on their "A1", "A2", "A3", etc properties...
Answer: The knockout.js foreach works with Array. What you're providing is an object. Change your object to:
"SET1": [
            {
            "desc":"descA1",
            "value":"30",
            },
            {
            "desc":"descA2",
            "value":"30",
            },
            {
            "desc":"descA3",
            "value":"30",
            }
    ],

Can't bind nested JSON in Knockout


Let $B$ be countable subset of $\mathbb R^n$ where $n > 1$. Prove $\mathbb R^n\setminus B$ is connected space

Question: Let $B$ be countable subset of $\mathbb R^n$ where $n > 1$. Prove $\mathbb R^n\setminus B$ is connected space. But I have to show this without arc-connectedness. Hint is to use the fact that sum of connected spaces which have common point is again connected.
To be honest, I don't know how to use the hint. Any help would be great!
Answer: First prove that $[0,1]^n\setminus\{p\}$ is connected, where $p$ is arbitrary. This is not difficult, let me know if you need help. Now you can cover $\mathbb{R}^n$ by small enough cubes and use the hint.
to see the connectedness: use induction. I'll leave the proof for $n=2$ to you. wlog assume that $p=(1/2,\dots,1/2)$. Then write $X=[0,1]^n\setminus\{p\}$, and let
$$X_1=[0,1]^{n-1}\times[0,1/2]\setminus \{p\}, X_2=[0,1]^{n-1}\times [1/2,1]\setminus\{p\}$$
Then $X$ is a sum of $X_1$ and $X_2$, and $X_1\cong X_2$, so we need only prove that $X_1$ is connected. But we can consider e.g.
$$L=\{0\}^{n-1}\times[0,1/2]\cong [0,1/2]$$
Then consider
$$X_t=[0,1]^{n-1}\times \{t\}$$
if $t<1/2$ and
$$X_{1/2}=([0,1]\setminus\{1/2\})^{n-1}\times\{1/2\}\cong ([0,1]\setminus\{1/2\})^{n-1}$$
using induction this is connected. $X_1=\cup_{t\in[0,1/2]}X_t$ and each of the $X_t$ is connected, and intersects $L$, which is also connected. A standard theorem shows that $X_1$ is connected.
Comment: I don't know which equivalent definition of connectedness I suppose to use. Is it fine to try showing that there is continuous function between $[0,1]^N$ and $[0,1]^N \setminus \{p\}$
Comment: You can use the hint again, see my edit