Disponibilizar PDF na versão mobile é prejudicar a experiência do usuário?

Question: Em um projeto em que participo desenvolvendo as camadas Front-End, me deparei com um possível problema prestes a finalizar a versão mobile do mesmo.
A tal proposta a ser questionada, está em um certo trecho do site, em que há uma disponibilidade do Cardápio em PDF ao visitante, proporcionando a impressão ou o possibilidade de efetuar o download do Documento.
Este PDF não é criado via script(PHP ou alguma LIB), é um documento estático  "uppado" pelo usuário/cliente.
Na versão desktop, a proposta talvez não prejudique tanto a experiencia, mesmo levando em consideração que o arquivo possa ter alguns Mega Bytes excessivos (foi feito por um Designer que exagerou um pouco na caneta digital).
Na versão mobile/tablets, é obvio que esses Mega Bytes comedores de DADOS além de possivelmente acabar com os "créditos, animo, paciência, (entre outras situações frustrantes) do usuário, uma versão mais "leve" deste Documento torna-se obrigação "socioeconômico"(e por que não?) dos detentores do projeto.
Mas ai vem a pergunta:
Será que mesmo que uma versão mais leve seja a solução coerente para o usuário Mobile?
Acredito que grande parte do público alvo que o Site/Projeto tenta atender já teve alguma experiência com o uso de documentos PDF alguma vez na vida, logo, em questão de uso, o usuário não se "perderia". Mas a pessoa que entra pelo Smartphone/Cel/Tablet deseja esse tipo de situação?
Particularmente eu não gosto muito de me deparar com PDF no Celular, mas e o "Povão", aceita isso? É convencionalmente uma boa ideia praticar isso?
Comment: Imagina um pdf de 3mb e um usuário que tem 10mb de pacote de dados para gastar, na minha opinião(que vale aqui nos comentarios :P) o ideal seria fazer um html especial/leve para mobile.
Comment: Apresentar cardápio em PDF pra consulta no navegador é ruim em qualquer dispositivo. Até em imagem fica menos desagradável. Se é um site, basta fazer em HTML, não? O PDF pode ser um mero link pra download, caso a pessoa queira ver offline.
Comment: Recentemente o Whats up liberou o envio de arquivos PDF no aplicativo. Muita gente pode usar a versão com WiFi. Acho válido você dar uma amostra pro usuário com os dados simplificados e perguntar antes se ele quer gerar o PDF completo com diversos megas, estimando mais ou menos o tamanho do arquivo. Assim ele decide o que é melhor pra ele.
Answer: Primeiramente, vamos entender bem o objetivo do usuário nesse contexto de tarefa. Pelo que eu entendi (você não descreveu detalhes da aplicação), o usuário está acessando o site do restaurante e deseja simplesmente acessar o cardápio. Mas você não ofereceu informações essenciais, tais como: o cardápio é do dia? ou seria um cardápio fixo?
Essas informações podem mudar completamente a nossa percepção (como projetistas) de que algo é mais fácil ou difícil de prejudicar a experiência do usuário. Quer ver?
Cenário 1: Baixando PDF
Suponha que o cardápio é fixo. Isto é, ele é completo (tem todas as opções oferecidas pelo restaurante) e não muda com muita frequência (e, por isso, provavelmente não inclui os valores das opções oferecidas). Nesse caso, não há tanto mal em permitir que o usuário baixe o cardápio mesmo sendo um PDF grande. Se o tamanho do arquivo for informado claramente antes do download (um critério importante de usabilidade é a clareza das informações), o usuário pode decidir por baixar o PDF em casa em seu Wifi. Se ele também souber previamente que o cardápio é completo, ele pode mesmo assim decidir por baixar o PDF usando seu acesso móvel (e pagando o custo relacionado), pois deseja o cardápio e sabe que uma vez baixado não precisará fazê-lo novamente (pois o PDF já estará no dispositivo, facilmente acessível).
Nesse caso, a usabilidade da leitura do cardápio fica em parte por conta do designer (e, convenhamos, um cardápio bem feito é atraente e produz inúmeras outras vantagens hedônicas para o negócio) e em parte pelo leitor de PDF usado pelo cliente, que você simplesmente não tem controle.
Se, por outro lado, o cardápio não é fixo ou não tem tudo o que é oferecido (por exemplo, ele muda todos os dias, todas as semanas), é terrivelmente ruim para o usuário ter que baixar vários PDFs diferentes. Não somente pelo custo de transmissão, mas pelo gerenciamento que isso requer. Nesse caso, esse cenário não é mesmo interessante (e eu diria que também não é interessante para um acesso via Desktop!).
Cenário 2: Acesso Dinâmico
Suponha então que o cardápio não é fixo. Nesse cenário, o cliente abre o site do restaurante e o sistema apresenta imediatamente os dados do cardápio do dia (ou do momento desejado pelo cliente). Talvez seja mais difícil permitir que o dono do restaurante mude facilmente as informações ali contidas (afinal, usando PDF o cara pode simplesmente ir no Word, fazer um cardápio qualquer e gerar em PDF para colocar no site), mas por outro lado o acesso é centralizado e retira do usuário (o cliente do restaurante) qualquer necessidade de precisar ele mesmo gerenciar os possíveis cardápios que vão ser gerados ao longo do tempo.
Um design bonito e agradável continua igualmente importante para o engajamento do cliente do restaurante. E se você parar pra pensar, os custos de transmissão/download envolvidos não vão mudar tanto assim, pois as imagens, layout e textos coloridos que seriam baixados em um PDF são agora diretamente transmitidos no HTML. Mas o conteúdo é essencialmente o mesmo! Isto é, o seu designer pode ter também uma mão pesada na caneta tinteiro digital fazendo os CSS's! rs
Assim, esse cenário tende a ser melhor para a experiência porque o usuário tem a sensação de que o acesso é centralizado e facilitado, e de que a informação é garantidamente atualizada. Além de que ele não precisa ter o esforço cognitivo de saber onde raios ele baixou o último PDF do cardápio da segunda-feira.
Cenário 3: O Melhor dos Dois Mundos
Talvez o restaurante não tenha um cardápio realmente muito variável. Mas isso não quer dizer que ele não mude, que promoções eventuais não ocorram. E ainda assim você deseja (acredite em mim, vc deseja! rs) que o cliente do restaurante não tenha trabalho algum em lembrar onde acessar a informação que ele precisa. Então, uma abordagem em que você pode ter o melhor dos dois cenários anteriores é construindo tanto um site como um aplicativo para ser instalado no dispositivo móvel do cliente.
É verdade que a percepção do cliente a respeito da "necessidade" de instalar mais um aplicativo é complexa. Mas ela decorre exatamente da importância do conteúdo pra ele. Se o usuário acessa o cardápio uma vez, talvez seja porque esteja interessado em conhecer o restaurante. Mas se acessa frequentemente, é porque já gosta de comer lá e quer só saber o que tem pra janta hoje. Idealmente a sua solução deveria contar com o site para facilitar o acesso casual do primeiro tipo de usuário, e um aplicativo para facilitar o acesso do segundo.
O site simplesmente exibiria o cardápio tal como o faz na Web. Poderia até ser em um PDF, se ele pudesse ser exibido diretamente no navegador sem precisar ser baixado para uma pasta qualquer (isto é, o usuário só enxerga o conteúdo - o sistema operacional faz o download em uma pasta temporária). Afinal, lembre-se: estou considerando esse acesso móvel como de interesse inicial, casual.
O aplicativo, instalado pelo usuário menos casual e já frequentador assíduo do restaurante, também requer uma conexão com a Internet para baixar os dados. Mas o fato de ser um aplicativo local te permite construir um sistema de cache, em que você armazena o cardápio mais recente no dispositivo e apenas atualiza-o quando necessário (por um esquema de push, talvez, já que você pode até mesmo exibir promoções pontuais dessa forma).
A decisão por construir ou não um aplicativo é polêmica, principalmente do ponto de vista do dono do restaurante (que vai ter que pagar o dobro). Mas a minha experiência me diz que faz todo o sentido construir algo assim quando há realmente algum ganho para o usuário, como me parece ser o caso do seu cenário. Nele há ganho no cache do cardápio e no fato de que o usuário não precisa saber onde tal informação fica armazenada para ter a parcepção de que ela é atual.
Comment: Primeiramente, obrigado,muito obrigado mesmo!
Ok, sobre os Cenários, desculpe o pobre detalhamento a respeito da minha situação.
Acredito que o Cenário 1 é o mais próximo da realidade(investimento) do cliente, já que o projeto do cenário 3 não seria possível[que ao meu ver é o melhor]. Como a escolha dos cenários não são baseadas apenas em poder aquisitivo, mas sim no melhor encadeamento nas decisões do projeto, tenho expor melhor os dados essenciais como, tamanho do arquivo, frequência de mudança e se possível uma versão prévia em HTML, como havia recomendado para adequar melhor o projeto.
Comment: Por nada. Talvez você possa fazer os dois no cenário 1. Isto é, ofereça uma página HTML para acesso online das informações, e *também* um link para o PDF (claro, indicando informações como o tamanho do arquivo e preferencialmente tendo dentro dele a data da atualização). Um usuário que *preferir* baixar o PDF, vai ficar feliz em ter acesso offiline às informações.
Comment: Bom, talvez essa seja a única lanchonete disponível na escola e por pior que seja a experiência os usuários vão usar assim mesmo (por falta de alternativa). Mas, mesmo assim, eu diria pra vc analisar bem quem são os usuários. São só os pais, ou os pais *e também* os alunos? Todos esses potenciais usuários lidam bem com o download de PDFs no celular? Isto é, eles sabem fazer o download e depois acessar novamente o PDF já gravado no disco? Porque se não souberem, vão acessar tal como fariam com uma página HTML (baixando-toda-santa-vez). E ai, o propósito de usar PDF se perde. Enfim, cuidado.
Comment: O projeto trata-se de uma lanchonete escolar que além da prestação convencional atendendo os alunos da instituição(tá ai o uso do cardápio), atende a Buffets e encomendas, delivery de almoço, além das certificações de padrão de qualidade da cozinha e nutrição. Dentre os objetivos e público-alvo, foi projetado este espaço para pais e alunos acessarem diariamente. Está mais do que na hora de começar a participar nas projeções do layout. rsrs


How fast SQOOP can transfer from RDBMS to Hadoop?

Question: Can someone tell me, how fast SQOOP can transfer 2 billion record in one time. And i know it must be fast because sqoop run in parallel, where some inputs will be produced also some file Output on Hadoop. but I want to know the details of the speed MapReduce transfer amount of 2 billion records in one time.
Comment: It depends upon number of mappers assigned for that job. So for example , if standalone(single) process taking 4 minutes to transfer the data, Sqoop with 4 mappers will take less than 1 min.
Answer: You need to understand the points responsible for faster transfer of data from RDBMS to Hadoop.

Number of Mappers:
Increasing the number of mappers will increase your speed because it divides the task in parts and performs import parallelly.

Balanced load on Mappers:
You need to split on a column that is uniform (prefer integer). It will give balanced load to all the mappers and transfer is faster.

Number of connection from RDBMS:
You can not just blindly increase the number of mappers (like 100 or more). Your RDBMS should allow these concurrent connections otherwise it will be a bottleneck from RDBMS side.

Use <code>--Direct</code> mode:
If direct connector is provided by sqoop for a particular RDBMS, you should use it. It will make transfer faster.

In a nutshell, sqoop is faster enough to tranfer billions of record just keep these points in your mind while writing import command.
Comment: @MaxNevermind I agree with you. you can another answer mentioning other points..:)
Comment: You did't point out the network and RDMS itself as limiting factors, we(this is a real life example) have a remote cluster and it has only limited bandwidth, as a result it caps the maximum transfer speed and nothing of what you pointed out is going to help with that. RDMS also matters, is it a single node system or distributed one, how heavily is it loaded?


Speeding up monte carlo code in python

Question: Consider points Y given in increasing order from [0,T). We are to consider these points as lying on a circle of circumference T. Now consider points X also from [0,T) and also lying on a circle of circumference T.
We say the distance between X and Y is the sum of the absolute distance between the each point in X and its closest point in Y recalling that both are considered to be lying in a circle. Write this distance as Delta(X, Y).
I am trying to find a quick way of approximating the distributions of distance between the circles over all possible rotations of X.  I am currently does this by Monte Carlo simulation. First here is my code to make some fake data.
import random
import numpy as np
from bisect import bisect_left

def simul(rate, T):
    time = np.random.exponential(rate)
    times = [0]
    newtime = times[-1]+time
    while (newtime < T):
        times.append(newtime)
        newtime = newtime+np.random.exponential(rate)
    return times[1:]

Now the code the find the distance between two circles.
def takeClosest(myList, myNumber, T):
    """
    Assumes myList is sorted. Returns closest value to myNumber in a circle of circumference T.

    If two numbers are equally close, return the smallest number.
    """
    pos = bisect_left(myList, myNumber)
    if (pos == 0 and myList[pos] != myNumber):
        before = myList[pos - 1] - T
        after = myList[0]
    elif (pos == len(myList)):
        before = myList[pos-1]
        after = myList[0] + T
    else:
        before = myList[pos - 1]
        after = myList[pos]
    if after - myNumber < myNumber - before:
        return after
    else:
        return before

def circle_dist(timesY, timesX):
    dist = 0
    for t in timesX:
        closest_number = takeClosest(timesY, t, T)
        dist += np.abs(closest_number - t)
    return dist

Now the main code to make the data and to try 1000 different random rotations.
T = 50000
timesX = simul(1, T)
timesY = simul(10, T)

dists=[]
iters = 100
for i in xrange(iters):
       offset = np.random.randint(0,T)
       timesX = [(t+offset) % T for t in timesX]
       dists.append(circle_dist(timesY, timesX))

We can now print out any statistics we like of the distances. I am particularly interested in the variance.
print "Variance is ", np.var(dists)

Unfortunately I need to do this a lot and it takes around 16 seconds currently.  I find this a little surprising it is so slow. Any suggestions for how to speed it up gratefully received.

Edit 1. Reduced the number of iterations to 100 (the previous value didn't correspond to my timings correctly). This now takes around 16 seconds on my computer.
Edit 2. Fixed bug in takeClosest
Comment: [Code Review](https://codereview.stackexchange.com/) is more appropriate for these types of questions.
Comment: have you tried [numba](http://numba.pydata.org/)?
Comment: @Aprillion Thanks an interesting suggestion. Thank you. I was hoping their might be some python/numpy/scipy speed up before I went down that route as there is a problem with portability with numba.
Comment: First you have to profile your code to see which operations are taking the lasrgest time to execute.
Comment: hmm.. `circle_dist` is `O(n*logn)` and I don't see a way to make the algorithm any faster - but you can try making `times` a numpy array of floats instead of python array of dynamic types..
Comment: @rano - generally that would be a good advice, but there's only 1 nested loop in this code, what do you hope can be learned from profiling? perhaps if `bisect_left` is not implemented as an actual `O(logn)` binary search, but there's some mistake that makes it `O(n)`...
Comment: Unfortunately your code is not running. ```bisect_left``` and ```poisson_simul``` are undefined. (The latter is probably ```simul```. Oh and I found the first one: An import was missing.) For a quick code review it's always nice to copy/paste a piece of code and it just works.
Comment: @Falko Sorry about that. Fixed now I hope.
Comment: `takeClosest` doesn't appear to actually use `T`; is that intentional?
Comment: What kind of speedup are you looking for?  There are tricks, like saving attribute lookups in local variables, etc. but they will only get you so far..
Comment: @thebjorn If one could get a factor of 10 that would be great. In fact I only really want an estimate for the variance but I can't think of a faster way of getting it.
Comment: @KarlKnechtel That was left over from before I learned about using -1 as an index. Fixed. Thanks.
Comment: @KarlKnechtel good spot, `T` is actually required to compute the correct value of distance - the implementation in the question is not correct (see my edited answer).
Answer: EDIT: I've just noticed that performance optimization is a little premature, because the expression closest_number - t is not a valid implementation of any definition of a distance on a "circle" - that is only a distance on an open-ended line
sample test case (pseudocode):
T = 10
X = [1, 2]
Y = [9]
dist(X, Y) = dist(1, 9) + dist(2, 9)
dist_on_line   = 8 + 7 = 15
dist_on_circle = 2 + 3 = 5

Note that definition of the circle [0,10) implies that dist(0, 10) is not defined, but in the limit it approaches 0: lim(dist(0, t), t->10) = 0

A correct implementation of a distance on a circle would be:
dist_of_t = min(t - closest_number_before_t,
                closes_number_after_t - t,
                T - t + closes_number_before_t,
                T - closest_number_after_t + t)

Original answer:
you could rotate and iterate over timesY instead of timesX since that array is an order of magnitude smaller - doing bisect_left of timeX is negligible (O(logn)) compared to iterating over all the elements (O(n))
but IMHO, the real slowdown if because of Python dynamic typing (every of the ~50000 items in timesX has to be checked for type compatibility each time you try to compare it to some other value) => converting timesX and timesY to numpy arrays should help, if that is not enought CPU acceleration (cython, numba, ...) is the think you need
Comment: for the picture, I used Excel pie chart with 3 series `{3,3,4}, {1,1,1,1,1,1,1,1,1,1}, {4,2,4}` (the one that looks like doughnut can use multiple series), edited colors (white for the "transparent" parts), removed all labels, copied as picture and flip-flopped it around (so the area on top is continuous) and added labels manually
Comment: Great idea. Looks like the time improvement is about 90 % when switching the rates for ```timesX``` and ```timesY```. I'm not sure if there is any impact on the result. So it's up to the OP.
Comment: I am happy to switch to numpy arrays but I can't switch the order of comparison. You get a completely different answer.
Comment: Simply switching to timesX = np.array(simul(1, T))
timesY = np.array(simul(10, T)) **doubled** the time . Then changing from bisect_left to np.searchsorted increased the time by another 50% ... :(
Comment: I'm no expert in `numpy`, so I have no idea why that's slower than pure Python.. but if simply by switching the order you get a different results, the result you get cannot be defined as the `distance between X and Y` - at most, it could be "distance of X from Y", but not "between ... and ..." => are you sure you are implementing a correct definition of the distance??
Comment: ah, I found the problem with your distance implementation, see my edited answer.
Comment: You are quite right. I have hopefully fixed that now. It's not a formal distance function. As you say it's an asymmetric measure of similarity. I could make it symmetric by just doing X, Y and Y,X and summing them but I don't think that helps me.
Comment: How did you draw the lovely picture by the way?
Comment: OK I give in :) I managed to install numba. Any idea how to get my code to use it?
Answer: The function circle_dist can be replaced by a one-liner. So you can plug it into your outer for i loop:
sum(abs(takeClosest(timesY, t) - t) for t in timesX)

Furthermore, you should always - if possible - allocate arrays like dists in one step and avoid appending elements many thousand times.
But, unfortunately, both improvements only save a few percent of computing time.
Edit 1: Replacing np.abs(...) with abs(...) decreases computing time by 50 % on my machine (on a reduced data set)!
Edit 2: Updated the one-liner according to Aprillion's comment.
Comment: you could also replace the list comprehension `[]` by a generator `sum(np.abs...` to save some memory
Comment: @Aprillion: Oh you mean ```sum(abs(takeClosest(timesY, t) - t) for t in timesX)```? Cool. I wasn't aware of that this is possible. :)

Speeding up monte carlo code in python


What is this notation in Debussy's "Engulfed Cathedral"?

Question: In light of the recent portato question at What do the dots and lines underneath these chords mean?, what did Debussy mean by the tied portato on the third quarter note of the second measure of Debussy's La Cathédrale engloutie?

On one hand, portato on the piano indicates a slight re-articulation of the pitch. If that's the case, then why is there a tie between the two Gs, apparently telling us not to re-articulate?
The situation becomes stranger when we hear Debussy himself perform this (via a piano roll); he does not re-articulate this G.
What is the point of the dot above this G?
For anyone curious, the three separate scores on IMSLP all have this exact same notation.
Comment: @MichaelCurtis That would be one alternate notation I guess, yes. Ultimately my question is: What is this dot doing here? It doesn't seem to be portato, because Debussy performed it as if there is no dot. Is it indicative of something else?
Comment: Why is the dot over the first G instead of the G it's tied to? I would have put the dot over that second G.
Comment: Is it unusual to have the dots on top of the stem, instead of under the head?
Comment: I'd say the notation here is correct. Since the line with quarter notes is the upper voice in this clef, the articulation markings are also pushed above the notes. (At least one score also inverts the direction of the tie to show that it's the upper voice.)
Comment: I'm just trying to follow the question: by Debussy's piano roll the dot on the tied G1 shouldn't be in the score, right? If the dot is used - and the G1 should be staccato - would it make sense to have G1 quarter note followed by a quarter note _rest_?
Answer: There is nothing really to explain here. Articulations on tied notes are not very common, but they don't mean anything different from articulations on non-tied notes. There are different opinions about whether the articulation should be written on the first or second note of the tie, but in a published score that decision has already been made.
The reason for writing two tied quarter notes instead of one half note is simply to reinforce the fact that the initial time signature is 6/4 (two groups of three) not 3/2 (three groups of two). That doesn't make much practical difference to bar two, but it does make a difference to the way the quarter notes in bars 1 and 3 are accented.
The initial time signature shows both alternatives, which sidesteps someone thinking that the tempo relationship between 6/4 and 3/2 might be "dotted half note = half note" rather than "quarter note = quarter note" if the time signature changes were marked where they occurred. On the first page, the rhythmic notation shows there is a change to 3/2 at bar 7, and back to 6/4 at bar 13.
Comment: So you're saying it's a regularly portato marking on what is effectively a half note, only written as two tied quarters to clarify the meter. Is that correct? It certainly sounds plausible!
Answer: As the Guest answer said, it's simply a tied note indicating the local meter is 6/4, as the tied quarter notes commonly represent a rhythm that shows the second primary beat in a 6/4 bar.  (Note ties used in a similar fashion for that rhythm in the left hand in mm. 14-15 later, as well as a tied half to quarter in m. 6.  All of these clearly indicate a 6/4 meter in those bars.)
I would only disagree with that answer saying it makes no "practical difference" in bar two, as it clearly implies a different "feel" for the rhythm in that bar.  Debussy wrote this piece intending the meter to go back and forth between 3/2 and 6/4.  If he had written the last two notes of the second bar as half notes, the meter would appear to be 3/2, and those notes would be felt "on the beat."  As they are written with the tie, the rhythm is syncopated and neither of those notes is "on a beat."  The practical interpretation for a performer is that the notes will not be played "straight" with a metric accent, but instead should feel "off-beat," which will likely affect microtiming of the rhythm (as well as affecting articulation/dynamic, as the notes do not line up with metric accent) in that bar.
Answer: Debussy's piano music is written for a grand piano. Without the sostenuto pedal (the middle one) the quoted bars can't be played quite as he intended, though you can get close!
On the first beat of the second bar the pianist presses the sostenuto pedal. That holds ('sustains') the notes which are already sounding: the low G-D-G, plus the five-note chord E-A-E-A-E which has just been played. (The ties on all these show they are to be sustained.)
Although the sostenuto pedal is now held down until the end of the bar, it doesn't sustain any of the notes played in bar 2! That's the brilliant thing about the sostenuto pedal. Only the notes which were already sounding at the precise moment the pedal was depressed get sustained. It has no effect on notes played afterwards: staccato notes SOUND staccato! Once it's pressed no new notes get added to that sustained group. This is not at all what happens with the sustain pedal of a two-pedal upright piano!
AND of course while the sostenuto pedal is down you still have the normal sustain pedal (and the soft pedal) available, so the markings on those three LH notes really can be observed.


Storing the functions return values in array in javascript?

Question: Can we store some of the functions return value in the array. for example i have a array in javascript and i am wanted to store the function return value in that array its either true or false.
Then after that checking how many occurrences of true or false present in the array.
Comment: Please [edit] the question and show your code and your attempts so far. There are multiple ways of storing return values in arrays and there are multiple ways of counting them.
Comment: yes why not? can you be more specific? A fiddle perhaps http://jsfiddle.net?
Comment: Have you tried storing a function's return value in an array?
Answer: I'm not sure I know precisely what you are asking
function Foo(i) {
    return i%2 == 0 ? true : false
}

var bar= [];

for(var i = 0; i < 100; i++) {
    bar.push(Foo(i));
}

Will result in an array of the results of Foo(). In this case alternating true/false values;
Answer: var x = [];

function xyz(){

    ....
    // Whatever definition
    ...

    if(...){
    x.push(true);
    return true;
    }

    else{
    x.push(false);
    return false;
    }

}

Now check in x the occurrences of true of false.


Missing NPN Extension

Question: I'm trying to set up mod_spdy with Apache (mod_spdy-0.9.4.3-r420 and apache2-2.2.22-13+deb7u3 on Debian Wheezy).  As far as I can tell, everything is the way it's supposed to be, but I'm getting the "Missing NPN Extension in SSL/TLS Handshake" error from http://spdycheck.org/.
mods-enabled/ssl.load just has:  (everything else is commented out)
LoadModule ssl_module /usr/lib/apache2/modules/mod_ssl_with_npn.so

and I can confirm with lsof that that is the file that apache is using right now.
Any clue why SSL isn't doing the NPN thing so that mod_spdy will work?
I have another box that seems to be configured exactly the same in this regard and it is working just fine.  I'm assuming I'm missing some detail that is different :-/
Answer: I figured out what was wrong.  Apache, for some reason, was set to use SSL3 only.  Adding TLS v1 (and v1.1, v1.2) made everything work. TLS is required for SPDY to work.  I changed my apache config to have
SSLProtocol +SSLv3 +TLSv1 +TLSv1.1 +TLSv1.2

And that works like a charm.
Even better, leave out SSLv3 altogether, as it's known to be insecure:
SSLProtocol +TLSv1 +TLSv1.1 +TLSv1.2

Missing NPN Extension


listen for device changes using API state did change

Question: Im am using Mbient Lab API to talk to a device. Using the api I discovered there is a stateDidChange Variable that looks like this:
var stateDidChange: (() -> Void)? { get set }
How would I use this method in viewcontroller to detect a change in the device (such as another device has connected to it already) or can someone provide documentation on what this variable does. Link to the API is https://mbientlab.com/documents/metawear/ios/latest/Classes/ScannerModelItem.html
Answer: Simply assign a block to stateDidChange and handle your logic inside that block.
let item = ScannerModelItem()
item.stateDidChange = {
   // Handle state change
}

Comment: thanks for the response! Now is there a way to know exactly what the change was? One of the things i'm having trouble doing is checking if the device has already connected to another iOS device
Comment: @AntonioRodriguez I'm not quite familiar with Mbient Lab since I don't use it myself, so I'm afraid you have to look to their doc for help.


Whether to enter all predictors at once or perform a hierarchical regression?

Question: Firstly, excuse my naivity but I am just starting out in research.
Overview of study
I am doing a project looking at Social anxiety in adolescence and using social network analysis (SNA). I argue that negative peer relations accounts for variance in social anxiety above and beyond individual level characteristics (in this case personality variables).
I have the following variables:

Dependent Variable: Social anxiety score
Independent Variables:

Demographics: Ethnicity, SES from fathers income, SES from mothers income
Personality variables (Big 5): Neuroticism, Openness, Conscientiousness, Extroversion, Agreeableness
Network variables: Unilateral rejection (indegree of a dislike network), Mutual antipathy (sum of reciprocated dislike ties); relational dissonance (sum of dislike tie received with a like tie sent).

My total number of participants was 94.
From past research and as expected Social anxiety is predicted by Neuro and extroversion. Past research indicated that unilateral rejection should be associated with Social anxiety. In my study none of the network variables have an expected association with Social anxiety, none of them are significant predictors of Social anxiety. In fact it was only Neuroticism and extroversion that came anywhere close to significant. All other bivariate correlations were extremely low.
I believe the non significant results is largely due to methodological issues.
As regression assumes independent observations but SNA assumes interdependent then the analysis may not be able to pick up on the associations. Also with a low sample size there is not enough power.
OK. That is my story in a nutshell. I am not looking to find significant results I just want to know the best way to do a regression, so I at least know I am doing that correctly.
I would like to enter them in blocks as this gives the R squared change but I do not want to make any false assumptions and do something that is inappropriate.
Questions

Should I use the hierarchical method or not?  My initial thought
was to have demographics in block 1; personality variables in block 2
and network variables in block 3.
Or should I just enter the predictors  simultaneously
and report the results as they were not significant anyway?
Comment: How were participants sampled? I.e., are all participants from the one network, or are you using something like ego networks to calculate network measures?
Comment: Participants formed one complete network. They were all from a year 9 level at school with a 78% participation rate.
Answer: Whether to use hierarchical regression or enter all predictors at once

As a starting point, the final block of a hierarchical regression is the same as if you had entered all predictors at once.
If you have an hypothesis that is aligned with hierarchical regression, then you should perform a hierarchical regression. Your hypothesis is phrased in terms of one set of variables explaining variance over and above another set. Therefore, you have an hypothesis aligned with hierarchical regression.

Issues with non significant bivariate correlations

If all correlations between each predictor and the dependent variable are non-significant, then it is quite likely, although as discussed here not necessarily the case, that your overall regression model, and the r-square changes in a hierarchical regression will all be non-significant. Thus, as you have gathered, a quick look at the correlations can give you a sense of what the answer is likely to be to your hierarchical regression question.
Nonetheless, multiple regressions can vary in the degree to which they are performed for exploratory versus confirmatory purposes. Thus, if you are being confirmatory, then the fact that the predictors are not significantly correlated with the dependent variable should not stop you from performing the hierarchical regression.
Answer: The rule of thumb is 10 cases for each IV. You have (if I counted right) 11 IVs. Not too far over that. Surely the two SES variables are highly correlated? They could be combined and that gets you down to 10 IVs.
Regarding dependent vs. independent - you haven't said what your sampling plan is. You can do SNA and still get independent observations if the SNA aspect is only in the variables and not in the sample.  But if all the students were from one or a few classes, then you probably do have dependent data.
Regarding your questions: You can do either. Each will be just as much a violation of assumptions as the other. This doesn't depend on significance or even effect size. Since you want to report change in R squared, I would go with your first option.  However, this may cause other people (editors, professors, whoever) to look askance.
Comment: They were all from one chool year level so it is a complete network. Therefore data is dependent.
Comment: Then I believe you ought to apply the specialized tools of SNA.  I did some of this, but that was a decade ago and I am not up to date on the latest. But I know there are packages (in R and standalone) to do SNA.
Comment: Thank you for the information. Could you provide a source (paper or statistical result or whatever citable) to cite when using the rule of thumb of 10 cases for each IV


How to use a powerhsell serialized object?

Question: I have machine that I need to analyze for information.  I use powershell to gather the information into an object and then I write that object out to a file using Export-Clixml myObject.xml.
I then try to test import this object using $placeholder = Import-Clixml myObject.xml and this works fine as I can see all the methods and access data in the methods.
However, whenever I try to use this object in my program where this type of object is required, I get a Type Mismatch error.
Is this not possible with serialized object?
Answer: If you look at the full typename of the objects you deserialized you will see that they begin with "Deserialzed".  For instance if I take a bunch of System.Diagnostics.Process objects and export them using Export-Clixml, when I use Import-Clixml to import them, the types are now Deserialized.System.Diagnostics.Process objects.  What PowerShell is doing is saving the data out and then giving you access to that again.  You're not getting back live objects. Typically the only method available is ToString().  This is similar to what happens with serialization over remoting.  If you want full fidelity .NET type serialization. I would use one of the .NET serializers such as the BinarySerializer or the XmlSerializer or the newer DataContractSerializer.
Comment: How can I find the binary serializer?
Comment: See the docs on the BinaryFormatter - http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter.aspx


Only 1 custom metabox open at a time

Question: I have custom metaboxes each have the classes '.postbox .acf-postbox', when closed they get the class '.closed'.
To have them all closed by default I have:
$('.postbox.acf-postbox').addClass('closed');
But what I need is to only have one open at a time. So start with the first metabox open and the others closed, if I open another one it must auto-close the current metabox and open the clicked one.
The issue is they all have the same class so I am unsure how to target the active one so I can close the others.
edit:
Managed to add dynamic ID's so if I use:
<code>$('.postbox.acf-postbox').click( function(){
    console.log( $(this).attr('id') );
});
</code>
I am able to view the metabox ID, so I just need to close the metaboxes that do not have the clicked ID.
Answer: Sorry for the noob question, solved it by simply:
<code>$('.postbox.acf-postbox').click( function(){
    $('.postbox.acf-postbox').addClass('closed');
    $(this).removeClass('closed');
});
</code>

Only 1 custom metabox open at a time


Choosing elements of an array based on given probabilities for each element

Question: I'm not well-versed in statistics at all. I'm currently working on an implementing an optimization algorithm, and am having a bit of trouble on this part.
I have an array of $n$ elements $A = \left\{a_{i}\right\}$ where $a_{i}\in\mathbb{R}$ and $1 \le i \le n$. Furthermore, I have an array of probabilities given by $P = \left\{p_{i}\right\}$ with $p_{i}\in[0,1]$. (Also, $\sum_{i} p_{i} = 1$ of course) If it matters, the probability distribution is triangular with $i=1$ having the highest probability and $i=n$ having the smallest probability.
Now I want to choose $q < n$ distinct elements from $A$ using the probabilities of selection from $P$. I'm currently coding the algorithm in MATLAB, but I'm not sure how to go about choosing the $q$ elements.
Comment: Sampling with replacement, or without? When you say the "probability is triangular", the result is underdetermined - what is the ratio $p_2/p_1$?
Comment: If you're sampling with replacement than the randsample function can do exactly what you ask (the exact line will be something like $samples=randsample(A,q,true,P)$).
Comment: If without replacement then you'll need to specify exactly how the probabilities change when you remove a sample from the pool. The obvious way is to just renormalise the probabilites $P$ and repeat, until you've drawn $q$ samples (so you'll probably end up building a $for$ loop over $q$ iterations, each time calling randsample to draw a single weighted sample from the remaining available ones). But be sure this renormalisation makes physical sense for the system - it's entirely concievable that some systems may need a more involved re-calculation of sample probabilities.
Answer: To get a weighted random sample without replacement of size $m<n$ draw $n$ independent $u_i$'s with $\mathrm{Uniform}[0,1]$ distribution (using rand()), compute the keys $k_i=u_i^{1/p_i}$, and pick the $m$ elements with largest $k_i$'s. The $p_i$'s don't need to be normalized.
This amazingly simple algorithm is due to:
Efraimidis, P.S. and Spirakis, P.G. Information Processing Letters, 97, 181–185 (2006).
Comment: Fabulous!!! I'll thank you and that paper in my code :)
Answer: In Matlab you can call this line q times
r(ii) = 1 + sum( rand() > cumsum(P) );

Comment: could you explain this? I'm proficient in MATLAB but I'm not sure what this line of code is supposed to do. I used my P array but it just returns 1. And what is `ii` supposed to be?


How to optimise fit for function where a parameter depends on independant variable

Question: I have some data with three columns, x, y, and b. Here, b has associated values for each x value. (N.b. x always increases)
That is, the data looks something like:
x y b
1 4 7
2 5 8
3 6 9

Say this data is fit by some model y = ax + math.log(b). I could compute each value by doing something like:
def findB(x):
    for i in range(0, len(xData)):
        if xData[i] >= x:
            return bData[i]

def f(x, a):
    b = findB(x)
    result = a*x + math.log(b)

    return result

Now say I want to optimise this fit for f(x,a) to find the parameter a using scipy.optimise.curve_fit.
I have attempted to do so like this:
popt, pcov = scipy.optimize.curve_fit(f, xData, yData)

but doing so results in the error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
This is due to the curve_fit function passing all the x data as one array resulting in the if xData[i] >= x: statement being rendered ambiguous.
I can't figure out a away around this. I have tried creating a paired list of xData and bData and passing this to curve_fit to no avail.
This works if I simply hardcode b to some pre-determined value so I believe I am calling the curve_fit function correctly. Advice welcome.
Comment: Thanks, Leporello, I hadn't spotted that question and the solution there seems much more elegant,.
Comment: Can you describe what `findB` is supposed to do in words? It's evolved from a single loop to a nested loop now, and frankly, neither one makes sense.
Comment: The problem is that `curve_fit` expects an array function, and `if` cannot be used on arrays, for that you use a mask. Same problem in `math.log` (it expects scalars, not vectors: use `np.log` instead). In your particular case, since all you are doing is the same as an excel VLOOKUP, and assuming your array is sorted (as in your example) you can get the `i` index using `np.searchsorted`: `def findB(x): return bData[np.searchsorted(xData, x)]`
Answer: In discussion with some colleagues, I think we found the solution.
Using a numpy array for the values of b and replacing math.log with np.log seems to solve this:
def findB(x):
    tempArray = np.zeros(len(x))

    for value in x:
        for i in range(0, len(xData)):
            if xData[i] >= value:
                tempArray[i] = bData[i]

    return tempArray

def f(x, a):
    b = findB(x)
    result = a*x + np.log(b)

    return result


Passar array para um método php

Question: Colegas.
Tenho um formulário onde um dos campos é file multiple, ou seja, o usuário pode enviar mais de uma foto para o banco de dados, porém preciso passar as fotos, caso seja mais de uma, para o método de cadastro. Veja abaixo:
$nomeProduto = filter_input(INPUT_POST,"NomeProduto");
$valorProduto = filter_input(INPUT_POST,"ValorProduto");
......
$fotos = $_FILES["FotoProduto"]["name"];

$metodos->cadastrarProdutos($nomeProduto,$valorProduto,....,$fotos);

O método:
public function cadastrarProdutos($nomeProduto,$valorProduto,....,$fotos){
   // Aqui eu pegar todas as fotos que foram enviadas
}

Como eu faria para passar essas fotos para método? Pensei em usar o foreach() e o implode(",",$fotos); e dentro do método resgatar com o explode(",",$fotos);. Teria alguma outra solução?
Answer: As vezes é mais simples do que a gente pensa. Em vez de você já passar como parâmetro o $_FILES["FotoProduto"]["name"], passe simplesmente o $_FILES["FotoProduto"] e no foreach você pode usar o ["name"] como quiser. Veja um exemplo abaixo:
foreach($_FILES["FotoProduto"] as $file) {
  if($file['size'])
    echo $file['name']."\n";
}

Então no seu método você pode fazer desta forma:
$fotos = $_FILES["FotoProduto"];

public function cadastrarProdutos($nomeProduto,$valorProduto,....,$fotos){
   foreach($fotos as $file) {
      if($file['size'])
        echo $file['name']."\n";
    }
}

Comment: Obrigado Ack Lay.

Passar array para um método php


Using custom functions in react

Question: I have a component like this
class Hourly extends Component {
  render() {
    return (

{this._theDay(this.props.day)}

{this.props.summary}

    );
  }
}

I want to use a custom function (_theDay) in the component which i use later in another component
Custom function:
_theDay(time) {
   moment.locale('en-gb');
   var dateTime = moment(time*1000).format('dddd');
   return dateTime;
  }

I call the component later with
        <Hourly
          key={hour.time}
          id={hour.time}
          day={hour.time}
          summary={hour.summary}
        />

However i get the error: Uncaught (in promise) DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.(…)
When i just use
{this.props.day}
; everything works fine, but then i can't use my custom function
Comment: Right, so I put the `_theDay` function inside the Hourly class, which I'm guessing doesn't work for you since you need to reuse that function elsewhere. If that's the case, don't use `this._theDay` when calling it, and put the function somewhere that's accessible to both components.
Comment: Tried to reproduce your issue, seems to work for me :-/ http://jsbin.com/wuqupehaqa/edit?html,js,output
Comment: hmmm i can see that... I tried to reorganize my code like in your example, which now tells me ` _this4._theDay is not a function`
Comment: You're using `this._theDay`, but the function is not part of `this`, the component. You need to reference it differently. Perhaps try without the `this`.
Comment: Thanks @BFree - works as intended
Answer: I think this has something to do with React trying to update the DOM after props change. Try utilizing a key on the
 tied to the props.day to help it know that the children have changed.
class Comp extends React.Component {
  render() {
    let day = this._theDay(this.props.day)
    return
{day}
;
  }
}

Here's the documentation on reconciling the DOM.
Comment: I stripped the component for simplicity which might have been a bad idea. I already have a key. I just updated my question

Using custom functions in react


Is it possible to exclude nuget dependencies for target framework versions above NET40?

Question: I have a library that has NuGet package dependencies on a few Microsoft BCL libraries in order to use some .NET 4.5 features but maintain compatibility with .NET 4.0.
Here is the relevant part of packages.config
<packages>
  <package id="Microsoft.Bcl" version="1.0.19" targetFramework="net40" />
  <package id="Microsoft.Bcl.Async" version="1.0.16" targetFramework="net40" />
  <package id="Microsoft.Bcl.Build" version="1.0.10" targetFramework="net40" />
  <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net40" />
</packages>

Since these libraries are not necessary in .NET 4.5 and above, I'd like to exclude the dependencies for anything above .NET 4.0.
Is this possible without maintaining a second project file? Thanks.
Answer: If you want to have only one project file, you may create several build configurations and use msbuild conditions in csproj file:
<ItemGroup Condition="'$(Configuration)' == 'ReleaseNet40'">
  <Reference Include="Microsoft.Threading.Tasks">
    <HintPath>..\packages\Microsoft.Bcl.Async.1.0.16\lib\net40\Microsoft.Threading.Tasks.dll</HintPath>
  </Reference>
</ItemGroup>

<PropertyGroup Condition="'$(Configuration)' == 'ReleaseNet40'">
  <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)' == 'ReleaseNet45'">
  <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>

Comment: This ended up not working. I can generate the .dlls fine, but when I try to use the compiled DLL with the Bcl dependencies, project says the referenced namespace can't be found. :(
Answer: http://docs.nuget.org/docs/reference/package-manager-console-powershell-reference
Install-Package
  -IgnoreDependencies
      Installs only this package and not its dependencies.

Comment: This assumes the project has no other dependencies except for the Bcl.


SQL: Posso ter cláusulas no GroupBy que não aparecem no Select?

Question: Sei que não posso ter cláusulas no select que não apareçam no Group By. Mas e o contrário, é possível? Por exemplo:
Select B
From Table
Group By A,B

Answer: Vou responder para os dois SGBDs nas tags da pergunta:
O Group By junta um conjunto de registos e produz um sumário (um único registo) para cada um dos grupos identificados. Os grupos são identificados com base numa ou mais colunas ou expressões incluídas na cláusula Group By.
Tanto o MySql como o Oracle permitem que a tua cláusula SELECT omita colunas incluidas no Group By. Por exemplo, esta instrução irá funcionar nos dois SGBDs.
SELECT coluna1, COUNT(1)
FROM tbl_tabela
GROUP BY coluna1, coluna2

(A utilidade de uma expressão como a anterior pode ser questionada, é claro. Visto que perdes informação essencial para identificar o grupo criado para cada uma das linhas no resultado.)
Para completar, e porque é o SGBD que estou a usar ultimamente, o Sql Server, de acordo com a informação no manual, permite também que as expressões Group By contenham colunas das tabelas, tabelas derivadas, views da cláusula FROM. No entanto, as colunas do Group By não necessitam obrigatoriamente de aparecer na cláusula SELECT.
Um último comentário em relação à tua pergunta, o MySql permite que na tua cláusula SELECT incluas colunas que não estão no GROUP BY. Mais info na página do manual
Comment: Muito obrigado! E quanto ao SQL padrão, isto também é possível?


Looking for reason of two projects with different folder on laravel pointing to same website on localhost

Question: I've two projects on laravel with different folder as in:
<code>localhost/hgwebstore/public/    -- Working for more than 2 months
localhost/exposition/public/    -- Recently created
</code>
Both of the projects are created from composer.
My problem is while I open the first URL initially, Its content loads normally. But as I try to open second URL, instead of showing the content of second URL its pointing to first URL.
URL: localhost/hgwebstore/public/

Now If I try to open URL: localhost/exposition/public/

Here the style changes because the CSS files are not found in later URL.
But problem goes weirdest when I restart apache server and visit the later URL at first. Here, the content of later URL is displayed in both of the URL.
Visiting URL :localhost/exposition/public/

Visiting URL: localhost/hgwebstore/public/

How is this issue occurred? How could the issue be resolved?
Comment: While debuggin the bootstrap/autoload.php, I found ____DIR____ returning the path of previously opened URL. Is the issue somewhere related to opcode?
Answer: Here, the reason the webserver behaving such is due to enable of APC extension that has taken the same cache for both websites. By disabling, the APC fixed the issue.


Showing that $E=X/{\sim}$ (where $X=[0,1]\times\mathbb{R}^n$) is a smooth vector bundle over $S^1$

Question: I want to show that $E=X/{\sim}$ (where $X=[0,1]\times\mathbb{R}^n$) is the total space of a smooth vector bundle over $S^1$. Here $\sim$ is defined as follows: fix a linear isomorphism $L$ of $\mathbb{R}^n$ and set $(0,v)\sim(1,Lv)$ for all $v\in\mathbb{R}^n$.
Here's what I've thought so far and my idea for solving this.
There is a smooth map $\pi:E\longrightarrow S^1$ that maps points $[(t,v)]$, $0<t<1$, to points $s(t)\in S^1$, $s(t)\neq \mathbf{1}$, where $\mathbf{1}\in S^1$ is the point where the gluing of $[0,1]$ took place ($s(t)$ is $p(t)$ where $p:[0,1]\longrightarrow S^1$ is just the defining quotient map of $S^1$), and $\pi$ maps $[(0,v)]=[(1,v)]$ to $\mathbf{1}\in S^1$.
One local trivialization is the easier one, which is where there is no gluing so basically it is the passage to the quotient of the identity map of $(0,1)\times \mathbb{R}^n$. I'm stuck with the other trivialization. My idea is to construct a map $[0,\epsilon)\cup (1-\epsilon,1]$ into itself such that $(t,v)$ is sent to $(t,L_t v)$ where $L_t$ is a family of isomorphisms that "approaches $L$" smoothly as $t\to 0$.
Is this a good idea? If so, could you show me how to fill in the details?
Comment: It may be worth pointing out that your approach won't always work:  there may not exist such an $L_t$.  More specifically, $L_t$ exists iff $L$ is orientation preserving.
Comment: Did you mean $Lv$ when you wrote $Tv$?
Comment: @Thomas: yes. I corrected it. Thank you.
Comment: @Jason: thank you. How does one prove that $L_t$ exists iff $L$ is orientation-preserving?
Comment: If $L_t$ exists, then the map $[0,1]\rightarrow \mathbb{R}$ given by $t\mapsto \det(L_t)$ cannot have $0$ in the image (since $L_t$ is invertible) and has $1 (= \det(I))$ in the image, hence the image lies in the positive real numbers.  For the reverse direction, given $A$ with $\det(A) >0$, one applies the orientation preserving row operations one at a time to show that $A$ can be connected via a path to a diagonal matrix whose diagonal consists solely of $\pm 1$ and further, that there are an even number of $-1$s appearing.  Now, one using appropriate rotation matrices to move this to $I$.
Answer: Recall how do you construct the Möbius strip.
Localization is easy, the point is how they (two copies of $I\times \mathbb{R^n}$) glued together on the overlap. (I do not think you need to use $L_t$).
Details: Glue $(0,0.6)\times \mathbb{R}^n$ and $(0.5, 1.1)\times \mathbb{R}^n$ via $(x, v)\mapsto (x, v)$ if $x\in (0.5,0.6)$, and $(x, v)\mapsto (x+1, Lv)$ if $x\in (0, 0.1)$.
Comment: Thank you. Could you please give me more details? I'm very new in the subject.


Why restore interrupt flag of a task that ran in a thread pool's thread

Question: This snippet is from JCIP (Brian Goetz) listing 6.15
f.get() throws InterruptedException and ExecutionException.  Now, these exceptions are specific to the future correct?
Meaning the specific task represented by the future was interrupted or had an internal exception.
Questions -

Why do I need to restore the interrupt using "Thread.currentThread().interrupt()"? , because isnt the interrupt flag for the thread my task ran in?  This is a little confusing.
Why throw launderThrowable exception?  If one of the downloadImage had an issue, shouldnt we just process the other downloaded images intead of throwing from here and thus just "not" processing the remaining futures?
package net.jcip.examples;

import java.util.*;
import java.util.concurrent.*;
import static net.jcip.examples.LaunderThrowable.launderThrowable;

/**
 * Renderer
 *

 * Using CompletionService to render page elements as they become available
 *
 * @author Brian Goetz and Tim Peierls
 */
public abstract class Renderer {
    private final ExecutorService executor;

    Renderer(ExecutorService executor) {
        this.executor = executor;
    }

    void renderPage(CharSequence source) {
        final List<ImageInfo> info = scanForImageInfo(source);
        CompletionService<ImageData> completionService =
                new ExecutorCompletionService<ImageData>(executor);
        for (final ImageInfo imageInfo : info)
            completionService.submit(new Callable<ImageData>() {
                public ImageData call() {
                    return imageInfo.downloadImage();
                }
            });

        renderText(source);

        try {
            for (int t = 0, n = info.size(); t < n; t++) {
                Future<ImageData> f = completionService.take();
                ImageData imageData = f.get();
                renderImage(imageData);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (ExecutionException e) {
            throw launderThrowable(e.getCause());
        }
    }

    interface ImageData {
    }

    interface ImageInfo {
        ImageData downloadImage();
    }

    abstract void renderText(CharSequence s);

    abstract List<ImageInfo> scanForImageInfo(CharSequence s);

    abstract void renderImage(ImageData i);

}

Answer: When you catch InterruptedException  interrupted flag gets reset and your thread is technically not interrupted anymore. However, you don't know if the code that called your code (or other code in the same thread), requires any additional interrupt handling. By calling interrupt() you raise the flag again and effectively saying to the rest of the application "This thread is still interrupted - act on it if necessary".
Consider example. You method is called from the loop that must terminate if thread is interrupted. You caught the exception and if you don't raise the flag, the loop will not terminate as required.
Comment: Just to add more details: when some of the blocking methods in the Java libraries throws a `InterruptedException`, Thread's interrupted flag is reset to false. Check e.g the documentation of [`Thread.sleep()`](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep%28long%29) or [`Object.wait()`](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait%28%29)
Answer: By catching InterruptedException, you are stopping the interruption from reaching the Thread in which you are running. But you want it to reach it, in case there is any special processing the Thread needs to do in case of interruption - you can't tell, so you'd better play it safe and allow it to percolate up. You may do some processing yourself (to clean up, exit what you are doing, etc), but you must pass it on. The best way to do this is to call Thread.currentThread().interrupt().
Answer:
The interruption does not necessarily happen on the thread pool's thread.  The interruption is for a point when your current thread is interrupted while you are waiting on the future's get to complete.  For instance, if you made the Future accessible to another part of the program that can cancel the download, then Future.cancel(true) will cause that InterruptedException to occur which you can then clean up the rest of the data. And as Beohemaian mentioned, it is always safe to propogate the interruption.
Thats a good question.  I think that was more of a design choice of what he wanted it to do.  But you can easily hold onto that error and throw it after the rest complete.  Something to think about though, what if its an OutOfMemoryError?  Then the launder would be useful to only throw if its an Error and maybe not a RuntimeException.
Comment: `Error` is supposed to be something unrecoverable. How about `StackOverflowError`? The stack maybe corrupted. How about `InternalError`? it is corrupted VM state. You can't just catch them.
Comment: Yes you're right. That is where I was going with the OutOfMemoryError. Although the launder method will also rethrow runtime exceptions (at least in the example)


How do I automatically start supervisor on boot in FreeBSD?

Question: Is there a pre-existing startup script for supervisord on FreeBSD? If not, is there a good guide for writing rc.d scripts for FreeBSD? I'm pretty new to the platform.
Thanks.
UPDATE:
I now have the following in /usr/local/etc/rc.d/supervisord, but it doesn't seem to be working. I'm not seeing anything in the startup scroll related to supervisord.
#!/bin/sh

# PROVIDE: supervisord
# REQUIRE: LOGIN
# KEYWORD: shutdown

. /etc/rc.subr

name="supervisord"
rcvar=`set_rcvar`
load_rc_config "$name"

command="/usr/local/bin/${name}"
command_args="-c /usr/local/etc/supervisord.conf"

supervisord_enable=${supervisord_enable-"NO"}
supervisord_pidfile=${supervisord_pidfile-"/var/run/supervisord.pid"}

pidfile="${supervisord_pidfile}"

run_rc_command "$1"

Answer: If you installed supervisord from ports (sysutils/py-supervisor) you should have a functioning rc script in /usr/local/etc/rc.d/supervisord
Check the script for info/other configuration parameters, but simply adding supervisord_enable="YES" to /etc/rc.conf should be all you need to do to make it start automatically on boot.
Comment: Yup - it's actually called py-supervisor for some odd reason (sysutils/py-supervisor)
Comment: Can you edit to put the name of the port in the answer proper? I'd do it myself, but my rep isn't high enough.
Comment: Is there a port for supervisord? `make search name="supervisord"` doesn't show any results.
Answer: If you installed supervisord from the port sysutils/py-supervisor then this rc file is already present... (than to voretaq7 for pointing this out).
The basic framework of a rc file is:
#!/bin/sh

. /etc/rc.subr

name="supervisord"
rcvar=`set_rcvar`
load_rc_config "$name"

command="/usr/local/bin/${name}"
command_args=""

run_rc_command "$1"

Creating the file /usr/local/etc/rc.d/supervisord with the above, then chmodding it +x will get you started (probably).
I am assuming you have supervisord installed in /usr/local/bin, change that path as necessary. Also you can add any command line arguements you need (like a configuration file or whatever). I'm not familiar with supervisord, so I'm not sure what it needs.
Make sure you  have a line in /etc/rc.conf similar to supervisord_enable="YES" or the script will do precisely nothing.
Comment: See also this article on writing FreeBSD rc scripts: http://www.freebsd.org/doc/en_US.ISO8859-1/articles/rc-scripting/ -- Everything you ever wanted to know about the RC system but were afraid to ask.


Resources for singing

Question: Most of what i know (including my guitar playing) has been learnt without a teacher...i guess i just suck for that kind of learning. I want to learn to sing, but cannot find a viable way that does not involve a teacher.
I know feedback may be important in this case, but if you know of something that can be done or used to achieve this it would be helpful.
I don't want to become a great singer (i will still put most of my effort in improving my guitar playing) but i want to improve enough to sound decent.
Comment: Is there anything more you want from the answers so far?
Comment: Just waiting to see if it can get more attention and/or extra information before the bounty period ends
Answer: The unfortunate thing about singing is that you can do your voice and yourself damage if your technique is wrong or you over exert yourself.  It's for this reason that I would say getting personal feedback is a top priority; however this doesn't mean you need to shell out hundreds on a face to face teacher.  you can:
Join some singing forums
Sign up to some singing forums, and see what advice people can give there.  The advantage to that is that you can post some videos and get real feedback on your progress.  While you're there try to find some people willing to have personal chats.  Maybe you can pick up a few friends in your area while you're there!

Harmony Central
The Modern Vocalist
Ultimate guitar vocal community

Join a Meetup group
There might be some singing meetups in your area where you can go and learn from entire groups of singers over a coffee(or room temperature water).  I can say for me they've been fantastic in learning to write, and always fun, but as for a group in your area you'll have to research yourself a bit!

Meetup website

Sign up to an on-line course
The advantage to paying for a course is that everyone involved is financially invested in their learning.  just the act of paying for something makes you more likely to put the effort in, so if real improvement is your goal then a paid course is a good way to motivate yourself into it.  Berklee will be the most expensive, but keep an eye out on Coursera for free courses coming up!

Berklee singing courses
Coursera

Lessons on Youtube
Now we're getting into areas where you really need to be careful.  I have never received any singing lessons nor safety lessons, but I could upload a clever sounding viral lesson to YouTube tonight and get thousands of people watching.  Always always always look for videos about vocal safety before you start learning how to go enter shikari on your vocal cords.
Ask Questions on Here!
I think singing questions are one of the weaker areas of the site at the moment, and we're all looking to help with singing problems.  Any gaps you find in your knowledge can be filled with the search, and ask question buttons!
I hope that gives you a few places to start!
Comment: coursera - empty. Berklee - $1200... :(
Answer: There are already some good answers on how to learn technique, and just getting out there and singing. I wanted to give some ideas as to how to listen to yourself outside your head.
One method to listen to yourself is to use an audio recorder. The average phone will be adequate, although if you have higher quality equipment, it might be better. But speed trumps quality here. The main thing is to record, then listen immediately, while you still remember exactly what it felt like when you were singing the notes.
Another method, using a little more equipment, would be to sing into a microphone, and listen to the sound either through speakers or headphones. This is more immediate feedback, but you're listening to both your voice as it sounds inside your head, and how it sounds to others.
I'll often sing for a few seconds or half a minute, then listen to the recording to better hear what I've done. At the end of the practice session, I delete everything, unless there was something particularly good I want to save as marking progress.
I'd also say that the danger of injuring yourself is overrated, as long as you pay attention to how you feel and don't try to go from no singing at all to singing several hours a day. If you notice that you are getting a sore throat from singing, ease back and try to troubleshoot the problem, don't just push through the pain.
Answer: My suggestion would be to work on singing from your center - using your diaphragm.  While it will be nice to hone the edge of the tool (fine-tuning the pitch of your voice), you must first shape the tool into its form.  Once you are able to effectively sing from your center, I think you will find that your range will be defined by how you sing when you are not pushing yourself.
Here are some tips to get you started working on your diaphragm:

Watch yourself in the mirror. If you see your shoulders go up while you breathe, then you're not utilizing your diaphragm.
Breathe deep into the body, and continue that sensation of a downward push while you're singing in order to regulate the flow of air.
When in doubt, you can lie on the ground and place a book on your stomach to ensure that it's expanding while you breathe. Also, you can use the same sensation you get while going to the bathroom as mentioned earlier.
Finally, if you're feeling pressure in your throat underneath your cords before you start singing, then you're breathing in too much air.

These suggestions were taken from the following site: http://www.askavocalcoach.com/how-do-i-sing-from-my-diaphragm-not-my-throat-641/
Answer: I've been researching for years.
I've been trying different teachers, books, forums, etc...
The only real help I got came from Brett Manning's cd lessons.
I am not affilated at all and I can say that he allowed my voice to do things impossible for me before.
Just one last thing: without a (great) teacher you're taking more than twice the time you need to get to your goal.
Have fun and try the course: you'll thank me (and Brett) :)
Answer: The easiest and fastest way to make your singing voice sounded better is to avoid pushing your voice too hard. You will have the problems of voice cracking, off-key, strained voice if you doing so.
You have to learn how to sing from your diaphragm, so that you will be strained to not push your sound too hard. Your voice will sounded more natural and nicer if you release your voice from your diaphragm while singing.
Source:
http://www.becomesingers.com/techniques/how-to-sing-from-diaphragm

Resources for singing


How to prove $E(I(X \in A)) = P (X \in A)$?

Question: How to prove $E(I(X \in A)) = P(X \in A)$?
Comment: $I$  is   the indicator function ?
Comment: I think that the LHS is meant to be $\mathbb E1_A(X)$. If $I$ on its own is a function on its own allready then in your question it has a rather strange argument: the event "$X\in A$".
Comment: I is an indicator function
Comment: As mentioned, this question is too context-dependent to be usefully answered.
Comment: @drhab Actually, $\mathbf 1_A(X)$ and $\mathbf 1_{X\in A}$ and $\mathbf 1(X\in A)$ are synonyms.
Comment: @Did The third is new to me.
Answer: Depends on your knowledge of measure theory. In a discrete space, you can do :
$${\rm E}({\mathbf 1}(X\in A)) = \sum_{\omega\in\Omega} {\mathbf 1}(\omega\in A)p_\omega = \sum_{\omega\in A} p_\omega = P(A)$$
In a continuous space, you can do :
$${\rm E}({\mathbf 1}(X\in A)) = \int_\Omega {\mathbf 1}(\omega\in A){\rm d}P(\omega) = \int_A {\rm d}P(\omega) = P(A)$$
Comment: Merci, Nicolas. I believe that the probability that an X is in A is P(ω) so that I can sum up P(ω) of each X that is A. Thanks, again.
Comment: What exactly is $\mathbf1$ here? A function? If so then what is its domain?
Comment: @drhab : yes, it's a function, and you can see ${\mathbf 1}(X\in A)$ as a random variable : ${\mathbf 1}(X\in A)(\omega)=1$ if $X(\omega)\in A$, else $0$.
Answer: Let $(\Omega,\mathcal{F},\mathbb{P})$ be a probability space and $X:\Omega\to \mathbb{R}$ be a random variable. For every Borel set, we have
$$X^{-1}(A)=\{\omega\in \Omega\ : X(\omega)\in A\}\in\mathcal{F}$$
Sometimes, we use $X\in A$ instead of $X^{-1}(A)$. We have
\begin{align*}\mathbb{E}[I_{X\in A}]&=\mathbb{E}[I_{X^{-1}(A)}]=\int_{\Omega}I_{X^{-1}(A)} d\mathbb{P}=\int_{\Omega\,\cap \,X^{-1}(A)} d\mathbb{P}=\int_{ X^{-1}(A)} d\mathbb{P}=\mathbb{P}(X^{-1}(A))\\&=\mathbb{P}(X\in A)\end{align*}
Comment: What is F? Why do we use X-inverse of A?
Comment: A sigma algebra. See it: https://en.wikipedia.org/wiki/Sigma-algebra
Comment: Yes, I get it now. Sukran/thanks, Behrouz.
Comment: Please, good luck.
Answer: I am not familiar with the notation used in your question and preassume in this answer that you are asked to prove that:$$\mathbb E\mathbb1_A(X)=P(X\in A)$$
where $A$ denotes a measurable set and $X$ denotes a random variable.
Then $1_A(X)$ is also a random variable, and observe that it only takes values in $\{0,1\}$.
On set $\{X\in A\}:=\{\omega\in\Omega\mid X(\omega)\in A\}$ it takes value $1$ and on its component it takes value $0$.
From this we conclude that:$$\mathbb E\mathbb1_A(X)=1\times P(\{X\in A\})+0\times P(\{X\notin A\})=P(X\in A)$$
Here $P(X\in A)$ is an abbreviation of $P(\{X\in A\})$.


In a View, is there an easy/automatic way to generate a table out of all data in a list?

Question: I've got a list with 20+ columns and don't feel like manually building out the  and .  Is there an easy/automated way to just tell MVC to generate a basic table with all of the data in a certain list?
Comment: A DevExtreme DataGrid will do this. Their tool stuff isn't free, though. https://js.devexpress.com/Demos/WidgetsGallery/Demo/DataGrid/Overview/Mvc/Light/
Comment: use ef to reverse engineer the table to a class.  use mvc scaffolding to create a list view with the class. the link is for core, but the process is the same for mvc5 and below.  https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db
Comment: Unsure about automated way to create basic table but I would make such task simpler by using loops for both columns and data.

`// create list of headers and data
var headers = new List { "Make", "Colour"...."Price" };
var cars = new List { Audi, Mercedes, RangeRover };`

`// use those lists in view by looping separately for header and data

 @foreach (var header in headers)
 {
  @header
 }

@foreach (var car in cars)
{

@car.Make
@car.Colour
  .....lots of columns here....
  @car.Price

}`
Comment: Can you give us an example on what the list can look like? Difficult saying a lot without seeing any kind of code
Answer: How about using jQuery DataTables?
https://datatables.net/examples/data_sources/js_array.html
The view would then look something like this
@model  string[]


Household reflector or transformation

Question:
Let $A\in\mathbb{R}^{n\times k}$, $n\geq k$, and $rank(A) = k$. Consider the use of Household reflectors, $H_i$, $1\leq i\leq k$, to transform $A$ to upper trapezoidal form, i.e., $$H_{k}H_{k-1}\ldots H_2 H_1 A = \begin{pmatrix}R\\0\end{pmatrix}$$
  where $R\in\mathbb{R}^{k\times k}$ nonsingular upper triangular. We can define $$H_i = I + \alpha_i x_i x_i^{T}$$
  $$\alpha_i = \frac{-2}{\|x_i\|_{2}^{2}}$$
  not sure what $x_i$ is though don't see it in my notes anywhere.

So suppose $$A = \begin{pmatrix}
2 & 1\\
1 & 2\\
1 & 2\\
\end{pmatrix}$$
and I want to get $R$. I tried to apply the formula but my $R$ is not upper trapezoidal. So there must be something I am doing wrong. Could someone kindly show the steps so I know how to do this?
Attempt - $$H_1 = I + \frac{-2}{6}\begin{pmatrix}
2\\
1\\
1\\
\end{pmatrix}\begin{pmatrix} 2 & 1 & 1\end{pmatrix}$$ thus we have $$\begin{pmatrix}
1 & 0 & 0\\
0 & 1 & 1\\
0 & 0 & 0\\
\end{pmatrix} - \frac{1}{3}\begin{pmatrix}
4 & 2 & 2\\
2 & 1 & 1\\
2 & 1 & 1\\
\end{pmatrix} = \begin{pmatrix}
-1/3 & -2/3 & -2/3\\
-2/3 & 2/3 & -1/3\\
-2/3 & -1/3 & 2/3\\
\end{pmatrix}$$
Thus $$H_1 A = \begin{pmatrix}
-2 & -3\\
-1 & 0\\
-1 & 0\\
\end{pmatrix}$$
thus I have a problem, please let me know if there is an error in my calculations.
Comment: Is $R$ supposed to be square?
Comment: I believe so from what I have in my notes
Comment: Are you able to make the first column $(\sqrt 6,0,0)$ with householder transformations?
Comment: No I don't get the zeros in the first column when I multiply $H_1$ by $A$. Thus I need to understand how to compute the $H_i$'s correctly and that should fix my issue
Comment: @Omnomnomnom can you help me?
Answer: The point of $H_1$ is to make the first column a column with zeros except in the top entry.
To find $x_1$, note that $\|(2,1,1)\| = \sqrt{6}$, so we should aim to get $(2,1,1)$ to $\sqrt{6}(1,0,0)$.  Take
$$
x_1 = (2,1,1) - (\sqrt{6},0,0) = (2-\sqrt{6},1,1)
$$
(why should this work? Try to figure it out geometrically).
In the next step, since the first column is already where we want it, we apply a Householder transformation for the $2 \times 2$ submatrix that comes from deleting the first row and column.  In this way, our upper-triangularization process is recursive.
Comment: I will try to clarify this if I have time to do the explicit calculations, but for now this will have to do.
Comment: Ok, if you can also see my calculations I think I must have made an arithmetic mistake somewhere
Comment: @Wolfy your mistake is clear: you have the wrong $x_1$.  Read my answer.
Comment: I tried to apply your technique but I still do not get $0$'s under the first entry after $H_1 A$. Perhaps you could expand on your answer to include formulas so that I can get the correct output.
Comment: Also could we just use $QR$ factorization to get the same thing as Householder reflectors?

Household reflector or transformation


Custom login form with signin button -- POSTing registration

Question: I have added a "register" button to the login form which is shown as a block on my homepage. I want the button to simply redirect to the registration page but it's POSTing to login and error'ing -- any ideas?
<code>  function MYMODULE_form_user_login_alter(&$form, &$form_state) {
    $form['actions']['register'] = array(
      '#type' => 'submit',
      '#value' => t('Sign Up'),
      '#submit' => array('_user_login_register_submit')
    );
  }

  function _user_login_register_submit($form, &$form_state) {
    drupal_goto('user/register');
  }
</code>
Answer: It's not working because the login form validate handler is executed, and fails, before the function you call with the #submit attribute.
You can use #validate like a workaround probably, but there's a cleaner way to achieve what you are after.
I wouldn't create a button element at all. Make it a link to user/register instead and style it to look like a button if needed.
Comment: A link is a more elegant solution...didn't even think of that. Thanks :)


Trazer o return de uma function para uma variável de uma outra function

Question: gostaria de se há possibilidades de fazer isso:
function trazerNumero(){
    return 7;
}

function mostrarNumero(){
    numero = trazerNumero();
    alert(numero);
}

$(function(){
    mostrarNumero()
})

Sei que você vão falar que é melhor fazer um único método, mas no que eu quero não da para fazer isso, preciso pegar um valor que será gerado em uma outra function e usar em outra function.
Comment: Pode passar o retorno de `trazerNumero` como argumento para `mostrarNumero`.
Answer: O que perguntas é perfeitamente válido e se testares funciona.
Para teres código mais modular faria sentido, como o renan disse, passar o valor já como argumento assim:
function trazerNumero(){
    return 7;
}

function mostrarNumero(numero){
    alert(numero);
}

$(function(){
    var numero = trazerNumero();
    mostrarNumero(numero);
})

Comment: Mas na minha necessidade teria que ser assim, foi só um exemplo básico isso, mas deixa quieto consegui dar um jeito aqui. Obrigado!
Comment: @RomarioPires se explicares melhor o código que tens e não mostraste na pergunta posso ajudar mais e/ou dar ideias.


PHP preg_replace turning $ to the letter S

Question: I currently have a really great preg_replace system going on for my seo needs, but I'm having trouble with one character specifically and that's the $. The code I have returns the $ as a blank but I would prefer it if it turned the $ to the letter S. It's probably just a minor tweak but I'm sure how to single it out.
    $urlname = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $info['name']);
    $urlname = strtolower(trim($urlname, '-'));
    $urlname = preg_replace("/[\/_|+ -]+/", '-', $urlname);
    $seourl = strtolower($urlname);

Answer: you can use, strtr
echo strtr('Hello. I have $ Please replace the $', '$', 'S');

See Demo Here
Answer: <?php
echo str_replace("$","s","Hello $!");

?>

Answer: I was overthinking it. I should have changed it before I stripped out all the other special characters. Thanks, Siddhu Siddhartha Roy.
    $urlname = str_replace("$","s", $info['name']);
    $urlname = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $urlname);
    $urlname = strtolower(trim($urlname, '-'));
    $urlname = preg_replace("/[\/_|+ -]+/", '-', $urlname);
    $seourl = strtolower($urlname);


RETORNAR VALORES ESPECÍFICOS DE ACORDO COM A DATA [SQL]

Question: Bom dia,
Estou travado em uma query que estou desenvolvendo para um projeto. Tenho duas tabelas distintas. A primeira contém os dados cadastrais dos colaboradores. A segunda contém dados da Diretoria que esses colaboradores pertencem e as respectivas mudanças de cargo/salário.
cadastro_colaborador Modelo Tabela Colaborador
dados_diretoria Modelo Tabela Diretoria
Preciso que na tabela cadastro_colaborador apareça o cargo mais recente de cada colaborador, de acordo com a dt_fotografia da tabela dados_diretoria. Para isso, estou usando a query abaixo:
select
  dc.nome,
  dc.matricula,
  dc.cpf,
  dd.dt_atualizacao
from cadastro_colaborador dc
left join dados_diretoria dd on
  dc.cpf = dd.cpf
where dt_atualizacao =
  (select max(dt_fotografia) from dados_diretoria)

Entretanto, o resultado apresentado é Tabela Resultado Query. Nessa tabela são apresentadas apenas as informações em que a data de atualização máxima é = 31/08/2023. Dessa forma, as informações do Marcio não são exibidas, porque a data de atualização máxima dele é 01/01/2023.
Preciso que a query retorne as informações de cada colaborador de acordo com a dt_atualizacao máxima de cada um, ou seja, as informações da Rebecca, Antonio e Felipe devem ser com base na dt_atualizacao = 31/08/2023. Por outro lado, as informações do Marcio devem ser com base na dt_atualizacao = 01/01/2023.
Qual o erro da minha query original? O que posso fazer para que ela retorne o resultado que preciso?
Obrigado!
Comment: Pelo que entendi ....  dt_atualizacao =  (select max(dt_fotografia) from dados_diretoria dd2 where dd2.cpf = dd.cpf) ....
Answer: Teste a select desta maneira:
select dc.nome,
       dc.matricula,
       dc.cpf,
       dd.dt_atualizacao
from cadastro_colaborador dc
         left join dados_diretoria dd on
    dc.cpf = dd.cpf
where (dt_atualizacao, dd.cpf) in
      (select max(dt_fotografia), cpf
       from dados_diretoria
       group by cpf)
Dessa forma, ele deve trazer as maiores datas pra cada cpf cadastrado, já que a subselect agrupa os dados por cpf e retorna o valor máximo respectivo a cada um deles.

É importante tomar cuidado com o volume de dados, já que o group by pode fazer com que a select demore mais.

É importante tomar cuidado com o volume de dados, já que o group by pode fazer com que a select demore mais.
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


solving second-order nonlinear ordinary differential equation

Question: I am trying to solve the following:
$$y''(x)=\frac{4}{3} y(x)^3 y'(x)$$
given that $y(0)=1$ and $y'(0)=1/3$. This is a link to Wolfram Alpha.
My idea was that because when $y=1$, $y^3 = 1$ it can be solved for the private case only by putting $1$ instead of $y^3$
the question is to find y I need the way as I have no clue what to do.
Comment: Although I edited the $\LaTeX$, I think you still need to clarify your question.
Answer: Hint: By the chain rule, the right-hand side equals $\frac{d}{dx}\frac{y^4}{3}$. Now integrate both sides...
Comment: Gee, thanks, @Nahum. Now I'll never fly again.
Comment: @makholm , you are the bomb!
Answer: let's make substitution $v=y'$
$y''=\frac{dv}{dx}=\frac{dv}{dy}\frac{dy}{dx}=v\frac{dv}{dy}$ , so we may write:
$v\frac{dv}{dy}=f(y,v)$ , which is in your specific case equal to:
$v\frac{dv}{dy}=\frac{4}{3}y^3v$  , which is separable first order differential equation:
$dv=\frac{4}{3}y^3dy$
After you find $v$ you have to solve $y'=\frac{dy}{dx}=v$  ,which is also separable first order equation.
Comment: +1 But it IS a mess.
Answer: For this exact case, the route suggested by makholm is easiest. I just want to mention the general solution for a more general equation, $ g''=f(g)g'$, where $f$ is some function of $g(x)$, is:
$$ \int \frac{dg}{F(g)+C_1}=C_2+x$$
where $F(g)=\int f(g)dg$ and $C_1$ and $C_2$ are integration constants. In this case $f(g)=\frac{4}{3} g^3$. Thus $F(g)=\frac{1}{3} g^4$...
Cheers,
Paul Safier


Suddenly SoundCloud JSON data doesn't parse correctly

Question: We have a custom widget that worked fine for years until last week.
It seems that the Json callback is only working now for playlists but not for tracks.
Playlist <code>/**/jQuery31108094578850496614_1482167143815({"duration":215707,"release_day":null,"permalink_url":"http://soundcloud.com/puremagnetik/sets/analog-...</code>
Versus Track
<code>{"kind":"track","id":3028745,"created_at":"2010/05/20 18:26:31 +0000","user_id":54749,"duration":74450,"commentable":true,"state":"finished",...
</code>
See the Track is missing the JQuery element. I'm not sure why this is happening now but if anyone can recommend a fix I would be grateful.
Live with the widget on our site:
Playlist  https://puremagnetik.com/collections/keyboards-ableton-live-pack-kontakt-logic-samples/products/harpsikord-harpsichord-ableton-live-pack-samples
Track  https://puremagnetik.com/collections/glitch-toy-lo-fi/products/bender-circuit-bent-speak-and-spell-ableton-live-pack-kontakt-instrument-apple-logic-samples
Comment: Seems like a few others may have gone through what you're going through. At this point I'd recommend getting in touch with SoundCloud directly.
Comment: Could you show us the code that makes those AJAX calls in case there's a problem there?
Comment: @MMM not sure how to format that in this space but it is making a `
              $.getJSON(apiUrl, function(data) { ` call
Answer: This is something that was fixed recently, and should be working again.


Relacionamento One-To-One com EF?

Question: Estou tentando criar um relacionamento OneToOne com EF6. No meu esquema tenho uma classe de Usuario e uma de Plano e o relacionamento seria 1 Usuario tem 1 Plano, porem, esse relacionamento é feito quando o Usuario paga o Plano que então faço o relacionamento.
Usei o HasOptional<Plano>(u => u.plano) para fazer o mapeamento do lado do Usuario, salvo as informações no banco de dados normalmente com o relacionamento, o problema é que quando faço uma busca o Plano não retorna junto com o Usuario e não sei pq isso acontece.
Como resolver isso ?
public class Usuario
{
    public long id { get; set; }
    public Plano plano { get; set; }
}

public class Plano
{
    public int id { get; set; }
}

Mapeamento:
public class UsuarioMap : EntityTypeConfiguration<Usuario>
{
    public UsuarioMap()
    {
        this.ToTable("Usuarios");
        this.HasKey<long>(u => u.id);

        this.HasOptional<Plano>(u => u.plano);
    }
}

No código abaixo, a propriedade Plano fica nula.
Usuario usuario = context.usuarios.Where(u => u.id == usuarioSession.id).FirstOrDefault();

Answer: Você deve usar o método Include(x => x.NomeDaSuaEntidade) junto a chamada do context quando for retornar entidades relacionadas a sua model.
Porém além disso você deve também colocar uma propriedade de Foreign Key (chave estrangeira) que permite que o banco identifique qual campo relaciona as duas entidades, ou seja suas models deveriam ficar assim:
public class Usuario{
    public long id                  { get; set; }
    public virtual Plano plano      { get; set; }

public class Plano{
    [ForeignKey("Usuario")]
    public long id                   { get; set; }

Após configurar suas entidades corretamente, pode fazer a chamada a seguir para pegar os Usuários e os Planos relacionados a eles.
Usuario usuario = context.usuarios.Include(x => x.plano).Where(u => u.id == usuarioSession.id).FirstOrDefault();

Comment: ao invés de `Include(x => x.plano)` eu usei o `Include("Plano")` e funcionou blzinha. Obrigado.

Relacionamento One-To-One com EF?


angle chasing in quadrilaterals

Question:
Let $ABCD$ be a convex quadrilateral
with
  $\measuredangle{ABD} = 18^{\circ}$, $\measuredangle{ACB} = 54^{\circ}$,
  $\measuredangle{ACD} = 36^{\circ}$ and
  $\measuredangle{ADB} = 27^{\circ}$.
Let $\{P\}$
  be the intersection of the two diagonals $AC$ and $BD$.
What is the degree value of $\measuredangle{APB}$?
Comment: I have added a figure made with Geogebra.
Comment: thank you. This question really confuses me. I am now trying to find sin36 degrees and use law of sine now... Is there a smart way to do this?
Comment: A technical remark that will allow you simpler computations is to replace all your angle values by 2a,3a,4a,6a, with a=9°, keeping in mind that 10a=90° for simplifications.
Comment: yeah that make this a lot easier... Thank you!
Comment: um this is still somehow confusing. Can you give me another hint? Thank you.
Comment: give the names, x,y,z to angles APB, CBD and BDC resp. (x being the value you are looking for). You can notice that $y+z=10a$ by reasoning on the sum of angles in triangle BDC. Find two other equations linking $x,y,z$. You will end up with a system of 3 (linear) equations in the 3 unknowns $x,y,z$ that you will ultimately solve.
Comment: Hint: Prove that C is the circum-center of $\triangle DAB.
Comment: Oops. Should have thought about that.... Thank you!
Answer: After some angle chasing, we have the following:-

The configuration seems like C is the circum-center of the circle DAB.
Added:-
The tricky part is:- "Is C really the circum-center of $\triangle ABD$?"

This is done by extending AC to cut the circum-circle at F. Again by angle chasing, we get $\beta = \angle 1 = \angle 2$. This means $\triangle CFB$ is isosceles. The same is true for $\triangle CFD$. Then, point C (not the red dot anymore) is indeed the circum-center of $\triangle ABD$ (because (1) CB = CF = CD and (2) B, F, D are points on the circumference of the same circle).
Finally, we have $\angle CDB = \angle CBD = 45^0$. Result follows.
Comment: um dont it get proved immediately by the subtended arc theorem?
Comment: @Mick If $C$ is a circumcenter it's holds. But why from the given follows that $C$ is a circumcenter?
Comment: @MichaelRozenberg See added.
Comment: @Mick Why $C\in AF$?
Comment: @MichaelRozenberg F is constructed by extending AC to cut the circumcircle at F.
Comment: @Mick Now I see it! Nice solution! +1
Answer: Let $CK$ be a bisector of $\Delta ADC$ and $CL$ be a bisector of $\Delta ABC$.
Thus, $KCLA$ is cyclic and from here $\measuredangle KLA=\measuredangle KCA=18^{\circ}=\measuredangle ABD$.
Thus, $KL||DB$, which says $AC:DC=AK:KD=AL:LB=AC:BC$,
which gives $DC=BC$, $\measuredangle CBA=45^{\circ}$ and $\measuredangle APB=54^{\circ}+45^{\circ}=99^{\circ}.$
Comment: I can't follow why KCLA is cyclic after setting CK and CL as (angle) bisectors.
Comment: @Mick Because $\measuredangle KCL+\measuredangle KAL=45^{\circ}+135^{\circ}=180^{\circ}$.
Comment: Uh! I see. Nice solution using angle bisector theorem.  +1
Answer: Let S be the center of the circumcircle of triangle ABD. D is a point on that circumcircle, and ∠ADB = 18∘, so therefore, ∠ASD = 36∘. Consider the circumcircle of ASD. S is a point on that circumcircle and ∠ASD = 36∘, so therefore for each point on that circumcircle Q and only for those points, ∠AQD = 36∘ is a true statement.
We know ∠ACD = 36∘, so therefore, C is on the circumcircle of ADS.
Analogically, since ∠BCA = ∠BSA = 2 * ∠BDA = 54∘, C is also on the circumcircle of ABS.
Out of this, we can conclude points C and S are on the intersections of ABS's and ADS's circumcircles. The only such intersections are points A and C. Obviously, S is not the same point as A (otherwise, ∠BDA = ∠DBA would be true), and neither is C (otherwise, ∠ACB = 54∘ makes no sense) so we conclude S is C.
Therefore, C is ABD's circumcenter. Out of that, we can get DC = BC (two radii in the same circle), and by that we conclude BCD is bilateral and ∠DBC = ∠BDC.
We know ∠BCD = 36∘ + 54∘ = 90∘. Therefore , ∠DBC=45∘.
Finally, ∠APB = 54∘ + 45∘ = 99∘.

angle chasing in quadrilaterals


What do singing teachers refer to when they say "relax and sing"?

Question: I have heard singing teachers say something like "relax and sing".
My understanding is that you cannot sing with all the muscles relaxed.
Some teachers say that using the wrong muscles are bad and that those need to be relaxed but I am not sure this is what these words refer to.
I have been asking myself if it is not more of a psychological thing (affecting how you sing) that they are refering to. Since I haven't really heard it as much from eg piano or accordion teachers it must be very much related to vocals.
Vocal terminology can really confuse me.
What do singing teachers refer to when they say "relax and sing"?
Answer: There is a difference between being "relaxed" and not using any muscles.
Your statement reminds me of my Tai Chi instructor saying "Raise your arms without any tension in the muscles".  That drives me nuts every time I hear it.
The fact is you do need to have the CORRECT muscles activated in the correct manner to sing properly.  But as beginners, when you don't quite know how much flexing is required to support a note with steady air flow, we over do it.  "Forcing" is not necessary or required to get a good tone or even volume.  Proper singing technique will excite and sustain a resonance of acoustic waves in your head cavity.  When you develop the ability to feel this you will realize that you barely need force to drive the sound.
Another thing it could refer to is mental relaxation.  If you are overthinking what you're doing that will lead to all sorts of tension in the mind and body that will impede your singing.
You are asking us "What do singing teachers refer to when they say "relax and sing"?", and maybe that's a red herring.  What does your teacher mean when he or she says that?  Not all teachers say that.  It's not a universal message in singing with a single meaning.  So there could be more than one thing being referred to by each persona whose said it.
Answer: Firstly - I agree with Richard & ggcg's answers, that in order to sit in the zone, the only muscles tensed should be the ones you're actually using, not everything else, making you a tensed-up bundle of wasted energy.
Nothing good ever comes of being over-tense. If you're pushing too hard you will be screechy, or belty-in-a-bad-way, too far into your head, or shaky, or out of tune (probably sharp), your vibrato will be uncontrolled or unattainable, you will run out of breath. Not good for you & not good for your audience.
One thing that becomes apparent once you can get into that zone is how long you can hold a note or be able to run two lines together without running out of breath. This is a good judge of it, internally. If you're running out of breath, fading towards the end, or slipping out of tune, or you find you can't slide in & out of vibrato as you wish, can't vary vib speed or intensity, then slide back to no vib, then you're not relaxed enough.
Two fun exercises.
The big money notes at the end of Bill Withers' Lovely Day & Chris Isaak's Wicked Game. Neither is particularly difficult to sing, yet both have a good long note at the end, that you can tackle once you've used the rest of the song as a warm-up.
I wouldn't suggest ever trying either of them from cold. Use at least the full song itself to get you prepared & properly relaxed into it - then off you go. Each track gives you several shorter 'rehearsal takes' before arriving at the biggie at the end, letting you prepare for it in stages.
Neither is too difficult once you're in the zone.
Bonus points for 'playing' with your voice tone as you do it. Slide vibrato in & out, vary speed/intensity. Vary volume & intensity of the held note too, depending on your break-point move from chest to head or head to falsetto & back again.

I've actually been using the Chris Isaak as my warm-up song for about 25 years or so. I find it gives me a feel for how my voice is going to work for the rest of the day/night/session/show/whatever. It's gentle, doesn't need too much aggression & checks out whether you can open your range well enough without too much effort or any real extreme range. No belting, just control.
Added bonus for a live show on a strange stage, it lets you judge your mic proximity over several octaves & volumes for projection & on-stage monitoring. Very useful if you don't have in-ear monitoring & aren't on the monitor engineer's xmas card list for whatever reason ;)
Answer: My singing teacher sometimes says that when I tense up on high notes, and I take it to mean exactly what you write in your second paragraph: relax all muscles that are not needed (in particular in the neck), don't try to force it. (Also, focus on breathing from the abdomen, and don't worry if the tone doesn't come out as powerful as you'd like). And it helps.
The same principle applies to some degree to most instruments - tensing up reduces speed, precision and stamina - but maybe most students understand it intuitively after a while, so it doesn't have to be stressed as much?