how to save checkBox state as you move between activities?

Question: In my application, I use a checkBox that when it is checked, a piece of music is played.
        But when the user moves to another activity and then returns to the activity that the checkBox is there, it is unchecked.
        In order to stop the music, you have to check the checkBox again and after that uncheck it.
        How can I save the state of checkBox unchanged as I move between activities?
    This is my XML code:
    <CheckBox
    android:id="@+id/chk_box_music"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:gravity="center"
    android:layout_marginTop="4dp"
    android:layout_marginLeft="12dp"
    android:layout_gravity="center"
    android:layout_marginStart="12dp"/>

This is my JAVA code:
CheckBox checkBox = (CheckBox) findViewById(R.id.chk_box_music);
checkBox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener({
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b == true){
startService(new Intent(SettingsActivity.this, MyService.class));
}else{ stopService(new Intent(SettingsActivity.this, MyService.class));
}
}
});

Answer: You can either save the CheckBox state in:

Shared preferences
Bundle onSaveInstanceState(Bundle) and then getting that value/flag in onCreate(Bundle).
Local database (using Room, SQLite or any other tool)
Comment: I don't agree with this, by moving between activities work in object oriented para time Don't need to save in shared preferences or in database.
Comment: The thing is, since this is configuration, it should be centralized somewhere, since this is the good practice. For scalability, if you had more configurations it makes all sense to save them into a table inside database. For small projects, this isn't the best approach, therefore you should be using `onSaveInstanceState(Bundle)`
Comment: I understand what you mean when you say it is just a work between activities, but this is specific case where you should send or pass your configuration settings around. This approach follows the best architecture practices like MVVM, MVP or Clean Architecture.
Comment: For sending and receiving info between activities the simplest and easiest approach is to startActivityForResult & OnAcitivityResult Methods, I already mentioned the link in my answer.  https://stackoverflow.com/questions/10407159/how-to-manage-startactivityforresult-on-android/10407371#10407371
Answer: You can override onResume Method of your activity. This method will be called when Activity will be resumed again. so in this method you can set checkbox state whatever you want to set, like
  @Override
   protected void onResume() {
    super.onResume();
    checkBox.setChecked(true); // or false, according to your logic
    }

And if you want to send/receive some information from the other Activity then you need to start activity for result and handle its results. its help is here
Edited:
Another simplest way could be to save info in Shared Preferences Like
 @Override
 protected void onResume() {
    super.onResume();

    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
    boolean isChecked  = pref.getBoolean("isChecked", false);
   checkBox.setChecked(isChecked); // or false, according to your logic

    // And on checked change update shared Preferences

    checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
            pref.edit().putBoolean("isChecked",isChecked).commit();
        }
    });

}

Now as you told that you want to clear checkbox when App closed, so that next time when user comes checkbox should be cleared. for that update SharedPreferences in same Activity on Destroy method, where checkbox is present.
@Override
 public onDestroy() {

     SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
     pref.edit().putBoolean("isChecked",false).commit();
     super.onDestroy();
 }

Comment: Many thanks. But the onResume() method keeps it checked or not checked when I totally exit the app and run it again.
Comment: I need a method when the user checks the checkbox, keep the checkbox checked as the user moves across the activities. and when he/she closes the app and runs it again, the checkbox must be empty and unchecked.
Comment: if you have checkbox in activity A and you move to Activity B, C & D. If you simply finish() activity D, C & B. Checkbox will still be checked in Activity A. It will be only change if you start activity A again. don't start it again, just keep it in stack, it will remain checked. Other possible way could be the shared Preferences. Let me update my code for shared preferences.
Comment: please check my updated answer it should work now. Now Only thing is to try to avoid finishing activity A where checkbox is present, because I am clearing SharedPreferences in its OnDestroy() method.
Comment: If you still face some issue let me know. Or If it works, please accept my answer, Thanks.
Comment: It does not work. How can I send you the full code? I mean the codes in MyService class and those in the activity in which the checkbox is placed?
Comment: The problem might be somewhere else. because I have tried many many ways.
Comment: you can post code in the question, service is not the issue, you just need to tell the flow of activities and how are you are starting and finishing in between activities.


Missing "app engine service account" in developers console

Question: I'm currently in the proces of updating an old appengine application to use the new cloudstorage based files API (python).
This also means setting up cloudstorage for this application.
I've done this successfully but my application isn't able to actually upload to the cloudstorage bucket. After some IRC debugging it turns out this is probably related to this account not having an "App Engine Service Account in it's permissions section.
Explicitly adding @appspot.gserviceaccount.com to the buckets permissions (user permission owner role) solves the problem. But still the application permission configuration is in some inconsistent state since it's missing this account.
Is there a way to reset/update these permissions/users?
(Creating a fresh / new application and moving to it is not really an option at this point)
Answer: Turns out google provides direct support for the files API migration. The solution is to just manually add the user back (i.e. @appspot.gserviceaccount.com) to your project. The user was never removed internally.
Comment: Can you please accept your own answer so the question is properly seen as solved? Thanks!


Remove automatically Azure Staging Services

Question: I would like to use Azure Automation to delete all the staging deployments in my cloud services. I would like to run a Powershell script once a day to do so.
Is there any predefined script out there to do so? Any examples?
Comment: was my answer helpful or are you still having the issue?
Answer: the following Powershell cmdlet can be used to delete deployment slots on a website.You can either loop thru the list of deployment slots or do one by one.
<code>Remove-AzureWebsite -Name webappslotstest -Slot staging
</code>
There's three ways to do this;

Running this on a VM or a client machine
Running this as a Webjob in the webapp as powershell script (I'd go with this one)
Azure Automation as you've asked. You can use a Runbook for this, here you can find more info on runbooks and sample scripts.

Hope this helps


Matplotlib: plots two extra lines on my graph?

Question: I have a csv file which has two sets of data. Basically:
    for row in reader:
    ###I have some other code but here's the stuff that applies to the question###

        disorder_long = sequence_analysis(looped_region.upper(), mode = 'long')
        disorder_short = sequence_analysis(looped_region.upper(), mode = 'short')

        length = len(list(disorder_short))
        #print length

        xmin = 1
        xmax_long = length
        ymin = 0
        ymax_long = max(disorder_long)
        ymax_short = max(disorder_short)

        y_limit = max([ymax_long, ymax_short])
        #print y_limit

        while True:
            try:
                newfig = str(raw_input('Name the graph to be created: '))
                break #break out of loop
            except ValueError:
                print("error")
                continue #return to start of loop

        plt.figure

        #data
        x_series = np.array(range(1,length+1))
        # print "x series: "
        # print x_series
        # print len(x_series)
        y_series1 = np.array(disorder_long)
        y_series2 = np.array(disorder_short)
        # print y_series1, y_series2

        #plot data
        plt.plot(x_series, y_series1, label=uniprot_id+' long')
        plt.plot(x_series, y_series2, label=uniprot_id+' short')

        #add limits to the x and y axis
        plt.xlim(xmin, xmax_long)
        plt.ylim(ymin, 1)

        #create legend
        plt.legend(loc="upper left")

        #save figure to png
        plt.savefig(newfig)`

Returns me two graphs, one of which is perfectly fine (its the first set of data) but the other has two extra lines plotted and I have no idea where they came from. Second graph has two extra lines, the top two are extraneous.
Answer: Just at a cursory glance, the second graph, top two lines, appear to be the same as the lines in the first. I'm not the best with matplotlib but I do see that the line
plt.figure

doesn't specify it needs to make a new one. You should use plt.figure(1) and plt.figure(2) to specify they are different figures
Comment: Is there a way for me to create a new figure without having to do `plt.figure(number)`? Like with files you can just use w to create a new file as opposed to a for appending. I'd like not to append to my graph.
Comment: Hold on I figured it out... `plt.clf()`
Comment: You need to _call_ `plt.figure()` to get a new figure, as it is you are just having python evaluate that the function `figure` exists in the pyplot name space
Answer: plt.clf()

works to create new plots without appending to the existing one.


Rounding off to the nearest 50's pandas dataframe

Question: I have a pandas dataframe , screenshot shown below:
ID     Price

100     1040.0
101     1025.0
102     750.0
103     891.0
104     924.0

Expected output shown below
ID     Price   Price_new

100     1040.0   1050
101     1025.0  1050
102     750.0   750
103     891.0   900
104     920.0    900

This is what I have done but it's not what I want. I want to round off to the nearest fifty in such a way that at 1025 it should round to 1050.
df['Price_new'] = (df['Price'] / 50).round().astype(int) * 50

Answer: This is due to the issue : round with python 3
s = (df['Price'] % 50)
df['new'] = df['Price']  + np.where(s>=25,50-s,-s)
df
Out[33]:
    ID  Price   new
0  100   1040  1050
1  101   1025  1050
2  102    750   750
3  103    891   900
4  104    924   900

Answer: Follow my suggestion:
    import pandas as pd

    dt = pd.DataFrame({'ID':[100,101,102,103,104], 'Price':
                      [1040,1025,750,891,924]})

    #VERSION1
    dt['Price_new'] = round((dt['Price']+1)/50).astype(int)*50
    #VERSION2
    dt['Price_new_v2'] = dt['Price']-(dt['Price'].map(lambda x: x%50)) +
     (dt['Price'].map(lambda x: round((((x%50)+1)/50))))*50

         ID Price   Price_new   Price_new_V2
    0   100 1040    1050        1050
    1   101 1025    1050        1050
    2   102 750     750         750
    3   103 891     900         900
    4   104 924     900         900

Just plus 1 in your math you will be able to find your correct answer. But there is another way to do it, my opnião is more understandable than the second version even though I used the modulo operator.


Padrão de Projeto para Filtros

Question: Primeiramente, filtro no meu atual contexto é uma lista de objetos a serem utilizados em controles do tipo ComboBox para que o usuário possa escolher dentre as opções.
Meu cenário:
Tela 1 - Possui filtros de empresas, estoques, clientes, formas de pagamento.
Tela 2 - Possui filtros de empresas e estoques.
Tela 3 - Possui filtros de clientes, cidades, estados.
Meu objetivo é implementar um padrão de projeto que utilize uma mesma estrutura, ex: FiltroTela, e vá adicionando dentro os filtros (empresas, clientes, estoques) dependendo da tela que o solicitou.
Essas telas são de um projeto windows forms, a solicitação será feita a um WCF Service, que irá fazer a consulta em uma base de dados e devolver a estrutura com todos os filtros ao client (windows forms).
Algo em torno de, WCF Service eu "Tela 1" quero os filtros empresas, estoques, clientes e formas de pagamento, ao receber a msg de volta, faria o respectivo binding para cada controle.
Alguém consegue me indicar um padrão de projeto para resolver essa questão?
Comment: Crie view, e partir dae crie os filtros
Comment: Obrigado pela ajuda @LuizVichiatto, mas a camada de acesso a dados já existe e inclusive já utilizo views, meu problema mesmo é encaixar um design patterns para tratar a ida e vinda da lista de objetos (filtros) ao longo do projeto.
Comment: usa como parametro no sql
Answer: Você pode combinar a resposta do @RogerOliveira no lado do SQL com o padrão Builder e Interfaces Fluentes no lado do C#.
Basicamente você usaria o filtro assim:
new FiltroTelaBuilder().porEmpresa(empresa).build();

Ou assim:
new FiltroTelaBuilder().porCliente(cliente).build();

Ou assim:
new FiltroTelaBuilder().porEmpresa(empresa).porCliente(cliente).build();

Em todos os casos o método build() retorna uma instância imutável de FiltroTela.
Existem diferentes formas de implementar esse padrão. Esse é o mais comum.
Answer:
Resposta originalmente postada no corpo da pergunta por seu próprio autor

Bom, encontrei um padrão que me ajudou e muito, o Decorator, segue um link de referência "Decorator Design Pattern" e abaixo um pequeno exemplo de como ficou a implementação da montagem dos filtros, que me atende por tela:
private Dictionary<string, object> FiltroTela1()
    {
        IFilter filtro = new Filter();
        filtro = new FilterCompany(filtro);
        filtro = new FilterCustomer(filtro);
        filtro = new FilterPaymentType(filtro);
        return filtro.Filters();
    }

private Dictionary<string, object> FiltroTela2()
    {
        IFilter filtro = new Filter();
        filtro = new FilterCustomer(filtro);
        filtro = new FilterPaymentType(filtro);
        return filtro.Filters();
    }

Os dois exemplos acima utiliza o Decorator para "decorar" meu objeto Filtro com os filtros necessários para cada tela, e o método "Filters" obtém de cada filtro o tipo e um objeto para ser utilizado como critério na busca do filtro.
Na outra ponta "Server", utilizo o mesmo padrão, ele analisa o dicionário recebido e vai obtendo da base de dados os filtros solicitado, monta um novo filtro, porém com a lista de cada um e devolve pra tela, que por sua vez faz a análise dos filtros recebidos e realiza o binding para o respectivo controle.
Answer: Eu passo os filtros como parametros na Stored Procedure usando esse sql:
@parametro is null or campo = @parametro

Assim qdo vc passar null no parametro ele ira ignorar, dai simplesmente repassa sempre parametros pra SP se forem nulos tu trata antes.

Padrão de Projeto para Filtros


If $\psi(m+IM)=\phi(m)+IN$ for an R-module homomorphism $\phi$, why is $\psi(M/IM)=(\phi(M)+IN)/IN$?

Question:
Let $I$ be a nilpotent ideal in a commutative ring $R$, let $M$ and $N$ be $R$-modules and let $ϕ:M→N$ be an $R$-module homomorphism. Show that if the induced map $\psi :M/IM→N/IN$ is surjective, then $ϕ$ is surjective.

On every solution I've found for this exercise, it is stated that $\psi(M/IM)=(\phi(M)+IN)/IN$.
I don't understand why this is true. Every element of $M/IM$ is of the form $m+IM$, and $\psi(m+IM)=\phi(m)+IN$. So why is $\psi(M/IM)$ not just $\phi(M)+IN\subset N/IN$?
Answer: That is because $\phi(M)+IN$ is a submodule of $N$, not of $N/IN$. Therefore, you have to determine the canonical image of $\phi(M)+IN$ in $N/IN$, which obviously is  $(\phi(M)+IN)/IN$.
More generally, if $N'$ is a submodule of $N$, its image in $N/IN$ is simply $(N'+IN)/IN$.
Answer: The induced map is defined by
$$
\psi(x+IM)=\phi(x)+IN
$$
The image of $\psi$ is some submodule of $N/IN$, so it has the form $K/IN$, for a unique submodule $K$ of $N$, with $IN\subseteq K$.
Let's show that $K=\phi(M)+IN$. If $y\in K$, then $y+IN\in\psi(M/IM)$, which is equivalent to saying that $y+IN=\phi(x)+IN$, for some $x\in M$. Therefore $y-\phi(x)\in IN$, so $y\in\phi(M)+IN$. Conversely, if $y\in\phi(M)+IN$, then $y=\phi(x)+z$, with $z\in IN$ and therefore
$$
y+IN=\phi(x)+z+IN=\phi(x)+IN\in\psi(M/IM)
$$
so $y\in K$.


An interesting relation of integrals

Question: Proof that there does not exist an $F: \mathbb{R}\times \mathbb{R} \to \mathbb{R}$ such that
$\int_{0}^{1} f(x)g(x)dx =F(\int_{0}^{1}f(x)dx, \int_{0}^{1}g(x)dx).$
Answer: Hint: First consider $f(x)=g(x) = x-\frac{1}{2}$. Then consider $f(x)=g(x)=\frac{1}{2}(x-\frac{1}{2})$.
Hint2: Consider $f(x) = x-\frac{1}{2}+a$ and $g(x) =x-\frac{1}{2}+b$. Then $f(x)=a$ and $g(x) = b$.
Comment: Can you detail , please?
Answer: Let $a,b \in \mathbb R$, $f=2a$ for $x<1/2$, 0 elsewhere, $g=2b$ on $(1/2,1)$, 0 elsewhere. We get $F(a,b)=0$. Obviously a contradiction.
Comment: F($\int_{0}^{1}f(x)dx$, $\int_{0}^{1}g(x)dx$) is a combination of these integrals at any power.
Comment: Thanks! But why F(a,b)=0 is a contradiction?
Comment: You get a contradiction by taking $f(x)=g(x)=1$ for all $x$.

An interesting relation of integrals


Meaning of shortcuts like "128S/96Q/64D/32X" for tennis tournaments

Question: In several places, where you can find information about tennis tournaments (for example: 2014 WTA Tour or 2014 ATP World Tour at Wikipedia), there are often shortcuts like this: 28S/32Q/16D (Brisbane), 128S/128Q/64D/32X (Australian Open), 32S/16Q/16D/4Q (Rotterdam).
I can see that they are somehow related to number of players and number of seeded players, but what do these shortcuts mean exactly?
Comment: Now I found a similar question at Yahoo Answers: [Can someone explain to me the Tennis Draw terms?](http://answers.yahoo.com/question/index?qid=20120528205440AAjKnu4)
Answer: These codes refer to the draw size of various aspects of the tournaments.
For each category of the tournament, the number of participants in the main draw (the main tournament) is listed.

S: Singles tournament
D: Doubles tournament
X: Mixed doubles tournament

For example, at the Rotterdam tournament (32S/16Q/16D/4Q), there were 32 participants in the singles main draw and 16 teams in the doubles tournament.
There are different ways to get into the main draw.  Some of the participants are direct acceptances, which means that their ATP or WTA rankings are high enough to get into the main draw directly.  Others are wild cards; the tournament organizers have a few spots that they can award to anyone they want.  Finally, some spots in the main draws are for qualifiers; these are players who finished at the top of a qualifying tournament that happens before the main tournament.  If there is a qualifying tournament for a category, the draw size of the qualifying tournament is listed as "Q" after the main draw size.
In the examples you mentioned:

Brisbane (28S/32Q/16D)
Australian Open (128S/128Q/64D/32X)
Rotterdam (32S/16Q/16D/4Q)

For the 2014 Brisbane International Men's Singles tournament, there were 28 participants in the main draw.  Of those 28, 20 were direct acceptances and 2 were wild cards. There was a qualifying tournament held before the main tournament to fill the remaining spots, and there were 32 participants in this tournament.  Of these 32, 4 were qualifiers, accepted into the main draw having won their bracket in the qualifying tournament.  The remaining 2 places in the main draw were filled by lucky losers, two participants in the qualifying tournament who lost their bracket final, but were still accepted into the main draw due to last minute withdrawals in the main draw.
Brisbane and the Australian Open had no doubles qualifying tournament, but Rotterdam had a small doubles qualifying tournament with 4 teams competing for 1 spot in the doubles main draw.  (The runner-up was admitted as a lucky loser.)
The Australian Open is the only one of the three examples that had a mixed doubles tournament; there was no qualifying tournament for this category.
Answer: 128S relates to the number of singles, 128Q is related to the number of players qualifying, 64D is doubles and 32X is mixed doubles.


How can I use WMIC to add an user to the administrator of a remote computer?

Question: Does anyone know of a way (other than psexec) to add a user to the local administrators group of a remote machine?
I'm having trouble figuring out the syntax for wmic.
Answer: If you're in an Active Directory Domain you can use Restricted Groups or Group Policy Preferences Groups. The latter is newer, more flexible, and recommended if possible.
There is a PowerShell solution here if you don't have an AD Domain.
Doing it through Group Policy is the right way to do it, though. It'll allow you to change it later very easily if you need to.


Can't resolve 'kotlin' in '/home/marcin/Projects/EduKotlinAcademy/web/build/node_modules_imported/kotlinx-html-js'

Question: I started Kotlin/JS react library on kotlin frontend Gradle plugin. I have the following error:
<code>> Task :web:webpack-bundle FAILED
js/kotlinx-html-js.js
Module not found: Error: Can't resolve 'kotlin' in '/home/marcin/Projects/EduKotlinAcademy/web/build/node_modules_imported/kotlinx-html-js'
 @ ../node_modules_imported/kotlinx-html-js/kotlinx-html-js.js 3:4-42
 @ ../node_modules_imported/kotlin-react-dom/kotlin-react-dom.js
 @ ./web.js

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':web:webpack-bundle'.
> node webpack.js failed (exit code = 2)
</code>
It looks like dependency to Kotlin can't be found on kotlinx-html-js. Although I define Kotlin and it should be generated fine.
For this configuration:
<code>group "org.kotlinacademy" version "1.0-SNAPSHOT"

apply plugin: 'kotlin2js'
apply plugin: 'org.jetbrains.kotlin.frontend'

repositories {
    jcenter()
}

kotlinFrontend {
    npm {
        dependency("webpack-cli", "v2.0.12")
        dependency("react", "15.6.1")
        dependency("react-dom", "15.6.1")
        dependency("react-router-dom", "4.2.2")
        dependency("jquery")
        dependency("react-markdown")
    }

    sourceMaps = true

    webpackBundle {
        bundleName = "main"
        contentPath = file('src/main/web')
        proxyUrl = "http://localhost:8090"
    }
}

dependencies {
    compile project(':common-js')
    compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version"
    compile "org.jetbrains.kotlinx:kotlinx-coroutines-core-js:0.22.5"
    compile("org.jetbrains.kotlinx:kotlinx-html-js:0.6.10") { force = true }
    compile 'org.jetbrains:kotlin-react:16.3.1-pre.27-kotlin-1.2.30'
    compile "org.jetbrains:kotlin-react-dom:16.3.1-pre.27-kotlin-1.2.30"
}

compileKotlin2Js {
    kotlinOptions.metaInfo = true
    kotlinOptions.outputFile = "$project.buildDir.path/js/${project.name}.js"
    kotlinOptions.sourceMap = true
    kotlinOptions.moduleKind = 'commonjs'
    kotlinOptions.main = "call" }
</code>
Comment: Have you tried using a SSCCE to see if the problem exists there too? If so, please post that instead of this seemingly more mature project
Answer: To fix it, add:
<code> dependency("kotlin", kotlin_version)
</code>
To NPM dependencies


What does "learn the linear part of a mapping" mean?

Question: In the paper "Efficient BackProp" , the authors talk about initializing the weights  not too small and not too large:

Intermediate weights that range over the sigmoid's linear region have the advantage that (1) the gradients are large enough that learning can proceed and (2) the network will learn the linear part of the mapping before the more difficult nonlinear part.

What do they mean by "learn the linear part of the mapping first"? And why is this a good thing?
Comment: Look at the graph of the "sigmoid" (whatever that might mean--it's a vague term).  Focus on the middle rather than the tails.  What does it look like?
Comment: @whuber, sure, I see that the sigmoid is linear in the middle (it's actually also linear at the tails, just not between the middle and the tails). Let me rephrase the question.
Comment: How is the question meant: do you want a mathematical deduction (which might be a bit more difficult)? Or are you interested in a more intuitive explanation? The paper you cite is one of the 'core' papers regarding ANN/Backpropagation, even it is aimed more at "best practices" than mathematical derivations.
Comment: @cherub, my question is not "how do we prove that this is the case", or "why intuitively is this the case". My question is: "what does it even mean?" (although as soon as I know what it means, I'll probably also want to know the intuition behind it).
Answer: What does it even mean?
As whuber already mentioned, look at the function graph of a sigmoid :

What stands out are the parts between [-1,+1], which are approximately linear, and the parts before/beyond that.
If you look at this kind of mapping, then the linear region is the steepest; mathematically it has the largest derivative. This also means a change in the input values/argument values creates the largest change in output values.
Which means, you want to use mostly this part. In a neural network, the output of this kind of function is input to another node, usually summing several input nodes. Since one knows that the function values is limited to [0, +1], it is straightforward to set the initial weight so that "on average" the linear part is used.
In short: since all that is changed in "standard backpropagation" are the weights, one aims at "hitting" the linear spot of the sigmoids in the beginning/at the initialization stage.
Edit; add second part of the question:
What does "learn the linear part of the mapping" mean?
For this question you have to know a bit about what a neural network is: in principal it is just a function (or mapping) from the input space to the output space.
If you are familiar with functions, then you have several possiblities to interpret them.
On of the key parts of ANNs is the fact they represent a class of functions that is capable of approximating any function.
And the process of approximating is called "learning" or "training".
I don't really like analogies, but here it might be helpful. So the following statement is not exactly true:
Think that ANNs behave like polynomials (under certain circumstances).
If you want to approximate an unknown function with a polynomial, then there are lots of ways to do it.
Most approximations in application end at the linear term, where there are even more ways to find clever solutions to it.
The main reason is that linear approximations have very nice properties and are relatively easy to calculate.
If you then also think about the Taylor series expansion, then you'll see that the elements are also polynomials.
Constant + linear + quadratic + ... and so on.
The problem, and more specifically its numerical solution becomes increasingly more difficult, or expensive to compute.
To summarize:
An ANN is a mapping of the input to the output space.
It can be decomposed (represented) by a polynomial expansion series.
The lower the order of the exponential, the less expensive/complex the elements are to compute.
Comment: This still doesn't explain what "learn the linear part of the mapping" means
Comment: OK, now I understand what the actual question is. I'll give the answer another try/edit it later.


Button (Botão) dentro de um A (Link)? Isso é uma má prática?

Question: Eu estava utilizando uma biblioteca de Scaffold para geração automática de códigos HTML. Era especificamente para gerar formulários em Boostrap 3.
Daí eu notei que os links de ações que estavem sendo gerados estavem assim:

     <button class="btn btn-primary"></button>

Parece que o Scaffold dessa biblioteca estava gerando o código do Anchor (O famoso Link) com um Button dentro apenas para a formatação do Link ficar igual a do botão.
Mas nem precisa, no bootstrap você pode usar assim:
Tipo como se fosse um botão

A dúvida que me surgiu é: A biblioteca de geração automática de código fez isso como se fosse "algo normal". É realmente "normal"?
Existe algum problema em usar um Button dentro de um A, ou vice-versa?
Não sei, mas institivamente (ninguém me falou nada ou nenhum artigo que eu li me ensinou isso), tenho uma pequena impressão de que isso é uma má prática (ou gambiarra).
Fazer isso é válido? Esses validadores de código html da vida aprovaria colocar um botão dentro de um link ?
Comment: **Relacionado:** [É aceitável usar tags , , ,  dentro de links/âncoras ()?](http://pt.stackoverflow.com/q/107718/3635)
Comment: **Não**, basta colar seu código [aqui](https://validator.w3.org/) e pedir para validar.
Comment: O que está de errado com a pergunta? Poderia fornecer uma sugestão de melhoria
Answer:
Essa pergunta já foi respondida no SOen, e foi muito bem respondia. Então eu apenas irei traduzir esta resposta.

Isto não é válido!
Apenas com o fato de funcionar, não significa que algo seja válido.

Modelo de conteúdo: transparente (tanto o conteúdo fraseado ou conteúdo de fluxo) , mas não deve haver qualquer conteúdo interativo descendente.
O elemento pode ser envolvida em torno de parágrafos inteiros, listas, tabelas, e assim por diante, até secções inteiras, contanto que não há conteúdo interativo dentro (por exemplo, botões ou outros links).

Segundo a W3C, a tag a () pode receber qualquer elemento, exceto esses:

<audio>
<button>

<embed>

 (Se o atributo usemap estiver presente)
<input>
<keygen>

<menu>
<object>
<select>
<textarea>
<video> (Se o atributo controls estiver presente)

Da série, aconteceu comigo...
Em um código que eu estava desenvolvendo eu tinha um input dentro de uma tag . Ao utilizar no Chrome e Firefox estava "funcionando" normalmente, mas utilizar o IE (que é o melhor validador, rsrs) ele apresentava um efeito diferente do apresentado, no meu caso um X, por não encontrar os elementos.
Somente depois de algum tempo, que percebi que aquele comportamento "diferente", se dava pelo fato de eu não estar usando o HTML corretamente.
E como dito pelo @renan nos comentários, basta utilizar um validador de código, que verá o motivo de não ser válido explicado em maiores detalhes.
Nota
No HTML5 algumas coisas foram mudadas. Como por exemplo, a tag a pode conter a tag img. Caso não acredite, em min, use o validador da W3 com o seguinte exemplo:
<!DOCTYPE html>

  <title>Estou testando</title>

Click the image, and the click coordinates will be sent to the server as a URL query string.

Comment: tanto img quanto div sempre achei que poderia usar. Vivendo e aprendendo!!!!
Comment: @MarceloDiniz Até pode funcionar, mas não é válido. Isso influência em diversos fatores, inclusive no SEO de seu site.
Comment: @Randrade isso me deu idéia para outra pergunta, o que acha de questiornamos alternativas disso no SOPT?
Comment: Desculpe se não entendi, porém, utilizar link () em imagem é considerado uma má prática? Mas por que? Muitos sites grandes (inclusive SO) utilizam  em  e é uma questão de usabilidade além de necessidade ou estou enganado? Desculpe se entendi errado...
Comment: @VictorGomes Em que parte do SO possui isso? O que é feito, geralmente, é colocar a imagem via CSS. O que não é "certo", é colocar a tag `` dentro de uma tag ``.
Comment: Sim sim você está certo, me enganei, cara que triste saber que eu estava fazendo errado durante esse tempo todo, olha só, como disse o @MarceloDiniz "Vivendo e Aprendendo!!!"
Comment: De acordo com os testes que fizemos aqui utilizando o validador do w3c a tag   não pode conter dentro do  apenas se tiver o atributo usermap. Fora isso, não é errado.
Comment: @Randrade estou ajudando atualizar a sua resposta, é bom fazer isso, para ninguém ficar com informações erradas na cabeça
Comment: @MiguelBatista Isso é um comportamento do `HTML5`. Adicionei uma nota explicando esse detalhe.


Labeling half-diminished seventh chords - [X]m7♭5 or [Y]m6?

Question: On my older question Are the diminished chords not that common in modern popular music?, I got this answer:

"The half-diminished (or m7♭5) is usually suggested as the diatonic chord on the 7th degree in major keys and the 2nd degree in minor keys, and is fairly common in most styles of music."

That's right.  Half-diminished sevenths are pretty common in popular music.  However, if such chord is used, it would not be usually labeled as [X]m7♭5, but rather [Y]m6.  (Believe me, I always have been labeling them as m7♭5.)
For example, in a circle of fifths progression in C major, they would usually write:

CㅡFㅡDm6ㅡEmㅡAmㅡDmㅡGㅡC

What's the reason here?
Comment: Don't see the relevance of your last comment. A lot of people use keyboards insead of pianos - all my 88 note ones have A at the bottom, but my 76 has E, and my 61s all have C. Also - to follow the circle, C-F-B-E etc. is considered up in 4ths (or down 5ths). Count the letter names.
Comment: A bit of a nit-pick, but I think a better example would be E7 rather than E minor there
Answer: If I understood the question correctly, you seem confused about the chords Dm6 (D F A B) and Bm7b5 (B D F A), because they have the same notes.
These two chords have different harmonic function, so you would distinguish the two of them like that. The vii usually acts like a dominant, so you'd find it followed by some kind of tonic, whereas the ii isn't a dominant chord, so you can follow it up with any other chord you want.
You can see that in the progression you posted:

C - F - Dm6 - Em - Am - Dm - G - C

The Dm6 is used here as ii-iii, which is acceptable. If you had a Bm7b5, it would be something like:

C - Bm7b5 - C
Comment: I'd also point out that OP's example is a circle of fifths progression, which usually uses the "Bm7♭5" notation to show the fifth between B and F, and also between E and B.
Answer: Depends on the bass note. If the bass note of that third chord is in fact D, it functions as a mi6 chord. But if you put a B in the bass, it's a mi7(b5). Alternately, if you put a G in the bass it could also be a G9 chord. All about context. All those chords have somewhat different sounds, so choosing a different bass note for one chord can change the tone of the progression.
Edit:
Even though Dmi6 and Bmi7b5 have the same notes, they're different chords with different functions so I wouldn't recommend writing "mi6" to indicate "m7b5 a minor 3rd down" unless you truly don't care about the bass note. You could always write Dmi6/B if you want that half-diminished sound but aren't confident others will understand mi7b5 symbols.
Also, shouldn't Bmi7b5 usually lead to E7 or Ema rather than Emi if it's going to E in the bass, since usually its function is the ii of A?
Comment: If you put a different, extra note in the bass - or anywhere - it changes the chord and its name entirely!
Answer: Yes, popular editions will often write 'Dm6' even when the bass note clearly indicates that it's 'Bm7♭5'.  Conversely, you'll sometimes see what is undisputedly 'C6' notated as 'Am7'.
Don't waste time looking for a subtle reason.   The editor isn't thinking about harmonic analysis but purely about chord shapes for ukulele or guitar.  (The 'Am7 for C6' thing tends to be found in music from the ukulele era, accompanied by 4-string chord shape diagrams.  'Dm6' for 'Bm7♭5' has persisted.)
Answer: D minor6 (Dm6) is spelled D F A B.
D half-diminished (Dm7♭5)is spelled D F A♭ C.
D diminished (Do) is spelled D F A♭ C♭.
So, diatonically, Dm6 works in key C. Dm7♭5 cannot. It may be the weapon of choice in pop songs, but it's not diatonic to the key.
They are not the same chord, don't sound the same, so what's the question?
EDIT - thinking that now, the OP is considering Bm7♭5 and Dm6 both with reference to key C, another thought comes along.
Yes, both contain the same notes (as do C6 and Am7), so context would probably be a deciding factor. Often I find Bm7♭5 followed by Em, whereas Dm6 is followed by G (circle of 4ths/5ths idea). In root position, those sound believable. Using inversions always plays tricks with the ears, so it makes it difficut to pinpoit a 'correct' name. As already stated, it's also the best part of G9 - made up from G B D F A - but missing the important G note can't actually make it G anything!
Comment: I think you're misunderstanding. The OP is saying that Bm7b5 contains the same notes as Dm6. In the given example, Dm6 is substituting for Bm7b5.
Answer: TL;DR: it should often be labelled as Dm6/B.
How to label a chord... In discussions around questions like this, there seem to be implied assumptions like the following:

(1) for any combination of notes, there exists one way to label it as a chord symbol that's "correct" for all intents and purposes in all imaginable contexts
(2) chord symbols in songs should be understood as some kind of harmonic analysis
(3) the chord's root note is the be-all and end-all "this changes everything" factor in harmonic meaning
(4) in order to know the one-and-only correct functional role and perspective for a chord, you need to identify the one-and-only correct chord symbol label.

I disagree on all of those points, and "Bm7-5" in particular is a prime example. In many cases, instead of Bm7-5 what should really be written is Dm6/B, or even Dm/B or simply Dm. When the chord is used in a simple Am - Dm - E7 - Am song as a fancier Dm, writing "Bm7-5" badly obfuscates the fact that it's doing the job of a Dm. Many players might not even know what the "7" is, let alone the "-5" (sometimes even written in small letters), which is IMO often the most important note in the chord. So they play "Bm" or "Bm7" - with the F# note and all. I know naturally musical people who don't know theory, but can accompany songs by ear, and when hearing this "Bm7-5" chord in a song, they'll play a Dm - which is what the chord really does.
If you write lead sheets for amateur musicians, please stop the "Bm7♭5" nonsense and leave that for theory snobs and more advanced audiences.
Chords are not monolithic objects, even though the practice of using chord symbols might lead you to that conclusion. There's no half-diminished chord receptor in your brain, which would activate only upon hearing a half-diminished chord. Chords consist of separate notes, and each of them can have its own role in the harmonic story. The bass note is not necessarily the most important note in affecting where the harmony seems to turn. Take a song that's in Am and has this "Bm7-5" chord written in it. If you were writing an arrangement of the song for, say, two horns, and if you had to choose just one note from B-D-F-A for a harmony voice, to deliver a barebones version of essentially the same harmonic feeling, which note would you select? Self-evidently the bass note because it changes everything? YMMV, but as a first choice, I'd select either F or D. What if it was a B7 chord? Then the obvious first choice would be D#, not B.
By the way, Thelonius Monk called it "minor six with the six in the bass".
Comment: It could be argued that in  'Am - Dm - E7 - Am'  the Dm is a pre-dominant and thus could be usefully thought of as a watered-down B-rooted chord.
Comment: @LaurencePayne Interesting way to put it, thanks. That's in a way how it feels too. On the other hand, Dm also tastes like a mix between what you say, "B-rooted chord" and F major or IV of C major. I guess my point is that all of these tastes, feelings and perspectives can be correct and applicable at the same time. Many different harmonic patterns can be seen in any set of notes. For some reason, students tend to come out of theory classes thinking, "there's only one correct perspective". Anyway, for many people, Am - Dm - E7 is a well-known harmonic pattern they can identify and play by ear.


Por que não está mostrando o login salvo no LocalStorage?

Question: Estou criando um app híbrido com cordova, e quero que ao usuário efetuar o primeiro login, ele permaneça logado direto. Se ele sair do app por exemplo, e entrar novamente, ele não precisará efetuar um novo login. Estou usando o código abaixo até o momento, o valor é armazenado no LocalStorage, mais não é exibido no input após atualizar o mesmo.
index.html

Login

                    <input type="name" class="form-control" id="txt_username" name="txt_username" placeholder="Usuário">

                    <input type="password" class="form-control mt-2" id="txt_pwd" name="txt_pwd" placeholder="Senha"/>

                    <input type="button" value="Entrar" class="btn btn-danger btn-block mt-3" name="but_submit" id="but_submit" />

index.js

var login = document.getElementById('txt_username');

login.addEventListener('input', (e)=>{

window.localStorage.setItem('login', login.value);

var cat = window.localStorage.getItem('login');

$("#txt_username").val(cat);
})

Comment: @AndréSantos pode fazer isso usando o [`addEventListener`](https://developer.mozilla.org/pt-BR/docs/Web/API/Element/addEventListener), existe o evento de [`change`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) e de [`input`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event). Então, ao ser digitado/modificado você armazena o valor.
Comment: O `document.getElementById('txt_username').value();` vai pegar o valor do elemento no momento em que ele foi executado. Se a página foi carregada neste instante e o `#txt_username` tiver com valor vazio, será salvo o valor de vazio. Usa o proprio inspecionar elemento e veja no LocalStorage o valor salvo, mesmo no mobile é possível fazer isso.
Comment: Como faria para pegar o valor no momento em que ele é digitado?
Comment: Continua o mesmo problema, fiz o seguinte teste  `var login = "Olá" `; e ele exibe normalmente.
Comment: Desculpem mais nunca usei addEventListener, poderia me dar um exemplo de como ficaria meu código com ele?
Comment: @AugustoVasques entendo mais pretendo passar depois para o sqlite. Por enquanto o LocalStorage quebraria um galho.
Comment: A não funcionou :(  Adicionei uma imagem a pergunta de como ficou meu código final, mais não funcionou
Comment: Se eu tirar `value` vai dar erro `[object HTMLInputElement]`
Comment: há não tá salvando mesmo assim
Comment: Edite a pergunta e coloque um [mcve] contendo o html e código que está tentando usar o localStorage.
Comment: Eu não entendo, não está armazenando no LocalStorage o valor, mais como eu disse se eu fizer `var login = "Olá"` ele armazena normalmente
Comment: Modifiquei a pergunta, adicionei as sugestões e o HTML
Comment: O código **funciona perfeitamente**. Veja: https://repl.it/repls/EquatorialExtrasmallCircles o problema é que você está tentando atualiza um input com um valor que ela já contém e a mudança é visualmente redundante.
Comment: Sim ele pega o valor, mais ao atualizar a página o valor não é exibido no input
Comment: Mas você não programou para isso!!! Poxa, tem que colocar essa funcionalidade de recuperar os dados do localStorage  no evento `load` da página. No evento `input` você armazena os dados no `load` você recupera.
Comment: @AugustoVasques eu atualizei a pergunta quando vc pediu, e coloquei esse detalhe :)
Answer: No onload da página você tem que chamar uma função para verificar se há alguma coisa no localStorage, se houver, ele insere no input, caso não, o input continua limpo.
Dei uma olhada rápida na documentação do cordova e achei isso aqui. Acho que pode te ajudar.
Fiz um código com js puro para você dar uma olhada.

const login = document.getElementById('txt_username');

login.addEventListener('input', (e)=>{
  window.localStorage.setItem('login', login.value);
  const cat = window.localStorage.getItem('login');
  login.val(cat);
});

window.onload = () => {
  const cat = window.localStorage.getItem('login');
  if (cat) {
    login.value = cat
  }
}

Login

  <input type="name" class="form-control" id="txt_username" name="txt_username" placeholder="Usuário">

  <input type="password" class="form-control mt-2" id="txt_pwd" name="txt_pwd" placeholder="Senha"/>

  <input type="button" value="Entrar" class="btn btn-danger btn-block mt-3" name="but_submit" id="but_submit" />


Is this version of the Gaussian distribution function correct?

Question: I am currently doing an exercise in which the following is said:

Let $f(x, t)$ be the Gaussian distribution function with variance $t$:
$$
          f(x, t) = \frac{1}{\sqrt{2 \pi t}} e^{-x^2/2t} $$

But when I look at https://en.wikipedia.org/wiki/Normal_distribution the function seems to be different :/ For example, $t$(the variance) is not in the square root with $2 \pi$ in the Wiki link :/
Comment: You wrote it correctly.
Answer: You are implicitly assuming that:
$$t = \sigma^2.$$
Therefore:
$$\frac{1}{\sqrt{2 \pi t}} e^{-x^2/2t} = \frac{1}{\sqrt{2 \pi}~~ \sigma} e^{-x^2/2\sigma^2}.$$
Comment: If $a > 0$ and $b>0$, then $\sqrt{a} \cdot \sqrt{b} = \sqrt{a \cdot b}$ is true. In your case, $a = 2\pi$ and $b = t = \sigma^2.$
Comment: Oh, thanks sir :)
Comment: But it is not in general true that $\sqrt{a} \cdot \sqrt{b} = \sqrt{a \cdot b}$, right? So why can you do that?
Comment: Notice also that for a random variable, $\sigma \geq 0$ by definition.
Comment: Yes, thanks. Appreciate it. Cannot accept answers yet :))
Comment: @ThatGuy ok, but you can upvote it if you like using the triangle pointing up!
Answer: Write your $t$ as $t=\sigma ^2$ and you will see that both are equivalent


Random numbers generator CLT , problem with dependence on $n$

Question: I have a few exercises concerning Central Limit Theorem in which I stumble upon the same problem.
Here is one of them:
A random numbers generator generates numbers with exponential distribution with parameter $\lambda$. What should $\lambda$ be and how many numbers should we generate so that the arithmetic mean of those numbers is $1$ with accuracy
$0,01$ and the probability of this event is at least $0,9.$
This is how I do it:
$X_i = k_i$ = the number generated in the $i$-th draw, $S_n = \sum_{i=1}^n X_i$
$EX_i = \frac{1}{\lambda}$ and $\sigma = \frac{1}{\lambda}$
Standarization $$Z_n = \frac{S_n - \frac{n}{\lambda}}{\sqrt{n} \frac{1}{\lambda}} = \frac{\lambda S_n - n}{\sqrt{n}}$$
We need to estimate the following:
$$P(|\frac{S_n}{n}-1|<0,01) = P(\sqrt{n}(-0,01 \lambda + \lambda -1) < Z_n < \sqrt{n}(0,01 \lambda + \lambda -1)) = \Phi(\sqrt{n}(1,01 \lambda  -1)) - \Phi(\sqrt{n}(-0,99 \lambda +1)) = 0,9$$
And I do not know how to find $n$ or $\lambda$.
Could you explain to me what I am doing wrong?
Comment: At least when n is large, the sample should have a mean close to 1/lambda and you want this mean to be close to 1 with large probability. This strongly suggests to choose lambda = $___$ . Can you finish the question now?
Comment: No, λ is not 1/n, not even closely. If you "don't see why the sample has a mean close to 1/λ", pondering the consequences of the law of large numbers might help.
Comment: So $\lambda = \frac{1}{n}?$. I'm sorry but I don't see why the sample has a mean close to $1/ \lambda$. All I know is that $1 / \lambda $ is the expected value of $X_i$
Comment: The law of numbers says that a sequence of indpendent radnom variables tith identical distr. satisfy $\frac{S_n}{n} \to EX_1$ a.s. $\iff$ $E|X_n|< \infty$. This condition is satisfied for $\lambda \neq 0$. Now I know why the means tend to $1 / \lambda$.
Answer: Let $M_N$ be the RV representing the mean of samples of size $N$. This has mean $E(M_N)=1/\lambda$ and variance $\mbox{Var}(M_N)=(1/\lambda^2)/ N$.
As we want $E(M_N)=1/\lambda=1$ we need $\lambda=1$.
Now assume the required sample size is large so we can use the CLT to justify a normal approximation for the distribution of $M_N \sim N(1,1/N)$
Now the question is what is the smallest $N$ such that
$$
\mbox{Pr}(|m_N-1|\le 0.01) \ge 0.9
$$
So we are asking for the smallest $N$ such that the absolute value of a Standard Normal RV is less than or equal $0.01\times \sqrt{N}$and noting that a two-sided critical value for a $90\%$ interval has $z_{crit}=\pm 1.645$. That is that $0.01 \sqrt N \ge \Phi^{-1}(0.95)=1.645$
Hence we require the smallest $N$ for which $\sqrt N\ge1.645/0.01$
Comment: Thank you for your answer. As you can see, I wrote the same inequality while trying to solve this problem. But then I ended up with a difference of values of $\Phi$, both depending on $n$. Could you tell me how you found $N\ge1.645/0.01$? I mean, could you add some more detailed calculations so that I can see where I make mistakes?


Bizzare error from Qt

Question: Having this code executed in Qt editor:
<code> QPushButton button("Animated Button");
 button.show();

 QPropertyAnimation animation(&button, "geometry");
 animation.setDuration(3000);
 animation.setStartValue(QRect(0, 0, 100, 30));
 animation.setEndValue(QRect(250, 250, 100, 30));

 animation.setEasingCurve(QEasingCurve::OutBounce);

 animation.start();
</code>
I'm getting an pop up with error msg:
Comment: Hook it with the visual studio debugger?
Answer: You should always create your QWidgets on the heap, otherwise you'll indeed get all sorts of errors:
<code>QPushButton* button = new QPushButton("Animated Button");
</code>
Comment: You can create widgets on the stack. It's best not to, but I've never experienced "all sorts of errors" when doing so.
Comment: I didn't even notice that was part of the code since he formatted it incorrectly. Good catch
Comment: @Laurent thanks for your help, this bloody code is taken from http://doc.qt.nokia.com/solutions/4/qtanimationframework/animation.html so I didn't think they would screw up something as simple as this.
Comment: Indeed, this is not a good tutorial. Most likely, what's happening is that the button gets deleted when it gets out of scope, however the animation might still be referring it, and you end up with a runtime error.
Comment: That's strange, because objects go out of scope in reverse order of declaration, and therefore the animation will go out of scope _before_ the button. So there's no way it might still be referring to it.
Comment: Sure he can create them on the stack, but that's just looking for troubles in my opinion. Qt is designed to manage the deletion of QWidgets by itself so it's better to let it do it.

Bizzare error from Qt


How can I sync my data between a React frontend and Firestore backend?

Question: If I have some user that I create and I give them some currency, what is the best way to sync the data between my firestore and the frontend? Like for example I wanna display their currency on the screen at all times and it'll be updating if they do some task, should I just update the firestore first and make that frontend data always depend on the firestore? Or how would I possibly do this?
Have done a bunch of research but I'm not really sure what a good way to do something like this would be.
Comment: Please provide enough code so others can better understand or reproduce the problem.
Comment: @Tay Baye, please let me know if the below information was helpful
Answer: As per your question you are looking for the possible way to sync data between firestore and reactjs frontend and so if you want to  auto-update the data in your react application -when something in your database is updated you need some kind of socket server for that. You can fire an event from your backend, and subscribe to it in your frontend, and then perform a query to fetch the data.
You could look into a websockets library such as socket.io although this will need configuration server-side.
Also referring to the second line of query you have for

if you should just update the firestore first and make that frontend data always depend on the firestore

most people would recommend developing the frontend first,but that is again case dependent .This is especially true if you are talking about a site or application that depends heavily on the user experience. In most cases, it's easier to work the backend to meet the needs of the frontend instead of following the process in reverse.
I would recommend you to have a look at the below examples with similar implementations for a better understanding of the concept.

Sync multiple properties on state between react app and firebase
database
How to sync data between users and reactjs
Getting data from backend after page refresh


What happens if root CA expired in Android

Question: What happens if one of system CA certificate got expired (GlobalSign Root CA - R2 gonna expire in 2021) in Android?
How I can update to latest root CA in my android phone(user-build that never receives any OTA), if one got expired?
Answer: You can use Google Play Services to update the devices Root-CAs and other security relevant issues.
https://developers.google.com/android/reference/com/google/android/gms/security/ProviderInstaller
try {
    ProviderInstaller.installIfNeeded(this);
} catch (GooglePlayServicesRepairableException e) {
    GoogleApiAvailability.getInstance().showErrorNotification(this, e.getConnectionStatusCode());
} catch (GooglePlayServicesNotAvailableException e) {
}

The required class should be provided with the GooglePlayServices-Base artifact:
dependencies {
    implementation 'com.google.android.gms:play-services-base:17.1.0'
}

See this article for more details.
Comment: Thanks for your reply. Is it applicable for system wide? or just within application?
Comment: @VivekRajendran just within the application. I don't think there is a way of updating the devices Root-CAs without rooting the whole device.


Throttle limit reached. Retry later

Question: I apologize in advance for the lack of information on this, I'm at a bit of a loss.
I have a rails 5 API backend, with Postgres database hosted on heroku. It is serving to an iOS client. The main screen in the client is a map which uses the Google API on the front end to draw locations. The backend uses the Geocoder gem to search for places near to the user.
So the front end hits /restaurants and sends user_lat, user_long, search_lat, search_long and distance. The API returns a list of locations that meet those params and the client draws them.
Occasionally the front end displays "Throttle limit reached. Retry Later". This error is supposed to be coming from the back end API but I don't see this error anywhere in the heroku logs.
I've searched the Google API docs, Geocoder gem docs and can't find much. The error doesn't seem to match the OVER_QUERY_LIMIT errors mentioned in that other users have reported with the Google maps API.
Any help is much appreciated.
Answer: This was coming from the RackAttack Gem.

Throttle limit reached. Retry later


R command "which(apply(data, 2, var)==0)" in Python

Question: I'd like to know how to write an R command
which(apply(data, 2, var)==0)

... in Python.
Now I'm trying to run an R script to do a PCA.
But, pca() accepts only non-constant columns (=Variance is not 0).
For example, only Col2 can be accepted as non-constant column in the following:
Col1 Col2 Col3
0.0  1.2  4.0
0.0  1.5  4.0
0.0  1.3  4.0
0.0  1.1  4.0

I thought I removed all constant columns.
However, I got an error:
> Error in prcomp.default(data, center = TRUE, scale = TRUE) :
  cannot rescale a constant/zero column to unit variance

I googled and found this question and the R command solution:
which(apply(oopsmat, 2, var)==0)

It worked for me. The command specified which columns were still constant.
So, I removed the columns manually, and the R script did a PCA.
Now I'd like to do the same thing in Python.
How would you write this R command in Python?
#####################################################
Please don't read below, or you'll waste your time.
I leave this as an evidence that I asked a silly question:
NOTE: This R command is strange.
As I said, I already removed all constant columns from my data.
This R command tells that the variance of the following column is 0
(Excerpted from roughly 50,000 data):
:
0
0
4
0
19
0
32
61
878
4
1
13
16
14
2
4
13
:

The result of Excel's variance command VAR.P is 231.4.
This is not even close to 0!
I don't know what's going on and I can't find such a command in Python.
So, please explain this strange behavior, too.
*I overlooked the code that removed all outliers, that's why only 0s were left.
Comment: In R, `apply` is run on arrays and (ill-advised but possible) on data frames (see #1 on [here](https://stackoverflow.com/users/3001626/david-arenburg)). These structures are built-in in R but not Python as its standard library does not maintain arrays or data frames. Please tag and describe the Python module being used.
Comment: Incidentally the `which` function call is superfluous in the R code.
Comment: @Parfait OK, understood. I accept your answer as it is. Thank you.
Answer: Essentially, the command apply(data, 2, var) in R runs on two-dimensional structures such as matrices or data frames (but not advised for latter) to compute a variance of all columns:
Data frame
set.seed(73120)

random_df <- data.frame(
  num1 = runif(500, 1, 100),
  num2 = runif(500, 1, 100),
  num3 = runif(500, 1, 100),
  num4 = runif(500, 1, 100),
  num5 = runif(500, 1, 100)
)

apply(random_df, 2, var)
#     num1     num2     num3     num4     num5
# 822.9465 902.5558 782.4820 804.1448 830.1097

And once which is applied, the index of named vector (i.e., 1-D array) is returned according to logic.
which(apply(random_df, 2, var) > 900)
# num2
#    2

Matrix
set.seed(73120)

random_mat <- replicate(5, runif(500, 1, 100))

apply(random_mat, 2, var)
# [1] 822.9465 902.5558 782.4820 804.1448 830.1097

which(apply(random_mat, 2, var) > 900)
# [1] 2

Pandas
In Python, using pandas (data analytics library), the equivalent is also apply: DataFrame.apply with axis set to index to run operations on all columns. Equivalently, you can run DataFrame.aggregate. The return is a Pandas Series, similar to R's named vector as a 1-D array.
import numpy as np
import pandas as pd

np.random.seed(7312020)

random_df = pd.DataFrame({'num1': np.random.uniform(1, 100, 500),
                          'num2': np.random.uniform(1, 100, 500),
                          'num3': np.random.uniform(1, 100, 500),
                          'num4': np.random.uniform(1, 100, 500),
                          'num5': np.random.uniform(1, 100, 500)
                         })

agg1 = random_df.apply('var', axis='index')
print(agg1)
# num1    828.538378
# num2    810.755215
# num3    820.480400
# num4    811.728108
# num5    885.514924
# dtype: float64

agg2 = random_df.aggregate('var')
print(agg2)
# num1    828.538378
# num2    810.755215
# num3    820.480400
# num4    811.728108
# num5    885.514924
# dtype: float64

R's which can be achieved with simple bracketed [...] (also doable in R), .loc, or where (keeping original dimensions):
agg[agg > 850]
# num5    885.514924
# dtype: float64

agg.loc[agg > 850]
# num5    885.514924
# dtype: float64

agg.where(agg > 850)
# num1           NaN
# num2           NaN
# num3           NaN
# num4           NaN
# num5    885.514924
# dtype: float64

Numpy
Additionally using Python's numpy (the numeric computing library that supports arrays), you can use numpy.apply_along_axis. And to equate to Pandas' var, adjust default ddof accordingly:
random_arry = random_df.to_numpy()

agg = np.apply_along_axis(lambda x: np.var(x, ddof=1), 0, random_arry)
print(agg)
# [828.53837793 810.75521479 820.48039962 811.72810753 885.51492378]

print(agg[agg > 850])
# [885.51492378]

Comment: This is good, except it forgets/violates the advice your own comment gave, because you are using `apply` on a data.frame. You could just use `sapply`/`vapply` here (or, since the point is to explain OP's code, a matrix instead of a data frame).
Comment: Thanks @KonradRudolph,. Yes, I do run `apply` on R data frame really to show the translation to Pandas. I do not endorse the practice though and have edited the opening text.


Propriedade Name não funciona usando o Razor HiddenFor

Question: Estou criando vários campos dinamicamente usando Asp.net Razor e para isso estou passando o índice para uma partial view e setando a propriedade name de cada field. Tudo está funcionando bem com todos os campos exceto Id e PessoaId que são construídos usando @Html.HiddenFor e ficam ocultos.
Se eu setar a propriedade name conforme o exemplo abaixo e passar o índice, funciona:
Contato

Se eu tentar usar o Razor @Html.HiddenFor, a propriedade name não está recebendo o índice corretamente (Não sei se é pelo fato de eu estar usando @name) e os fields são setados com valor 0:
@Html.HiddenFor(model => model.Id, new { @class = "hid-id", @name = "PessoasContatosViewModel["+@indice+"].Id"})
@Html.HiddenFor(model => model.PessoaId, new { @class = "hid-pessoaId", @name = "PessoasContatosViewModel["+@indice+"].PessoaId"})

O que está dando errado? Existe alguma maneira de setar o name desses dois fields para o índice ser passado corretamente.
Código completo da view:
@model Retaguarda.Application.ViewModels.Pessoa.PessoaContatoViewModel
@{
    int indice = ViewBag.indice;
}

            @Html.HiddenFor(model => model.Id, new { @class = "hid-id", @name = "PessoasContatosViewModel["+@indice+"].Id"})
            @Html.HiddenFor(model => model.PessoaId, new { @class = "hid-pessoaId", @name = "PessoasContatosViewModel["+@indice+"].PessoaId"})
            Tipo de Contato
            <select asp-for="ContatoTipoId" asp-items="Model.ContatosTipos" name="PessoasContatosViewModel[@indice].ContatoTipoId" data-plugin="selectpicker" title="Selecione uma opção" class="form-control show-tick show-menu-arrow sel-contatoTipo"></select>

            Contato
            <input type="text" asp-for="Contato" name="PessoasContatosViewModel[@indice].Contato" class="form-control txt-contato" />

            Detalhes
            <textarea asp-for="Detalhes" name="PessoasContatosViewModel[@indice].Detalhes" class="form-control txt-detalhes"></textarea>

                <input type="checkbox" asp-for="ContatoPrincipal" name="PessoasContatosViewModel[@indice].ContatoPrincipal" class="ckb-contatoPrincipal" checked autocomplete="off" />
                Contato Principal

            <button type="button" class="btn btn-icon btn-default btn-outline btn-remover-contato" data-id="@Model.Id." style="margin-top: 30px;"></button>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Answer: Tente assim:

<input type="hidden" asp-for="Id" name="PessoasContatosViewModel[@indice].Id" />
Comment: Aaa entendi entao sua dúvida! Já tentou criar o hidden input manualmente então?``
Comment: Olá Victor Laio. Essa partial está certa assim mesmo, os demais campos funcional mesmo eu não passando o Índice Ex:  .... Eles funcionam pq possuim a propriedade name onde o índice é passado. O problema do Id e PessoaId é que a mesma forma não está funcionando se eu passar o name assim:  @name = "PessoasContatosViewModel["+@indice+"].Id"
Comment: Funcionou!!!!!! Obrigado Victor!! A resolução foi: . Comenta no post principal pata eu definir como resposta : )
Comment: Feito! Pode setar como resposta!


Order Statistics

Question: What is the motivation behind the use of order statistics in parameter estimation. In a very general sense, the first order statistic is considered to be an initial estimate to the location parameter. I wonder, how this would be possible. A layman based explanation would help.
Comment: Who considers the first order statistic to be a good initial estimate of a location parameter, & in what context? It would certainly be a very odd one for most situations.
Comment: I wonder, Vani, whether we might have a communication problem here.  Most people would understand a "first order statistic" to be the minimum (or sometimes the maximum) of a dataset.  I hope it's obvious that is a terrible estimate of a location parameter except under very special assumptions such as those described in Scortchi's answer.  Would you perhaps have something else in mind here, such as the median?  Could you clarify this point?
Comment: OP: please clarify the meaning of your question. It seems like you must either be misusing some terms or that you refer to a very particular context; in either case you can't hope for a very satisfying answer until the miscommunication is dealt with.
Comment: @Scortchi Whenever an iterative procedure is being used for parameter estimation, as the initial value for the location parameter is generally taken to be either the first order statistic, or a linear combination of the first few order statistic
Comment: Certainly not true in general. Are you thinking of say a three-parameter Weibull model?
Answer: The motivations for the use of an order statistic as an estimator are no different from the motivations for the use of any statistic as an estimator. For example, if you want to estimate the mean $\mu$ of a continuous uniform distribution from $0$ to $2\mu$, the sample maximum is the complete sufficient statistic for $\mu$, so both the maximum-likelihood & the uniformly minimum-variance unbiased estimators are based on it. If you want to estimate the mean $\theta$ of a normal distribution, the sample mean is the complete sufficient statistic for $\theta$, so both the maximum-likelihood & the uniformly minimum-variance unbiased estimators are based on it.
It's not true in general that the first order statistic is a good estimator of a  location parameter (in any reasonable sense of 'good'). Recall the mean of a normal distribution is a location parameter— in this case the sample minimum would not even be a consistent estimator. You've perhaps come across location parameters added to distributions like the Weibull, whose two-parameter version has a lower bound at zero. In cases like this the sample minimum is a consistent estimator of the population minimum, & I daresay a decent starting point for fitting algorithms.
Comment: I guess its about 'first order' approximations of something, not about order statistics.
Comment: @Michael: Might be, but something in the phrasing of the comment triggers old memories of reliability analysis & shifted failure-time distributions.

Order Statistics


Easy Question: Filter a View By Tax Term Menu Style Not Exposed Filters

Question: I dont know if im having a blonde moment or not. Im sure i learnt how to do this about 9 years ago way back on drupal 4 but ....well i seem stuck.
I have a page view. /match-previews. Its using the same vocab as im using across my website. I was wanting to create a menu link in the sidebar to each football league. I have it set up with an exposed filter but really i would prefer to have it as a menu system.
Ive tried cloning the page and adding a /match-previews/% page but thats where i seem to be stuck. Maybe just making up some normal pages and making a block view for each and taking the term from the page could be the way to go.
Can anyone put me out my misery as ive been at it too long for now tonight.
Thanks
my page is here if it helps
http://ukfootballbet.com/match-previews/
Answer: You can use the /match-previews/% as a contextual filter (advanced tab).  Here is a good tutorial on setting it up (http://www.metaltoad.com/blog/using-drupal-contextual-filters-views)
Comment: thanks Geoff looks good (and familiar) ill try it in a bit and come back and click your answer. sod it lets click the now as that is the way to do it.


Display mysql SUM in PHP

Question: I am trying to output a MySQL query in PHP, previously I have been using this statement to print echo("$line[meal_name]
");
In my code below I try to do it this way but I am getting errors and I am struggling to find out why
$query = 'SELECT SUM(meal.calorific_output), SUM(activity.calorific_output)
                            FROM meal
                            INNER JOIN activity
                            ON meal.customer_id=activity.customer_id AND meal.day=activity.day
                            WHERE meal.customer_id =
                "'. $_POST['customer_id'] .'"AND meal.day = "'. $day.'"';
            $result = mysql_query($query) or die('Query failed: ' . mysql_error());

            // Printing results
            while ($line = mysql_fetch_array($result)) {

                echo"
$day	";
                echo("$line[SUM(meal.calorific_output)]	");
                                echo("$line[SUM(meal.calorific_output)]
");

Answer: You should assign a name for your columns?  like SELECT SUM(meal.calorific_output) as sumMeal,
    $query = 'SELECT SUM(meal.calorific_output) as sumMeal, SUM(activity.calorific_output) as sumActivity
                            FROM meal
                            INNER JOIN activity
                            ON meal.customer_id=activity.customer_id AND meal.day=activity.day
                            WHERE meal.customer_id =
                "'. $_POST['customer_id'] .'"AND meal.day = "'. $day.'"';
            $result = mysql_query($query) or die('Query failed: ' . mysql_error());

            // Printing results
            while ($line = mysql_fetch_array($result)) {

                echo"
$day	";
                echo("$line["sumMeal"]	");
                                echo("$line["sumActivity"]
");

Display mysql SUM in PHP


"commenting out" in Jira markup

Question: This seems like such a simple question, but I've given it the obligatory 30 minutes of Googling, and I'm coming up with nothing.
We have pretty strict formatting requirements for our Jira tickets, but those tickets come into Jira from a variety of automated sources which we can't control.  I'm putting together a service that inspects Jira tickets using the API, and applies the correct formatting if necessary.  This would save us a lot of annoying labour.
It would be really useful if I could put invisible comments in the body of comment text, for both auditing purposes and manipulating the text.  I can't find any official/legitimate way of doing this.  I don't really think there'd be much call for it, aside from my quite specialist needs.
So does anyone have any ideas for Jira text markup tricks that would give readable comments in raw text form, but which wouldn't visibly render once the markup is applied?  I'll take a moderately future-proof hacky kludge.  Simply changing the text colour is not an option.
Comment: Sorry, didn't really understand, what are you trying to achieve? editing the body? editing comments? adding comments? mind giving an example?
Comment: I would take this to the Atlassian Forums. As far as I can remember, you could create a custom field. I don't think it would be wise to append comments to the issue body.
Comment: I've found a solution now.  As for an example, let's say I get a ticket with a badly formatted description field.  My service should pull out relevant content and prepend the description with the correctly formatted information.  Being able to leave machine-readable comments in there makes it a lot easier.
Comment: As long as you found a solution :)
Comment: Hmm. The Source Code editor plugin lets you see the underlying XHTML where you could add HTML comments.
Answer: The way I've ended up getting around this is to use anchors:
<code>{anchor: this text will not appear in the marked-up text in Jira}
</code>
It's not ideal, but it does the job, and shouldn't be removed in future versions of Jira.
Comment: Thanks!  I use this as `{anchor: vim:set filetype=confluencewiki nonu linebreak showbreak=...\  wrap nolist: }` so that I can edit JIRA comments in Vim, using [confluencewiki](http://www.vim.org/scripts/script.php?script_id=1994) syntax with the [It's All Text!](https://addons.mozilla.org/nl/firefox/addon/its-all-text/) Firefox plugin.
Answer:
I would create a new Role.  Set the comment's visibility to that
specific role.
To set it using REST take a look here.
For users who must see this comment, they should be assigned the specific role
which is documented here.
This should guarantee that your updates will not be deleted by JIRA upgrade.
Comment: This answers a different question, viz., "How can I hide specific JIRA comments?"  The original question is completely different: "How can I 'comment out' a _part_ of a JIRA description of comment, so that it only shows up in the 'source' form of the description or comment, and not in the final marked up form?"

"commenting out" in Jira markup


How can I show just one content with 5 images

Question: I create search page with views in Drupal 8.
In filter criteria, I choose "Content: images:target_id" because I want show contents that have images. (I set operator to not empty.) If a node has 5 images, the search page show that node for 5 times.
How can I fix this problem?
Comment: try using aggregation (if search views allows that).
Comment: @NoSssweat how can I using that ?
Comment: [see here](https://www.drupal.org/files/view3aggregation.png) and change No to Yes. idk if search views allows that though.
Answer: This can be solved by using aggregation

Change the No to Yes.


How to find music outside the 12TET system

Question: What are some cultures or bands that don't use the 12TET system and where can I find their music?
Comment: This seems like a broad identification question to me. With a hint of resource recommendation.
Comment: For microtonal studies in context of Indian music I recommend searching for "22 shrutis" and the works of vidyadhar oak https://youtu.be/YfF8ZEVOYks
Comment: How about old European music.  The ET in TET is Equal Temperament and prior too that there were more distinct tones used in European music.  Turkish music for example uses quarter tones.  They do not use a 24 TET scale.  It's more like a 7 note scale with one shifted note or an extra note (I don't recall the details).
Comment: @ToddWilcox would you suggest closing?
Answer: Expanding on @ggcg : That European music is absolutely 12TET-oriented is a notion that is not accurate
Practice
Violin intonation recommendation default pythagorean adjust chords towards just
Beethoven

Waldstein's third mvt. has, I believe, 17 bars with the pedal to be held down. Try this on a ET and it will quickly turn to a blur. Performed on a Young or Vallotti, it becomes an orchestral landscape
  https://www.pianostreet.com/smf/index.php?topic=39288.50

I can assent to this (almost)  – I don't have access to a Valloti/Young tuning – but with Werckmeister or Kirnberger one can keep the pedal depressed as Beethoven indicates which is messy with ET.
Current trends
Equal temperament "destroys everything"
Note 100% western setting
History misunderstood
Bach did not promote Equal temperament
Notation
Staff notation is not ET but closer to meantone ie there is one notion of whole tone (unlike Just's two) but C# is not 'spelt' same as Db. A pure 12 TET notation would be like midi numbers!
Comment: With regard to Beethoven and long passages with the pedal depressed, its not only the tuning but also the instrument.  The instrument of the early 19C was under much less tension and an undamped note would not sustain for as long.
Comment: @phoog Well yes and no: Yes: Instrument matters. No: Tuning matters more than is realized. Combined with the misunderstanding that Bach's "wohl temperierte (well tempered)" is the same/equivalent to "equal tempered"
Comment: @phoog You can try this small experiment to check "tuning matters more than instrument"  [Here](https://youtu.be/X7ti6HUX5xQ) is a performance. Make a bunch of people hear it without seeing it.  Make another see without hearing. And ask them all "What instrument did you see/hear and from which region of the world (if not western) "?


Prove that function is in $L^1$

Question: Let $E \subset \mathbb{R}$ be a measurable subset. Assume that $\int_{E} |x|^{1/4} |f(x)|^2 dx < \infty$ and $\int_{E} x^4 |f(x)|^3 dx < \infty$, then I want to prove $f \in L^1 (E)$.
Morally the first inequality says that $f(x)$ behaves nicely at $0$ and the second inequality says that $f(x)$ behaves nicely at $\pm \infty$ but I'm struggling to prove the statement rigorously. A possible idea is to use Holder's inequality: we know that $f(x) x^{1/8} \in L^2 (E)$ and $f(x) x^{4/3} \in L^3 (E)$ and probably it can be used somehow but I don't know how. Anyways, any ideas are greatly appreciated!
Comment: For integrability far from zero, it seems useful to write $ f(x) = f(x) x^r x^{-r} $ and then use Hölder inequality to compare with something finite.  It is possible this problem expects something more advanced, like some kind of $ L^p $ interpolation result.  I'm not sure.
Answer: 1. On  $\{x\in E: |x|\le 1\}$,  write $|f(x)| = \left(|f(x)| \cdot|x|^{1/8}\right)\cdot |x|^{-1/8}$ and apply the Cauchy-Schwarz inequality.
2. On $\{x\in E: |x|>1\}$, write $|f(x)| = \left(|f(x)| \cdot |x|^{4/3}\right)\cdot |x|^{-4/3}$ and apply Hölder with the conjugate exponents $p=3$, $q=3/2$.
Comment: If you are working with the Lebesgue measure (which I think is implicit), then you can calculate the integral of $x^{-1/8}$ over $[0,1]$ by using the Riemann integral.
Comment: @iou $\int_{[0,1]}\frac{1}{x^8}\,dx=\frac{x^{7/8}}{7/8}\bigg|_{x=0}^{x=1}$ which is certainly finite
Comment: How do you know that x^{-1/8} is in L^2 (E_1) where E_1 is this set of x in E such that |x| \le 1? I think it may happen that it contains a small interval around 0.
Comment: Yes, that's right but it may happen that this set contains a heigbourhood of infinity. Nevertheless, how to see that $x^{-1/8} is integral on this set?

Prove that function is in $L^1$


What is the minimum cost to connect all the islands?

Question: There is a grid of size N x M. Some cells are islands denoted by '0' and the others are water. Each water cell has a number on it denoting the cost of a bridge made on that cell. You have to find the minimum cost for which all the islands can be connected. A cell is connected to another cell if it shares an edge or a vertex.
What algorithm can be used to solve this problem? What can be used as a brute force approach if the values of N, M are very small, say NxM <= 100?
Example: In the given image, green cells indicate islands, blue cells indicate water and light blue cells indicate the cells on which a bridge should be made. Thus for the following image, the answer will be 17.

Initially I thought of marking all the islands as nodes and connecting every pair of islands by a shortest bridge. Then the problem could be reduced to Minimum spanning tree, but in this approach I missed the case where edges are overlapping. For example, in the following image, the shortest distance between any two islands is 7 (marked in yellow), so by using Minimum Spanning Trees the answer would be 14, but the answer should be 11 (marked in light blue).
Comment: This is a variant of [Steiner tree problem](https://en.wikipedia.org/wiki/Steiner_tree_problem). Follow the link to Wikipedia for some insights. In short, the exact solution perhaps cannot be found in polynomial time, but a minimal spanning tree is a not-so-bad approximation.
Comment: Could you please share the code you're currently using? This would make coming up with an answer a bit easier and would also show us exactly what your current approach is.
Comment: The solution approach you've described in your questions seems to be correct. Could you elaborate on what you mean by "I missed the case where edges are overlapping"?
Comment: @Asad : I have added an image to explain the problem in the MST approach.
Comment: "connect *every two* islands by a shortest bridge" - as you can see, that's clearly a bad approach.
Comment: You might want to check out the following paper about [2D Euclidean Distance Transform Algorithms:
A Comparative Survey](http://www.agencia.fapesp.br/arquivos/survey-final-fabbri-ACMCSurvFeb2008.pdf)
Comment: See here for example: http://www.csie.ntu.edu.tw/~kmchao/tree10spr/Steiner.pdf
Comment: There's a [related](http://cs.stackexchange.com/questions/68145/hardness-of-the-minimum-steiner-tree-problem-on-grid) question about whether this problem is in NP.
Comment: This is not the Traveling Salesman Problem. It looks like finding a "convenient meeting point" answered in this thread but more advanced (because the island is not a point, distance is modified by different cells' costs, and it doesn't have just one meeting point):
https://stackoverflow.com/questions/8718086/algorithm-to-find-point-of-minimum-total-distance-from-locations
Answer: To approach this problem, I would use an integer programming framework and define three sets of decision variables:

x_ij: A binary indicator variable for whether we build a bridge at water location (i, j).
y_ijbcn: A binary indicator for whether water location (i, j) is the n^th location linking island b to island c.
l_bc: A binary indicator variable for whether islands b and c are directly linked (aka you can walk only on bridge squares from b to c).

For bridge building costs c_ij, the objective value to minimize is sum_ij c_ij * x_ij. We need to add the following constraints to the model:

We need to ensure the y_ijbcn variables are valid. We can always only reach a water square if we build a bridge there, so y_ijbcn <= x_ij for every water location (i, j). Further, y_ijbc1 must equal 0 if (i, j) does not border island b. Finally, for n > 1, y_ijbcn can only be used if a neighboring water location was used in step n-1. Defining N(i, j) to be the water squares neighboring (i, j), this is equivalent to y_ijbcn <= sum_{(l, m) in N(i, j)} y_lmbc(n-1).
We need to ensure the l_bc variables are only set if b and c are linked. If we define I(c) to be the locations bordering island c, this can be accomplished with l_bc <= sum_{(i, j) in I(c), n} y_ijbcn.
We need to ensure that all islands are linked, either directly or indirectly. This can be accomplished in the following way: for every non-empty proper subset S of islands, require that at least one island in S is linked to at least one island in the complement of S, which we'll call S'. In constraints, we can implement this by adding a constraint for every non-empty set S of size <= K/2 (where K is the number of islands), sum_{b in S} sum_{c in S'} l_bc >= 1.

For a problem instance with K islands, W water squares, and specified maximum path length N, this is a mixed integer programming model with O(K^2WN) variables and O(K^2WN + 2^K) constraints. Obviously this will become intractable as the problem size becomes large, but it may be solvable for the sizes you care about. To get a sense of the scalability, I'll implement it in python using the pulp package. Let's first start with the smaller 7 x 9 map with 3 islands at the bottom of the question:
import itertools
import pulp
water = {(0, 2): 2.0, (0, 3): 1.0, (0, 4): 1.0, (0, 5): 1.0, (0, 6): 2.0,
         (1, 0): 2.0, (1, 1): 9.0, (1, 2): 1.0, (1, 3): 9.0, (1, 4): 9.0,
         (1, 5): 9.0, (1, 6): 1.0, (1, 7): 9.0, (1, 8): 2.0,
         (2, 0): 1.0, (2, 1): 9.0, (2, 2): 9.0, (2, 3): 1.0, (2, 4): 9.0,
         (2, 5): 1.0, (2, 6): 9.0, (2, 7): 9.0, (2, 8): 1.0,
         (3, 0): 9.0, (3, 1): 1.0, (3, 2): 9.0, (3, 3): 9.0, (3, 4): 5.0,
         (3, 5): 9.0, (3, 6): 9.0, (3, 7): 1.0, (3, 8): 9.0,
         (4, 0): 9.0, (4, 1): 9.0, (4, 2): 1.0, (4, 3): 9.0, (4, 4): 1.0,
         (4, 5): 9.0, (4, 6): 1.0, (4, 7): 9.0, (4, 8): 9.0,
         (5, 0): 9.0, (5, 1): 9.0, (5, 2): 9.0, (5, 3): 2.0, (5, 4): 1.0,
         (5, 5): 2.0, (5, 6): 9.0, (5, 7): 9.0, (5, 8): 9.0,
         (6, 0): 9.0, (6, 1): 9.0, (6, 2): 9.0, (6, 6): 9.0, (6, 7): 9.0,
         (6, 8): 9.0}
islands = {0: [(0, 0), (0, 1)], 1: [(0, 7), (0, 8)], 2: [(6, 3), (6, 4), (6, 5)]}
N = 6

# Island borders
iborders = {}
for k in islands:
    iborders[k] = {}
    for i, j in islands[k]:
        for dx in [-1, 0, 1]:
            for dy in [-1, 0, 1]:
                if (i+dx, j+dy) in water:
                    iborders[k][(i+dx, j+dy)] = True

# Create models with specified variables
x = pulp.LpVariable.dicts("x", water.keys(), lowBound=0, upBound=1, cat=pulp.LpInteger)
pairs = [(b, c) for b in islands for c in islands if b < c]
yvals = []
for i, j in water:
    for b, c in pairs:
        for n in range(N):
            yvals.append((i, j, b, c, n))

y = pulp.LpVariable.dicts("y", yvals, lowBound=0, upBound=1)
l = pulp.LpVariable.dicts("l", pairs, lowBound=0, upBound=1)
mod = pulp.LpProblem("Islands", pulp.LpMinimize)

# Objective
mod += sum([water[k] * x[k] for k in water])

# Valid y
for k in yvals:
    i, j, b, c, n = k
    mod += y[k] <= x[(i, j)]
    if n == 0 and not (i, j) in iborders[b]:
        mod += y[k] == 0
    elif n > 0:
        mod += y[k] <= sum([y[(i+dx, j+dy, b, c, n-1)] for dx in [-1, 0, 1] for dy in [-1, 0, 1] if (i+dx, j+dy) in water])

# Valid l
for b, c in pairs:
    mod += l[(b, c)] <= sum([y[(i, j, B, C, n)] for i, j, B, C, n in yvals if (i, j) in iborders[c] and B==b and C==c])

# All islands connected (directly or indirectly)
ikeys = islands.keys()
for size in range(1, len(ikeys)/2+1):
    for S in itertools.combinations(ikeys, size):
        thisSubset = {m: True for m in S}
        Sprime = [m for m in ikeys if not m in thisSubset]
        mod += sum([l[(min(b, c), max(b, c))] for b in S for c in Sprime]) >= 1

# Solve and output
mod.solve()
for row in range(min([m[0] for m in water]), max([m[0] for m in water])+1):
    for col in range(min([m[1] for m in water]), max([m[1] for m in water])+1):
        if (row, col) in water:
            if x[(row, col)].value() > 0.999:
                print "B",
            else:
                print "-",
        else:
            print "I",
    print ""

This takes 1.4 seconds to run using the default solver from the pulp package (the CBC solver) and outputs the correct solution:
I I - - - - - I I
- - B - - - B - -
- - - B - B - - -
- - - - B - - - -
- - - - B - - - -
- - - - B - - - -
- - - I I I - - -

Next, consider the full problem at the top of the question, which is a 13 x 14 grid with 7 islands:
water = {(i, j): 1.0 for i in range(13) for j in range(14)}
islands = {0: [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)],
           1: [(9, 0), (9, 1), (10, 0), (10, 1), (10, 2), (11, 0), (11, 1),
               (11, 2), (12, 0)],
           2: [(0, 7), (0, 8), (1, 7), (1, 8), (2, 7)],
           3: [(7, 7), (8, 6), (8, 7), (8, 8), (9, 7)],
           4: [(0, 11), (0, 12), (0, 13), (1, 12)],
           5: [(4, 10), (4, 11), (5, 10), (5, 11)],
           6: [(11, 8), (11, 9), (11, 13), (12, 8), (12, 9), (12, 10), (12, 11),
               (12, 12), (12, 13)]}
for k in islands:
    for i, j in islands[k]:
        del water[(i, j)]

for i, j in [(10, 7), (10, 8), (10, 9), (10, 10), (10, 11), (10, 12),
             (11, 7), (12, 7)]:
    water[(i, j)] = 20.0

N = 7

MIP solvers often obtain good solutions relatively quickly and then spend a huge about of time trying to prove the optimality of the solution. Using the same solver code as above, the program does not complete within 30 minutes. However, you can provide a timeout to the solver to get an approximate solution:
mod.solve(pulp.solvers.PULP_CBC_CMD(maxSeconds=120))

This yields a solution with objective value 17:
I I - - - - - I I - - I I I
I I - - - - - I I - - - I -
I I - - - - - I - B - B - -
- - B - - - B - - - B - - -
- - - B - B - - - - I I - -
- - - - B - - - - - I I - -
- - - - - B - - - - - B - -
- - - - - B - I - - - - B -
- - - - B - I I I - - B - -
I I - B - - - I - - - - B -
I I I - - - - - - - - - - B
I I I - - - - - I I - - - I
I - - - - - - - I I I I I I

To improve the quality of the solutions you obtain, you could use a commercial MIP solver (this is free if you are at an academic institution and likely not free otherwise). For instance, here's the performance of Gurobi 6.0.4, again with a 2-minute time limit (though from the solution log we read that the solver found the current best solution within 7 seconds):
mod.solve(pulp.solvers.GUROBI(timeLimit=120))

This actually finds a solution of objective value 16, one better than the OP was able to find by hand!
I I - - - - - I I - - I I I
I I - - - - - I I - - - I -
I I - - - - - I - B - B - -
- - B - - - - - - - B - - -
- - - B - - - - - - I I - -
- - - - B - - - - - I I - -
- - - - - B - - B B - - - -
- - - - - B - I - - B - - -
- - - - B - I I I - - B - -
I I - B - - - I - - - - B -
I I I - - - - - - - - - - B
I I I - - - - - I I - - - I
I - - - - - - - I I I I I I

Comment: This is **exactly** what I was looking for when I started the bounty. It amazes me how such a trivial-to-describe problem can give such a hard time to MIP solvers. I was wondering if the following is true: A path linking two islands is a shortest path with the additional constraint that it has to pass through  some cell (i, j). For example, the top left and middle islands in Gurobi's solution are linked with a SP that is constrained to pass through cell (6, 5). Not sure if this is true, but ill look into it at some point. Thanks for the answer!
Comment: @DavidEisenstat thanks for the suggestion -- I just tried it out and unfortunately it solved a good deal more slowly for these problem instances.
Comment: Instead of the y_ijbcn formulation, I'd try a formulation based on flow (variable for each tuple consisting of an island pair and square adjacency; conservation constraints, with excess 1 at the sink and -1 at the source; bound total in-flow at a square by whether it was purchased).
Comment: @Ioannis interesting question -- I'm not sure if your conjecture is true but it seems quite plausible to me. You could think of the cell (i, j) as where the bridges from these islands need to go to further connect to other islands, and then subject to reaching that coordinating point you would just want to build the cheapest bridges possible to connect the island pair.
Answer: A brute-force approach, in pseudo-code:
start with a horrible "best" answer
given an nxm map,
    try all 2^(n*m) combinations of bridge/no-bridge for each cell
        if the result is connected, and better than previous best, store it

return best

In C++, this could be written as
// map = linearized map; map[x*n + y] is the equivalent of map2d[y][x]
// nm = n*m
// bridged = true if bridge there, false if not. Also linearized
// nBridged = depth of recursion (= current bridge being considered)
// cost = total cost of bridges in 'bridged'
// best, bestCost = best answer so far. Initialized to "horrible"
void findBestBridges(char map[], int nm,
   bool bridged[], int nBridged, int cost, bool best[], int &bestCost) {
   if (nBridged == nm) {
      if (connected(map, nm, bridged) && cost < bestCost) {
          memcpy(best, bridged, nBridged);
          bestCost = best;
      }
      return;
   }
   if (map[nBridged] != 0) {
      // try with a bridge there
      bridged[nBridged] = true;
      cost += map[nBridged];

      // see how it turns out
      findBestBridges(map, nm, bridged, nBridged+1, cost, best, bestCost);

      // remove bridge for further recursion
      bridged[nBridged] = false;
      cost -= map[nBridged];
   }
   // and try without a bridge there
   findBestBridges(map, nm, bridged, nBridged+1, cost, best, bestCost);
}

After making a first call (I am assuming you are transforming your 2d maps to 1d arrays for ease of copying around), bestCost will contain the cost of the best answer, and best will contain the pattern of bridges that yields it. This is, however extremely slow.
Optimizations:

By using a "bridge limit", and running the algorithm for increasing maximum numbers of bridges, you can find minimal answers without exploring the whole tree. Finding a 1-bridge answer, if it existed, would be O(nm) instead of O(2^nm) - a drastic improvement.
You can avoid searching (by stopping recursion; this is also called "pruning") once you have exceeded bestCost, because it makes no sense to keep looking afterwards. If it can't get better, don't keep digging.
The above pruning works better if you look at "good" candidates before looking at "bad" ones (as it is, cells are all looked at in left-to-right, top-to-bottom order). A good heuristic would be to consider cells that are near to several unconnected components as higher-priority than cells that are not. However, once you add heuristics, your search starts to resemble A* (and you need some kind of priority queue, too).
Duplicate bridges and bridges to nowhere are to be avoided. Any bridge that does not disconnect the island network if removed is redundant.

A general search algorithm such as A* allows much faster search, although finding better heuristics is not a simple task. For a more problem-specific approach, using existing results on Steiner trees, as suggested by @Gassa, is the way to go. Note, however, that the problem of building Steiner trees on orthogonal grids is NP-Complete, according to this paper by Garey and Johnson.
If "good enough" is enough, a genetic algorithm can probably find acceptable solutions quickly, as long as you add a few key heuristics as to preferred bridge placement.
Comment: "try all 2^(n*m) combinations"  uh, `2^(13*14) ~ 6.1299822e+54` iterations.  If we assume you can do a million iterations per second, that would only take... ~194380460000000000000000000000000000000000` years.  Those optimizations are very necessary.
Comment: OP *did* ask for "a brute force approach if values of N,M are very small, say NxM <= 100". Assuming, say, 20 bridges are enough, and the only optimization you use is the bridge-limiting one above, the optimal solution will be found in O(2^20), which is well in range of your hypothetical computer.
Comment: Most backtracking algorithms are horribly inefficient until you add pruning, iterative deepening, and so on. This is not to say that they are useless. For example, chess engines routinely beat grandmasters with these algorithms (granted - they use every trick in the book to prune aggressively)
Answer: This problem is a variant of Steiner tree called node-weighted Steiner tree, specialized a certain class of graphs. Compactly, node-weighted Steiner tree is, given a node-weighted undirected graph where some nodes are terminals, find the cheapest set of nodes including all terminals that induces a connected subgraph. Sadly, I can't seem to find any solvers in some cursory searches.
To formulate as an integer program, make a 0-1 variable for each non-terminal node, then for all subsets of non-terminal nodes whose removal from the starting graph disconnects two terminals, require that the sum of variables in the subset be at least 1. This induces way too many constraints, so you'll have to enforce them lazily, using an efficient algorithm for node connectivity (max flow, basically) to detect a maximally violated constraint. Sorry for the lack of details, but this is going to be a pain to implement even if you are already familiar with integer programming.
Answer: Given that this problem takes place in a grid, and you have well defined parameters, I would approach the problem with systematic elimination of the problem space via creating a minimum spanning tree. In doing so, it makes sense to me if you approach this problem with Prim's Algorithm.
Unfortunately, you now run into the problem of abstracting away the grid to create a set of nodes and edges... ergo the real problem of this post is how do I convert my n x m grid into {V} and {E}?
This conversion process is, at a glance, likely NP-Hard because of the sheer number of combinations possible (assume that all waterway costs are identical). To handle instances where paths overlap, you should consider making a virtual island.
When this is done, run Prim's Algorithm and you should arrive at the optimal solution.
I do not believe that Dynamic Programming can be run effectively here because there is no observable principle of optimality. If we find the minimum cost between two islands, that doesn't necessarily mean that we can find the minimum cost between those two and the third island, or another subset of islands which will be (by my definition to find the MST via Prim) connected.
If you would like code (pseudo or otherwise) to convert your grid into a set of {V} and {E}, please send me a private message and I will look into splicing together an implementation.
Comment: All water-costs are not identical (see examples). Since Prim has no notion of creating those "virtual nodes", you should consider an algorithm that does: Steiner trees (where your virtual nodes are called "Steiner points").
Comment: @tucuxi : Mentioning that all waterway costs *could* be identical is necessary for analysis of the worst case because this is the condition that inflates the search space to its maximum potential. This is why I brought it up. In regards to Prim, I assume that the programmer in charge of implementing Prim for this problem recognizes that Prim does not create virtual nodes and handles this at the implementation level. I have not yet seen Steiner trees yet (still undergrad) so thank you for the new material to learn!


FlashBuilder ASP.NET Development Server not installed

Question: This annoying error appears when I try to Import an existing project (from the code repository) into the workspace.  It prevents the IDE from even letting me view the source code, let alone compile it.  I don't need ASP.NET to compile to a /bin/ folder, let alone view code with color syntax highlighting just to help a junior, and I don't wish to install a bunch of stuff just to do so.
How to erase this error?
Answer: Edit the file .flexProperties in the project root.
Remove any mention of aspNet, and change flexServerType from 32 or whatever to 0.