How are chords assigned for song notes in a bar?

Question: I have this piece of song for guitar:

It has chords written on top of each bar.
But I have pieces without chords on top of them:

Is there a way to know the chords based on the notes?
Comment: Are you asking about how to spontaneously add chords to a melody or how to figure out what the published chords are, or the composer's intended chords?
Answer: Assigning chords to a melody is an art in itself, and there's no "correct" way to do it. There are countless ways to harmonize a melody with chords, but it can be learned.
Do you want to just play songs, or do you want to learn to find chords to melodies? If you want ready-made chords, there are song books and online resources for that. But if you want to learn to find chords yourself, you have to know a little bit of music theory, like (1) how to identify the key of the song, and (2) what chords are commonly used in each key. When you know these two things, you can start trying out chords until you find ones that sound good.
To get you started with the example, the second melody you posted is in the key of G major, where the most common chords to try are:

(I) G major, (IV) C major, (V) D major (or D7)
(vi) E minor, (ii) A minor, (III) B major (or B7)

And in this particular case, you also want to try:

(II) A major

I think you can tell by ear when you feel that the chord should change. Then try any of the other chords. You'll get better at it.
Answer: There are a lot of different ways to harmonize a melody. It's especially dependent on musical style.
With the examples you gave the musical style seems to be traditional or folk tunes, perhaps pop tunes.
One approach to try is use the primary chords of the key. Those are the triads built of the 1st, 4th, and 5th degrees of the scale. So in Bb major the primary chords are Bb, Eb, and F. Another common set of chords to try using includes the relative minor
 of the 1st chord instead of the 4th chord. In Bb that would be Bb, Gm, and F.
From these two simple set of chord the idea is select a chord that contains the melody note. The first chord in a bar often has special importance. Some melody notes will have two chord options. Ex. F in the key Bb could be harmonized with either Bb or F chords.
To some degree you can make choices based on if a phrases is and ending. In Bb the Bb chord can make an ending whereas F tends to create a feeling to continue. This is the level where melody harmonization is not a 'paint by numbers' process. Studying the use of chords in songs and experience eventually will guide your sense of harmonization.
My answer is just quick intro to the subject. You should seek out some books on the topic - harmony textbooks for starts - for a deeper understanding.
BTW, We Wish You a Merry Christmas is actually not a simple example to start with. Even though the song is super familiar it actually uses some chords that are not in the key. That's chromatic harmony. It isn't too hard to learn about chromatic harmony, but it definitely is not the place to start learning harmony.
Answer: There's no way to figure out the original (composer intended) chords based on melody. You might be lucky or get close by trying to infer the chords from the notes and phrases but these methods are not a sure way to "reenngineer" the original harmony. Especially as you put it "assignments to the bars" which is harmonic rythm is a bit of a guess game. For your examples the best and practical way is to simply find another source that actually has the chords written out. I'm sure you'll find chords to "We Wish You a Merry Christmas" in like five seconds.
Comment: "...no way to figure out the chords based on melody." Not true. This is actually a _very common_ music study assignment. There is a method.
Comment: I think you mistake "matching" a reasonable chords to a melody with guessing (successfully) the actual chords of a song based on melody. How would that method work for One Note Samba?
Comment: @Jarek.D ...One Note Samba, that's an interesting example, but you're cherry picking. The OP needs basic examples of the method. _After_ gaining a grasp of the topic, harmonizing melodies like One Note Samba would be appropriate. Your cherry-picked example doesn't mean there isn't a method.
Comment: @MichaelCurtis It's not a cherrypicking, but simply providing an example that falsifies the method. And I'm not saying "there is no method" but "there is not way to figure out composer intended harmony of the song based on melody". Simple answer to simple question.
Comment: @user45266 OP asks about "the correct" answer which is as composer intended. Hence my answer. I find it super weird nobody seem to get it.
Comment: @MichaelCurtis I've responded to all the comments. OP is asking "is there a way to know the chords based on the melody" and gives an example of EXISTING song. I interpret that as "chords intended by composer". Sorry, but you just keep making false statements and unfairly downvote fair answer.
Comment: That seems to be something to ask in a comment for clarification.
Comment: OP asks about existing songs and gives examples. So no, there is no method to guess the chords to existing song based on melody.
Comment: Of course there is a method. :) Particularly a method to _guess_, and it isn't really even very hard to do. The method is: when you feel the chord should change, try the other ones. For most pop songs, there aren't that many alternatives to try, if you know the key.
Comment: That's the definition of cherry picking. You have given the OP a non-answer, and mislead them about the topic.
Comment: @Jarek.D There is a way to figure out chords by melody, namely using one's knowledge of music theory and one's ear to infer chords. Not to say that there's always one correct answer, or that the "correct" harmonisation for any one version of a song can really be found, but it's not impossible.
Comment: @MichaelCurtis again, no, that is not a "definition of cherrypicking". Cherrypicking happens when a statement cannot be falsified by a single example. In this case it can. And my answer is an answer - sometimes answers are short and simple. Matching chords to melodies is an interesting subject but here it's not strictly on topic.
Comment: @Jarek.D. The OP _did not_ ask for "correct" anything. Neither the word nor that meaning are in the question. Sorry, but I have to downvote. You aren't responding to legitimate comments.
Comment: @Jarek.D After the qualifying edit, I think your answer is all right. Undownvoted, though I don't necessarily agree. Thank you for editing.
Answer: As you ask about a "song" and also your examples are showing what kind of songs you mean. So this songtunes  are mainly harmony based:

we can  derive from the final note the root tone and the key,
As the final chord normally is the tonic, we can also derive the dominant chord and
find out where the tonic in the beginning will appear (in most cases it will be in the first measure ... with exceptions.
As this songs that you might have in mind are chord based you will find some clausulas and formulas in the melody that contain the notes of a certain chord of which you can conclude what chord this must be.
There are usually chord patterns and typical progressions (as cadences and sequences, secondary fifths and subdominant cadence) underlying to the melodical ideas of the composer. (Especially in folk music and popsongs, also in blues and jazz).

But eventhough there always more or less different and more or less "originally" harmonizations possible.


Inequality in the eigenvalues of $B$

Question: Suppose $B \in M_{n \times n} (\mathbb C)$ is Hermitian. Prove that $$\lambda_{min}\leq b_{kk} \leq \lambda_{max}, \; \text{for}\; 1 \leq k \leq n.$$ With the equality in both sides for some $k$ only if $b_{kj}=b_{jk}=0,$ for all $k\neq j.$ Here $\lambda_{min} \;\& \; \lambda_{max}$ are the minimum and maximum eigenvalues of $B$ and $b_{kj}$ is the $(k,j)$- entry of $B$.   Attempt: Using Rayleigh-Ritz theorem we achieved the inequalities above. How can I show the equality in both sides if $b_{kj}=b_{jk}=0,$ does it follow from Rayleigh-Ritz? Also suppose we take the matrix $\text{diag}(1,2,3)$
does the condition $b_{kj}=b_{jk}=0,$ for all $k\neq j$ imply that $b_{kk}$ is equal to either $\lambda_{min} \;\vee \; \lambda_{max}?$
Any help and hint would be much appreciated.
Answer: It follows from Rayleigh Ritz. In particular: part of the Rayleigh Ritz theorem states that if $x$ is a unit vector with $x^*Bx = \lambda_{\max}$, then it must hold that $x$ is an eigenvector of $B$ associated with $\lambda_\max$. Now, note that if $b_{kk} = \lambda_{\max}$, then then the vector $x = e_k$ (the $k$th standard basis vector) satisfies $x^*Bx = \lambda_\max$. Similar logic can be applied in the case that $b_{kk} = \lambda_\min$.
Comment: Yup I already prove that part, what I dont know is the equality part does it follow from rayleigh ritz?
Comment: Yes, the second sentence of my answer is part of Rayleigh Ritz
Comment: Sorry can you enlighten me a bit, I dont get the part where the equality holds specially if $b_{kj}=b_{jk}=0,$ for all $k \neq j$. Also about my example does it holds? Or is it wrong?
Comment: @TokitaOhma It seems that you misinterpreted the phrase "only if". Equality holds "only if" $b_{kj} = b_{jk} = 0$ means that equality can only hold if $b_{jk} = b_{kj} = 0$. In other words: the statement is "if equality holds, then (there exists a $k$ such that for all $j \neq k$) $b_{jk} = b_{kj} = 0$".
Comment: My bad sorry about that. Sorry for my dumbness, so the example  doesnt holds?
Comment: @TokitaOhma The statement after your example is a bit too imprecise to say that it either "holds" or "doesn't hold". In your example, it is not true that $b_{kk} = \lambda_\min$ or $b_{kk} = \lambda_\max$ holds for every $k$, which is the statement that you seem interested in. In particular, $b_{22}$ is not equal to $\lambda_\min$ or $\lambda_\max$. It is true, however, that there exists a $k$ such that $b_{kk} = \lambda_\min$ and there exists a $k$ such that $b_{kk} = \lambda_\max$.
Comment: @TokitaOhma And you have nothing to apologize for. If everybody understood math perfectly the first time, there wouldn't be much reason for this website.
Comment: Thanks a lot. I guess that solves it.
Comment: @TokitaOhma You're welcome. By the way, your statement was perfectly fine; I realize now that I just read it incorrectly. The statement does not hold for your example.

Inequality in the eigenvalues of $B$


Wordpress shortcode for date in 4 days

Question: I'm trying to make a shortcode that displays the day in four days.
So far, I have this:
add_shortcode( 'datein4days', 'mythankyoupage' );
function mythankyoupage() {
    $date = date_i18n( 'j. F' );
    ob_start();
    echo $date;
    return ob_get_clean();
}

I want to do something like this:
$date = date_i18n( 'j. F' . **"+4 day"** );

But this does obviously not work.
It's important to me that it writes out my date in my local month-names.
Anyone have any suggestions?
Answer: The Wordpress date_i18n function's second parameter is the time you wish to display in the format given in the first parameter. This needs to be in UnixTime, an integer representing number of seconds since Jan 1, 1970. You can use the PHP function strtotime to get this number, passing in the "+4 days" as the parameter.
$date = date_i18n('j. F', strtotime("+4 days"));

Wordpress shortcode for date in 4 days


Best approaches for feature selection in multilabel classification

Question: I have a dataset which consists of around 46k observations and 20k features. The target vector is of length 75 (and so the target matrix is 46k x 75). Among the features few are categorical and others are numerical. What are the possible best approaches for feature selection for these kind of datasets?
I am aware that unsupervised techniques such as PCA could be applied here, but what other approaches could be applied. Many variables with 0 variance were initially removed.
Comment: why would feature selection methods for multilabel classification be any different from feature selection for any other form of classification?
Answer: Well, there are actually many feature selection methods in literature so you could try some of them. One interesting FS method is the model based one.
The idea is that you train a model with all the features and then calculate the feature importance (it is provided by many models e.g. in scikit-learn). You keep only those features that are in the top-N positions or those whose importance is above X. You have to select N or X manually.
Take care to do this inside a cross-validation loop. A good idea is to keep features who remain in the top-N positions for all CV folds. You can adapt this procedure to work for the multilabel classification setting.


set variable _SERVER["PHP_AUTH_USER"] using php

Question: I need a little help with php_auth I have used HTTP authentication with Php and it seems to working fine (when you go to the url it asks for username and password and is working fine) but what i need to do is pass the username and password for the authentication from another page and authenticate automatically. Something like set variable _SERVER["PHP_AUTH_USER"] using php from another page.

Edit: I forgot to mention that My problem is that two pages are completely different application and
  both maintain separate sessions. Application "A" and Application "B"
  may or may not be hosted on the same domain.
Answer: I used a zend function setAuth(username, password); to get the work done.
$client = new Zend_Http_Client();
$client->setAuth($username, $password);
$response = $client->request('POST');

How the setAuth function works is it embeds/encodes the authentication params as header to the url
// Set HTTP authentication if needed
if (is_array($this->auth)) {
     $auth = self::encodeAuthHeader($this->auth['user'], $this->auth['password'],      $this->auth['type']);
       $headers[] = "Authorization: {$auth}";
}

Answer: You can pass around whatever data about the user you want between requests with sessions.
//on one page
session_start();
$_SESSION['logged_in_user'] = $_SERVER['PHP_AUTH_USER'];

//on the 'another page'
session_start();
$user = $_SESSION['logged_in_user'];

http://php.net/manual/en/features.sessions.php
Comment: I tried but doesnt work with my code. heres a snippet of the code
`//page of application 1:
$_SESSION['USERNAME'] = 'username';
$_SESSION['PASSWORD'] = 'password';
$client->setUri("http://application2.com/some/");
$response = $client->request('POST');

//page of application 2:

if(isset($_SESSION['USERNAME']))
$_SERVER['PHP_AUTH_USER'] = $_SESSION['USERNAME'];
return (isset($_SERVER['PHP_AUTH_USER'])) ? $_SERVER['PHP_AUTH_USER'] : null;
// but the function is always returning null `

_I am using zend and sessions are auto started. Is it like sessions cannot be used with requesting uri?_
Comment: Next time, provide the details of what you're doing. We answered based on what you wrote last week. You said you wanted to pass details between pages, not between different sites on different hosts. Since that's not the actual situation, you wasted everyone's time and didn't get the help you needed.
Answer: You should use the $_SESSION for this. $_SESSION is meant to pass variable from pages.
on each script when you need to access a session variable :
session_start();
$_SESSION['user'] = $_SERVER['PHP_AUTH_USER'];

And on the other script :
session_start();
$user = $_SESSION['user'];

Have a look here : http://www.tizag.com/phpT/phpsessions.php and there for the php reference : http://www.php.net/manual/en/session.examples.basic.php
Comment: My problem is that two pages are completely different application and both maintain separate sessions. Application "A" and Application "B" may or may not be hosted on the same domain.


Who acts as load balancer if I have several dispathers in cq5 web application?

Question: As I understand, usually in CQ5 dispatcher acts as load balancer.
But I know that our instance has several dispatchers.
I imagine this like so:

What do you think about this picture? Is it possible variant?
Which variants are possible else?
What does act as load balancer at this case?
Comment: We usually just have one disptacher per publish instance and never used it as a load balancer. Check the documentation at http://docs.adobe.com/docs/en/dispatcher.html
Comment: But I know that we have several dispatcher per environment
Answer: There is a sector of devices called Hardware Load Balancers that are a part of network layer that can act as top level load balancers. This item looks similar to hub/router but is able to balance the traffic.
Quite often, load balancing is solved on the cloud e.g. Amazon provides such functionality through Elastic Load Balancing. This way it's a provider responsibility to divide the traffic equally and care about system durability via healthchecks.


Permutation-How to approach problems that have "At Least" requirements?

Question: I am trying to solve this problem on my own yet it is somewhat tricky because I have never seen this type of problem before.
Say I need to create a 10-character password from uppercase letters and digits with following requirements:

The password must contain at least $3$ uppercase letters
The password must contain at least $1$ digit
The digits cannot be repeated

I tried to apply the permutation formula $\boldsymbol{n!/(n-r)!}$ to this problem yet I still cannot see the pattern, and my original thought was that since at least 3 character must be letters, I only had $7$ choices left, and then I just got stuck because I could not make it work on the digits part.
I would be much appreciated with the help, thank you
Comment: The permutation formula only applies when no object can be repeated, which is not the case for the uppercase letters here.
Answer: [choose spaces for alphabets and insert]*[permute digits in remaining space]
Assuming English alphabet,
With $3$ repeatable alphabets, $7$ distinct digits, we get $\binom{10}3\cdot{26}^3\cdot P^{10}_7$
Continue thus upto  $9$ repeatable alphabets and one distinct digit, viz $\binom{10}9\cdot{26}^9\cdot P^{10}_1$ and add up computations from $3 \;thru\; 9$ repeatable alphabets
Comment: Thank you, that really gave me an insight on how to solve this problem, but there are still quite a few things that I don't understand. I understand that add computations from 3 through 9 part, but I don't get it why do we need to multiply 26 to the power of 3 through 9, and that would be a really huge number. Would you care to elaborate more on that? Thank you
Comment: Well, if you used only alphabets, the number of three letter passwords would be $26\times26\times26\; = 26^3$, wouldn't it, because you are allowed to repeat a letter, each slot has $26$ possibilities. This is just the *multiplication principle*
Comment: Oh, I get it now, I just didn't expect it to be such a great number, thank you for your help
Comment: You're welcome !


Covering songs by other artists - does money change hands?

Question: Many bands cover songs by other bands, unofficially at concerts, or usually on live recordings (for example, Kurt doing Man Who Sold the World by David Bowie, at an MTV unplugged concert.
I always thought it was a form of "bigging up" the other band.  The other band being covered is probably complimented by the "free promo" they get by having their song re-done by another set of hands.  But, perhaps there is more to it.  Perhaps there is money changing hands for the privilege to cover a song.
Is it so?  Or do most people just perform the cover without permission from the original artist/estate?
Looking for a practical what actually happens answer, not "legal advice" or what a "should happen" answer.
Answer: Is it only performance of the covers you are interested in, or also recording the covers?
If the former, in practice I suspect most small, independent bands DON'T contact the original artist and ask permission to perform a cover of their song - unless the artist is a friend! As a case in point, my little band haven't contacted Joni Mitchell (whose songs we perform regularly). [In legal terms, as far as I understand, this is all fine because the venues in which we perform should be paying a fee to a performing rights organisation such as PRS etc.] We have, however, contacted our singer-songwriter friend to ask permission to use her songs. No money changed hands for that, and we do a bit of mutual advertising.
Recording a cover is a different matter, however, and I believe it doesn't matter whether it is a recording of a live performance or a studio recording. Legally you are required to get a license from the band whose songs you are covering. I can't vouch whether all bands follow the law, but as an example of 'what actually happens' I can tell you what my band did when we released a CD including covers of other artists' songs:

We contacted the bands (which included successful folk artists such as Show of Hands and Tracy Grammer) whose songs we were covering, explained we would like to put our versions of their songs on a CD that we'd be selling, and asked their permission/conditions.
Some of them sent us a standard 'Mechanical License Request Form' with a fixed royalty rate per 1000 copies of CDs produced. We paid this rate upfront.
Some of them gave us permission to use their song for no payment, but told us how they would like to be credited.
One artist's estate refused permission. We therefore did not record their song.
For singer-songwriters who are our friends, we drafted a suggested Mechanical License Request Form for their agreement - to respect the fact that they too deserve to earn money from their music! We are therefore still both colleagues and friends.

So this specific example reflects both your scenarios, the no-money 'bigging up' and the 'money-changing-hands'. I have to say, though, as a small independent band we are providing only limited promotion to any successful band whose songs we cover, so it makes sense for us to pay for the privilege of using their material!
Comment: @Phelios, I don't know, but the PRS website says that there are performing rights organisations all over the world (http://www.prsformusic.com/creators/wanttojoin/how_it_works/international/Pages/default.aspx) and they work together. So from this I would assume that Malaysia has something similar and that therefore the Stadium pays a performing rights organisation. As far as I know, regardless of whether the venue has an arrangement with such an organisation, the performer still doesn't pay. My search found MACP (http://www.macp.com.my) which might be the Malaysian equivalent...
Comment: when your band grow bigger and famous, I believe you will start touring. What happen when you cover other songs that are not in your album during your tour?
Comment: @Phelios, the same would apply as above - during the live performances on tour there is no problem (venues pay the PRS, the performers don't have to do anything), however if we want to record any of these performances, or release another CD with these new covers, we'll need to contact the relevant artists. As an aside, the company who manufactured our CD asked us to provide evidence that the artists we were covering had given permission for us to record their songs - so it's just as well we'd taken the legal approach!    (PS. Roll on the 'bigger and famous' days! :-D)
Comment: You need no agreement whatsoever to cover a song in the UK, so long as you don't 'substantially' alter it. In the US you need to get a Mechanicals licence.
Answer: We have two songs we play differently live to studio, one because it has two bars the owner refused to licence to us for recording, and the other one which has a range of riffs we play at the end that are instantly recognisable and despite getting permission for a couple it was too difficult to get all of them.
Live, it is a non-issue. Performance royalties are paid to the performers from PRS subs from the venue.
On a recording, the mechanical royalties will be the issue. Get agreement from the owner here (in writing) and you'll be fine.


Quotient of a quotient.

Question: Let $\mathfrak{g}$ be a complex reductive Lie algebra. Let $M,N,L$ be finite dimensional $\mathfrak{g}$-modules.
Suppose $M$ is a quotient of $N$ and $N$ is a quotient of $L$.
My question: Is $M$ a quotient of $L$?
Comment: Where presumably "being a quotient" means "being isomorphic to a quotient"? (Otherwise it's almost never true.)
Comment: Yes. That is what I meant. Thank you for pointing out this issue.
Answer: If $q: L \twoheadrightarrow M$ is the canonical quotient map for $M$, and $p: M \twoheadrightarrow N$ is the canonical quotient map, then $pq: L \to N$ is surjective, and thus $N \cong L / \mathrm{ker}(pq)$.
Note that this did not use any structure of $\mathfrak{g}$ or the finite-dimensionality of the modules $L$, $M$, and $N$; it follows only from the fact that if $\varphi: A \twoheadrightarrow B$ is a surjective morphism of "modules," then $B \cong A / \mathrm{ker}(\varphi)$. This is true for abelian groups, and a "module" of any kind should be an abelian group with extra structure. In fact, this fact is true* in any abelian category, which are the most general categories of modules.
*: modulowink wink replacing surjectivity with the categorical notion of epimorphism.

Quotient of a quotient.


javascript confirm cancel still submits form

Question: I have the following sequence on a form page, first it runs through the captcha then it validates the email address and then asks if you are sure you want to unsubscribe.
Everything works perfectly except that clicking "Cancel" still submits the form.  I can't use "onclick" in the submit button because it will bypass the captcha code.  In my "if the email is true 'else'" statement I've tried both "return" and "return:false" but neither of them stop the form submission.
Thanks for your help.
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' name="unsubscribe" method='post' onsubmit="return checkForm(this);"">

function checkForm(form) {
var frm = document.unsubscribe;
 if(!form.captcha.value.match(/^\d{5}$/)) {
      alert('Please enter the CAPTCHA digits in the box provided');
        form.captcha.focus();
        return false;
        }
        if (validEmail(frm.Email.value) != true) {
                alert("Please enter a valid email address");
                frm.Email.focus();
                return false;
        }
        if (validEmail(frm.Email.value) == true) {
                confirm('Are you sure you want to unsubscribe?');
                return true;
        }
        else {
            return false;
    }
}

function validEmail(email){
    var status = false;
    var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
    if (email.search(emailRegEx) == -1) {
    status = false;
}
    else {
    status = true;
}
    return status;
}

Comment: Your code does not check the return value from `confirm()`.
Comment: Also use `return emailRegEx.test(email);` instead of the code you have; yours will always return `true`.
Comment: possible duplicate of [JavaScript Form Submit - Confirm or Cancel Submission Dialog Box](http://stackoverflow.com/questions/6515502/javascript-form-submit-confirm-or-cancel-submission-dialog-box)
Answer: confirm returns a boolean - true if the user clicked "Ok", false if they clicked "Cancel", so simply return the result of the confirm call:
if (validEmail(frm.Email.value) == true) {
  return confirm('Are you sure you want to unsubscribe?');
}


Trocar valores de objetos vindo da api?

Question: é possivel mudar valores no frontend vindo a api?
Por exemplo, eu tenho uma api que me retorna isso:
"data":[
"nome": "sp",
"nome": "mg",
"nome": "rj"
]

Aí eu por exemplo faço um simples request dela usando GET
this.axios.get("http://localhost/api/exemplo/").then(response => {
    this.items = response.data;
});

Tem como no frontend eu trocar esses valores para eles serem exibidos de uma forma mais "agradável" pro usuário? Isso sem ter que alterar nada no banco, e exibindo isso num v-for.
Como por exemplo : São Paulo, Minas Gerais, Rio de Janeiro
Comment: Como assim **trocar esses valores para eles serem exibidos de uma forma mais "agradável" pro usuário** e **exibindo isso num v-for.**??
Comment: Se eu fizesse um v-for com essa array `items` ele me exibiria: `sp`, `mg`, `rj`.
E eu queria saber se há alguma forma de mudar isso. Esse é só um exemplo de algo próximo do que eu quero fazer, que realmente não rola trocar os nomes pelo banco.
Comment: Ué claro que tem como, partindo do seu exemplo que os valores são um **array**, você pode pegar e mostrar cada valor separadamente através do `índice` do array, não precisa fazer um **for**.
Comment: O retorno da API que você mostrou não é nem JSON válido. É um array? é um objeto? se for array vai dar erro porque um array literal não tem chaves, e se for um objeto também vai dar erro porque não dá pra ter chaves duplicadas.

Ajusta isso pra gente entender melhor por favor
Answer: Recomendo se for possível, você aplicar essa alteração na sua api, pois normalmente seu front-end deve ser apenas um consultor de dados, caso você tenha essa informação no lado da api, pode tentar enviar esses dados da seguinte maneira:
"data": [
   {"acornym": "sp", full_name: "São Paulo"},
   {"acornym": "mg", full_name: "Minas Gerais"}
]

Mas como fazer isso se você não pode alterar no banco? Bom, se estivermos falando apenas de estados brasileiros, recomendo vc usar alguma solução de internacionalização, e usar as siglas como chaves e as strings como valor, essa solução se limita a opções fixas no seu sistema, pois não necessita de alterações no banco de dados. Abaixo deixarei um exemplo de arquivo .yml para deixar mais claro o que eu quis dizer
sp: 'São Paulo'
mg: 'Minas Gerais'
...

Caso as opções sejam dinâmicas, e você não tenha controle, recomendo fazer um esforço e criar mais uma informação no seu banco de dados. Espero ter ajudado, abraços!
Comment: Mas não é errado eu ter 2 colunas no banco pra esse tipo de coisa?
Comment: Não, vamos imaginar uma tabela chamada Estado, poderíamos ter dois atributos: acronym, e full_name, o que nos ajuda a guardar a informação por completo.
Comment: Então são duas colunas, em todo caso. Mas valeu.
Answer: Uma forma que utilizo para alterar um retorno é pela função map(). Usando o seu exemplo ficaria assim:
this.axios.get("http://localhost/api/exemplo/").then(response => {
   this.items = response.data.map(item => {
      //alteracões que desejar no objeto item
      return item;
   });
});

Você pode usar a mesma ideia para filtrar:
this.axios.get("http://localhost/api/exemplo/").then(response => {
   this.items = response.data.filter(item => {
      //Se o retorno for true então fará parte do novo array.
      return item.nome == "sp";
   });
});

Trocar valores de objetos vindo da api?


The Properties.load would close the InputStream?

Question: I saw this example, and I didn't see the close() method invoked on the InputStream, so would prop.load() close the stream automatically? Or is there a bug in the example?
Comment: I just checked the java code for load(stream) and it doesn't close the stream.
Comment: Bug in the example. `Properties.load()` doesn't close the stream. You have to do that. Very poor quality example all round.  It wouldn't even work on some operating systems. Don't rely on arbitrary Internet junk. Use the Oracle Java Tutorials.
Answer: The Stream is not closed after Properties.load ()
public static void main(String[] args) throws IOException {

    InputStream in = new FileInputStream(new File("abc.properties"));

    new Properties().load(in);

    System.out.println(in.read());
}

The above code returns "-1" so the stream is not closed. Otherwise it should have thrown java.io.IOException: Stream Closed
Answer: Why do you ask when the javadoc of Properties.load(InputStream inStream) says this?

The specified stream remains open after this method returns.

It has been saying that since Java 6.
As EJP said in a comment: Don't rely on arbitrary Internet junk. Use the official Oracle Java documentation as your primary source of information.
Answer: The following try-with-resources will close the InputStream automatically (you can add catch and finally if needed):
try (InputStream is = new FileInputStream("properties.txt")) {
    // is will be closed automatically
}

Any resource declared within a try block opening will be closed. Hence, the new construct shields you from having to pair try blocks with corresponding finally blocks that are dedicated to proper resource management.

Article by Oracle here: http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html.


Lack of required permissions despite being member of group whit appropriate permissions

Question: I have strange issue with file permissions.
F.e. On Windows 7 under Virtual PC I have VM with enabled undo disk.
Permissions for .vhd file of this VM grant full control to local Administrators group, of which I'm a member. I have checked in advanced properties of this file and confirmed that my user account (it domain account) has full effective permissions.  Ok, this expected. However, when I try to applying changes in virtual machine undo disk, I receive an error message saying that one of master or undo disk for this VM is busy (I have checked, this is not true - both files are not open by any process). Notice, that this error message doesn't mention anything about permissions at all! However, after explicitly granting to my domain account full permissions  for this VM vhd file (which doesn't change my effective permissions, as I already have full permissions as a member of local administrator group! I have checked it!), I could apply with any errors changes made to VM undo disk!
Strange.
Described here case of applying changes to VM undo disk is only one example of many other similar situations, when granting appropriate permissions to groups of which I'm a member is not enough and I have explicitly grant permissions to my account  too. I have observed this behavior under Windows 7 and Windows Server 2008, but not on Windows XP.
(P.S. In any of such case, none of permissions entry uses explicitly denying permissions)
Could someone explain me where is the problem?
Answer: I'm not familiar with all the pieces of what you're doing, but any time that I find that adding explicit permissions for an account with "Administrator" permissions "works" when an already-existing permission applying to "Administrators" isn't working I think "User Account Control". I have a suspicion that the operation you're attempting that's failing is running with a token that has your domain account's "Administrators" group membership stripped out of it. Applying a permission that explicitly names the domain user account "works" because your token does have your account's SID in it.
Try doing the operation from an "Administrator" instance of "Explorer" or command-prompt and I think you'll find it works fine w/o the explicit permission being added for your domain account.
Comment: Hm, you probably have right, that may be an explanation, but shouldn't I get an UAC prompt in such situations?
Comment: UAC prompts come from "Explorer". Other applications that you run aren't going to generate them. I'm not familiar with "Virtual PC" at all, so I don't know *exactly* what you're doing. My guess is that you're running something that doesn't bother checking to see if it's running w/ a stripped token and doesn't ask Explorer to elevate. You can graphically demonstrate this by running a command prompt while logged-on as an "Administrator" user w/o elevating and then trying to change a file in the "\WINDOWS" directory. You'll just get an "Access denied" message-- no UAC prompts at all.


React Native - Dismiss Menu on Any Touch Event

Question: I would like to have a small menu that closes if the user interacts with any other component. For example if the user tries to scroll or interact with any of the content in a scrollview behind the menu (see the image below for reference).

I have two ideas for how this might be achieved:

A transparent layer behind the menu with an absolute position and dimensions matching the device. If this layer registers a touch event the menu can be dismissed. The problem with this is that from the users perspective the touch event was totally ignored. So for this to work well I would need to be able to still pass the touch event through the absolute layer to the content behind it.
Add callbacks to every component that could be interacted with to notify the menu that it should close. This option seems like it would be very messy and because of the large number of components in my use case it is not practical to implement and maintain.

Is there an other proper way to solve this problem? Can any of the issues I raised with the ideas above be resolved or mitigated?
Answer: Wrap your view with a TouchableWithoutFeedback component and provide it a onPress callback that hides the menu if it's open. Depending on how top-level the 'expand' icon is, you may want to track the menu's visibility in redux and dispatch an action onPress to track globally.


How do you estimate correlations between ordinal and binary data in SPSS?

Question: I'm struggling with my lab report. I have a questionnaire which contains Likert responses (1-7) as well as questions that require only yes or no answers. I want to see if there is a correlation between higher scores on the likert scale and responses to the binary answers to the other questions.
Specifically - the likert response is about anxiety levels. The binary (yes/no) answer is about negative consequences due to alcohol use. I want to just run the one ordinal likert item with all the negative consequence responses to see if there is a relationship. Can anyone help me?

Thanks so much for the fast comments. It definitely assures me that Spearman's Rho can be used but my main problem is the fact that i am mixing binary and ordinal variables together in the one correlation matrix.  I have one ordinal variable (anxiety - 1-7 on likert scale) crossed with 13 dichotomous (0 or 1 representing yes or no) to answers ("have you ever been hospitalised due to your alcohol use?). I get statistically significant answers (<.05 and < .01 but the Correlation coefficients are tiny (i.e o.2) at best.
the hospitalisation is the DV an the anxiety levels the IV.
I just think i'm doing something wrong here. should i collapse the 13 binary variables in to one some how?
i can't see how SPSS will recognise the values between 1-7 when correlating with binary answers. i keep thinking it will just read that there is something in that box (ordinal) but not recognise the value (i.e 1-7) . but people keep saying that SPSS does in fact recognise this difference and account for it.
Comment: What is your hypothesized relationship among the variables? Is the Likert scale question to be thought of as a dependent variable? An independent variable? Neither? (Sounds like a DV to me, that is, anxiety depends on consequences).
Answer: If you're comparing the correlation of two variables, just report the Spearman correlation coefficient. The Spearman correlation is recommended over Pearson correlation for this type of data: How to choose between Pearson and Spearman correlation?.
If you want to know how multiple variables impact the answer to one of the binary questions, do a logit or probit model. I've never used SPSS, but I'm sure there's a menu option for it. Select the binary answer as the dependent variable in the model.
Answer: When one of the variables is binary (such as group membership) just any kind of correlation (whether the other variable is continuous, likert ,  ...) is not much more than some rescaled version of some difference of means between the two groups defined by the binary variable.   So normally it is better to just focus on difference in mean (or some kind of mean, mean of ranks, ...). Se my answer to this question:  Correlations between continuous and categorical (nominal) variables


MDX - Média Mensal aberta por Data

Question: Necessito de uma grande ajuda.
Estou trabalhando com MDX para geração de gráficos no Pentaho - CDE / CTools. E necessito realizar uma série de filtros que serão setados pelo usuário. O gráfico é uma evolução diária, e eu gostaria de adicionar uma linha de média no mesmo. Porém não está dando muito certo.
O que estou fazendo de errado? Não tenho muito conhecimento com MDX. Deveria aparecer os valores e repetir a média do mês todo, mas está repetindo os mesmos valores.
WITH
MEMBER [Measures].[MEDIA] AS
AVG ([MES].[MES].CurrentMember, [Measures].[QTDE])
SELECT NON EMPTY {[Measures].[QTDE], [Measures].[MEDIA]} ON COLUMNS,
       {[DATA].[DATA].Members} ON ROWS
from [DW20_DIA]
where Crossjoin(Crossjoin(Crossjoin({[MES].[All MESs]}, {[CAUSE].[All CAUSEs]}), {[TIPO].[All TIPOs]}), {[MODEL].[All MODELs]})

Com algum filtro:
WITH
MEMBER [Measures].[MEDIA] AS
AVG ([MES].[MES].Currentmember , [Measures].[QTDE])
SELECT NON EMPTY {[Measures].[QTDE], [Measures].[MEDIA]} ON COLUMNS,
            NON EMPTY {[DATA].[DATA].Members} ON ROWS
from [DW20_DIA]
where Crossjoin(Crossjoin(Crossjoin({[MES].[2016-11-01]}, {[STOP CAUSE].[All CAUSEs]}), {[TIPO].[All TIPOs]}), {[MODEL].[All MODELs]})

Amostra dos dados - Neste caso a média deveria ser: 7.567.743
  DATA        QNTD        MEDIA         MEDIA DEVE SER
01/11/2016  7.731.442   7.731.442       7.567.743
02/11/2016  7.973.846   7.973.846       7.567.743
03/11/2016  7.430.333   7.430.333       7.567.743
04/11/2016  7.517.061   7.517.061       7.567.743
05/11/2016  6.738.677   6.738.677       7.567.743
06/11/2016  6.796.424   6.796.424       7.567.743
07/11/2016  7.631.584   7.631.584       7.567.743
08/11/2016  7.907.649   7.907.649       7.567.743
09/11/2016  8.995.933   8.995.933       7.567.743
10/11/2016  7.444.471   7.444.471       7.567.743
11/11/2016  8.039.431   8.039.431       7.567.743
12/11/2016  7.240.583   7.240.583       7.567.743
13/11/2016  6.779.103   6.779.103       7.567.743
14/11/2016  7.648.149   7.648.149       7.567.743
15/11/2016  7.641.452   7.641.452       7.567.743

----- Edição:
Consegui acesso aos objetos e criei uma dimensão de tempo.
Ano - Mes - Dia
Tentei esta query, mas não deu muito certo.
WITH MEMBER [Measures].[MEDIA] AS
Avg( Descendants([TEMPO].[MES].CURRENTMEMBER, [TEMPO].[DATA])
, [Measures].[QTDE]
)
SELECT {[Measures].[QTDE], [Measures].[MEDIA]} ON COLUMNS,
            NON EMPTY{[TEMPO].[DATA].MEMBERS} ON ROWS
FROM [DW20_DIA]

Ele repete os mesmos valores para todos os dias.
Comment: Você tem uma dimensão de tempo com hierarquia (ano, mês, dia)? Ou apenas dimensões separadas de Dia, Mes e Ano como parece ser pelos "Unique Names" que estão no MDX? Normalmente você usa uma dimensão de data com hierarquia colocando o nível de dia na linha e usa a função "Descendants" para tirar a média com os membros da mesma dimensão no nível "dia"
Comment: @Pagotti, sim, são duas dimensões separadas. Construíram os objetos errado. Acabei de criar uma dimensão de tempo, vou tentar montar a query novamente. Obrigado.
Comment: @Pagotti criei uma nova dimensão... mas ainda não consegui...
Comment: `[Tempo].CurrentMember` ao invés de `[Tempo].[Mes].CurrentMember` ajuda?
Comment: @Pagotti Se eu coloco apenas `Descendants([TEMPO].CURRENTMEMBER, [TEMPO].[MES])` e no select uso `NON EMPTY{[TEMPO].[DATA].MEMBERS}` a coluna de média retorna vazia.
Comment: @Pagotti coloquei no quadro ali, como deveria aparecer... Deveria aparecer o mesmo valor pro mês todo, e alterar quando selecionado.
Comment: Talvez ele não esteja pegando todos os itens. Tente especificar para trazer todos dessa forma: `Descendants([TEMPO].CURRENTMEMBER, [TEMPO].[DATA], SELF_BEFORE_AFTER)` - Desculpe as tentativas é que não tenho um ambiente OLAP para testar.
Comment: Outra forma seria buscar os dias pelo membro pai: Descendants([TEMPO].CURRENTMEMBER.PARENT, [TEMPO].[DATA]). Vou colocar essa opção como resposta, caso funcione.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/56609/discussion-between-pagotti-and-fernando-a-w).
Comment: @Pagotti... Perfeito, o Parent funcionou...  Desculpe a demora, tive que sair para uma reunião, testei aqui agora e funcionou perfeitamente...
Answer: Use a função Descendants
A função Descendants retorna os membros de um certo nível a partir do membro especificado. Assim, você teria como set de resultado para aplicar no AVG as datas que são filhas do mês da data corrente. Quando colocar na linha os dias, para cada linha ele vai pegar o mês daquele dia e buscar todos os dias daquele mês e tirar a média com os valores.
WITH MEMBER [Measures].[MEDIA] AS
   Avg( Descendants([TEMPO].CURRENTMEMBER.PARENT, [TEMPO].[DATA])
      , [Measures].[QTDE])
SELECT {[Measures].[QTDE], [Measures].[MEDIA]} ON COLUMNS,
       NON EMPTY{[TEMPO].[DATA].MEMBERS} ON ROWS
FROM [DW20_DIA]

MDX - Média Mensal aberta por Data


Delegates help java to c#

Question: I am trying to have some fun by converting some java into c#, I have the following code from java.
public void calculate() {
    UnivariateFunction forceBalance = (double x) -> {
        return Mu - k1 * fcu * b * x * (d - k2 * x);
    };
    BrentSolver biSolver = new BrentSolver(1e-6);
    x = biSolver.solve(1000, forceBalance, 0, d / 2, 1);

    As = Mu / (gamma_r * fy * (d - k2 * x));
}

No all i can find in c# is that seems to solve this MathNet.Numerics as this contains RootFinding.Brent.FindRoot.
I found other stuff that could solve this however I do not have $900.
Here is what i have come up with however i think I might be missing something as my knowledge regarding delegates isn't the best.
class Program
{
    public static double Mu = 100e6;
    public static double K1 = 0.45 * (1 - (Math.Sqrt(fcu) / 52.5));
    public static double fcu = 30.00;
    public static double b = 300.00;
    //public static double c = 0.00;
    public static double d = 500.00;
    public static double k2  = (Math.Pow(2 - Math.Sqrt(fcu) / 17.5, 2) + 2) / (4 * (3 - (Math.Sqrt(fcu) / 17.5)));

    static void Main(string[] args)
    {
        Calculate();
    }

    public static void Calculate()
    {
        Func<double, double> abc = x => Mu - K1 * fcu * b * x * (d - k2 * x);

        var a = MathNet.Numerics.RootFinding.Brent.FindRoot(abc, 0, 10000, 1e-6);

        Console.WriteLine();
        Console.ReadLine();
    }

}

Running this gives me the following error: failed, exceeded the number of iterations allowed or there is no root within the provided bounds.'
Now i am assuming that this is because the func isn't resolving x.
Am i missing something?
Also please take note that this is way above my skill level but I am trying to improve.
Comment: Why do you try to solve quadratic equation numerically?
Answer: Input Values
Firstly if your question is about input values, look at the answer posted by soton. You may be using the wrong FindRoot input values. Brent Math.Net.
double FindRoot(Func<double, double> f, double lowerBound, double upperBound, double accuracy, int maxIterations)

Delegates
Now, with your question I believe you are asking about how delegates are handled in C# vs Java. (I won't spoil your fun).
A delegate is the placeholder for a method which matches a specified signature (a reference to a method).
The following is an example of a variable which matches the delegate type of Func<int, bool> meaning it accepts an integer (x) as a parameter and return a boolean.
The way this example is declared (with an anonymous method body) is known as a Lambda Expression.
Func<int, bool> greaterThanZero = (int x) =>
{
    if (x > 0)
        return true;
    else
        return false;
};

Here is the same again, but the delegate variable is assigned from a method declaration.
Func<int, bool> greaterThanZero = SomeGreaterThanZeroMethod;

How do we call a delegate? We Invoke it! e.g.
bool isGreater = greaterThanZero(5);         // should be true
bool isGreater = greaterThanZero.Invoke(-1); // should be false

In many situations you will want to make sure the method body is not null e.g.
bool isGreater = false;
if (greaterThanZero != null)
    isGreater = greaterThanZero.Invoke(-1);

Or using the fancy new Null-Conditional Operator (?)
bool isGreater = greaterThanZero?.Invoke(-1);

There is more here than you could possibly sum up in an answer. Some resources:
https://www.tutorialspoint.com/csharp/csharp_delegates.htm
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions
Comment: Increasing maxIterations count won't help if there is no root on the inteval
Comment: Hi, Thank you so much for the reply, I gave up on using Brent. Turns out having a math genius as a friend pays off. He helped by just doing the maths without any helper functions then we just converted that to code, also turns our Delegates isn't magic and I had no idea what they should actually be used for. Your explanation helped a lot thank you.
Comment: You are correct. I'm trying to work out if he wants to know correct input values or how to use delegates? I'll update section about iterations in my answer.
Answer: Your isssue is neither caused by MathNet Numerics implementation of Brent method nor by improper delegates usage. You get this error because there are both roots in fact on the interval provided and evaluation of the given function for both interval ends results in positive numbers i.e. 100000000 and 162453965327 while Brent method requires them to differ in sign. Actual roots for this particular equations are about in 51.8 and 1057.15 so your input interval should contain a point between these two.
To be honest I am a bit surprised why Java implementation works for this set of parameters. Are you sure you have not mistyped anything during conversion?
Comment: I appreciate the help but to be honest it is still way above my skill level. I will stick to what I am good at (Developing web applications) and leave the maths to the math gods.

Delegates help java to c#


How to find the parametric vector $r(u,v)$?

Question: find the  area of that portion of the paraboloid $x^2 + z^2 = 2ay$ which is cut off by the
plane $y = a$
My Question : How to find the parametric vector  $r(u,v)$  of the given paraboloid cut off by the plane $y = a$?
My attempt :I was thinking about $x = r \cos θ$, $y = r \sin θ$ but it doesn't work
Answer: It is the circle $x^2+z^2=2a^2$ in the plane $y=a$
$\left(a\sqrt{2} \cos t,a,a\sqrt{2} \sin t\right);\;t\in [0,2\pi]$
It's area is $2a^2\pi$
Comment: thanks  a  lots for diagram @Raffaele sir


How do I interpret a negative relative standard deviation and a relative standard deviation greater than 100 in this example?

Question: I have the following astronomical data
data1vcoord =array([[ 709.4497, 1500.3387, 1573.9434,  292.9126,  930.4643],
[1423.7768, 1242.1892,  407.6168,  346.3528,  541.8568]])
data10vcoord=array([[ 718.5531, 1505.431 , 1579.0752,  298.2245,  935.6432],
[1379.5269, 1236.0935,  401.8907,  341.7608,  535.6279]])
which are coordinates of stars in 2 images, and I want to calulate the standard deviation of the shifts and say how good or bad it is. The following are python commands
<code>shift=data1vcoord-data10vcoord
shiftx,shifty=shift

meanshiftx=shiftx.mean()
meanshifty=shifty.mean()
meanshiftx
-5.963659999999971
meanshifty
13.378520000000037

stdshiftsx = np.std(shiftx)
stdshiftsy = np.std(shifty)
relstdshiftsx= 100*stdshiftsx/meanshiftx
relstdshiftsy= 100*stdshiftsy/meanshifty

#How wel do the values agree? To answer the question let's find the relative standard deviation

stdshiftsx = np.std(shiftx)
stdshiftsy = np.std(shifty)

relstdshiftsx= 100*stdshiftsx/meanshiftx
relstdshiftsy= 100*stdshiftsy/meanshifty
stdshiftsx
1.571614833984457
stdshiftsy
15.446430668397145

Here I am computing the relative standarddeviation
relstdshiftsx
-26.35319307244988
relstdshiftsy
relstdshiftsy
115.45694642155561
</code>
question: How do I interpret these results?
1) relstdshiftsx= -26.35319307244988
The formula for the relative standar deviation that I used is 100*SD/mean, if the mean is negative as it happened in my case for one of my means, this value is negative, so how do I interpret this?
2)relstdshiftsy= 115.45694642155561
How come I am getting more than 115, it is supposed to be a percentage, doesn't it? I should be getting at most 100
Comment: Relative coordinates rarely are meaningful because they can totally change simply by changing the origin of the coordinate system.  And percents can be literally any number (even negative), because they are merely re-expressing ratios.  What, then, you you intend to mean by "interpret"?
Comment: @whuber This are shift in coordinates, but that does not matter, forget they are coordinates. what is the range of acceptable values for a relative std deviation to consider it low? 0 to x%, x=?
Comment: and 115%? Shouldn't the relative std be less than 100, since it in percentange?
Comment: That's unanswerable because (1) as I said, your statistics are meaningless and (2) even if they were meaningful, that's a question for your application, whatever it might be.  I recommend you review the concept of percent (with a focus on the distinction between percent and proportion) before proceeding.
Comment: @whuber Why is the statistics not meaningful? These are not relative coordinates. The data are the variation of coordinates (shifts) in two pictures that a camera is taking. The image is not supposed to move, but due to imperfections in the camera or many other reasons, the image may move a bit. So we have these shifts and want to assess how good or bad is this variability. So we are not supposed to change the origin or anything, although that may not affect the shift between two images either
Comment: And I haven't invented this stuff, it is standard in astronomy. And my question was about the relative standard deviation. I wanted a normalized interpretation of the standard deviation so I found this concept of relative standard deviation but it looks like it is not a number between 0 and 100 in absolute value, unless numpy is calculating the standard deviation with "n-1" in the denominator, and I getting another value of standard deviation
Answer: This is the shift data you seem to be analysing:
<code>> shift
      shiftx  shifty
[1,] -9.1034 44.2499
[2,] -5.0923  6.0957
[3,] -5.1318  5.7261
[4,] -5.3119  4.5920
[5,] -5.1789  6.2289
</code>
So $x$s shifted down and $y$s up (and the first pair of shifts looks distinct compared to the other four).

Since all the $x$ shifts were negative, $\bar x$ was also negative while $s_x$ is inevitably positive, and so $\frac{s_x}{\bar x}$ is also negative and you calculate it as $-26\%$ (without Bessel's correction).  Shifts can be in either direction so the sign should not worry you.

Since one of the $y$ shifts is over $7$ times the others, $s_y$ is large compared to $\bar y$, and you calculate $\frac{s_y}{\bar y}$ as $115\%$.  This highlights the consequence of a massive outlier in the shift data.

Percentages are frequently understood as a positive fraction of a positive whole.  But your calculations just divide one number by another, where the numerator is not part of the denominator and where the numerator and denominator can have different signs.  So the naive expectation that percentages should be between $0\%$ and $100\%$ does not apply here, since your calculations do not follow the naive assumptions about percentages.


Augmented 5th on B double sharp?

Question: So a perfect fifth on B natural is F♯, an augmented 5th on B natural is F♯♯, would that then mean that an augmented 5th on B♯♯ would be F♯♯♯♯?
Answer: Technically yes, but you would almost never see B♯♯ as B♯♯ is an enharmonic equivalent to C♯ which makes much more senses in most cases.
Likewise I've never seen more than 3 accidentals applied to a note so a quadrupled sharped F you would never see. Going back to C♯, the equivalent interval would be G♯♯ or Gx better known as A.
So yes B♯♯ to F♯♯♯♯ is an augmented 5th, but you would most likely see it written as C♯ to Gx for everyone's sake.
Answer: Yes, as Dom said, it would be F#### indeed, despite how cumbersome that seems.  The reason why is because if instead you wrote G## or A, it would no longer be a fifth (of any type).  It would instead become either a 6th or 7th, because of the choice of note letter.
Answer: Whilst technically there may be a key called B##, there would never be any reason for it. There's not even a good reason for the key of B#, which from a writing and reading perspective has no credibility over the enharmonic C. Here, we're talking of intervals rather than keys, but B## will almost never exist, so an augmented 5th on it would be rare too.
Sensibility would make a B## to be called C#,(or even Db) making the aug 5 Gx,(or even A) thus reasonably writable and readable for all concerned. Apart from that, there is no sign for triple or quadruple sharp, as there has been no perceptible need.
Comment: @caters Double and triple accidentals had a surge in popularity in the early 20th century, but now most musicians see them as impractical and unnecessary. C## Major does not exist.
Comment: actually in music from the 1800's to now the flat and sharp has been extended to double sharps and double flats and more recently triple sharps and triple flats as part of standard accidental notation. B# is there for a good reason. It would not make sense to have a key signature with one of the sharps being C, so they use B# instead, same goes for Cb, Fb, and E# as well as all double sharps. So C## Major does exist and it is D major written in terms of C. This might be done for several reasons.
Comment: @caters ever heard of C Lydian? It's got one sharp with C as a tonic. Also why would every want your tonic represented by a different letter name instead of the natural one?
Comment: https://www.basicmusictheory.com/c-double-sharp-major-scale This proves my point that the C## major scale actually exists.
Comment: And the same website has things about notes like F### and Bbbb
Comment: @caters - one could hardly call double sharps 'basic music'! The excerpt pretty well sums up most of the answers. Why on earth a key such as this would be USED beggars belief. Reinventing the wheel... Couldn't find the key sig on a stave - wonder why?
Comment: I now have a burning need to see some music written in this key.

Augmented 5th on B double sharp?


NGINX proxy_pass with html hard links

Question: I'm trying to run a web app listening on a different port of the same server.
I'm using NGINX in order to proxy requests. I will show you an example to clarify.
server {
  listen 80;
  server_name example.org;
...
  location /app {
    proxy_pass http://localhost:8080/public/foo;
  }
...
}
...
server {
  server_name sub.example.org;
...
  location / {
    proxy_pass http://localhost:8080;
  }
...
}

When I go to http://example.org/app I can see the redirect is correct because I see the same html I can found at http://sub.example.org/public/foo, but the app at http://sub.example.org/public/foo/index.html includes some hard linked scripts.

The console logs says that http://example.org/static/library.js can't be found, but this is obvious!
How can I modify the configuration in order to have index.html searching for http://sub.example.org/static/library.js?
Answer: You need to configure your upstream application's root URL to sub.example.org. Then the application generates correct URLs to resources it loads.
Comment: Can you provide an example?
Comment: You need to look at your application's documentation. You have given no information about your application, so I cannot help.
Comment: Except the folder `/public/foo`, the application only uses the folder `/static` and its subfolders.

NGINX proxy_pass with html hard links


Cor Padrão de Background

Question: Qual a cor padrão do Background de uma nova activity no Android Studio, em Hexadecimal? Sendo que a mesma não é completamente branca (#FFFFFF)...
Answer: Perguntaram isso há dois anos no SO em inglês:
https://stackoverflow.com/questions/14507370/what-is-the-default-layout-background
E a resposta marcada como correta dizia que o tema light tem por fundo #EEEEEE, que é quase branco, mas não chega a ser totalmente branco. Depois a resposta foi editara para incluir que em versões mais recentes é #FAFAFA, que é ainda mais branco (e na minha opinião mais fácil de pronunciar).
Comment: Bacana... Meu android é api 22 e o que funcionou pra mim, foi a cor #EEEEEE... Obrigado! nao posso dar up vote (não sei pq) mas, +1 pra ti!
Comment: @ManfrinyPereira quando você tiver quinze pontos, vai poder dar voto positivo. Se você aceitar a minha resposta como correta você ganha mais dois pontos ;)
Comment: A resposta foi excelente! Para mim a resposta já está como 'aceita', não vi nenhum botão, ou link do tipo 'aceitar esta resposta como correta'.. se puder me ajudar, onde posso aceitar essa resposta como correta?
Comment: @ManfrinyPereira É um "V" cinza abaixo do botão de votar negativo.

Cor Padrão de Background


How can I turn an existing Windows Server 2008 EBS-backed instance into a S3-backed (instance-backed) AMI?

Question: I understand there is no direct conversion to get from EBS to S3. But is there some series of steps that can make this happen, or is rebuilding the image from scratch the best option?
Is there a way to create a volume or snapshot, download it, reupload it to S3, and then bundle it as an S3 AMI?
Thanks for any help
Comment: The typical approach is to use `ec2-bundle-vol` and `ec2-upload-bundle` - both run from the running instance. (I don't use Windows servers, but it should still work). Once your bundle is uploaded to S3, you can use the AWS console or `ec2-register` to register the AMI and be able to launch it.
Comment: I looked into this. Unfortunately, ec2-bundle-vol and ec2-upload-bundle only come as bash files, not windows cmd files.
Comment: Looks like the windows equivalent is ec2-bundle-instance. Perhaps the procedure described in [the docs](http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/creating-an-ami-s3.html) will work.
Comment: I gave this a shot but it wouldn't work. Additionally, on the console website, the bundle instance command is disabled.
Answer: You cannot create an instance-store (S3 based) AMI for Windows 2008 on Amazon EC2.
There is a limit of 10GB for the boot disk on an instance-store AMI and Windows 2008 requires more.
I list this as reason #11 for why you should use EBS boot instances on Amazon EC2.
Disclaimer: I am the furthest thing from a Windows expert there is, but I've been around AWS/EC2 long enough to have learned this particular Windows 2008 limitation from Amazon and others.


What is a proper way to test SQLAlchemy code that throw IntegrityError?

Question: I have read this Q&A, and already try to catch exception on my code that raise an IntegrityError exception, this way :
self.assertRaises(IntegrityError, db.session.commit())

But somehow my unit test still failed and stop with IntegrityError exception. I expect it to say OK as I already expect to have exception in my unit test.
This was cause by code that tries to insert row having the same unique field values.
Any idea?
Answer: One of these will to the trick:
# ... only if version >= 2.7
with self.assertRaises(IntegrityError):
    db.session.commit()

Or:
self.assertRaises(IntegrityError, db.session.commit)

The difference between your example and the correct way is:
# Your example: You call db.session.commit(), this will raise an exception before
# assertRaises is called
self.assertRaises(IntegrityError, db.session.commit())

# Correct way: Pass what should be called to assertRaises,
# let assertRaises invoke it and check for exception
self.assertRaises(IntegrityError, db.session.commit)

I prefer to use assertRaises as a context manager (using with).
Comment: I agree. I think using assertRaises as a context manager makes the test code clearer.
Comment: Phew.. this solved and brighten my day! Thanks! :) Right, I was thinking earlier that the argument accept function name, not call of the function. But, somehow I miss that when I do the actual code. But, why do you prefer to use a context manager? Isn't with this single line the result will be the same?
Comment: Added comment,I just use context manager as you pointed out, and I think the other benefit is that we can expand/refine our code much more in that indented block. I am still new in python, so that's what I am getting :)
Answer: I've just spent a few hours trying to understand why my test was failing with IntegrityError during execution, but failed to catch it with with pytest.raises block (session builder is simplified, but notice autocommit flag):
async with async_session_maker(autocommit=True) as session:
    with pytest.raises(sqlalchemy.exc.IntegrityError):
        sqlachemy.execute(statement_which_violates_foreign_key_contstraint)

Trouble appeared on an order of session block and pytest block. The exception will be raised on session.commit() statement which is hidden in __aexit__ method of AsyncSession.
Solution - change the order:
with pytest.raises(sqlalchemy.exc.IntegrityError):
    async with async_session_maker(autocommit=True) as session:
        sqlachemy.execute(statement_which_violates_foreign_key_contstraint)


Differentiation of inverse trigonometric functions

Question: I am unable to get this sum.
Find $\frac{dy}{dx}$.
This is the Question as a picture. Here is the Mathjax of the equation:
$y = \arcsin(x\sqrt{1-x}-\sqrt{x}\sqrt{1-x^2})$
In the answer key that I have, it has been directly simplified to: $[\arcsin(x) - \arcsin(rt x) ]$ (I am unable to understand how this was obtained). and then it has been differentiated.
Comment: Use https://math.stackexchange.com/questions/672575/proof-for-the-formula-of-sum-of-arcsine-functions-arcsin-x-arcsin-y and https://math.stackexchange.com/questions/2099342/why-does-arcsin-x-arcsinx
Answer: HINT: Use the chain rule $$\frac{d}{dx} f(g(x))=g'(x)f'(g(x))$$ with $f(x)=\arcsin(x)$ and $g(x)=x\sqrt{1-x}-\sqrt{x(1-x^2)}$. You can use the product rule to differentiate $g(x)$.
Answer: To answer your question thoroughly I would insist you learn the chain rule, and the product rule to answer your question. I will highlight what the chain rule is and what the product rule is, and when they are being used, orange is both.
\begin{array}{|c|c|}\hline \bbox[yellow]{\text{Chain Rule}}&\frac{d}{dx}f(u(x))=
\frac{d}{du}f(u(x))\frac{du}{dx}u(x)=f'(u(x))u'(x) \\ \hline \bbox[red]{\text{Product Rule}}& \frac{d}{dx}(u(x)v(x))=u(x)v'(x)+u'(x)v(x)\\ \hline \end{array}
For simplicity I will start the problem highlighting the initial problem as being a usage of chain rule.
\begin{align}&\frac{d}{dx}(\bbox[yellow]{\arcsin(x\sqrt{1-x}-\sqrt{x-x^2})}\\ &\frac{1}{1-(x\sqrt{1-x^2}-\sqrt{x-x^2})^2}(\frac{d}{dx}(\bbox[orange]{x\sqrt{1-x}}-\bbox[yellow]{\sqrt{x-x^2}})\\ &\frac{d}{dx}(\bbox[yellow]{\arcsin(x\sqrt{1-x}-\sqrt{x-x^2})}=\frac{\sqrt{1-x}-\frac{x}{2\sqrt{1-x}}-\frac{1-3x^2}{2\sqrt{x-x^3}}}{\sqrt{1-\left(x\sqrt{\left(1-x\right)}-\sqrt{x-x^3}\right)^2}}\end{align}


Can the referee end the game while someone is about to shoot?

Question: I recently played a football game. We conceded a goal in the start of the first half.
During the allowance for time lost at the end of the second half, our team member was in front of the goal with the ball. As he was about to shoot, the referee gave the final whistle and ended the game.
Was the referee's decision fair?
Answer: Yes - the decision was at least correct by Law, and most likely fair as well. The referee is the sole arbiter of timekeeping, as shown in the following Laws.
Law 5 - The Refereee, Section 3 - Powers and Duties:

The referee:

acts as timekeeper, keeps a record of the match and provides the appropriate authorities with a match report, including information on disciplinary action and any other incidents that occurred before, during or after the match

Law 7 - The Duration of The Match, Section 3 - Allowance For Time Lost:

The fourth official indicates the minimum additional time decided by the referee at the end of the final minute of each half. The additional time may be increased by the referee but not reduced.

If the referee had decided that the amount of additional time added on had compensated for time lost during the second half, they were correct by Law to stop play.
Now, as to the question of the decision being fair - some referees may decide to "find" a few more seconds if there is a promising attack, since the time added on is generally a very rough estimate. This generous helping of a few extra seconds is acceptable to most referees.
However, the longer play is allowed to continue after the initial allotment of additional time, the unfairer this is on the defending team. If a team has had 90 minutes plus additional time (along with a few seconds more) to score - why should the other team be placed at a disadvantage by allowing even more time?
In the 1978 World Cup, in a match between Sweden and Brazil, referee Clive Thomas signalled for the expiry of time from a Brazilian corner kick while the ball was in mid-flight, with the ball ending up in the net. The tournament's refereeing committee decided that this was a poor use of Thomas's discretionary powers relating to additional time, sending him home from the tournament. It is clear that in this case, Thomas would have been better using his discretion to either end the match before the corner kick was taken, or to find the extra couple of seconds required to see what the outcome of the kick was.
Finally, it is important to note that in some competitions, referees are not permitted to add on any time to allow for time lost. In this case, the referee must end the period as soon as their watch shows that time has exprired for that period (ie 45 minutes, or whatever the competition rules state that the length of the half is).
Comment: One famous (at least to me) example: World Cup 1978, group stage, Brazil-Sweden tied 1-1, Brazil has a corner kick at the very end of the match, they take their time, they shoot the ball, there is a header and goal! Or not... the referee had whistled for the end of the match while the ball was on flight from the corner. Controversial? Very! For sure. Nearly 40 years later it came to my mind immediately when I read the question :-) See it on YouTube: https://www.youtube.com/watch?v=MDfV35ddpu0
Comment: @RolazaroAzeveires - I've edited the link and anecdote in. Thank you.
Comment: Clive Thomas was the referee. He was sent home from the tournament for failing to find a couple of extra seconds here. I think he should have either not allowed the corner to be taken, or allowed it to be taken - blowing the whistle with the ball in mid air, while it may have been technically correct in his mind, was not a good use of his discretionary powers.
Comment: Nice, thanks. And I agree it was a poor decision by the referee. As Brazil was taking their time to score the corner kick he could (should...) have stopped the game there. It does happen often enough not to be notable.
Comment: Something quite similar happened at WC2014, during France v. Switzerland. However the goal would have made the score 6-2 for France, so it was not decisive.
Answer: Yes; moreover, it has happened: take a look at this referee decision in a League Two game that actually decided Accrington Stanley's fate of keeping them from promotion to League One.
Was it fair? It's hard to say. The reason for this decision, as was explained in the media, was that the referee didn't blow the whistle on time and wanted to end the half once the ball was in the air. Since that was only done when the ball was in Wimbledon's box, and he didn't want to influence the course of the game by his mistake, he blew the whistle just before the ball hit the net.
Of course, no referee should ever do anything like it. According to the footballing regulations, "the referee may not change a decision on realising that it is incorrect or on the advice of another match official if play has restarted or the referee". This has since been interpreted as, and extended to, "made decisions that the referee realises to be wrong must not affect the character of their future decisions". As such sorts of decision cannot be anything but a compensation for an earlier mistake, most such half-time/full-time whistles can be regarded as poor refereeing.
As to your referee, I don't now the context, so I can't precisely tell. But if I were to guess, I'd say their decision was a poor one.


Initializing using properties with Dependency keyword and UnityContainer

Question: I have a code sample which look something like this.
public class AdventureWorksRepository
{
    [Dependency]
    private AdventureWorksEntities Context
    {
        get; set;
    }

    public AdventureWorksRepository()
    {
         SelectDemo();
    }

    public void SelectDemo()
    {
        var productNames = Context.Products.Select(item => item.Name);

        foreach (var productName in productNames)
        {
           Console.WriteLine("Name : "productName);
        }
    }
}

and heres the main programe
private static void Main(string[] args)
{
    UnityProvider.Container = new UnityContainer();
    UnityProvider.Container.RegisterInstance<AdventureWorksEntities>(new AdventureWorksEntities());
    var repository = UnityProvider.Container.Resolve<AdventureWorksRepository>();
}

from what i've understood the Dependency keyword should tell Unity to initialize the the AdventureworksEntities property but I keep getting and null refrence exception  any tips what I'm doing or assuming wrong
Answer: I would recommend that you don't use the [Dependency] attribute. With them you have references to your container everywhere in your codebase. See this article for detailed explanation.
You can tell Unity that you want a dependency injected using InjectionProperty like this
container.RegisterType(typeof(IMyInterface), typeof(MyImplementation), new InjectionProperty("MyProperty"));

instead. If you want to inject a specific value into that property instead of letting Unity resolve that value you can also specify your own value in the constructor of InjectionProperty.
Btw.: Your property must be public. It won't work on private properties. If you don't want to make that property public you should instead go for constructor injection
public class AdventureWorksRepository
{
  private readonly AdventureWorksContext context;
  public AdventureWorksRepository(AdventureWorksContext context)
  {
    if(context == null) throw new ArgumentNullException("context");
    this.context = context;
  }
}