Separar conteúdo de uma coluna em outras colunas

Question: Tenho um arquivo em forma de tabela. Preciso separar o conteúdo de uma coluna específica em outras colunas, os dados são separados por ;.
Bem eu consegui fazer isto, mas o problema é que o conteúdo resultará para cada linha um número diferente de colunas. E por este código ele replica até o conteúdo até atingir o número de colunas. Eu queria que ele exibisse NA.
Pelo meu código obtenho isto:
  v1      v2      v3    p/sep  sep sep  sep sep
dados1  dados2  dados3  a;b;c   a   b   c   a
dados1  dados2  dados3  a;c     a   c   a   c
dados1  dados2  dados3  a       a   a   a   a
dados1  dados2  dados3  a;b     a   b   a   b
dados1  dados2  dados3  a;b;c;d a   b   c   d
dados1  dados2  dados3  a;b     a   b   a   b

Mas o resultado que espero ter é:
  v1      v2      v3 separar  sep sep   sep sep
dados1  dados2  dados3  a;b;c   a   b   c   NA
dados1  dados2  dados3  a;c     a   c   a   c
dados1  dados2  dados3  a       a   NA  NA  NA
dados1  dados2  dados3  a;b     a   b   NA  NA
dados1  dados2  dados3  a;b;c;d a   b   c   d
dados1  dados2  dados3  a;b     a   b   NA  NA

library(reshape)
file_split = data.frame(file,colsplit(file$separar,split=";",names="buffer",))

Comment: Na segunda linha da resposta esperada é realmente "a c a c" ou "a c NA NA"
Comment: @JoyceMaia se quiser usar "buffer", você precisa diferenciar as colunas de algum jeito, pois colunas com nomes iguais não são uma boa ideia. Uma forma de fazer isso é usar `paste` como eu fiz na minha resposta.
Comment: Tem outro erro no código, não existe a vírgula depois de `"buffer"`, e também esse argumento não tem muito sentido pois define um nome de coluna, sendo que 4 são criadas. Não que seja um grande problema neste caso, mas o ideal é colocar o código exato e o output exato gerados, aparentemente você editou algumas coisas à mão.
Comment: 'buffer" foi um erro de sintaxe, achei que ele repetiria o nome buffer como cabeçalho de todas as colunas novas @Molx
Comment: foi erro de digitação @MarcosBanik
Answer: Você esteve muito próxima da solução. Se ao invés do reshape utilizar o reshape2, utilizando a mesma função (trocando o argumento split por pattern), você chega próxima do que gostaria:
> file <- read.table(text="  v1      v2      v3    separar  sep sep  sep sep
dados1  dados2  dados3  a;b;c   a   b   c   a
dados1  dados2  dados3  a;c     a   c   a   c
dados1  dados2  dados3  a       a   a   a   a
dados1  dados2  dados3  a;b     a   b   a   b
dados1  dados2  dados3  a;b;c;d a   b   c   d
dados1  dados2  dados3  a;b     a   b   a   b", header=T, as.is=T)[,1:4]
> library(reshape2)
> file_split = data.frame(file, colsplit(file$separar, pattern=";", names=paste0("sep", 1:4)))

Resultando em
> file_split
      v1     v2     v3 separar sep1 sep2 sep3 sep4
1 dados1 dados2 dados3   a;b;c    a    b    c
2 dados1 dados2 dados3     a;c    a    c
3 dados1 dados2 dados3       a    a
4 dados1 dados2 dados3     a;b    a    b
5 dados1 dados2 dados3 a;b;c;d    a    b    c    d
6 dados1 dados2 dados3     a;b    a    b

Isso é uma questão de definição padrão da função. Em ambos pacotes, não é possível controlar o comportamento para número de colunas diferentes, mas o reshape usa reciclagem, enquanto o reshape2completa com strings vazias. Para substituir os espaços vazios por NA, você pode fazer, por exemplo:
> file_split[file_split == ""] <- NA
> file_split
      v1     v2     v3 separar sep1 sep2 sep3 sep4
1 dados1 dados2 dados3   a;b;c    a    b    c <NA>
2 dados1 dados2 dados3     a;c    a    c <NA> <NA>
3 dados1 dados2 dados3       a    a <NA> <NA> <NA>
4 dados1 dados2 dados3     a;b    a    b <NA> <NA>
5 dados1 dados2 dados3 a;b;c;d    a    b    c    d
6 dados1 dados2 dados3     a;b    a    b <NA> <NA>

Só é importante tomar cuidado aqui pois essa substituição troca todos os valores "" da tabela, talvez seja mais seguro usar os nomes/índices das colunas para não correr o risco de alterar outros dados que deveriam se manter vazios e não NA (se houver).

Antes de achar essa diferença do reshape2 eu fiz uma alternativa usando base e seguindo essa dica. Não é tão sucinta, mas já que está pronta, segue abaixo:
> file.split <- strsplit(file$separar, ";")
> n.obs <- sapply(file.split, length)
> seq.max <- seq_len(max(n.obs))
> resultado <- cbind(file, t(sapply(file.split, "[", i = seq.max)))
> resultado
      v1     v2     v3 separar 1    2    3    4
1 dados1 dados2 dados3   a;b;c a    b    c <NA>
2 dados1 dados2 dados3     a;c a    c <NA> <NA>
3 dados1 dados2 dados3       a a <NA> <NA> <NA>
4 dados1 dados2 dados3     a;b a    b <NA> <NA>
5 dados1 dados2 dados3 a;b;c;d a    b    c    d
6 dados1 dados2 dados3     a;b a    b <NA> <NA>

Answer: A maior dificuldade é fornecer nomes para as novas colunas. Vou adotar a mesma variável file e o mesmo esquema para os nomes das colunas que o Molx utilizou.
Caso saiba de antemão o número de colunas contido em separar. (4, nesse caso)
colunas <- paste0("sep", 1:4)

O número de colunas pode ser obtido por meio da função str_count do pacote stringr.
library(stringr);
colunas <- paste0("sep", 1:(max(str_count(file$separar, ';')) + 1));

Agora é possível dividir a coluna separar utilizando a função separate do pacote tidry.
library(tidyr);
separate(file, separar, into = colunas, sep = ';', remove = FALSE,
         extra = "merge");

Answer: library(reshape)
file_split = data.frame(file,colsplit(file$separar,split=";",names="buffer",))

Para colocar nome nas duas colunas precisa alterar o final names = c("Buffer", "Buffer2"))
Ou seja, fica assim
library(reshape)
file_split = data.frame(file,colsplit(file$separar,split=";",names= c("buffer","Buffer2")))


Getting number of events on a certain day in Swift

Question: In my app I want to display notifications when the app startups that states the number of events of the current day. So far my code looks like this:
//after appending the arrays with data from api
    DispatchQueue.main.async {
        print("Dates in array: \(self.datesArray)")

        if self.datesArray.contains(dateString){
            //check how many events on that day
            let newIndex = self.datesArray.index(of: dateString)

            print("newIndex: ", newIndex!)// position of current date
            print("Events today: ", self.datesArray)
            self.notificationPublisher.sendNotification(title: "Events", subtitle: "", body: "\(self.datesArray.count) today", delayInterval: nil )
        } else {
            self.notificationPublisher.sendNotification(title: "Events", subtitle: "", body: "No events today", delayInterval: nil)
        }
    }

I thought about somehow finding a way to have the datesArray array fill up so I can display the number of events of the current day but I'm unsure of how to do that. Am I going about this in the right way?
EDIT: I used a method of checking repeating elements in an array from here: How to count occurrences of an element in a Swift array?
So now my code looks like this: `DispatchQueue.main.async {
                    print("Dates in array: (self.datesArray)")
                if self.datesArray.contains(dateString){

                    self.datesArray.forEach{self.counts[$0, default: 0] += 1}
                    print("Counts: ", self.counts)

                    self.notificationPublisher.sendNotification(title: "Events", subtitle: "", body: "No events today", delayInterval: nil)

                }

            }`

Count outputs all the array elements and how many occurrences of them there are. How can I use that data to display how many events are on a particular day?
Comment: What is your `dateString `?
Comment: My dateString is  `let dateString = dateFormatter.string(from: currentDate)` and the dateFormatter is : fileprivate lazy var dateFormatter: `DateFormatter = {'
        `let formatter = DateFormatter()`
        `formatter.dateFormat = "yyyy-MM-dd"`
        `return formatter`
    `}()`
Comment: And `self.datesArray`?
Comment: Same format. The output of the array looks something like `["2018-08-21", "2018-08-10", "2018-08-30", "2018-08-21"]`
Answer: Check if your self.datesArray have some values with,
print(self.datesArray)

And calculate the number of today's events as:
let todayEvent = self.datesArray.filter({ $0 == dateString })

In total:
let datesArray = ["2018-08-21", "2018-08-10", "2018-08-30", "2018-09-17", "2018-08-21", "2018-09-17"]

fileprivate lazy var dateFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    return formatter
}()

func postNotificationForTodaysEvent() {
    print("Dates in array: \(self.datesArray)")

    DispatchQueue.main.async {
        let dateString = self.dateFormatter.string(from: Date())
        let todayEvent = self.datesArray.filter({ $0 == dateString }) // It will fetched the event from same date
        print(todayEvent)
        if todayEvent.isEmpty {
            self.notificationPublisher.sendNotification(title: "Events", subtitle: "WeAsean", body: "No events today", delayInterval: nil)
        } else {
            self.notificationPublisher.sendNotification(title: "Events", subtitle: "WeAsean", body: "\(todayEvent.count) today", delayInterval: nil )
        }
    }
}

and, result will be:
Dates in array: ["2018-08-21", "2018-08-10", "2018-08-30", "2018-09-17", "2018-08-21", "2018-09-17"]

today's events are:["2018-09-17", "2018-09-17"]


Nginx err too many redirects error after ssl configuration

Question: I have googled for the past 6 hours and not found what is wrong with my nginx.conf. My setup is django>gunicorn>nginx. my nginx.conf is below (Due to many trials is a bit messy):
upstream app_server {
    server unix:/home/django/gunicorn.socket fail_timeout=0;
}
server {
    listen 80 ;
    listen [::]:80  ipv6only=on;
    server_name comparebet.co.ke www.comparebet.co.ke;

    return 301 https://$server_name$request_uri;

    client_max_body_size 4G;
    keepalive_timeout 5;

    location /media  {
        alias /home/django/django_project/django_project/media;
    }

    access_log /var/log/access.log;
    error_log /var/log/error.log;
}

server  {
    listen 443;
    ssl on;
    listen [::]:443 ssl http2;
    include snippets/ssl-example.com.conf;
    include snippets/ssl-params.conf;

    server_name comparebet.co.ke;

    root /usr/share/nginx/html;
    index index.html index.htm;

    location /static {
        alias /home/django/django_project/django_project/static;
    }

    location /static/admin {
       alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/;
    }

    location / {
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
        proxy_buffering off;
        proxy_pass http://comparebet.co.ke;
    }

    location ~ /.well-known {
        allow all;
    }

    access_log /var/log/access.log;
    error_log /var/log/error.log;
}

I will appreciate any help. Thanks
Edited to include curl response headers
* Rebuilt URL to: comparebet.co.ke/
*   Trying 22.214.171.124...
* Connected to comparebet.co.ke (18.104.22.168) port 80 (#0)
> GET / HTTP/1.1
> Host: comparebet.co.ke
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 301 Moved Permanently
< Server: nginx/1.10.0 (Ubuntu)
< Date: Wed, 22 Mar 2017 00:18:58 GMT
< Content-Type: text/html
< Content-Length: 194
< Connection: keep-alive
< Location: https://comparebet.co.ke/
<

<title>301 Moved Permanently</title>

301 Moved Permanently

nginx/1.10.0 (Ubuntu)

* Connection #0 to host comparebet.co.ke left intact

Main issue is when domain is accessed by Chrome browser it returns "ERR: TOO MANY REDIRECTS". This is what I want to solve
Comment: Please edit your question to more clearly state your problem, and show matching curl (with response headers) and logs demonstrating the problem. Please also tidy up your configuration so it's easier to read.
Comment: Edited the nginx.conf file and included the curl response headers
Comment: Right, so now we need to see the matching log entry from Nginx, django, and gunicorn, to work how which piece of software is sending the 301.
Answer: Your https server contains these line (excerpt). This tells it to send any requests going to the https site back to the http site
location / {
    proxy_pass http://comparebet.co.ke;
}

Your http server contains these lines, forwarding requests back to the https site.
server_name comparebet.co.ke www.comparebet.co.ke;
return 301 https://$server_name$request_uri;

Nginx is doing exactly what you told it to do, which is to create a redirect loop. The solution depends on what you're trying to do.
Comment: I know that solution for @LawrenceMuriuki is found, but I'd like to help with a similiar issue I recenly faced and this answer gave me a clue. So I changed    proxy_set_header X-Forwarded-Proto http; to proxy_set_header X-Forwarded-Proto https;


Complex integral inequality

Question: Statement
Let $\gamma$ be the curve that goes through the upper unit circle counterclockwise (positive orientation). Prove that $$\left|\int_{\gamma} \dfrac{\sin(z)}{z^2}dz\right|\leq \pi\dfrac{1+e}{2}$$
The attempt at a solution
What I did is:$$\left|\int_{\gamma} \dfrac{\sin(z)}{z^2}dz\right|=\left|\int_0^{\pi} \dfrac{\sin(e^{i\theta})ie^{i\theta}}{e^{i2\theta}}d\theta\right|$$
The right member equals to $$\left|\int_0^{\pi} \dfrac{\sin(e^{i\theta})ie^{i\theta}}{e^{i2\theta}}d\theta\right|=\left|\int_0^{\pi} \sin(e^{i\theta})e^{-i\theta}d\theta\right|$$
Now, $$\left|\int_0^{\pi} \sin(e^{i\theta})e^{-i\theta}d\theta\right|\leq \int_0^{\pi}\left|\sin(e^{i\theta})\right|d\theta$$
For real numbers, I know that $|\sin(x)|\leq 1$, but I don't know if this inequality holds for complex numbers as well. If that was the case, then I could say that the last member is less than or equal to $$\int_0^{\pi} d\theta=\pi < \pi\dfrac{1+e}{2}$$ and then the original statement would be proved. If $|\sin(z)| \not \leq 1$ for all $z \in \mathbb C$ (or at least in the unit circle), then I don't know what to do next. I would appreciate some help.
Comment: Generally, you don't have $\lvert \sin z\rvert \leqslant 1$ for $z \notin\mathbb{R}$. If you use Euler's formula for $\sin z$, you can get a bound for the integrand.
Comment: @user156441 Euler had many formulae. I meant $$\sin z = \frac{1}{2i}\left(e^{iz} - e^{-iz}\right).$$
Comment: You need $\lvert e^w\rvert = e^{\operatorname{Re} w}$. With that, a simple application of the triangle inequality yields exactly the given bound. The inequality $\lvert \sin z\rvert \leqslant \sinh \lvert z\rvert$ yields a sharper bound. One can, however, also evaluate the integral exactly, as per Michael's comment, or by expanding $\sin z$ into its Taylor series.
Comment: $\sin (x+iy) = \frac{1}{2i}(e^{x+iy}-e^{-x-iy})$
Comment: @DanielFischer Euler's formula for $\sin(z)$ is $\sin(z)=z\prod_{n=1}^{\infty} (1-\dfrac{z^2}{n{\pi}^2})$. I am not so sure how to get a bound for $\prod_{n=1}^{\infty} (1-\dfrac{z^2}{n{\pi}^2})$, I was going to affirm $\prod_{n=1}^{\infty} (1-\dfrac{z^2}{n{\pi}^2})\leq \prod_{n=1}^{\infty} 1$, but this isn't always true for $z \in \mathbb C$ (it would be true for real numbers). Can I get some help with that expression?
Comment: If you use the Cauchy integral formula, you can show that the exact integral of $\sin(z)/z^2$ around half the unit circle is $i\pi$.  That is because $\sin(z)/z^2$ is an odd function, so the integral over half the circle is half the integral of the full circle.
http://en.wikipedia.org/wiki/Cauchy%27s_integral_formula
Comment: Hmm, I'm not so sure I can apply Cauchy's integral formula here since f(z) is not holomorphic on the circle's interior.
Comment: @DanielFischer Sorry for that, I googled Euler's formula and assumed you were talking about the other one. Using that formula, I get $\int_0^{\pi} |\sin(e^{i\theta})|d\theta=\int_0^{\pi} |\dfrac{1}{2i}(e^{i\cos(\theta)}e^{-\sin(\theta)}-e^{-i\cos(\theta)}e^{\sin(\theta)}|d\theta$. Seeing the inequality I want to arrive to, I suppose that maybe $|(e^{i\cos(\theta)}e^{-\sin(\theta)}-e^{-i\cos(\theta)}e^{\sin(\theta)})|<1+e$. If that was the case, I have no idea how can I prove this inequality. If this is incorrect, then I am having problems finding a bound for that expression.
Comment: @DanielFischer Thank you very much. So $|e^{i\cos(\theta)}e^{-\sin(\theta)}-e^{-i\cos(theta)}e^{\sin(\theta)}|\leq |e^{i\cos(\theta)}e^{-\sin(\theta)}|+|e^{-i\cos(\theta)}e^{\sin(\theta)}|=e^{- \sin(\theta)}+e^{\sin(\theta)}<1+e$. Is this correct?
Comment: @DanielFischer If you want, you can write your suggestions as an answer, you've been of great help.
Answer: From Euler's formula
$$\sin z = \frac{1}{2i}\left(e^{iz} - e^{-iz}\right)$$
and $\lvert e^{\pm iz}\rvert = e^{\pm \operatorname{Re} (iz)} = e^{\mp \operatorname{Im} z}$, we obtain the estimate
$$\lvert \sin (x+iy)\rvert \leqslant \frac{1}{2}\left(e^{-y} + e^y\right).$$
On the unit circle, we have $\lvert y\rvert \leqslant 1$, so
$$\lvert \sin z\rvert \leqslant \frac{1+e}{2}$$
there, which gives exactly the suggested bound.

Complex integral inequality


How can I achieve basic authentication in Drupal?

Question: I am trying to get working webservices in drupal (Services, restws,...), but ,as a first step I am trying to get a cookie using 'Basic Authorization' using the following python script:
import urllib2
import base64

def login(u,p):
    url = 'http://127.0.0.1/drupal/node?destination=node'
    r = urllib2.Request(url,None,{'Authorization':'Basic '+base64.b64encode(u +':' + p),
                                  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                              'Accept-Encoding': 'gzip, deflate'})
    f = urllib2.urlopen(r)
    cookie = f.headers.dict['set-cookie'] # <--- this fails, raises exception
    csrf = f.read()
    return csrf,cookie

csrf, cookie= login('username', 'password')
print base64.b64encode(csrf)
print "cookie:", cookie

The line 'cookie=f.headers.dict['set-cookie']' fails, since there's no cookie returned in the response.
What could I have  missed ?
Answer: Drupal 7 will not set a session cookie unless it has to, for performance reasons. If there is no form under http://127.0.0.1/drupal/node, and no module requires sessions, you will not get any session, simple as that.


Difference and confidence intervals

Question: I performed a few series of simulation to evaluate values of two parameters. Let's say, the results can be presented like this:
SIM 1
X:      1.0 2.0 3.0 4.0 etc.
FA(X):  1.1 2.3 4.5 1.1 etc.
FB(X):  1.2 2.1 3.2 2.3 etc.

SIM 2
X:      1.0 2.0 3.0 4.0 etc.
FA(X):  1.3 2.2 4.3 1.1 etc.
FB(X):  1.2 2.1 3.2 2.4 etc.

SIM 3
X:      1.0 2.0 3.0 4.0 etc.
FA(X):  1.1 2.3 4.5 1.4 etc.
FB(X):  1.5 2.2 3.3 2.3 etc.

Now, I'm willing to calculate difference between those F's and its confidence interval. So the desired result would be like "difference between A and B is below 0.1 with confidence 95 %".
I was thinking about calculating max(abs(FA - FB)) for every set of data and then using those numbers to calculate mean value and one-sided confidence interval. But actually I'm not certain it's the right method. Could anyone point out a method of doing such things?
Any help appreciated. Thank you.
Answer: Your explanation is a bit vague for a precisely targeted response, but you are flirting with ideas that are really
important in modern data analysis. In particular, it seems mentioning two well-established inferential methods that use simulation methods somewhat similar to yours. I will discuss one in some detail and mention the other.
Permutation Test. Suppose you have samples of size 15 from two different populations and want to test whether one tends to give larger values than the
other. Also suppose that standard 2-sample tests are inappropriate (perhaps too many tied observations for a Wilcoxon signed rank test, and data obviously too
far from normal for a 2-sample t-test).
The first thing you need to do is to decide on a "metric"--a way to measure differences between two sets of data. The simplest is the difference between the
two sample means. (You might pick the difference between two sample medians,
the Wilcoxon statistic, or the t-statistic. The latter two are not necessarily
bad metrics just because circumstances may cause their actual distributions to be different from the published ones.)
We begin by finding the two sample means and then the difference between them
and call this 'd.obs'--for observed difference. This is a benchmark for comparison with what comes later.
If the two populations really are equal, then the two samples of 15 observations are essentially equivalent. We combine them into one sample of 30, permute the sample at random, and pick the first 15 as a first permuted sample and the second 15 as a second permuted sample. For the first iteration we find the difference between the means of the two permuted samples, and call it 'd.perm[1]'.
There are C(30, 15) = 155,117,520 ways to split the 30 into two samples of 15,
and we can't possibly look at them all. If we could, we could look at the distribution of all the d.perm's and see whether d.obs is far out in its right tail, leading us to reject the null hypothesis and conclude that the first population tends to give larger values than the second; otherwise decide the data at hand don't have enough information to come to that conclusion.
While we can't look at all C(30, 15) splits, we can use a simulation program in R to look at a large enough number of them to do the job. This gives us a 'simulated permutation distribution'. The program below does 100,000 permutations (splits) and records the metric 'd.perm[i]' for each. The proportion of values of the metric to the right of d.obs is called the P-value. If it is smaller than 5% we reject the null hypothesis.
For the (fake) data shown in the program the means are 0.923 and 0.893, giving d.obs=0.03. The program gives slightly different answers on each run. One run gave a P-value of 0.001 rounded to three places. the last line of code makes a relevant graph (not shown here). [For one elementary introduction to other kinds of permutation tests, see Eudey, Kerr, and Trumbo (J. Stat. Educ. V18 #1 (2010), and you can do a web search for more.]

a = c(.88,.96,.92,.94,.93,.90,.95,.92,.89,.94,.92,.95,.93,.91,.91)
b = c(.87,.94,.87,.95,.86,.88,.89,.91,.86,.92,.89,.90,.89,.88,.89)
d.obs = mean(a) - mean(b);  n1 = length(a);  n2 = length(b)
m = 10^5;  d.perm = numeric(m);  all = c(a,b)
for(i in 1:m) {perm = sample(all, n1+n2)  # random permutation
d.perm[i] = mean(perm[1:n1]) - mean(perm[(n1+1):(n1+n2)]) }
d.obs;  mean(d.perm > d.obs)  # P.value
hist(d.perm, prob=T); abline(v=d.obs, col="red")

Bootstrap Confidence Intervals. This is a simulation method for finding
confidence intervals in situations where standard methods do not work well.
One difference from permutation tests is that the data are repeatedly
're-sampled' WITH replacement. [There is rich literature on this topic and you can get a good start from the bibliography in Wikipedia on 'bootstrapping (statistics)'.]

Difference and confidence intervals


Why do I get "Access Denied" on every page?

Question: I've been trying out Drupal 8 on localhost which has been great, and I've now transferred it to a server, but every page gives me Access Denied. I can't even access the front page, or the user login page.
I have tried truncating the session and cache tables, and deleting cookies, but don't know what else to try. I've also installed drush, cleared the cache, and tried user-login drush command - still no access.
What things should I check? How do I fix this?
Comment: Got the same situation over here.  Same code and db locally work fine, but on platform.sh access denied everywhere.  Strange.  Since this is a top search result, I hope I remember to come back here once I've figured it out. :)
Answer: Don't edit core code as suggested by Flounders answer. If you're not using HTTP auth then simply disable the Basic Auth module via the UI or Drush:
drush pmu basic_auth -y

Drupal has different authentication providers. The defaults are: basic_auth and cookie, basic_auth has a higher priority but is not enabled by default.
Comment: I had similar problem But uninstalling is not the solution. So how do we perform basic authentication?
Comment: Please don't edit this answer unless you're actually adding value to it, if you have comments to add, leave a comment.
Comment: uninstall won't solve the problem. we need a basic auth on our Site.
Answer: If you came here with the intention on figuring out why your Drupal 8 site is now throwing Access Denied messages after enabling the Relaxed module (dependency on Workspace which is also dependent on core's Basic_Auth module) you'll want to read this:
https://www.drupal.org/node/2842858
It took me several days of hunting around to finally get the right Google Search query to find the right answer. I hope this finds others in the same spot I was in.
Answer: I had this happen to me when I accidentally changed the password of the mysql username that Drupal was using for authentication to the DB.  Make sure the DB user/pass is correct in settings.php.
Answer: After debugging I found what was the problem for me.
Drupal has some authentication providers. For standard pages this are:
basic_auth and cookie (basic_auth has higher priority).
Because test site has a basic_auth from the htaccess, this resulted in that Drupal marked my request as using basic_auth.
Only all pages did not require this.
Result was just redirect to the 403 page (access denied in the watchdog table)
My temporary fix was the following:
Open the file core/modules/basic_auth/src/Authentication/Provider/BasicAuth.php
Go to this code:
public function applies(Request $request) {
    $username = $request->headers->get('PHP_AUTH_USER');
    $password = $request->headers->get('PHP_AUTH_PW');
    return isset($username) && isset($password);
}

Change it to this:
public function applies(Request $request) {
    return false;
    //$username = $request->headers->get('PHP_AUTH_USER');
    //$password = $request->headers->get('PHP_AUTH_PW');
    //return isset($username) && isset($password);
}

If there is a better solution, let me know. But this makes the site working.
Comment: You shouldn't edit core code, see my answer for an alternative solution.
Comment: @benjy Your answer is not a solution.
Comment: Don't ever hack core code. There are better troubleshooting techniques out there.


Passing json_encoded array to jQuery

Question: I am trying to pass an array I am creating in PHP using json_encode(). I am running an AJAX request, see as follows:
AJAX CALL:
$.ajax({
        type: "POST",
        url: "../includes/ajax.php?imagemeta=1",
        data: {
            'id' : $(this).attr('id')
        },
        datatype:"json",
        success: function(data) {
            console.log(data);
            console.log(data["image_height"]);
        },
        error: function(data) {
            console.log(data);
        }
    });

PHP JSON RESPONSE:
if(isset($_GET["imagemeta"])){

$id = intval($_POST["id"]);
$path = "../uploads/images/" . $fm->selectImageById($id);
$meta = array();

list($width, $height) = getimagesize($path);
$meta["image_height"]   = $height . 'px';
$meta["image_width"]    = $width . 'px';

print json_encode($meta);

}
Although, the console.log(data) returns the following: {"image_height":"1374px","image_width":"920px"}
The following line console.log(data["image_height"]) returns undefined.
I have tried multiple attempts and have read through majority of the top rated questions regarding the subject. I am fairly new with JSON encoding so please inform me if I have a misunderstanding somewhere.
Comment: Try `data.image_height`?
Answer: datatype:"json",

should be:
dataType:"json",
    ^

Javascript is case-sensitive.
Comment: Oh my goodness. I hate my minor errors that throw me off for hours. Thanks a ton!
Answer: If console.log displaying you following:-
{"image_height":"1374px","image_width":"920px"}

Then you can access "image_height" as follows:-
data.image_height;

Answer: Either set php JSON response header or return plain text from php and use $.parseJSON in success function.
 success: function(data) {
        jSon = $.parseJSON(data);
        console.log(jSon.image_height);
    }

Passing json_encoded array to jQuery


The extension of Fourier transform from $L^1\cap L^2$ to $L^2$

Question: In Grafakos's book, in order to the define Fourier transform on $L^2$, he claims that the Fourier transform is an isometry on $L^1\cap L^2$. Since Fourier transform is an isometry, thus $\hat{f}\in L^2$. However, I couldn't figure out why $\hat{f}\in L^1$.
Comment: Actually some of the nicest functions you can think of don't have their Fourier transform in $L^1(\mathbb{R})$. A good exercise is to show that there is a function $f\in L^1(\mathbb{R})\cap L^{\infty}(\mathbb{R})\cap C^{\infty}(\mathbb{R})$ such that $\hat{f}\not\in L^1(\mathbb{R})$. One instance where $\hat{f}\in L^1(\mathbb{R})$ is when $f$ is such that $f\in L^1(\mathbb{R})\cap C^1(\mathbb{R})$ and $f'\in L^1(\mathbb{R})\cap L^2(\mathbb{R})$.
Answer: In general, it isn't. Here, "on" doesn't mean what it usually means, that is one space to itself, but rather that it is an $L^2$ isometry from $L^1\cap L^2$ to $L^2$. A good example is the Fourier transform of $\chi_{[-1,1]}$. Its Fourier transform has finite $L^2$ norm, but it is not Lebesgue integrable.
Answer: Assuming the Fourier transform of $f\in L^1(\mathbb{R})$ is the function $\hat{f}:\mathbb{R}\to\mathbb{C}$ defined by
$$
\hat{f}(\xi):=\int_{-\infty}^{\infty}f(x)e^{-ix\xi}\,dx
$$
Here's a way to see that $f:=\chi_{[-1,1]}$ (which is in $L^1(\mathbb{R})\cap L^2(\mathbb{R}))$ is such that $\hat{f}\not\in L^1(\mathbb{R})$. Suppose the contrary. Then the Inversion Theorem would apply and we would have
$$
\hat{\hat{f}}(-x)=2\pi f(x)
$$
at every point where $f$ is continuous, so (since $f$ is pair)
$$
\hat{\hat{f}}(x)=2\pi\chi_{[-1,1]}(x)
$$
for all $x\neq1,-1$. So $\hat{\hat{f}}$ would be continuous (since it would be the FT of $\hat{f}\in L^1(\mathbb{R})$ by hypothesis) and such that
$$
\hat{\hat{f}}=\begin{cases}2\pi&&|x|<1\\0&&|x|>1\end{cases}
$$
This is impossible, so $\hat{f}\not\in L^1(\mathbb{R})$.
Comment: This approach is really good for showing that the abstract Fourier transform of the characteristic function of an open set isn't in $L^1$. Great argument!
Comment: @Cameron Williams I have no merit! This argument was shown to me when I took a class dealing with Fourier analysis.


how to take jave heap dump every 30 seconds using kill -3  command

Question: Please help in this, i want to run a shell script where it should take jave heap dump every 30 seconds using kill -3  command. Thanks in advance.
Comment: Have you looked into [cron](http://stackoverflow.com/questions/9619362/running-a-cron-every-30-seconds)?
Comment: @Thomas Use `cron` to trigger every 30 seconds?
Comment: True, cron can only get down to every 60 seconds.
Answer: Have you tried such a simple shell script?
while true
do
  jmap -dump:file=/tmp/java-`date +%s`.hprof PID_OF_JVM
  sleep 30
done

This will create one file pear each snapshot. For thread dump you can use similar script:
while true
do
  jstack PID_OF_JVM > stack-`date +%s`.txt
  sleep 30
done

I guess you can use kill -3 instead of jstack.
Comment: +1 but kill -3 won't dump the stack to the console that you run it from, unlike jstack
Comment: @BrianAgnew: thanks, I tried first with `kill -3` but I thought it's my fault that I can't see the stack dump.
Comment: kill -3 will dump it to the process' stdout (err?) but jstack appears to dump it to the jstack's console
Answer: you can do thread dumping from java application using code like this
 public static String getDumpFor(Thread thread) {
    StringBuilder sb = new StringBuilder();
    if (thread.isAlive()) {
        StackTraceElement[] stackTrace = thread.getStackTrace();
        sb.append(thread.toString()).append("\n")
                .append(String.format(" State - %s,", thread.getState()))
                .append(String.format(" Is daemon = %s,", thread.isDaemon()));
        for (StackTraceElement s : stackTrace)
            sb.append("\tat ").append(s.getClassName()).append(".").append(s.getMethodName()).append("(").append(s.getFileName()).append(":").append(s.getLineNumber()).append(")")
                    .append("\n");
    }
    return sb.toString();
}

public static void dumpActiveThreads() {
    Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();
    Set<Thread> keySet = stackTraces.keySet();
    System.out.println("\nThread dump begin:");
    for (Thread thread : keySet)
        dumpActiveThread(thread);
    System.out.println("\nThread dump end.");

}

and then schedule task like this
 final ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(
            new Runnable() {dumpActiveThreads()},
            0,
            30, TimeUnit.SECONDS);

Answer: I have not used kill -3 command but i have used jmap command provided by sun sdk
You can write a script and then in script run below command.
${JAVA_HOME}/bin/jmap -dump:file=/home/MyDump.hprof PID

Answer: 3 will give only the thread dump but not the heap dump.Thread dump means you can only check the stack traces for each thread in the JVM.But you are lookin g for the heap dump on linux then need to use the below commands.
jmap -dump:file=myheap.bin {pid of which you are looking to take heap dump}. The output "myheap.bin" is not human readable,to read the file you can use the MAT tool.
MAT download link: http://www.eclipse.org/mat/


Problem in derivation of the volume of a sphere

Question: I tried to find the formula for the volume of a sphere using calculus, so I took a sphere of radius $R$ and partitioned it into infinitely many circles that start from radius $r$ of 0 up to $R$ and to 0 again, such that the sum of their areas makes up the volume of the sphere. Then, I noticed this is $2\int_{0}^{R} \pi r^2dr$ which works out to be $2\pi r^3 \over 3$, which is just the volume of a sphere divided by 2
Where was I wrong?
Comment: See https://www.youtube.com/watch?v=afjHpHRdPFo
Comment: To increase the radius from $r$ to $r+dr$ doesn't involve translating the circle through a distance $dr$ orthogonal to its plane, so the volume thereby swept out isn't $\pi r^2dr$. Since $x^2+r^2=R^2\implies dx=-\frac{rdr}{\sqrt{R^2-r^2}}$, your strategy should write the volume as $2\int_0^R\frac{\pi r^3dr}{\sqrt{R^2-r^2}}$, which is indeed $\frac{4\pi R^3}{3}$ (see if you can prove it).
Comment: You've find volume of figure made of two cones with common base. Volume of rotation body is $\int_{z_1}^{z_2} \pi r(z)^2 dz$, because every disk has thickness $dz$ which can be different with $dr$. In your case $dz=dr$ which means $r=a+z$, which describes cone, not sphere. For sphere one needs to use $r=\sqrt{R^2-z^2}$ which leads to $V=2 \int_0^R \pi (R^2-z^2) dz$.
Answer: I think the correct sweeping formula by circles (disks) is $$2\int_0^R \pi(R^2-r^2)dr.$$
You sweep by disks from $0$ to $R$ for half ball.
Or you may try sweeping by concentric spheres: $\int_0^R 4\pi\rho^2d\rho$.


How to convert app-release.apk to app.apk

Question: I am developing an android app in Cordova by Command-Line-Interface. I have strictly follow this documentation https://cordova.apache.org/docs/en/5.0.0/guide/cli/index.html. and i have successfully build the application in release mode. Finally I got an apk like app-release.apk .I have added keystore and signed my app. So my question is can I directly upload this "app-release.apk" in google play or i have to make app.apk . Please consider me as novice in this platform. thanks.
Answer: Yes, you can directly upload the app-release.apk file. The name of the apk does not matter.


Connecting to an analog dial-in PSTN terminal without a PSTN line

Question: there's a computer ("server") that has no Internet connection, and it is located in a place with no GSM signal. The only way to get connection to it is an analog modem (US Robotics 56Kbit/s). This modem is connected to a national PSTN line with a geographical number, and the server (running a modern Linux distribution) is configured to offer a dial-in serial terminal. To clarify, when you phone to this PSTN line, the modem handshakes (I think it's the V90 protocol), then you're presented with the login and then you are in on ttyS0. There's no IP/PPP protocol stack, just the serial terminal.
I would like to connect to this server in any way that does not require me to carry around a physical analog modem and (what's worse) finding around a physical PSTN line which is really a scarce resource at least in business context here in Italy. To clarify: the PSTN line on the server side is the only way through, but I would like to be able to connect to it without a physical PSTN line on the client side.
Some ideas that came through my mind but I do not know if they can be really implemented or not:

Having a mobile phone connected through bluetooth/USB. Old phones exported a ttyUSB that handled AT commands, but then there was no way (AFAICT) to get the audio stream. I don't know if it's technically possible to write an Android app that makes a phone call, then encodes the audio into a semi-raw UDP stream.
Routing the call through VOIP. Googling around, some people seems to have had mixed success with doing analog modem calls through a VOIP termination with g711 (uLaw/aLaw). It looks like it is possible to get at least 9600bps, which is enough for me.
Even if one of the above is possible, is there any software available that emulates the full V90 protocol/handshake/whatever and en/decodes audio into bytes?
Is there any online service that offers a battery of analog modems to subscribers? Doesn't sound a business I would personally invest on, but you never know :)
Is there any physical object that is the modern UMTS equivalent of an analog modem, like a box connected through USB where you put the SIM inside, it does all the magic, and gives you a ttyUSB on your PC?
Assuming that I can physically access the server just once, is there anything I can install (either hardware or software) on the server and that would make my life easier? The only requisite is that must go through a standard national PSTN line (dual twisted copper), there's no other way to get any other signal. The modem looked like the best option, at first, but you never know.

Thanks!
Comment: Vocal now offer this, though I would be interested in finding an open source solution. https://vocal.com/voip/sip-analog-modem-solutions/
Answer: I suspect there are lots of ways to do this.  One that comes to mind is callback.
You register a dialin ISP account for the modem on the server; that's simple enough, and non-contentious.  You will need an ISP that will allocate you a static address; if this costs extra, pay it.
You then configure something like diald to bring the link up and down on demand.  Then write a little script, perhaps using swatch, to detect "RING" messages appearing in the modem logfiles, and when it sees them, to generate traffic that diald considers "interesting" - ie, traffic that causes it to bring up the line.
When you want to connect to the server over the regular internet, you call the phone line attached to the server, from any landline or GSM phone.  The script on the server detects the phone RINGing, and generates interesting traffic for diald.  Diald brings up the PPP connection, at which point the server is available on the known, static IP address.
You, using regular internet tools, connect in via SSH (or any other IP protocol or combination thereof which pleases you), until you're done.  When you're done, you drop all these connections, and after a short while diald realises the line is idle and hangs up the modem.
Rinse.  Repeat.
Possible enhancements: if you can't get an ISP service that does static addresses, you could configure diald so that the first thing that happens after the internet link comes up is that it emails it's current IP address to a pre-arranged address, or in some other way communicates it to the internet.  That way you can find out what dynamic address it's got each time the line comes up, so you can talk to it.  But a static address would be easier.
Alternative suggestion: consider that most GSM phones will happily make a PPP connection to any old POTS number, to establish the terminal session.  I wrote this technote some years ago on the nuts and bolts of getting a GSM phone with a modem that honoured the AT command set (which is most of them) to dial in to an ISP.
It's completely legal to have the GSM phone dial a standard landline instead of the magic "bring up GPRS" number, just replace
atd*99***1#

with
atd0039nnnnnnnn

in /etc/ppp/chat-gprs, where nnnnnnnn is your server's landline number.  Note this will only work with GPRS, and maybe EDGE.  3G is a whole different protocol accessed in different ways, so you'll only get a slow (20kb/s or so) connection this way.  But for a straight terminal session, that may be enough.
Comment: Thank you, I managed to login through a GSM phone (even if not the first one I tried).The callback approach is also interesting even if I am not sure I can actually *make* calls through that landline (will have to check for the billing, etc:), as most (all?) dialup ISP in Italy nowadays directly bills through special phone numbers, sometimes without even requiring a registration.
Answer: There are a variety of terminal servers on the market -- you telnet/ssh to them and upon connection, you can interact with one or more serial ports on the console server, which are typically hooked via a null-modem cable to other servers. If the server has a serial port, this is the best way to go. You can then use a mobile broadband device to get a connection, and add some dynamic DNS or VPN magic to deal with changes of the IP.
Older GPRS/EDGE USB modules (or handsets with USB) would present as a serial device (ttyUSB or ttyACM) in Linux; it should be possible to switch the server's inittab to bind the getty to that. I've done this in the past with an external (actual-serial-port connected) GSM modem; I'd imagine it should work with USB as well.
If the server has an internal modem, not a serial port, and you can't replace it, things get more complicated. VoIP might work -- the closer to raw PCM, the better the odds are. Fixed wireless terminals (basically a cell phone but with an FXS port instead of a speaker/mic/keypad) might work as well, but are likely to have the same issues as VoIP.
Comment: There's no way to get into the server if not the PSTN line; there's no Internet connection and no GSM signal.
Comment: Ah, now I understand. The USB stick or phone sugguestion still stands; if you have GSM service where you are, if you treat it just like a normal modem (ATDT phonenumber), it should make a data connection (with the actual modem parts happening within your mobile carrier.)
Comment: +1. Drop a terminal server with a modem and a phone line in your office, with remote access, to dial the server.
Answer: I'm no t sure I completely understand your requirements. I'll type what I think you are asking and go from there:
1) There's a server with only a pstn line conected to an analog modem.
2) You want to free the phone line (for other uses) and want to keep having accesss to the server.
Iff 1 & 2 are correct, then I don't see other choice but to use some form of internet connection, an USB 3G stick should give you a connection you can tap on via ssh to make any administrative task you may need.
You could also install some sort of xDSL line, that will free your pstn line to use as regular phone and give you internet access at the same time.
Comment: No, I want to still use the PSTN line on the server side (because it's the only thing I can use, there's not GSM signal where the server is located), but I want to be able to connect to it without a physical PSTN line on my side, since I can be anywhere and PSTN lines are scarces.


Finding the inverse of a $1-1$ function that is defined to be $f(X_1, \ldots, X_n) = \left(\sum_{i=1}^{n}X_i, X_2, \ldots, X_n\right)$.

Question: I found a class paper that mentioned that if we have $1-1$ function $f$ that takes a vector, $(X_1, X_2, \ldots, X_n)$ and returns:
$$
f(X_1, \ldots, X_n) = \left(\sum_{i=1}^{n}X_i, X_2, \ldots, X_n\right)
$$
then the inverse is defined to be:
$$
f^{-1}(y, y_2, \ldots, y_n) = \left(y-\sum_{i=2}^{n}y_i, y_2, \ldots, y_n\right)
$$
where $y$ is defined as: $y = f(X_1, \ldots, X_k) = \sum_{i=1}^{n}X_i$.
I am wondering how I can find the inverse and where exactly the subtraction of the first entry of the inverse comes in. Would anyone have any ideas? Thanks.
Comment: "where $y$ is defined as..." No, $y$ is not defined as what follows in your post, actually $y$ is simply part of the argument for the function $f^{-1}$ hence $y$ does not need to be defined.
Answer: We set :
$$f(X_1, \ldots, X_n) = \left(\sum_{i=1}^{n}X_i, X_2, \ldots, X_n\right)=(y, y_2, \ldots, y_n).$$
Then we have the following linear system :
$$\left\{\begin{matrix}
\sum_\limits{i=1}^{n}X_i  = y_1\\
 X_2 =  y_2 \\
 \vdots\\
 X_n =  y_n
\end{matrix}\right. \Leftrightarrow\left\{\begin{matrix}
X_1+\sum_\limits{i=2}^{n} y_i =  y_1\\
 X_2 =  y_2 \\
\vdots  \\
 X_n =  y_n
\end{matrix}\right.$$
Since $\forall i, n\geq i \geq 2, X_i=y_i $. Then the system is equivalent to :
$$\left\{\begin{matrix}
X_1 =  y_1-\sum_\limits{i=2}^{n} y_i\\
 X_2 = y_2 \\
\vdots  \\
 X_n =  y_n
\end{matrix}\right.$$
Then $$f^{-1}(y_1,\dots,y_n)=(X_1,\dots,X_n)=\left(y_1-\sum_\limits{i=2}^{n} y_i,y_2,\dots,y_n\right).$$


Why is my guitar untunable after I recently changed the strings?

Question: I have had the same telecaster for 20 years. I have been playing guitar all my life. I have an electronic tuner. I recently changed the strings. All the strings are tunable when open. So for example, the low E string reads neither flat nor sharp when tuned. However, when I play that same string by pressing a fret (for example, the 5th fret) the resulting note plays quite sharp. In this case it is an A reading almost to the low A#. Same happens on the A string to a lesser extent , and it gets better as I get up to the lighter gauge strings.
I'm using d'addario XLNY strings, extra light (9s) and swapped out the lower string with a different d'addario product but that didn't change anything. Still sharp. This is freaking weird! Should be in tune!
Comment: Please do read up other similar questions in MusSE. I'm sure this already has a lot of answers. Might get closed as Duplicate anytime. Check String Height at Peghead, Check Truss Rod. You said you switched to Lighter strings, so Im assuming U checked Gauge already. If none of these work, then Saddle.
Comment: When was the last time you changed strings, and did you (or why did you) change the weights of your strings?
Comment: I did lighten the weight of the strings, but that on its own doesn't explain the problem. My guitar should accommodate a range of string gauges, and historically it has.
Answer: As has been mentioned, if you've changed gauge or type of string, your intonation may be off. But I would first check for obvious setup or installation issues with the strings. Changing gauges or types of string can and will cause your intonation to be off (which can be corrected on most electric guitars by adjusting the bridge saddles) but being nearly a semitone off at the 5th fret is way, way outside the type of error you'd expect to see for an intonation issue - even after changing string type or gauge. It might be more typical to be off by half that amount, at the 12th fret. So, I would start by checking the following:

Make sure the nut hasn't shifted. On a telecaster, the nut sits in a slot and usually stays put. But make sure it's not slipped out of position (or backwards, or otherwise incorrectly installed)
Make sure the strings are seated well in the nut slots and break smoothly over the nut. Make sure they're routed correctly to the tuners.
Make sure the strings are breaking correctly over the slots in the bridge saddles (versus being hung up next to the saddles or otherwise incorrectly installed).
Make sure the bridge saddles haven't shifted. On some bridges the saddles are essentially held in place by a spring, if the saddles get tweaked during string install, the spring can get compressed and string tension can "clamp" the saddle in an incorrect position.

Finally, make sure you are deliberately setting the witness points if you're not already doing that - basically, the witness point is the point at which the string bends over the nut or the bridge saddle. In some cases, a string needs to be "set" over the witness point when first installed (by gently pressing down to crease the string). Otherwise, the string can exhibit a sort of spring-like behavior where the pitch changes as notes are fretted, which basically makes it impossible to set or maintain intonation. Often, when a string exhibits intonation issues near the extreme ends of the fretboard, it's because this is happening. It's more commonly a problem on bass guitars or other instruments with heavy strings, but it can be an issue on guitars as well, especially if the nut slots aren't well formed or the break angle over the nut or bridge are really shallow.
Comment: After working with my guitar today, it's clear that the problem is the action is somehow too high. That is, if I play a harmonic on the 12th feet the pitch is fine but the distance to the fret is sufficient to bring the tone almost 1/3 the way to the next semitone. The contribution discussing witness points makes the most sense, that the string under tension is arcing and thus further from the fret board, and when I press it, there is increased tension and tone is off. The newness of the string, lack of elasticity might also make it more sensitive to the 1-2mm stretch to the fret board.
Answer: Seem like you changed the gauge of strings. Let us know! If so, it'll be the intonation.
Answer: How long was the last set of strings on?  Also, where do you live?  We are in the change of seasons right now and that means wood will get finicky, more so for an acoustic but electrics are also affected.  This happens to my Gibson every couple years and I need an adjustment.  It could be that you inadvertently moved the bridge pieces when changing strings, neck might have bowed a little.  You say you pot 9s on it but did you change from 8s or 11s.  A change a gauge can require a new set up.
Comment: Lad set was on for a long time, years. I live in Washington state. New strings are lighter.


Pixel level classification using deep network

Question: I am new to deep learning and have already got my hands dirty with running deep network on MNIST and CIFAR datasets.
Is there a way to directly use deep learning for semantic segmentation of image?
Suppose, the training images consist of RGB images and images of their corresponding groundtruth (i.e. pixel level annotation). If I want the network to directly classify a pixel as one of the N classes (say), what should be the network architecture ?
Comment: Read [Semantic Segmentation](https://github.com/kjw0612/awesome-deep-vision#semantic-segmentation) section of [Awesome Deep Vision](https://github.com/kjw0612/awesome-deep-vision) repo.
Comment: When I think about this [link](http://ltcf.mechse.illinois.edu/downloads/Software/PIVSleuth/PIVSleuthManual.pdf) I wonder about sub-pixel classification.  What is your interpolating function?  Each pixel is a time and space average of incident light from (typically 3) spectral window(s).  It approximates a system where the physics are nearly continuously varying, but the sampling isn't.  (If we can abandon the regular grid, and we can use more physically valid interpolating functions than cosine, then we might do better there).  What can you share about the physics that drive pixel values?
Comment: Maybe you can have a look at "U-nets", a comparably simple, yet powerful architecture for segmentation. Input and outputs are images and the net connects them by a U-shaped sequence of (up-)convolutions. You will find many such nets on kaggle or github, e.g. made with keras.
Answer: While this approach looses one of the main advantages of DCNN's; it can be done utilizing sequence classifiers, see Kera's Sequence tutorial or Jason Brownlee's http://machinelearningmastery.com/tutorial-first-neural-network-python-keras/
note: you'll likely have just as much accuracy as if you did a Bayesian classifier, which is going to be easier to visualize and troubleshoot.  A note that you want to ensure the classes are separable and not bi-modal; so you do want to plot your training space to ensure you have enough classes.  If one class is bi-modal, just figure out how to break it into two classes.
Also note that the old-style Neural nets typically never out-perform a Baye's classifier.  It's only been the recent advances in DNN that do.


Como instalar o WordPress Multisite?

Question: Estou usando a opção de multi-sites do WordPress, mas não está funcionando como o esperado.
Já habilitei e criei os subdomínios, porém retorna:

Not Found
The requested URL /index.php was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

Acredito que este problema esteja acontecendo pois:
Tenho 2 domínios

dominio1.com é o domínio principal
dominio2.com é um domínio adicional

o WordPress está instalado no domínio adicional e neste domínio criei os subdomínios.
Eu pensava que fosse o arquivo .htaccess, mas pelo visto não é:
http://codex.wordpress.org/htaccess
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^wp-admin$ wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule . index.php [L]

Gera o erro 404, porquê não existe arquivos dentro do subdomínio. O que eu tenho que fazer para corrigir isso?
Comment: esse .htaccess que você colocou na pergunta é o do seu domínio ou do codex do Wordpres?
Answer: Vou tentar colocar passo a passo aqui tudo o que você precisa fazer para habilitar o Multisite do WordPress. Vamos lá.
Requisitos

WordPress 3.0 ou maior. (recomendo a última versão).
Suporte a wildcards na criação de subdomínios pelo host.

Se você precisar usar o WP MS com subdomínios, ou seja, acessar seus sites criados na instância do WP usando: http://site1.example.com, http:///site2.example.com e por aí vai, seu host irá precisar ter o suporte de wildcards na criação de subdomínios. Seu site principal ficaria em http://example.com e os outros sites em subdomínio desse domínio.
O que são os wildcards?
Quando você cria um subdomínio em host, você geralmente especifica o nome do subdomínio e a pasta root que ele deve ler. Por exemplo:

http://site1.example.com - /home/seuusuario/site1/public_html
http://site2.example.com - /home/seuusuario/site2/public_html

No entanto, você irá precisar transferir essa responsabilidade de responder as chamadas (requests) de domínios ao WP. Por isso, você tem que criar um domínio com wildcard, que responda a qualquer nome. Isso pode ser feito quando você cria o domínio usando:

*.example.com -> /home/seuusuario/example.com/public_html

Dessa forma, qualquer request feito antes do example.com, será encaminhado para o WP instalado na pasta /home/seuusuario/example.com/public_html. Se o WP estiver configurado como MS ele responderá com o devido site criado dentro do MS.
Crie os wildcards para subdomínios (pule se não for usar subdomínios)
Como explicado acima, você terá que acessar o painel de controle do seu host e criar um subdomínio com o nome de *.example.com ou, dependendo do host, %.example.com. Aponte o DocumentRoot para a pasta onde está a instalação do seu WP ou onde você irá instalar o WP.
Se você não achar essa opção ou o host não permitir, abra um chamado perguntando se é possível criar um subdomínio usando wildcards e se for, como você faz. Se o host responder negativamente, então você só terá a opção de criar mais sites dentro do WP usando a opção de sub-diretórios, infelizmente.
Se você já tiver criado domínios pelo painel e que deseja usar no WP MS, remova esses subdomínios.
Habilitando o WP MS
Criada as configurações de subdomínios, vamos agora habilitar o Multisite no WordPress. Para isso, abra o arquivo wp-config.php e adicione a seguinte linha:
/* Multisite */
define( 'WP_ALLOW_MULTISITE', true );

Salve o arquivo, e acesse seu WordPress pelo navegador. Faça o login na administração do WP e vá em Tools > Network Setup.
Escolha a forma de instalação entre sub-domínios ou sub-pastas. Lembre-se das configurações acima caso for usar subdomínios.
Finalize a instalação ajustando o wp-config.php e o .htaccess conforme as instruções dessa página temporária em Ferramentas.

Alterando o wp-config.php
Acrescente estas linhas depois daquela primeira de antes:
/* Multisite */
define( 'WP_ALLOW_MULTISITE', true ); // <-- depois desta
define('SUBDOMAIN_INSTALL', true);
define('DOMAIN_CURRENT_SITE', 'seudominio.com.br');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);

Alterando o .htaccess
Agora só falta alterar o .htaccess pois ele é um pouco diferente quando usado com o WP MS. Abra seu .htaccess e substitua ele todo pelo seguinte conteúdo de acordo com o tipo de sua instalação:
Sub-domínios
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^wp-admin$ wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
RewriteRule ^(.*\.php)$ wp/$1 [L]
RewriteRule . index.php [L]

Sub-pastas
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]

Depois que mudar os arquivos wp-config.php e .htaccess, vai ter que fazer login de novo e aparecerá o ambiente Network completo.

Alterando o tipo de instalação de subdomínios para subpastas ou vice-versa
Se quiser alterar o tipo de instalação de um tipo para o outro depois de ter feito uma instalação, prévia, faça o seguinte. Abra o arquivo wp-config.php e modifique a seguinte linha:
define( 'SUBDOMAIN_INSTALL', true );

Use a flag true para usar a instalação por sub-domínios e false para usar a instalação por sub-pastas.
Mapeamento de domínios
Mapeamento é fazer com que um site do Multisite funcione com um domínio próprio, ou seja, mapear site.example.com para rodar como site.com.
Antigamente era necessário o plugin WordPress MU Domain Mapping mas hoje em dia isso é nativo no WordPress. É só definir a URL do site com o domínio mapeado site.com e o mapeamento é feito automaticamente, observando que os DNS e o SSL já devem estar funcionando antes de mapear o domínio.

Fontes:

https://wordpress.org/support/article/create-a-network/
https://wordpress.org/support/article/multisite-network-administration/
https://wordpress.org/support/article/wordpress-multisite-domain-mapping/
Answer: Na instalação do Multisite com subdomínios você não precisa criar os subdomínios. Se você criá-los o seu servidor vai direcioná-lo pro subdomínio, que está vazio e vai dar um erro 404.
Sugiro uma leitura nesse artigo do Codex. Faça um backup do seu site, apague tudo e reinstale do zero, seguindo o passo-a-passo da página do Codex.
Answer: Você tem acesso a Shell?
Caso sim, dá um tailf /var/log/apache/access.log para ver em qual pasta o navegador ta chegando.
Parece que o problema é o direcionamento do dominio, a pasta onde ele está sendo direcionada não é a pasta que o wp está instalado. Apenas uma sugestão.
Comment: Entrei em contato com eles, e eles disseram que a pasta é: public_html/dominio2.com/meusubdominio . Eu tenho que adicionar algum arquivo dentro do subdomínio?
Answer: Isso mesmo amigo, precisa de algo lá dentro para que não dê Not Found.
Mas no seu caso, pelo que entendi, você precisa fazer com que este subdomínio caia na mesma pasta do dominio atual pois quem lidará com isso será o proprio WP.
Se não usar o multilanguage, teria que fazer assim:
pt.seudominio.com.br -> Pasta com Instalação do WP em Pt
en.seudominio.com.br -> Pasta com Instalação do WP em En

Porém, vai fazer assim:
pt.seudominio.com.br -> Pasta com a única instalação do WP
en.seudominio.com.br -> Pasta com a única instalação do WP

Espero que tenha sido útil, desculpe a demora.
Comment: Multilanguage e Multisite são coisas diferentes.

Como instalar o WordPress Multisite?


Given Two 95% Confidence Intervals

Question: Suppose we have given a two $95 \%$ confidence intervals for $X_1$ and $X_2$. They are normally distributed. From this how would we get a $95 \%$ confidence interval for $X_{1}/X_{2}$?
Comment: What do you mean by "$X_1$" and "$X_2$"? Usually a confidence interval is a statement about a *property* of a family of distributions, but (unless you are doing a Bayesian analysis with a prior) properties are not normally distributed--only the variables described by those distributions can be. If the $X_i$ are intended to designate random variables, then you need to specify what property you are estimating: the mean?  Variance?  Something else?
Comment: Welcome to the site. Is this homework? If so, it should have the homework tag.
Comment: @PeterFlom: No it is not.
Answer: I dont think you can get the 95CI of mean(x1/x2) just by their separate 95CI.
Maybe you can do a simulation to get the empirical distribution of (x1/x2) if you also get the correlated relationship between x1 and x2

Given Two 95% Confidence Intervals


Why is my awk sub command failing?

Question: When I run
df -hl | grep '/dev/disk1' | awk '{sub(/%/, \"\");print $5}'

I'm getting the following error:
awk: syntax error at source line 1
context is
    {sub(/%/, >>>  \ <<< "\");}
awk: illegal statement at source line 1

I can't seem to find any documentation on awk sub.
df -hl | grep '/dev/disk1'

returns
/dev/disk1                         112Gi   94Gi   18Gi    85% 24672655 4649071   84%   /

As I understand, it should return the percentage of disk space used.
Answer: You simply need to remove the pair of backslashes:
df -hl | grep '/dev/disk1' | awk '{sub(/%/, "");print $5}'

Awk sub function is well documented to replace the first occurrence of the pattern passed as first parameter by the string passed as second parameter.
Here the pattern is the percent sign and the replacement string is an empty string. As it is written in your question, the second parameter is an invalid string so awk complains and quit. The corrected awk statement is removing the % appearing in its input and displaying the fifth field.
Note that the grep command is redundant here, as awk is able to do the filtering alone so the command can be simplified into:
df -hl | awk '/\/dev\/disk1/ {sub(/%/, "");print $5}'

Why is my awk sub command failing?


Não consigo inserir no BD com entity

Question: Esse é meu código de inserção. Porque dá erro? O que devo fazer?
public int abreOsParceiro(string os, string cnpj, string dataAbertura, string dataVisita, string tecnico)
        {
             WEBEntities db = new WEBEntities();
            PDVOsParceiro pdv = new PDVOsParceiro();
            List<string> lista = new List<string>();

            try
            {
                pdv.CNPJ = cnpj;
                pdv.DataAberturaOs = Convert.ToDateTime(dataAbertura);
                pdv.DataVisita = Convert.ToDateTime(dataVisita);
                pdv.Tecnico = tecnico;
                pdv.OS = Convert.ToInt32(os);

                db.T_OsParceiro.Add(pdv);==>> Aqui dá o erro
                db.SaveChanges();
            }

Esse é o erro:
The best overloaded method match for 'System.Data.Entity.DbSet<V99SuporteTecnico.Models.T_OsParceiro>.Add(V99SuporteTecnico.Models.T_OsParceiro)' has some invalid arguments

Quais os argumentos inválidos?
Minha classe está ssim:
[Table(Name = "T_TarefaParceiro")]
    public class PDVOsParceiro
    {
        [Column]
        [DataMember]
        public int IDTarefaParceiro { get; set; }
        [Column]
        [DataMember]
        public int OS { get; set; }
        [Column]
        [DataMember]
        public DateTime DataAberturaOs { get; set; }
        [Column]
        [DataMember]
        public string CNPJ { get; set; }
...............

É isso mesmo ou não?
Comment: Precisaria conhecer sua classe que declara o que é o membro `T_OsParceiro` de `db` e verificar o que o método `Add` está esperando. Existe lá algum método que espera um tipo `PDVOsParceiro`? Se não existe, ou precisa criar ou ver se pode passar um elemento de outro tipo ou ainda ver se é possível fazer um *cast* para o tipo esperado, o que me parece pouco provável.
Answer: A mensagem diz tudo.
O contexto espera um T_OsParceiro. Você está passando um PDVOsParceiro. O correto seria:
    public int abreOsParceiro(string os, string cnpj, string dataAbertura, string dataVisita, string tecnico)
    {
         WEBEntities db = new WEBEntities();
        T_OsParceiropdv = new T_OsParceiro();
        List<string> lista = new List<string>();

        try
        {
            /* Aqui não sei se o tipo T_OsParceiro tem os mesmos campos de PDVOsParceiro, mas a ideia é que ele seja preenchido neste ponto */

            db.T_OsParceiro.Add(pdv);
            db.SaveChanges();
        }
    }

Não consigo inserir no BD com entity


Titanium : Camera crashes the application

Question: I am using Titanium sdk's openCamera function to capture an image and storing it to sdcard.
function captureImage() {
        var capturedImg;
        Titanium.Media.showCamera({
            success : function(event) {
                /* Holds the captured image */
                capturedImg = event.media;

                /* Condition to check the selected media */
                if (event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO) {
                        var window1 = Project.AddDocumentSaveView.init(capturedImg, docImgModel);
                        window1.oldWindow = win;
                        Project.UI.Common.CommonViews.addWindowToTabGroup(window1);
                        activityInd.hide();

             }
            },
            cancel : function() {

            },
            error : function(error) {
                /* called when there's an error */
                var a = Titanium.UI.createAlertDialog({
                    titleid : Project.StringConstant.IMP_DOCS_CAMERA
                });

                if (error.code == Titanium.Media.NO_CAMERA) {
                    a.setMessage(Project.StringConstant.IMP_DOCS_ERROR_WITH_CAMERA);
                } else {
                    a.setMessage(Project.StringConstant.UNEXPECTED_ERROR + error.message);
                }

                a.show();
        }
        });
    }

It works fine in iphone and even samsung galaxy s2. But on one device, Motorola Milestone device, the application crashes when the picture is accepted after capturing.
Here is the log while the device was attached : Log for camera crash
I tried so many times but couldnt find the issue .I think its some memory issue but i am not sure.
Could someone look into it and help me find what the issue is.
Any help/suggestions will be appreciated.
Thanks
Comment: This issue still exists - at least on my Samsung S3 and Moto G (2nd Gen). There a lots of Jira issues about it but no real solution. Did you manage to use the camera reliably?
Answer: everything in this block should be done after the camera is close
if (event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO) {
}

the camera is memory intensive and you are opening new windows and doing a bunch of other stuff... not good.
Comment: Hey Aaron,
thanks for suggestion... i will try to implement it ...
but m just curious .. are you just suggesting the for the cleanness of the code ...or as a solution to the problem ..
Answer: This is an aging issue on Titanium (TIMOB-12848
On some devices the native camera app (Titanium calls it using an Intent) cause Android to destroy our app.
When it tries to restart it, there's no recovering of the previous state so the intent callback is not called.
I've found a simple workaround to minimize this issue but doesn't resolve it. It just "mask" it somehow.
The workaround is discussed in the previous link and the full example code is here


How can I simplify the use of flags with Views Bulk Operations?

Question: I have an administrative display (made with views) that lists content that is pending approval.
In the case of my site, approval means flagging with the approval_for_pub flag (which triggers a custom rule).
VBO allows nodes to be flagged/unflagged all at once by clicking a handy button:

However, upon clicking this button, by default it shows all possible flags and the flag/unflag option:

This is a problem on my site because some of the people responsible for approval get confused by the names of the flags and select the wrong option.  So, what I would like to do is create a VBO option that, when the button is pressed, automatically flags all applicable content with the approval_for_pub flag.
How can I approach this?
It seems like a small detail, but this step happens several times a day, so the chance of making a mistake is quite high.
Answer: Instead of using the "Flag (or unflag) a node" action directly, create new a rules component and show it in your administrative view.

Navigate to Configuration » Workflow » Rules » Components
Click on Add new component , choose Rule from the components plugin drop-down menu.
Choose a name (e.g. Approve), add a parameter with the type node.
Add a condition, choose Node is flagged from the drop-down menu.
Choose the appropriate flag, select the node-parameter for the node, choose site:current-user for the user on whose behalf the flagging-action will be performed, select negate such that the condition will evaluate to true when the node is not flagged.
Add an action, choose Flag a node from the drop-down menu.
Choose the appropriate flag, select the node-parameter for the node, choose site:current-user for the user on whose behalf the flagging-action will be performed.

Edit your administrative view, configure bulk operations such that the Approve operation is shown instead of the Flag (or unflag) a node
Comment: Great solution!  I have used Rules for VBO before but it didn't occur to me that I could apply it in this case as well.


What is a duplex

Question: In this article Surface Topology in Bach Canons, I: The Möbius strip the author wrote that

Canon 5 is described by Bach as a duplex, a 4: there are 4 voices singing two canons in parallel.

Could you please explain for me what is a duplex? And what is a 4?
Please help me.
Thanks
Comment: You quoted the definition of *duplex*: "*there are 4 voices singing two canons in parallel.*"
Comment: @Knumber10: No, *a 4* simply means any four-voices piece. It could be instrumental, sung or anything and it definitely does not need to be a canon, let alone two.
Comment: So a 4 is also defined by 4 voices singing two canons in parallel?
Answer: duplex: just as in duplex apartment means there are two floors, here it means there are two voices/tracks to sing, probably a deeper one and a higher one.
a 4: in French and Italian (and probably latin ?), this is how you would say with 4 people. For instance, to play (a game, music, ...) with 4 people would translate to jouer à 4 in French. So it really just means 4 people are singing.
In the end the definition of duplex a 4 is exactly what you wrote: there are 4 voices singing two canons in parallel.
EDIT: 4 people re singing in total if it's a 4. Then if it's duplex you just group those people onto different voices.
Comment: In my opinion it is still to undefined, how the grouping is: duplex (canon à 4) which means we have 4 voices per canon and so 8 voices in total, or (duplex canon) à 4 (four voices grouped into two canons).
Comment: duplex a 4 would means there are 4 people singing in total. Which are then grouped onto two voices. Though the grouping is not defined, so it doesn't say it's two and two people, I guess you could still call a canon with 3 and 1 persons singing on each voice a duplex canon a 4
Comment: Accepted for the the given example, difficult to generalize. I want to point out  however, that *4 voices canon* neither means, that someone sings at all, nor that each voice is only performed by one player/singer.
Answer: The phrase "duplex, a 4" is italicized, which leads me to believe it is a phrase from a different language rather than being a pair of separate terms. Looking at other places on that web page, I see there is at least one other case of italicized text in Latin ("motu recto et contrario") referring to Bach's descriptions. The phrase "duplex, a 4" could be translated from Latin as "double, from 4" or "two-fold, from 4."
When interpreted as "two canons from 4 voices," this properly matches the source text's explanation of "4 voices singing two canons in parallel."
Comment: @Knumber10 Two canons sung by four voices.  Two voices for each canon, as per the following sentence at your link.  "Canon simplex à 3 voci" would be one canon with three voices, as another example.  [Here's a visualization of a canon triplex à 6](https://www.youtube.com/watch?v=CmzDIE3onAk) which should help; you can clearly see three pairs of voices.
Comment: Translating "a" as "by" would probably make the most sense, given the latter half of the quote.
Comment: even that, what does "from 4" mean? I mean by 4 should be understood from 4 voices right?

What is a duplex


Is there any dataset that contains eye class for YOLO?

Question: I'm looking for something that can help me with detection of eye via YOLO method. Is it even possible? Saw that COCO and pascal VOC datasets are wide but there's lack of eye class. Is there any dataset or something that could help me with such detection?
Comment: SO isn't really the proper forum for this type of question. Questions about software recommendations are off topic.
Answer: You can manually train for custom classes. If you have GPU you can use or else use Google Colab.
Here is the link for tutorial
<code>https://youtu.be/GRtgLlwxpc4
</code>


Get current user password before it is overwritten in user form?

Question: I know this is probably unlikely, but I am doing the diligence anyway.
Is there any way to get the current user password from Drupal before updating it with a new one on the user form (user editing account info)?
When it is updated, I would like to trigger an API call to a remote system and update the account password there, too (authentication happens on an external system). However, the API call requires the old password as well as the new one before it will update it.
Otherwise, I need to lock off any way of updating a password in Drupal from privileged users.
Comment: the password is stored in a hash (salted to make it harder to guess), so no chance
Comment: Yep. Had to ask.
Comment: But you could to the same as the remote system, ask the user to provide the old password and check it against the stored hash, before allowing a password change.
Comment: Yeah, I could do that perhaps. I already augmented the user auth process to authenticate to the external system, even if the account exists in Drupal - if they validate then it overwrites the stored Drupal password and saves anyway. That helps in cases where they change it remotely, then come back... but not if say, an admin goes in and changes a user password.
Answer: Yes you can. The password only gets hashed when the user entity is saved as part of PasswordItem::preSave().
So you can add a submit handler to the user form, fetch both the old password and the new password (as users are required to enter both usually*) and do what you want with it.
There are discussions about that being insecure, so it is possible that this will change in the future.

There are exceptions to this, for example after using a one time login link, users are allowed to change their password without providing the current one.


For-loop index iteration over date vector

Question: I know this is probably a stupid question but why do I need to start from 2 instead of one to get this list to loop properly?
date <- seq(as.Date("2021-01-01"), as.Date("2021-12-31"), by="months")
num <- length(date)

for(i in 2:num-1){
    print(paste0("i = ",i))
  j = i+1
 sd <- date[i]
 ed <- date[i+1]
    print(paste0("start: ",sd))
    print(paste0("end: ",ed))
    }

Output:
[1] "i = 1"
[1] "start: 2021-05-01"
[1] "end: 2021-06-01"
[1] "i = 2"
[1] "start: 2021-06-01"
[1] "end: 2021-07-01"
[1] "i = 3"
[1] "start: 2021-07-01"
[1] "end: 2021-08-01"
[1] "i = 4"
[1] "start: 2021-08-01"
[1] "end: 2021-09-01"
[1] "i = 5"
[1] "start: 2021-09-01"
[1] "end: 2021-10-01"
But when I start with: for(i in 1:num-1)
It doesn't find the first indexed item properly:
[1] "i = 0"
[1] "start: "
[1] "end: 2021-05-01"
[1] "i = 1"
[1] "start: 2021-05-01"
[1] "end: 2021-06-01"
[1] "i = 2"
[1] "start: 2021-06-01"
[1] "end: 2021-07-01"
[1] "i = 3"
[1] "start: 2021-07-01"
[1] "end: 2021-08-01"
[1] "i = 4"
[1] "start: 2021-08-01"
[1] "end: 2021-09-01"
[1] "i = 5"
[1] "start: 2021-09-01"
[1] "end: 2021-10-01"
Comment: Try this `1:(num-1)`
Comment: Well, you haven't described what "proper" execution of the loop might be, but I think it would be informative to compare the results of what you have to those when you define the  loop as `for(i in 1:(num-1))`.  Clue: operator precendence.
Comment: Section 8.1.3 of the R Inferno: https://www.burns-stat.com/pages/Tutor/R_inferno.pdf
Comment: @AndreWildberg I think that was it! Didn't realize the order of operations was that way.
Answer: Ok So thanks to Andre Wildberg in the comments, I didn't realize there was an implied order of operations within the counter. So this was what worked, using parenthesis to make explicit the desired order of operations:
1:(num-1)
instead of
1:num-1


Data-binding between ngInclude and ngView

Question: I want to make a sidebar with list item that can be dynamically changed based on the settings page.
My app request settings.json via factory() and then called it in a controller. The controller will be used by settings.html (ngView) and sidebar.html (ngInclude).
The json will return Boolean value that also can be changed on setting page that contain checkbox which return true if check and false if not checked. I use ngShow on the sidebar to display/hide the list items.
How can I made the sidebar to reflect the changes as I tick the checkbox?
settings.factory.js
var settingsFactory = angular.module('settingsFactory', []);

settingsFactory.factory('SettingsFilterFactory', ['$http', function ($http) {

    var settingsFactory = {};

    settingsFactory.getSettings = function () {
        return $http.get('app/data/settings.json');
    };

    return settingsFactory;
}]);

controller
var settingsControllers = angular.module('settingsControllers', ['settingsFactory']);

settingsControllers.controller('SettingsFilterController', ['$scope', '$http', 'SettingsFilterFactory', function ($scope, $http, SettingsFilterFactory) {

    $scope.settings;
    $scope.status;

    getSettings();

    function getSettings() {
        SettingsFilterFactory.getSettings()
            .then(function (response) {
                $scope.settings = response.data;
            }, function (error) {
                $scope.status = 'Unable to load: ' + error.message;
            });
    }
}]);

app.js
var app = angular.module('app', ['ngRoute', 'settingsControllers']);
app.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.
    when('/settings', {
        title: 'Settings',
        templateUrl: 'app/components/settings/settings.html',
        controller: 'SettingsFilterController'
    }).
    otherwise({
        redirectTo: '/home'
    });
}]);

My index.html is something like this:
...

...

sidebar.html

This is secret link

settings.html
...

    <input type="checkbox" ng-model="settings.hiddenMenu" ng-true-value=true ng-false-value=false> Check this to show hidden menu

...

Comment: there are essentially 4 ways to accomplish what you are trying to do, and each has positives and negatives.  1) use a property on the `Settings` factory that each controller can see.  2) use `$scope.$broadcast` or `$emit`.  3) wrap the entire body in another controller 4) use `$rootScope`.  I ordered these approximately in my preference order.
Comment: it's not really clear what your complete setup is (you haven't shown the router that populates the `ng-route`), but from what you have provided, it *appears* that you are trying to use the same controller in two places.  Each time you declare the controller, you will get a new instance of the controller (they are not singletons).  changes in one instance of the controller won't be reflected in the other instance.  It is therefore not recommended to ever re-use a controller, if possible.
Comment: @Claies yes you're right. I re-use the same controller. So what is the correct way to write a singleton, or do I really need a singleton in this case? So reusing controller for different view is very bad practice in AngularJS?
Comment: @Claies I will explore more on the suggestions you provided. Basically, I manage to use `$rootScope` but I think it is a bad choice since I have a lot of sidebar list items. And also I'm not sure how to declare the $rootScope based on the json request.
Comment: in general, `$rootScope` is only useful because it can be convenient.  This is not really what `$rootScope` is designed for, and using it because it is easy can lead to unexpected code complexity.  The best way to accomplish this is with properties on a service that can be injected into each controller, and into the sidebar.
Answer: Try something like this (untested):
settings.factory.js
var settingsFactory = angular.module('settingsFactory', []);

settingsFactory.factory('SettingsFilterFactory', ['$http', function ($http) {

    var settingsFactory = {};

    settingsFactory.getSettings = function () {
        return $http.get('app/data/settings.json');
    };

    settingsFactory.hiddenMenu= true;
    settingsFactory.someOtherSetting = {};

    return settingsFactory;
}]);

sidebar controller
settingsControllers.controller('SidebarController', ['$scope', '$http', 'SettingsFilterFactory', function ($scope, $http, SettingsFilterFactory) {
  //do this in each controller, so that the factory becomes a property of $scope and can be seen in the HTML
  $scope.settingsFactory = SettingsFilterFactory;
}

sidebar.html

This is secret link

settings.html
...

  <input type="checkbox" ng-model="settingsFactory.hiddenMenu" ng-true-value=true ng-false-value=false> Check this to show hidden menu

...

Essentially, you are binding the settingsFactory object which is a singleton to each $scope that is provided by each controller.  Each controller is able to change the property on the factory object, which is then visible in all other controllers that have injected this object.
Comment: @FaizFizyRosle singleton is a generic programming pattern;  loosely, it means that a class is restricted to only creating one instance object.  Angular Dependency Injection uses the singleton pattern to ensure that no matter how many times you inject a provider, you always get the same object.  Controllers aren't providers, and aren't injected into anything else, so they don't fall under this pattern, though the providers injected into them are.
Comment: Yeah, it works. I guess I have to move the $http to the factory() in order to get the value from backend.
Comment: Thank you so much @Claies Is this actually called singleton in AngularJS? Or this concept has different name. Might explore into it for further understanding. Thanks again for your time and help. Really appreciate it. :)


Linear regression model with 2 categorical variables

Question: Let's consider the following problem : We want to predict a variable $y$ and we have two categorical variables : $A$ that can take 3 different values and $B$ than can take 2 different values.
A regression model with interaction would be  :
$$y = \sum_{k=1}^{3}\alpha_k\mathbb{1}_{A_k}+\sum_{k=1}^{2}\beta_k\mathbb{1}_{B_k}+\sum_{i,j}\gamma_{ij}\mathbb{1}_{A_iB_j}$$
Another equivalent formulation :
$$y = \mu +\sum_{k=1}^{3}\hat{\alpha_k}\mathbb{1}_{A_k}+\sum_{k=1}^{2}\hat{\beta_k}\mathbb{1}_{B_k}+\sum_{i,j}\hat{\gamma_{ij}}\mathbb{1}_{A_iB_j}$$
In the second formulation, do we have a "meaning" for $\mu$ ? Is it the mean of $y$ across all categories ? Is there any advantage of using one formula over the other in this setting ?
Also, if we consider's R output, which doesn't keep the first category for each variable, how would we interpret its intercept coefficient ?
Answer: The issue with your formulations is that different coefficients would give the same answers.  For example in the first expression you could add a constant $c$ to all the $\alpha_k$ and subtract the same $c$ from all the $\beta_k$ and get the same $y$, or in the second add $c$ to $\mu$ and subtract the same $c$ from all the $\hat{\beta}_k$
To give you an answer, R has used this property to set $\hat{\alpha}_1$ and $\hat{\beta}_1$ and all the $\hat{\gamma}_{1n}$ and $\hat{\gamma}_{m1}$ to zero, and this can allow a unique solution
In this case, the intercept $\mu$ is the intercept (or since you have no numerical independent variables, the predicted value) when the independent variables correspond to the first values of the factors.  As an illustration, consider this toy example:
mydf <- data.frame( a=c("F","F","F","G","G","G","H","H","H","H"),
                    b=c("S","S","T","S","T","T","S","S","T","T"),
                    y=c( 1 , 3 , 5 , 3 , 6,  8,  3 , 5 , 4,  6 ))
fit <- lm(y ~ a * b, data=mydf)

to give
> fit

Call:
lm(formula = y ~ a * b, data = mydf)

Coefficients:
(Intercept)           aG           aH           bT        aG:bT        aH:bT
          2            1            2            3            1           -2

The intercept of $2$ corresponds to the prediction when $a$ is "F" and $b$ is "S".  It is in fact the average of the first two $y$ values in the dataframe of $1$ and $3$, as you might intuitively expect.  Then for example

when you add the bT value of $3$ to the intercept to get $5$ you have the third value in the dataframe, the prediction when $a$ is "F" and $b$ is "T"
when you add the aG value of $1$ to the intercept to get $3$ you have the fourth value in the dataframe, the prediction when $a$ is "G" and $b$ is "S"
when you add the aG, bT and aG:bT values to the intercept to get $7$ you have the average of the fifth and sixth values in the dataframe, the prediction when $a$ is "G" and $b$ is "T"


Como usar AJAX em muitas Camadas?

Question: Estou Estudando DDD Tenho uma aplicação com 4 camadas sendo elas

Apresentação
Aplicação
Domínio
Infra

Na camada de apresentação busco dados via Ajax No DB, mas tenho uma duvida quanto a forma de fazer. Eu preciso fazer o ajax passar por todas as as camadas ? O que tenho percebido uma perda de performance na aplicação... Caso não, qual a melhor forma pra fazer ?
Answer: A maioria das vezes não é necessário, e nem recomendado usar essa arquitetura com      asp.net-mvc. Pelo contrário. Muitas vezes você está apenas complicando uma coisa simples, sem necessidade. Isso já foi comentado aqui algumas vezes, como nas perguntas/respostas abaixo:

Quando usar Entity Framework com Repository Pattern?
Entity Framework DDD Infra repositório Genérico
3 camadas vs MVC
Como implementar o Padrão Repository no C# com EF?

Mas, se mesmo assim você ainda quiser continuar com essa estrutura, você deve fazer exatamente dessa forma.
A requisição Ajax chamará uma Action em seu controller e ele passará os dados para as demais camadas.
Com relação a perca de performance, provavelmente não é somente a estrutura, e sim algo em seu código.
Comment: Para indicar uma forma mas performática, existe inúmeras formas, mas para isso é necessário saber o seu contexto ou como está fazendo, para verificar onde "possui erros".

Como usar AJAX em muitas Camadas?


System not being able to handle soft interrupts but having idle time?

Question: I have a constant 5% and more CPU time spent in handling soft interrupts. Doe to that, the ksoftirqd is running almost constantly, but is using a very small amount of CPU (less than 1%).
However, regardless of this heavy load there is still a fairly high percentage of idle time (30% and more)(this is the top value for idle, or the idle from mpstat).
Some background (However, I would like a conceptual answer, not one that solves the problem on my system). The system is used for routing (echo 1 > /proc/sys/net/ipv4/ip_forward) and NAT with iptables, and runs additional user space application not related to networking. Also, the load average is always above 1 (it's a single core processor)(this is the value Load average from top, or the output of sar -q).
What is preventing the system to use the idle time to prevent the handling of soft interrupts from being missed?
I would expect to see the idle time (id in top) be used for serving software interrupts (si in top) and not have the processor miss tasks and be idle at the same time.
Comment: At the risk of being dismissive of your question, I want to clarify: ksoftirqd doesn't indicate that soft IRQs are being missed, it indicates that soft IRQs are happening often.  In fact, ksoftirqd running is an indication that soft IRQs are **not** being missed!
Comment: We're missing basic information here: OS, version, kernel, distribution, platform, physical/virtual?, application. Also, what results do you *expect*?
Comment: @ewwhite I've added the expectations, that's the main thing I'd like to have explained. The server is not a standard one, it's running a custom distribution with the 3.14. kernel. I've dropped that because I'm interested in the conceptual answer not.
Comment: You write about missed soft Interrupts. Why "soft" and where do you see something is being missed?
Comment: @Nils Based on the existence of ksoftirqd. http://www.ms.sapientia.ro/~lszabo/unix_linux_hejprogramozas/man_en/htmlman9/ksoftirqd.9.html
Answer: There is no heavy load on your system.
The interrupts are handled correctly, just as your routing and your application. If it weren't so, your system didn't have 30% idle. (Anyways, where do you see that?)
Using a small system to many different things simultanously doesn't always mean an overload, especially if there is not too many data to NAT. If your network interfaces are working with DMA (which is very probable), then your interrupt handlers aren't even doing a single block copy in current kernels.
Next to that, you are loading your system very differently (while your network card chip is talking with the dma, your application can work).
The only major problem could be in your system the big ratio of the task switches. It is the major problem of the similar, single core, multipurpose, wonderful servers. But in your case it caused a heavy system load, which doesn't happen.
I were happy to extend this answer if you would explain, where is this "30% idle" thing is coming from. You say, the system load is always over 1.
Comment: The `idle` is the percentage `%id` in top and system load is `load average` in top.


bash script – MySQL commands and variables

Question: I have a bash script who automate a Nextcloud server installation.
To run MySQL commands I use the mysql -e command
user@hostname:~$ mysql -e "CREATE DATABASE 'NextcloudDataBaseName'"

I would like store db name, user name, password, etc. In variables
How write mysql -e commands with variables ?
user@hostname:~$ mysql -e "CREATE USER '$UserName'@'localhost' IDENTIFIED BY '$UserPass'"

user@hostname:~$ mysql -e "CREATE USER ${UserName}@'localhost' IDENTIFIED BY ${UserPass}"

The two command above don't run
Error message with user password (test password) :
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'qwerty1234'

This syntax seems to work :
user@hostname:~$ mysql -e "CREATE USER '${DbUserName}'@'localhost' IDENTIFIED BY '${DbUserPass}'"

Simple quotes around variable names but is this the best syntax, the best practice ?
Thanks :-)
Comment: BEWARE:  If there is a quite in the password, bash will give you a syntax error.
Answer: Like this (with here-doc):
mysql<<EOF
CREATE USER '$UserName'@'localhost' IDENTIFIED BY '$UserPass';
EOF

Learn how to quote properly in shell, it's very important :

"Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words
Comment: Thanks Gilles everything works with Here Doc.

Merci beaucoup tout fonctionne avec Here Doc et c'est plus propre !


No messages transferred to Dominoserver?

Question: We have two Lotus Domino servers, both running latest version 8.5.3.
in one of the servers we get the below messages on the server console all the time.
We have no problems with mail routing, evrything is working fine, but I want to get rid of these messages from the console/log.

2012-02-16 03:02:39   Router: No messages transferred to
  DOMINOSERVERUS/ACME via Notes 2012-02-16 03:02:42   Router: No
  messages transferred to DOMINOSERVERUS/ACME via Notes 2012-02-16
  03:02:45   Router: No messages transferred to DOMINOSERVERUS/ACME via
  Notes 2012-02-16 03:02:47   Router: No messages transferred to
  DOMINOSERVERUS/ACME via Notes 2012-02-16 03:02:50   Router: No
  messages transferred to DOMINOSERVERUS/ACME via Notes 2012-02-16
  03:03:43   Router: Successfully issued a request to push to
  DOMINOSERVERUS/ACME 2012-02-16 03:03:43   Router: Issuing a request to
  push to DOMINOSERVERUS/ACME 2012-02-16 03:03:43   Router: Transferring
  mail to DOMINOSERVERUS/ACME via Notes

any ideas?
Comment: This was a problem with Domino 5, which IBM fixed back then: https://www-304.ibm.com/support/docview.wss?uid=swg21086699

Have you tried debugging with DebugRouter=1|2|3 and/or Log_MailRouting=10|20|30|40 ?

Have you already opened a PMR with IBM?
Answer: this technote might explain it
Comment: I saw that technote, but it is old and does not apply to 8.5
Comment: I mentioned it because it might be the loglevel: http://publib.boulder.ibm.com/infocenter/domhelp/v8r0/index.jsp?topic=%2Fcom.ibm.help.domino.admin.doc%2FDOC%2FH_SELECTING_A_LOGGING_LEVEL_5289_OVER.html
Answer: I think that the notes.ini settings "LOG_DISABLE_SESSION_INFO=1" will disable these (and some other similar) console messages.
I can't test this easily at the moment, but I know it's part of my template for notes.ini settings. Along similar lines, I'd recommend LOG_SESSIONS=0 and LOG_REPLICATION=0.
Unfortunately Domino is still relatively chatty on the console log, but these remove most of the unnecessary stuff.
By the way - I believe that these messages are about Notes mail routing, rather than SMTP.