In math/stats terminology, $1/p$ is the reciprocal of $p$. So what is $1-p$ called, if anything?

Question: I just want to describe in plain text a function that has many $1-p$ terms:
$\frac{(1-p_1) + p_2}{2} × (1-p_3)$.
Comment: "The complement", or more accurately "the probability of the complementary event".
Answer: Assuming $p$ is the probability of an event, $1 - p$ is the probability of its complement.
If $p$ is not the probability of an event then I doubt that $1 - p$ has any special meaning or name.
Comment: I agree. Also, I'd add that if p is the probability of an event, then it's also common to denote 1-p as q. That might help simplify describing the function.
Comment: I've come across a few other settings in which $1-p$ was called the complement of $p$; notably in arithmetic modulo 2 (and more generally, linear algebra over $\mathbb{Z}/(2)$, but also I think some other settings, though I can't remember them now.
Answer: In addition to $1-p$ being the complement where $p$ is a probability.
There is also the general process of taking $1 - x$ or $0 - x$ or $c - x$ where $x$ is a variable and $c$ is a constant. This is sometimes referred to as reversing or reflecting a variable.
Comment: The same word is used in an analagous way in geometry. The sum of a probability and its complement comes to 1; the sum of an angle and its complement comes to a right angle. So in probability, the complement of 0.8 is 0.2, and in geometry the complement of 75 degrees is 15 degrees. "Complement" effectively means "what extra is needed to make it complete"!
Answer: In addition to the answers mentioning that $1-p$ may be regarded as the complement of $p$, it might be useful to note that the reason $1/p$ has a special name is because $1$ is the multiplicative identity (so that $p \times \frac{1}{p} = 1$).
When it comes to addition, the identity is $0$, and the value with a similar special name to the reciprocal is the negation $-p$ (so that $p + (-p) = 0$). For this reason, there's no necessity for $1-p$ to have a special name in the general case.
Comment: @JoshuaShaneLiberman That is true, but it's also true for any other number: $f(p) := k-p$ implies $f(f(p)) = k-(k-p)=p$. It's not practical to have a special name for every possible value of $k$. Maybe a name for the general $k-p$ case might exist, but there's no reason for the specific $1-p$ case to have one.
Comment: I don't see how $1-p$ not being an inverse makes it any less special. It still has some nice properties. For instance, $f(p) := 1-p$ implies $f(f(p)) = 1 - (1-p) = p$. If anything, taking a complement is made more similar to negating or inverting by having this property, so arguments for giving them a special name would also apply.


how to make an html page show in a frame in gwt

Question: My project is organized like this:
I have a gwt frame in my main html page (shuttle_website_2.html)
there is a folder in the war folder.... path war/Assets/Animation/airport_shuttle_animation.html
so in the gwt-frame url I put this Assets/Animation/airport shuttle animation.html and it works fine in hosted mode.
When I deploy it to appengine it says:
 Error: Not Found

The requested URL /Assets/Animation/airport%20shuttle%20animation.html was not found on this server.

How do I make the html page show up in the frame after it is deployed to appengine?
Here is the appengine-web.xml file:
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
  <application>reservationtransport1</application>
  <version>1</version>

  <static-files>
    <include path="**" />

    <include path="**.nocache.*" expiration="0s" />

    <include path="**.cache.*" expiration="365d" />
    <exclude path="**.gwt.rpc" />
  </static-files>

  <system-properties>
    <property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/>
  </system-properties>

</appengine-web-app>

Answer: Perhaps the file or folder is being excluded from GAE.  Check your appengine-web.xml (often located in war/lib).
appengine-web.xml docs:  http://code.google.com/appengine/docs/java/config/appconfig.html
Less likely (because it probably would have shown up in hosted mode), perhaps the web.xml file or the framework you are using isn't serving it out.
[EDIT]
Or, you also seem to be using spaces in one place and underscores in another.
One more debugging hint: Try accessing the html file just from the browser, e.g. http://reservationtransport1.appspot.com/Assets/Animation/airport%20shuttle%20animation.html
Comment: here is the appengine-web.xml


Em Orientação a Objetos, uma herança viola o encapsulamento?

Question: Segundo o livro Padrões de Projeto escrito por Erich Gamma, Richard Helm, Ralph Johnson e John Vlissides, realizam uma afirmação:
"...a herança viola o encapsulamento."
Segue abaixo o parágrafo que contém esta afirmação:

"... a herança de classe tem também algumas desvantagens. Em primeiro lugar, você não pode mudar as implementações herdadas das classes ancestrais em tempo de execução, porque a herança é definida em tempo de compilação. Em segundo lugar, e geralmente isso é o pior, as classes ancestrais frequentemente definem pelo menos parte da representação física das suas subclasses. Porque a herança expõe para uma subclasse os detalhes de implementação dos seus ancestrais, frequentemente é dito que "a herança viola o encapsulamento" [Sny86]. A implementação de uma subclasse, dessa forma, torna-se tão amarrada à implementação da sua classe-mãe que qualquer mudança na implementação desta forçará uma mudança naquela."

Eu não consegui visualizar na prática essa afirmação. Como que a herança viola o encapsulamento? Para elucidar melhor o entendimento, um exemplo que justifique essa afirmação é bem-vinda.
Answer: Isso significa que o acoplamento é forte e qualquer alteração de código na classe base, afeta as subclasses.
Por isso, não se recomenda fazer a herança para reaproveitamento de código. Porque se uma função precisar ser alterada na classe original, afetará todas as filhas e a solução fácil seria violar o encapsulamento (tornando protegido ou público algo que faria mais sentido como privado).
Em muitos casos hoje, se recomenda a composição no lugar da herança para estruturar um código. O objetivo é delegar partes menores para uma classe que é parte da classe maior.
Por exemplo, criando a classe Reserva e a classe Compra para fazerem parte da classe Transação. Nesse caso, deixa todas as funções bem separadas e com comportamentos bem definidos.
Answer: Temos que ver essa discussão do ponto de vista do que é encapsulamento:

Um mecanismo de restrição de acesso aos elementos da classe

O encapsulamento permite que você crie uma implementação isolada, portanto você pode testar isoladamente e garantir que mudanças na implementação (sem mudar a interface) tem impacto zero no restante do sistema.
O oposto disso, apenas para dar um contraste, é você mudar uma linha de código e ter que testar metade do sistema por causa de um código ruim extremamente acoplado.
Com isso em mente, a herança viola o encapsulamento no sentido de que a mudança em uma superclasse tem o potencial de afetar todas as subclasses.
Pense no caso onde uma superclasse é usada em vários projetos e agora todos eles precisarão ser atualizados e testados novamente.
Em geral, isso não ocorre se uma superclasse tem membros private (privados). Por outro lado, quando falamos em membros que podem ser acessados por subclasses (protected, por exemplo) temos que entender que, do ponto de vista da subclasse, protected e public são a mesma coisa, então é como se não existisse encapsulamento algum.
Finalmente, usar herança em contextos errados (não que seja fácil saber) leva você rapidamente de:

Olha que legal essa minha "super classe" que meus 10 colegas podem simplesmente estender e ter quase tudo implementado "de graça".

Para, depois de algum tempo:

Putz! Tenho que mudar essa porcaria de classe abstrata de novo, pedir para meus 10 colegas atualizarem as implementações deles, testar tudo novamente e exigir que todos os módulos do sistema sejam atualizados ao mesmo tempo em produção!
Comment: @DiegoF isso mesmo
Comment: +1, só uma dúvida, no último parágrafo, você quis dizer "privado" ali como tradução de `private` certo?
Answer: A herança, tal qual se ensinava em OO nos anos 90 (na época em que diziam que OO ia acabar com a fome no mundo), tem surpreendentemente poucos usos legítimos. Eu não usaria a expressão "viola o encapsulamento", eu diria antes que a herança "engessa" as subclasses. Linguagens "anos 90" tipo Delphi, que só tinham herança como meio de reutilização de código, tinham profundas hierarquias de classe no seu framework (vinha até um chart na caixinha do produto, tamanho A3, pra colar na parede), e quebrava tudo a cada versão nova.
Fica ainda mais canhestro quando se permite herança múltipla. Aquela coisa de "Quadrado é subclasse de Retângulo mas também é subclasse de PolígonoRegular"... aí "Círculo" deveria ser subclasse de "PolígonoRegular" ou não?? Ao menos descobriram ainda nos anos 90 que herança múltipla não era uma boa idéia, e o único uso realmente legítimo era a aderência a interfaces, ou seja, herança simples de uma classe concreta e herança múltipla de classes puramente abstratas (o Java é assim desde sempre).
Às vezes esse engessamento é perfeitamente adequado. Na totalidade dos frameworks visuais que conheço, cada controle da tela é descendente de uma classe View (UIView no iOS, View no Android, etc.) Nesse caso a herança é adequada porque as views derivadas têm de adequar-se rigidamente aos protocolos e ao funcionamento da View de base; e a View de base implementa a totalidade da funcionalidade básica (é ela, e não a derivada, que vai "conversar" com o driver de vídeo, etc.) Se a View mudar seu modus operandi, é legítimo e desejável "quebrar" todas as derivadas de View, de preferência em tempo de compilação, para que sejam readaptadas.
Mas na maioria dos casos essa herança hierárquica é uma forma ruim de reutilizar código. Mesmo a herança de interfaces é obsoleta, os "protocolos" do Objective-C/Swift ou "duck typing" de linguagens interpretadas, são muito melhores. Essas linguagens também permitem adicionar métodos a uma classe sem precisar definir uma subclasse ("composição"). Esses recursos permitem frameworks com hierarquias bem "rasas". como é o caso do UIKit da Apple: https://finalizedotcom.files.wordpress.com/2012/12/uikit_classes.jpg
Em resumo, o uso excessivo de herança era uma conseqüência dos poucos recursos das linguagens disponíveis, da "novidade" das técnicas de OO, e do mau entendimento do OO "de verdade" tal qual implementado em Smalltalk.
Comment: Resposta muito esclarecedora. Praticamente uma aula de história! :)
Answer: Em alguns momentos você pode acabar caindo em situações em que a implementação interna da classe mãe vai gerar comportamentos estranhos quando você sobrescrever algum método dela.
Ex: Caso que gera Stackoverflow
public class InheritanceOverflow {

  public static class Parent {

    public void foo() {
      bar();
    }

    public void bar() {}
  }

  public static class Child extends Parent {
    @Override
    public void bar() {
      // Não há como saber nesse ponto que o método foo chama o método bar
      // isso irá gerar uma recursão infinita
      foo();
    }
  }

  public static void main(String[] args) {
    new Child().bar();
  }
}

Basicamente esse exemplo quebra o encapsulamento pois você terá que saber qual a implementação interna da classe mãe pra poder resolver esse problema.


Optimal decision making with probabilities

Question: You are suing for company for 100000, which the company refuses to pay, but they are willing to settle for 35000. You give a counter-offer of 65000, which you think there is 40% change of the company accepting. If they refuse the counter-offer, the case goes into court that you think you have 50% of winning. If you win, you gain the 100000 or if you lose, you end up paying 55000 in legal fees. Which path you should take, and what is the expected value of perfect information for this problem.
I think there are two scenarios (accepting 35000 or countering), that I think have the expected values of:
\begin{align}
EV_{\text{accept}} &= 1\times35000=35000\\
EMV=EV_{\text{counter}} &= \overbrace{0.4\times65000}^{\text{counter is accepted}} + \overbrace{(1-0.4)[0.5\times100000-0.5\times55000]}^{\text{case goes to court}} = 39500
\end{align}
So you should choose to counter and not accept if you are risk neutral. But I have trouble understanding the value of perfect information. Wiki states that the value of perfect information is the difference between the (maximum) expected value with out information and with information. Would the expected value WITH information then be:
\begin{align}
EV|PI &= \sum_j p_j (\operatorname{max}_i R_{ij}), \\
 &= 1.0\times\operatorname{max}\{35000,0\} + 0.4\times\operatorname{max}\{65000,0\}+0.6\times \operatorname{max}\{ 0.5\times100000, -0.5\times55000\},\\ &= 91000.
\end{align}
Then the value of perfect information would be. But I cannot somehow intuitively confirm if its true or not..
\begin{equation}
EVPI =EV|PI - EMV = 91000-39500 = 56000.
\end{equation}
Edit: I'm actually not sure if the expected monetary value for the counter offer is calculated correctly.
Answer: The value of the option to counteroffer (relative to accepting settlement) with perfect information on what the result would be is:
40% of the time: raise settlement value by +65000 - 35000 = +30000
30% of the time: lawsuit award - refused settlement = +100000 -35000 = +65000
30% of the time: avoided lawsuit penalty + avoided settlement loss = +55000 + 35000 = +80000
The expected value of that is in the tens of thousands.
Without the information, the expected value of a counteroffer is calculated as +4500 in the question, or about 10 times lower.  The difference between the higher and the lower expected value is the value of the perfect information (assuming all decisions are made based on expected value).
Comment: Computing the expectations, I get 55.5K - 4.5K = 51000 as the difference due to information.
Comment: How can the expected monetary value without information be only 4.5k? Shouldn't it be 39500 like I calculated here:
\begin{align}
EV_{\text{accept}} &= 1\times35000=35000\\
EMV=EV_{\text{counter}} &= \overbrace{0.4\times65000}^{\text{counter is accepted}} + \overbrace{(1-0.4)[0.5\times100000-0.5\times55000]}^{\text{case goes to court}} = \textbf{39500}
\end{align}
Comment: As in: 40% of the time: get the counter offer of +65000, 30% of the time win in court +100000, 30% of the time lose in court -55000 which comes to $0.4\times65000+0.3\times100000-0.3\times55000 = 39500$?.
Comment: +4.5k and +55.5k relative to taking a settlement (so another +35k in total).  It doesn't matter what the baseline is since we subtract one from the other to get the difference in expectation due to the information.
Comment: Right! Thanks a lot. This cleared alot of doubts :)


How to transfer session data from one server to another server?

Question: We have developed one Web Application which is running in only one server. Now client needs our application be in two servers. So if one of the servers down then another server should be working. We are using sessions in our application. Now the problem is how to transfer the session data from one server to another??
Answer: You need a session server to do this.
That normally means a SQL server that will serve as one, but there are other options.
Comment: You can also store session info in a MySQL (http://dev.mysql.com/doc/refman/5.0/en/connector-net-tutorials-asp-provider-session-state.html) or PostgreSQL (http://dev.nauck-it.de/projects/show/aspsqlprovider) database.
Answer: Move to the SQL Session state model and backend it with a SQL Server. Here's the Microsoft How-To.
Answer: ASP.NET allows you to session information in one of three places (see list from MSDN below). Methods 2 or 3 would be good solutions to your dilemma.

InProc mode, which stores session state in memory on the Web server. This is the default.
StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
SQLServer mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.

Of course, unless you also have a redundant state machine you'll still have a single point of failure.
Answer: Read this Maintaining Session State & Sharing Data
Across Servers, Domains & the Entire Internet
Answer: What you need to do is maintain your session data in a replicated database (e.g., using SQL server), as opposed to locally on one machine.
Note that when you use this technique you will gain in reliability, but lose out in latency due to the overhead of using the database.
Answer: Look at the ScaleOut State Server. This gadget will share session state across mutliple servers so if one goes down, no sessions are lost.
Answer: There are typically a few ways to solve this:

Run a StateServer which lets a state service handle your session data. Saves you the trip to a database, but leaves you with a single point of failure
Put you State in SQLServer. Gives some extra load on the database. But if you have clustering you avoid having af single point of failure
Sticky connections in a loadbalancer. The loadbalancer remembers which server, served you last time, and sends you there again. If the server in question is down, your session is lost.
Then there are som distributed State Server products out there like NCache which lets you distribute you state service over multiple servers.


Da Capo in Lilypond

Question: I am typesetting scores using Lilypond and would like to print a Da Capo, but haven't found a standard command to do so. I am currently working around this issue by using \mark "D.C.".
However, the mark is sometimes placed on the next line. Also, I would rather use a single command and be sure to always get the same result, rather than having to type the text out every time.
Answer: As alephzero noted you have to set the visibility of the mark. Because these kind of marks frequently need the same treatment you can setup your own commands for them so you don't have to remember the details of the visibility controls and clutter up your code.
For example I keep a common library file around with a bunch of commands that I use a lot. Among them are some commands for getting marks the way I like them. These can then be used in my music just by calling \DS or whichever variant I want:
DSfine = {
  \once \override Score.RehearsalMark #'break-visibility = #'#(#t #t #f)
  \mark \markup { \small "D.S. al fine" }
}

DS = {
  \once \override Score.RehearsalMark #'break-visibility = #'#(#t #t #f)
  \mark \markup { \small "D.S." }
}

DCfine = {
  \once \override Score.RehearsalMark #'break-visibility = #'#(#t #t #f)
  \mark \markup { \small "D.C. al fine" }
}

DCcoda = {
  \once \override Score.RehearsalMark #'break-visibility = #'#(#t #t #f)
  \mark \markup { \small "D.C. al coda" }
}

DScoda = {
  \once \override Score.RehearsalMark #'break-visibility = #'#(#t #t #f)
  \mark \markup { \small "D.S. al coda" }
}

Fine = {
  \once \override Score.RehearsalMark #'break-visibility = #'#(#t #t #f)
  \mark \markup { \small \italic "fine" }
}

GotoCoda = {
  \once \override Score.RehearsalMark #'break-visibility = #'#(#t #t #f)
  \mark \markup { \small \musicglyph #"scripts.coda" }
}

Coda = {
  \once \override Score.RehearsalMark #'break-visibility = #'#(#f #t #t)
  \mark \markup { \small \musicglyph #"scripts.coda" }
}

Segno = {
  \once \override Score.RehearsalMark #'break-visibility = #'#(#f #t #t)
  \mark \markup { \small \musicglyph #"scripts.segno" }
}

Answer: When some music notation is attached to a bar line that coincides with the end of a system in the score, you may want to print the notation at the end of that system, at the start of the next system, or even in both places (for example a key signature change).
Lilypond "knows" the standard rules for various types of notation. The defaults are listed in http://lilypond.org/doc/v2.18/Documentation/notation/visibility-of-objects#using-break_002dvisibility, but you can override them as shown on that page.
To force your "fake rehearsal mark" to appear in the middle of a system or at the end, but not at the beginning, use
\once \override Score.RehearsalMark.break-visibility = #begin-of-line-invisible

Answer: For future readers:
Newer versions of LilyPond (v2.23 and above) have an inbuilt way to encode Da Capo and related repeats.
There is a new repeat structure \repeat segno, this works somewhat similarly to \repeat volta.  There are also new commands like \volta, \fine and \section that work with this new structure.  Using these, you won't have to type out the text at all.
Here is a simple example of a Da Capo repeat:
\version "2.23.6"

contents = {
    \new Staff {
        \repeat segno 2 {
            a'1 |
            b'1 |
            \volta 2 \fine
        }
    }
}

%% PDF
\score {
    \contents
    \layout { }
}

%% MIDI
\score {
    \unfoldRepeats
    \contents
    \midi { }
}

See this page of the documentation for more detail:
1.4.1 Long Repeats - Segno repeat structure

Da Capo in Lilypond


PHP ARRAY sort at third level

Question: Hi I am actually trying to sort an array at third level with different keys.
The below is Sample array input.
Array
(
    [19067] => Array
        (
            [Morrisville, PA] => 5.02
        )

    [18977] => Array
        (
            [Washington Crossing, PA] => 6.63
        )

    [08695] => Array
        (
            [Trenton, NJ] => 2.84
        )

    [08690] => Array
        (
            [Trenton, NJ] => 1
        )

    [08666] => Array
        (
            [Trenton, NJ] => 2.84
        )

    [08650] => Array
        (
            [Trenton, NJ] => 0
        )

    [08648] => Array
        (
            [Lawrence Township, NJ] => 2.88
        )

    [08647] => Array
        (
            [Trenton, NJ] => 2.84
        )

    [08646] => Array
        (
            [Trenton, NJ] => 2
        )

)

Can any body help me to sort the above array at third level
Expected result should like:
Output:
Array
(
    [08650] => Array
        (
            [Trenton, NJ] => 0
        )

    [08690] => Array
        (
            [Trenton, NJ] => 1
        )

     [08646] => Array
        (
            [Trenton, NJ] => 2
        )

    [08666] => Array
        (
            [Trenton, NJ] => 2.84
        )

    [08695] => Array
        (
            [Trenton, NJ] => 2.84
        )

    [08647] => Array
        (
            [Trenton, NJ] => 2.84
        )

    [08648] => Array
        (
            [Lawrence Township, NJ] => 2.88
        )

    [19067] => Array
        (
            [Morrisville, PA] => 5.02
        )

    [18977] => Array
        (
            [Washington Crossing, PA] => 6.63
        )

)

Thanks in advance..
Answer: uasort($array, function (array $a, array $b) {
    return current($a) - current($b);
});

Do note the comments: values which differ less than 1.0 will be sorted as the same. You may want to do (current($a) - current($b)) * 100 or otherwise round the value, depending on what value ranges you expect.
Comment: something tells me that float values don't always work very well for comparison values ... not sure where i've read that though :/ otherwise, +1
Comment: Found it, it will implicitly cast to integer, so 0.1 and 0.99 compare the same, which might not always be right :)
Comment: Floats are fine here. What you mean is that `$foo == 1.2345` will not typically work with floats, since their value isn't guaranteed to be precise.
Comment: Wut? Where will it cast to an integer?
Comment: it's in the manual under `usort()` - `cmp_function` parameter, the notice there
Comment: Hmm, I see. Thanks, I wasn't aware of that. O_o Multiplying the comparison value by, say, 100 may be a good idea then, depending on what values you expect.
Comment: I only found out recently myself actually; solved in much the same way as you've described ^^

PHP ARRAY sort at third level


What is the difference between Sigmoid neurons and Stochastic binary neurons?

Question: Both have the same equation : the logistic unit.
Sigmoid output a ral-valued number between 0 and 1 and Stochastic binary neuron a probability between 0 and 1 too.
Apart from the name/type given to the output (probability or real-valued number) what is the difference between this two types of neurons ?
Answer: The only difference is that :

The sigmoid neuron is able to output values between 0 and 1.
The stochastic binary neurons only can output either a 0 or a 1 with the probability given by the sigmoid activation function.
Answer: Stochastic Binary is not a smooth function, it is like a step function where as Sigmoid is a smooth function. Although at extreme ends, large positive and large negative Sigmoid give a similar behavior as Stochastic but on moderate values it transits slowly. So a small change in the weights and bias will cause small change in the output, whereas this is not the case with Stochastic Binary neurons.
Refer to this book by Michael Neilson and I'm sure your confusion will be blown away. He explains it so well.
http://neuralnetworksanddeeplearning.com/chap1.html


Notas e moedas C#

Question: Estou com um erro em um algoritmo que estou implementando na linguagem c# no site do JUDGE online, Notas e moedas e eu não sei muito bem o que seja, mas acredito que seja em relação aos cálculos, dá um erro de arrendondamento, percebi isso ao colocar vários writeln, depois do cálculo, só para acompanhar as variações, com algumas entradas funciona perfeitamente. só não funciona com essa entrada 576.43 e outras. dá tudo certo, mas a última linha de saída de dados dá 2 moedas de 1c, sendo que são 3 moedas..enfim talvez tenha ficado confuso, eu não sei muito bem explicar, mas espero que os senhores entendam a minha lógica rsrs
using System;

class MainClass {
  public static void Main (string[] args) {
    double n1,n2,n3,n4,n5,n6,m1,m2,m3,m4,m5,m6;
    double a = double.Parse(Console.ReadLine());

    n1 = (a - a % 100)/100;
    a = a % 100;

    n2 = (a - a % 50)/50;
    a = a % 50;

    n3 = (a - a % 20)/20;
    a = a % 20;

    n4 = (a - a % 10)/10;
    a = a % 10;

    n5 = (a - a % 5)/5;
    a = a % 5;

    n6 = (a - a % 2)/2;
    a = a % 2;

    m1 = (a - a % 1)/1;
    a = a % 1;

    m2 = (a - a % 0.50)/0.50;
    a = a % 0.50;

    m3 = (a - a % 0.25)/0.25;
    a = a % 0.25;

    m4 = (a - a % 0.10)/0.10;
    a = a % 0.10;

    m5 = (a - a % 0.05)/0.05;
    a = a % 0.05;

    m6 = (a - a % 0.01)/0.01;

    Console.WriteLine("NOTAS:");
    Console.WriteLine($"{n1} nota(s) de R$ 100.00");
    Console.WriteLine($"{n2} nota(s) de R$ 50.00");
    Console.WriteLine($"{n3} nota(s) de R$ 20.00");
    Console.WriteLine($"{n4} nota(s) de R$ 10.00");
    Console.WriteLine($"{n5} nota(s) de R$ 5.00");
    Console.WriteLine($"{n6} nota(s) de R$ 2.00");
    Console.WriteLine("MOEDAS:");
    Console.WriteLine($"{m1} moeda(s) de R$ 1.00");
    Console.WriteLine($"{m2} moeda(s) de R$ 0.50");
    Console.WriteLine($"{m3} moeda(s) de R$ 0.25");
    Console.WriteLine($"{m4} moeda(s) de R$ 0.10");
    Console.WriteLine($"{m5} moeda(s) de R$ 0.05");
    Console.WriteLine($"{m6} moeda(s) de R$ 0.01");
  }
}

Answer: Vamos supor que o preço de um produto é R$ 4,99 e você deseja saber o valor total de 17 itens desse produto.
Abaixo, temos o código usado para fazer o cálculo usando o tipo float para o preço do produto e naturalmente você vai esperar o resultado de R$ 84,83 visto que 4.99×17 = 84.83. Certo?
float preco = 4.99f;

int quantidade = 17;

float total = preco * quantidade;

Console.WriteLine(total);

Console.ReadLine();

Você esperava 84,83, mas o resultado obtido foi 84,82999. Para obter o resultado correto, você deve usar o tipo decimal.
Conclusão
Para qualquer cálculo que envolva dinheiro ou finanças, o tipo Decimal deve ser sempre utilizado. Só este tipo tem a precisão adequada para evitar os erros críticos de arredondamento.
Fonte: Usando o ponto flutuante nos cálculos
Use o sufixo M ou m para o tipo decimal.
decimal valor = 0.01m;

Comment: Obrigado amigo(a) pela sua resposta..mas como posso usar esse sufixo no meu caso? (se você se dispor, agradeceria um exemplo) é porque no meu programa eu to fazendo uma atribuição com cálculo, e esse exemplo ficou um pouco distante, mas vou dá uma olhada melhor como é que usa o decimal, de qualquer forma já deu uma luz!
Comment: `m2 = (a - a % 0.50m) / 0.50m;
            a = a % 0.50m;`
etc.. Mas seu código está muito repetitivo, pode usar uns arrays e ciclos para simplificar / encurtar..
Comment: Sim, é que eu ainda não aprendi..rsrs no c# não
Comment: Gostei muito da sua solução!! foi bem mais prático, obrigado mesmo!!!
Answer: Boa noite, a sintaxe com passagem de argumentos para Console.WriteLine() é Console.WriteLine("{0}{1}{2}", SUA_VAR1, SUA_VAR2, SUA_VAR3) .... pois o metodo contem um parametro que aceita args[] ou seja várias variáveis.
Console.WriteLine($"{m6} moeda(s) de R$ 0.01");

Remova o $, já  o {m6} deve ser sua variável de index 0 {0}. Coloque uma virgula ao final e passe os argumentos a função.
Quando você quer fazer operações matemáticas com duas casas decimais como por exemplo em moedas você deve fazer um arrendondamento pois o MOD ou no caso % usando double tem  valores muito grandes 64 bits que não necessitamos no caso, use o Math.Round() pra arredonda um valor para o inteiro mais próximo ou para o número especificado de casas decimais. Há e você não precisa calcular o m6 pois já é o resto do valor em si.
Exemplo:
    int n1,n2,n3,n4,n5,n6,m1,m2,m3,m4,m5,m6;
    double a = 576.43f;
    a = Math.Round(a, 2);

    n1 = (int)(a - a % 100)/100;
    a = Math.Round(a % 100, 2);
    n2 = (int)(a - a % 50)/50;
    a = Math.Round(a % 50, 2);
    n3 = (int)(a - a % 20)/20;
    a = Math.Round(a % 20, 2);
    n4 = (int)(a - a % 10)/10;
    a = Math.Round(a % 10, 2);
    n5 = (int)(a - a % 5)/5;
    a = Math.Round(a % 5, 2);
    n6 = (int)(a - a % 2)/2;
    a = Math.Round(a % 2, 2);
    m1 = (int)(a - a % 1)/1;
    a = Math.Round(a % 1, 2);
    m2 = Convert.ToInt32((a - a % 0.50)/0.50);
    a = Math.Round(a % 0.50, 2);
    m3 = Convert.ToInt32((a - a % 0.25)/0.25);
    a = Math.Round(a % 0.25, 2);
    m4 = Convert.ToInt32((a - a % 0.10)/0.10);
    a = Math.Round(a % 0.10, 2);
    m5 = Convert.ToInt32((a - a % 0.05)/0.05);
    a = Math.Round(a % 0.05, 2);
    m6 = Convert.ToInt32(a/0.01);

    Console.WriteLine("NOTAS:");
    Console.WriteLine("{0} nota(s) de R$ 100.00", n1);
    Console.WriteLine("{0} nota(s) de R$ 50.00", n2);
    Console.WriteLine("{0} nota(s) de R$ 20.00", n3);
    Console.WriteLine("{0} nota(s) de R$ 10.00", n4);
    Console.WriteLine("{0} nota(s) de R$ 5.00", n5);
    Console.WriteLine("{0} nota(s) de R$ 2.00", n6);
    Console.WriteLine("MOEDAS:");
    Console.WriteLine("{0} moeda(s) de R$ 1.00", m1);
    Console.WriteLine("{0} moeda(s) de R$ 0.50", m2);
    Console.WriteLine("{0} moeda(s) de R$ 0.25", m3);
    Console.WriteLine("{0} moeda(s) de R$ 0.10", m4);
    Console.WriteLine("{0} moeda(s) de R$ 0.05", m5);
    Console.WriteLine("{0} moeda(s) de R$ 0.01", m6);

Comment: Obrigado amigo! porém, não resolveu o meu problema ainda. :/ continua com o mesmo problema;
Comment: Eu acho que seja um problema com o arrendondamento na terceira variável (n3)ele atribui um número cheio de números depois da vírgula, um exemplo é se eu colocar 576.43 na entrada, deveria recebe-lá 6.43, mas quando chega ai acontece algo miraculoso que eu não entendi e atribui 6.4999999992 algo assim, saca? é por isso que dá erro, eu acho;
Comment: Não tinha visto esse detalhe, você deve usar o Math.Round() para arredondamento, de uma olhada na minha resposta novamente.
Comment: Parece que deu certo! não sei se o uri online vai aceitar ainda rsrs eu tinha tentado usar o comando math round, mas não havia conseguido.. muito obrigado!
Comment: Deu certo, fera!(em referência que o site aceitou também) ksks

Notas e moedas C#


Angular 2 application not working in IE, MAC Safari

Question: When I am opening my application in IE, Mac Safari the login page is not open and I am getting error in console :
SCRIPT5009: '_' is undefined
SCRIPT1006: Expected ')'
Comment: Possible duplicate of [Angular 2 / 4 / 5 not working in IE11](https://stackoverflow.com/questions/35140718/angular-2-4-5-not-working-in-ie11)
Answer: search polyfill.ts file in our project and uncomment the polyfills

Are you using lodash/underscore package in your project? If yes then you need to install it
Comment: Please don't forget to install classlist.js `npm install --save classlist.js`, if you uncommented that also. You may need this later in your project as you progress
Comment: can you please share this file
Comment: Currently this line "import 'classlist.js'" is commented in my ts file do I need to open or Uncomment this ?
Comment: @ShailendraTiwari  `'_' is undefined` generally means that you are using lodash or underscore lib
Comment: and you are not importing this
Answer: In polyfill.ts you need to uncomment below code.
<code>/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';
</code>
Comment: Can you post your polyfill.ts file in your question?
Comment: I applied all those options those you all mentioned in comment but not works for me.


Identify runs on array with ruby

Question: If we have an array
array = [1, 1, 0, 0, 2, 3, 0, 0, 0, 3, 3, 3 ]

How can we identify the run (amount of consecutive numbers with same value) of a given number?
By example:
run_pattern_for(array, 0) -> 2
run_pattern_for(array, 3) -> 1
run_pattern_for(array, 1) -> 1
run_pattern_for(array, 2) -> 0

There are no runs for 2 because there are no consecutive apparitions of two.
There are one run for 3 because there are only one apparition with the tree as consecutive numbers.
Comment: I think he means consecutive numbers of the same value.
Comment: how are you getting this pattern out of the array??
Comment: @ArnaldoIgnacioGasparVéjar According to your definition, a single isolated instance of a number does not count as a (trivial) consecutive number?
Comment: Define "the run of a given number".
Comment: Run as @LuisOrtegaAraneda says
Comment: @LuisOrtegaAraneda What makes it in case of `0` the value `2` instead of `3`? Can you tell for sure? Don't try to guess. It is the OP's responsibility to make it clear. On top of that, that is clearly not the case.
Comment: Because you have two times a list of consecutive 0's.
Comment: @LuisOrtegaAraneda ... and ...?
Comment: @LuisOrtegaAraneda By your phrase "consecutive numbers", did you mean "the numbers of (chunks of) consecutive numbers"? If that is the case, then you should study English. What your wrote does not mean what you thought you meant.
Comment: @sawa, i just edited the question. Can you get it now ?
Comment: @sawa I meant exactly what's in the comment.
Comment: A single isolated instance wouldn't count as the example is not counting them.
Comment: @sawa, yes. A single number doesn't count.
Comment: @sawa I'm not the OP in case you didn't notice it... I'm just trying to help. Regards.
Comment: May I suggest an edit to clarify?  "A "run" is a maximum-length sequence of identical elements from `array` that contains at least two elements.  For example, `[0,1,1,1,2,2,3,1,1,2]` contains two runs of  1', one run of `2` and zero runs of `0` and `3`. I would like to construct a hash whose keys are the elements of `array.uniq` and whose values are the numbers of runs for each of those keys."  I see there are two votes to close, no doubt because the question is clear.  It would be a shame for it to close, as it's an interesting question.
Comment: There are now four votes to close your question. If you do not edit to clarify, it likely will be closed.  Why would you refuse to do that?
Answer: try:
class Array
  def count_runs(element)
    chunk {|n| n}.count {|a,b| a == element && b.length > 1}
  end
end

a = [1, 1, 0, 0, 2, 3, 0, 0, 0, 3, 3, 3 ]
a.count_runs 0   #=> 2
a.count_runs 3   #=> 1
a.count_runs 1   #=> 1
a.count_runs 2   #=> 0

Comment: Wow, very great answer, i never knew chunk function until now
Answer: I agree with @BroiSatse that Enumerable#chunk should be used here, but I would like to show how an enumerator could be employed directly to solve this problem, using the methods Enumerator#next and Enumerator#peek.
Code
def count_em(array)
  return [] if array.empty?
  h = Hash.new(0)
  enum = array.each
  loop do
    x = enum.next
    if x == enum.peek
      h[x] += 1
      enum.next until (enum.peek != x)
    else
      h[x] = 0 unless h.key?(x)
    end
  end
  h
end

Example
array = [1, 1, 0, 0, 2, 3, 0, 0, 0, 3, 3, 3 ]
count_em(array) #=> {1=>1, 0=>2, 2=>0, 3=>1}

Explanation
Suppose
array = [1, 1, 1, 0, 2, 2]
h = Hash.new(0)
enum = array.each
  #=> #<Enumerator: [1, 1, 1, 0, 2, 2]:each>

x = enum.next #=> 1
enum.peek     #=> 1

so x == enum.peek #=> true, meaning there is a run of at least two 1's, so wish execute:
h[x] += 1 #=> h[1] += 1

which means
h[1] = h[1] + 1

Since h does not have a key 1, h[x] on the right side of the equality set to zero, the default value we established when creating the hash.  Therefore, the hash h is now { 1=>1 }.  Now we want need to enumerate and discard any more 1's in the run:
enum.next until (enum.peek != x)

enum.next #=> 1
enum.peek #=> 1
enum.next #=> 1
enum.peek #=> 0

Now go back to the top of the loop:
x = enum.next #=> 0
enum.peek     #=> 2

Since (x == enum.peek) => (0 == 2) => false, and h.key?(x) => false, we set
h[0] = 0

and the hash is now  { 1=>1, 0=>0 }.  Returning again to the top of the loop,
x = enum.next #=> 2
enum.peek     #=> 2

Since (x == enum.peek) => (2 == 2) => true, we execute:
h[2] += 1 #=> 1

so now h => {1=>1, 0=>0, 2=>1}.  Now when we execute
x = enum.next #=> 2
enum.peek #=> StopIteration: iteration reached an end

The exception is rescued by Kernel#loop.  That is, raising a StopIteration error is one way to break out of the loop, causing the last line of the method to be executed and returned:
h #=> {1=>1, 0=>0, 2=>1}

(Note this result differs from that in the example above because it is for a different array.)
Answer: Ruby 2.2, which was released roughly seven months after this question was posted, gave us a method that has application here, Enumerable#slice_when:
array.slice_when { |i,j| i != j }.each_with_object(Hash.new(0)) { |a,h|
  h[a.first] += (a.size > 1) ? 1 : 0 }
  #=> {1=>1, 0=>2, 2=>0, 3=>1}

Answer: It's a simple task; Here are two different ways I've done it:
array = [1, 1, 0, 0, 2, 3, 0, 0, 0, 3, 3, 3 ]

hash = Hash[array.group_by { |e| e }.map{ |k, v| [k, v.size] }]
# => {1=>2, 0=>5, 2=>1, 3=>4}

And:
hash = Hash.new{ |h,k| h[k] = 0 }
array.each { |e| hash[e] += 1 }
hash # => {1=>2, 0=>5, 2=>1, 3=>4}

Once you have the hash the rest is easy:
hash[0] # => 5
hash[1] # => 2
hash[2] # => 1
hash[3] # => 4

If it's possible you'll request a count for a number that didn't exist in the array, and want a numeric response instead of nil, use something like:
Integer(hash[4]) # => 0

Integer(...) converts nil to 0 for you.
In the first example above, group_by will do the heavy lifting, and results in:
array.group_by { |e| e } # => {1=>[1, 1], 0=>[0, 0, 0, 0, 0], 2=>[2], 3=>[3, 3, 3, 3]}

The map statement simply converts the array to its size.
Comment: This is not what OP wants to achieve.

Identify runs on array with ruby


Classe mãe assume atributos da filha?

Question: Criei duas classes, Funcionário e Assistente.
Funcionário possui: nome, idade, salario e o metodo exibirDados();
Assistente sobrescreve este método, e possui também o atributo matricula.
Eu fiz a herança e sobrescrevi o método na classe Assistente da seguinte forma:
public class Assistente extends Funcionario{

protected int matricula;

public int getMatricula() {
    return matricula;
}

public Assistente(String nome, int idade, int salario, int matricula) {
    super(nome, idade, salario);
    this.matricula = matricula;

}

public void exibirDados(Funcionario funcionario) {
    System.out.println("Nome = "+ funcionario.getNome()+" Matrícula: "+ funcionario.getMatricula)
}

}
O que eu esperava que acontecesse fosse que ao se criar a herança, mesmo que a classe Funcionario não tivesse esse atributo matricula, o compilador pudesse "compreender" que está nas classes filhas. No entanto, o compilador não reconhece o método de get que eu implementei ali. Como fazer com que a classe mãe "assuma" um atributo que está declarado em uma classe filha?
Vou colocar aqui também o código que fiz para a classe Funcionario:
public class Funcionario {
String nome;
int idade;
int salario;

public String getNome() {
    return nome;
}
public void setNome(String nome) {
    this.nome = nome;
}
public int getIdade() {
    return idade;
}
public void setIdade(int idade) {
    this.idade = idade;
}

public int getSalario() {
    return salario;
}
public void setSalario(int salario) {
    this.salario = salario;
}

public Funcionario(String nome, int idade, int salario ){
    this.nome = nome;
    this.idade = idade;
    this.salario = salario;

}

public void exibirDados(Funcionario funcionario) {
    System.out.println("Nome = "+ funcionario.getNome()+" | Idade = "+ funcionario.getIdade()+" | Salario = "+ funcionario.getSalario());
}

}
Além de Funcionario e Assistente, me foi pedido para criar classes-filhas de Assistente (assistente técnico e administrativo), onde eu devo modificar o valor do salário deles em algumas condições.
Comment: A noção de herança é de especialização, no sentido da classe base para a classe derivada e não o contrário. `Assistente` *extends* `Funcionario` e não o contrário.
Answer: Comece lendo Qual a diferença entre atributo e campo, nas classes?.
Eu não sei o que você quer dizer com "assume", o termo não costuma ser usado no assunto. Mas imagino o que é.
Bem a grosso modo, quando você cria uma herança de uma classe você está falando para o compilador dar um ^C e ^V por você.
Tudo que tem na classe base terá na classe derivada.
O compilador não deixará tudo ser acessado dentro da classe derivada, mas tudo está lá.
Outro ponto é que quando falo que tudo está lá, no objeto é só o estado, ou seja, os valores dos campos (todos eles, até os que não estão escritos no código mas vieram por herança). Dados da classe que são globais para todos os objetos e os métodos em si só existem uma vez, não tem porque copiar, e sempre está para todos objetos daquele tipo, inclusive os de tipos derivados. Se eles podem ser acessados dali ou se eles não podem porque foi dito que tem uma versão mais adequada dele nem um determinado contexto é outra questão, e isso vai depender do polimorfismo.
Essa última parte parece ter entendido.
Um campo com visibilidade privada estará no objeto de uma classe derivada, mas não poderá ser acesso diretamente dentro dessa nova classe. Poderá ser acessado por um método da classe base que esteja disponível na classe derivada.
Classes base não devem ter conhecimento das classes derivadas. O mecanismo de herança foi criado justamente para isto, se não for para fazer assim não precisa de herança, resolva como uma coisa só.
Então não, Funcionario não deve saber nada que está presente em Assistente, e se estiver por erro conceitual, você terá que fazer a classe Funcionario tratar disso manualmente, até por ser um erro o compilador não vai te ajudar, por isso nem tente se não souber muito o que está fazendo e souber que tem uma exceção para lidar aí, não parece ser o caso.
Não vou entrar no mérito que essa herança não costuma ser ideal, porque geralmente um Assistente é só um papel de um Funcionario e não é um Funcionario, ou seja, deveria ser uma composição, até porque quase todo material de OOP ensina isso errado, não posso culpar as pessoas por cometer esse erro. E também porque pode ter casos que essa herança pode ser sim adequada, só não costuma ser em quase tudo que as pessoas fazem, especialmente as menos experientes.
Nem vou falar que algo que exibe em um dispositivo específico não deveria fazer parte de um objeto que tem por objetivo guardar estado do objeto e não manipular o console, ou web, ou GUI, ou lidar com o DB, ou comunicar via rede ou outro serviço, ou fazer várias outras coisas que não tem ligação com o que um Assistente deve fazer.
Muito menos falarei que getters/setters nem sempre devem ser usados, apesar de ensinarem fazer isso por aí.
Provavelmente essa pergunta é um problema XY.
O método exibirDados() não parece fazer sentido. Por que ele recebe um parâmetro Funcionario? Não consigo imaginar. Retire isso e use o this que está disponível no método. Algo assim:
public void exibirDados() {
    System.out.println("Nome = " + this.getNome() + " Matrícula: " + this.getMatricula());
}

Coloquei no GitHub para referência futura.
Corrigi outros erros.
Muito provavelmente este método em Funcionário está errado também (confirmado depois da edição da pergunta) e precisa consertar, até para manter o polimorfismo tendo a mesma assinatura.
Se mantiver o parâmetro em cada método, mas adaptando para o tipo da própria classe em vez de manter o da classe base, como está agora, perderá o polimorfismo porque o método passa ser outro.
Reforço para ler todos os links. Justamente por pular etapas é que as pessoas aprendem errado. E só os links não são suficientes.

Herança em programação orientada a objetos
Herança, polimorfismo e acesso à métodos
Por que um método que usa polimorfismo está sendo chamado no lugar de outro em caso de herança?
Comment: olá, primeiramente, obrigado pela resposta, estudarei sim pelos links. vou complementar aqui a questão.
Comment: coloquei o código na questão, expliquei por que julgo precisar receber o parâmetro Funcionário. Queria também salientar que achei interessante essas visões sobre como o conteúdo de OOP é ensinado, mas destaco aqui que eu preciso resolver essa questão com herança e polimorfismo.
Answer: public void exibirDados(Funcionario funcionario) {
    System.out.println("Nome = "+ funcionario.getNome()+" Matrícula: "+ funcionario.getMatricula)
}

Dentro desse método você recebe um funcionário e ele não tem esse método getMatricula, quem tem é o assistente. Quando você utiliza herança o assistente herda de funcionário, mas não ao contrario, então ele não vai reconhecer que funcionário tem o método getMatricula.
Comment: então esse método deve ser implementado na classe Funcionário mesmo? tinha pensando rapidamente nisso mas achei meio estranho a implementação de um método referente a um atributo de Assistente ser feita em Funcionário, mas vou fazer a mudança e ver se dá bom viu! Obrigado :D!
Comment: Você pode ou adicionar o método dentro da classse funcionário ou só trocar o tipo para assistente, pois ele vai ter acesso aos mesmos gets e sets que já existem la dentro de funcionário e também ao matricula.

Classe mãe assume atributos da filha?


Is there any significance to the derivative of the average?

Question: I have a set of time vs. concentration data that I'm trying to turn into an average derivative value for use in an equation (I'm worried a simple average of the first and last points ignores too much data). The most obvious way to do it would be to simply do $\frac{C - C_0}{t - t_0}$ for each point and take the average, but I'm wondering, is there any significance to the value $\frac{C_{avg}}{t_{avg}}$? Since I have uniform time intervals I think this is equivalent to
$$\frac{1}{N} \sum_{i}{\frac{C_i}{\Delta}}$$
where $\Delta$ is the time interval length and $N$ is the number of samples. If possible, avoiding numerical differentiation would be great since I'm getting some weird values from that approach. Any advice would be greatly appreciated. Thanks!
Comment: Average of derivative or derivative of average?
Comment: @sds ,derivative of average.
Comment: Are you asking a theoretical question about the specific approach you suggested or are you open to other techniques ?
Answer: The derivative of the average value of the function on a range depends on both the range of the function and the function itself.
$$\text{avg of $f(x)$ on $x\in[a,b]$ of }=\frac1{b-a}\int_a^bf(t)dt$$
Let's consider how to calculate an average given the average of the elements before it. First, the discrete version where you only add one element to a set:
$$\overline f(x+1)=\frac{f(x+1)+n\overline f(x)}{n+1}$$
where $\overline f(x)$ is the average of the first $x$ elements and $n$ is the number of elements in the set before adding the new element. We can rewrite this in terms of a continuous interval:
$$\overline f(x+h)=\frac{hf(x+h)+(b-a)\overline f(x)}{b-a+h}$$
Finally, we can find $\frac d{dx}\overline f(x)$.
$$\begin{align}\frac d{dx}\overline f(x)&=\lim_{h\to0}\frac1h(\overline f(x+h)-\overline f(x))\\
&=\lim_{h\to0}\frac1h\left(\frac{hf(x+h)+(b-a)\overline f(x)}{b-a+h}-\overline f(x)\right)\\
&=\lim_{h\to0}\frac1h\left(\frac{hf(x+h)+(b-a)\overline f(x)-(b-a+h)\overline f(x)}{b-a+h}\right)\\
&=\lim_{h\to0}\frac1h\left(\frac{hf(x+h)-h\overline f(x)}{b-a+h}\right)\\
&=\lim_{h\to0}\frac{f(x+h)-\overline f(x)}{b-a+h}\\
&=\frac{f(x)-\overline f(x)}{b-a}
\end{align}
$$
That's the explicit formula for what you're looking for. I do not know the name of this idea yet.


DNS NS Redirect

Question: I've come across something interesting that I've never seen before and was hoping someone could help to explain what I'm seeing.
Here's the scenario: I have a domains testdomain.com zone file hosted with a DNS provider called SummitNetworks. On my side, I have a domain hosted with GoDaddy called mycustomdomain.com. Within mycustomdomain.com I have a glue record for ns2.mycustomdomain.com that points back to the name server at summitnetwork.
Now I told summitnetworks that I want the zone they host for me, testdomain.com to point to the NS server ns2.mycustomdomain.com. The reason for this is so that in the future if I choos to migrate this zone to a new DNS provider and a whole bunch of other domains, I would only have to update the NS glue record on mycustomdomain to the new DNS provider name server IP.
Now the question is, when I do a dig and zone lookup against testdomain.com the NS servers point to summitnetworks NS servers, but the referall path points back to ns2.mycustomdomain.com. How's this possible and how can I see the full path for resolution using dig? What's a referral path? When I do a dig against the domain there's no reference to it. The only way I was able to validate this is because I used dnsstuff toolbox
Answer: Your question is hard to answer without real information, but your reasoning behind using vanity servers makes no sense to me, when changing NameServers you want to actually change your nameservers, and not your glue records, you also want your SOA to be a real nameserver and not a glue record.
Here's what I think is happening: The Registrar NS record for example.com is different than the zone's NS records.
dig example.com
The Root Servers send you to the com servers, the com servers send you to the nameservers listed in your registrar(godaddy), but those servers do not have your vanity nameservers, they have the real name servers, which (although the same IPs) referres you to the real nameservers' A Record.
So again,
ns1.example.com, ns2.example.com is your nameserver with register.com.
but the zone says something like
@ IN NS ns3.example.com
@ IN NS ns4.example.com

Even if ns1.example.com and ns3.example.com are the same IP record, dns doesn't know that, it sees ns3 is not ns1 so it's referred to ns3 for the authoritative answer.
We could confirm this with real info.
If you want to use vanity nameservers, I would suggest keeping your DNS with Godady.
Comment: Can you post real data or create a chat room? I'd be happy to help
Comment: See updated answer, I hope this sheds some light on your issue.
Comment: Thanks for the response Jacob. Unfortunately it's something I walked into where there are a couple of thousand domains that are going to be migrated to another DNS provider. The reasoning for the vanity servers with glue records was to make this situation of migration easier of all the domains, where the only DNS change would be the vanity server glue records to point to the new DNS provider. It doesn't make sense to me either :(. Hopefully I can dig up some info on referral paths
Answer: Thank you Jacob for being willing to take the time and help me out with this; if I could I would give you +100 pts for that :).
I was able to track down my answer with some tools and DNS logic. So the first issue that I had was whenever I ran a dig www.example.com +trace on my mac, absolutely nothing would come up. At first I thought it was a domain issue but I tried other domains and received the same blank results. So then I said let me try another computer and voila, I was able to go through the full trace for DNS resolution which reveals the answer.
So essentially what happened is this... When testdomain.com was registered with the DNS Registrar, the people who registered the domain pointed the name servers to go to ns1 & ns2.mycustomdomain.com as they were instructed to. This process took place for a couple of hundred domains. The folks that own mycustomdomain.com created vanity servers with glue records pointing back to the DNS Hosting Provider.
What the dig trace revealed was this

First step - query DNS root servers to find which Top Level Domain to
talk to
Second step - query Top Level Domain DNS server to find out
who's authoritative for testdomain.com
1st Result - Found nameservers that can respond to queries ns1 & ns2.mycustomdomain.com
2nd Result - Because those glue records actually point to the NS servers @ summitnetworks.com we get an additional response with the name servers ns1 & ns2.summitnetworks.com - sidenote if we didn't have those glue records the dig would've ended at bullet 3.

Now the migration of these domains and all future domains is going to AWS Route 53. The zone files that I will receive from summitnetworks.com will of course include their SOA and NS servers. When you import your domain into Route53, they will strip out the SOA and Nameservers since they now own this piece. Since I'm doing a large migration into AWS I'm going to create a Delegation Set so that I have the same name servers for every domain that I create in AWS. This will make it so that all we have to do is update the glue records for our vanity servers to point to AWS servers and add 2 more glue records for more added reliability.
Hopefully this helps anyone else who bumps into this.
Sample dig www.google.com +trace so you can follow the path of resolution:
;; global options: +cmd
.           518400  IN  NS  D.ROOT-SERVERS.NET.
.           518400  IN  NS  E.ROOT-SERVERS.NET.
.           518400  IN  NS  F.ROOT-SERVERS.NET.
.           518400  IN  NS  G.ROOT-SERVERS.NET.
.           518400  IN  NS  H.ROOT-SERVERS.NET.
.           518400  IN  NS  I.ROOT-SERVERS.NET.
.           518400  IN  NS  J.ROOT-SERVERS.NET.
.           518400  IN  NS  K.ROOT-SERVERS.NET.
.           518400  IN  NS  L.ROOT-SERVERS.NET.
.           518400  IN  NS  M.ROOT-SERVERS.NET.
.           518400  IN  NS  A.ROOT-SERVERS.NET.
.           518400  IN  NS  B.ROOT-SERVERS.NET.
.           518400  IN  NS  C.ROOT-SERVERS.NET.
;; Received 496 bytes from 172.16.0.2#53(172.16.0.2) in 8 ms

com.            172800  IN  NS  m.gtld-servers.net.
com.            172800  IN  NS  l.gtld-servers.net.
com.            172800  IN  NS  k.gtld-servers.net.
com.            172800  IN  NS  j.gtld-servers.net.
com.            172800  IN  NS  i.gtld-servers.net.
com.            172800  IN  NS  h.gtld-servers.net.
com.            172800  IN  NS  g.gtld-servers.net.
com.            172800  IN  NS  f.gtld-servers.net.
com.            172800  IN  NS  e.gtld-servers.net.
com.            172800  IN  NS  d.gtld-servers.net.
com.            172800  IN  NS  c.gtld-servers.net.
com.            172800  IN  NS  b.gtld-servers.net.
com.            172800  IN  NS  a.gtld-servers.net.
;; Received 492 bytes from 184.108.40.206#53(188.8.131.52) in 100 ms

google.com.     172800  IN  NS  ns2.google.com.
google.com.     172800  IN  NS  ns1.google.com.
google.com.     172800  IN  NS  ns3.google.com.
google.com.     172800  IN  NS  ns4.google.com.
;; Received 168 bytes from 18.104.22.168#53(188.8.131.52) in 99 ms

www.google.com.     300 IN  A   126.96.36.199
;; Received 48 bytes from 18.104.22.168#53(188.8.131.52) in 13 ms

Here are some good DNS resources for any of you that need a refresh. Certainly got my DNS refresh for the year :)

Understanding DNS
Authority vs Authoritative

DNS NS Redirect


how to set all links in iframe to "google.com" by javascript or jQuery?

Question: how to set all links in iframe to "google.com" by javascript or jQuery ?
Comment: Is the iframe from the same domain as the parent page?
Comment: If it is not the same domain you can not do it. It is a security measure that all the major browsers implement. Else you could do things like show people their homebanking page in an iFrame and then redirect the login information.
Answer: Run this in iframe
$("a").attr("href", "http://www.google.com/" + $("a").attr("href"))

Example: jsfiddle

EDIT
If you need to replace the domain links with google.com, use this
$("a").each(function(){
    var pathname = $(this)[0].pathname;
    $(this).attr("href", "http://www.google.com" + pathname);
});

Example: jsfiddle
Answer: You can use the iframe's contentWindow attribute to get a hold on the global object running in the iframe.  From there you can do what you want.
$(iframe.contentWindow).find("a").each(function(){
  //replace url
})

But if url of the iframe is on another domain, this will trigger a XSS (cross server scripting) error and you won't be able to access the window dom.  This is a security feature, so it cannot be circumvented.  In other words, you cannot to that.


HTTPS no wordpress

Question: Comprei um certificado e passei minha url de http para https no wordpress. Usei as seguintes maneiras:

Vá até "Configurações" de seu WordPress, em "Geral" altere o "Endereço
  do WordPress (URL)" e "Endereço do site (URL)" para
  "https://www.seudominio.com", caso não use o WWW coloque apenas
  "https://seudominio.com", após salvar você poderá perder o acesso
  temporariamente ao seu WordPress, não faça nada, apenas continue.

Depois no wp-config.php:
define('FORCE_SSL_CONTENT', true);
define('FORCE_SSL_ADMIN', true);

E por fim no arquivo htaccess:
# BEGIN SSL
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</IfModule>
# END SSL

Muitas páginas são redirecionadas, de http para https, mas uma das que não redireciona, é a página de erro 404 e ás vezes ocorrem erros do usuário estar logado, e quando atualizo a página ele não esta mais, daí atualiza de novo ele volta a estar logado.
Alguém conhece algum jeito de redirecionar todos, sem ter problemas como os que estão acontecendo em meu site?
Comment: Use o plugin Really Simple SSL: https://br.wordpress.org/plugins/really-simple-ssl/ Já testei vários e este foi o que teve melhor resultado e foi o mais fácil de utilizar.
Comment: Atualmente não está dando mais erros, mas valeu pela dica... ATT
Answer: Você pode tentar adicionar no .htaccess:

RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^/(.*) https://www.seudominio.com/$1 [NC,R,L]

HTTPS no wordpress


Is by design, Drupal headless?

Question: If I understood correctly, "decoupling" a content management system means separating backend from frontend (having two "modules" for each under the same "program").
If I understood correctly, "headlessing" a content management system is making it to be possible to supply content to at least two different front-end interfaces at once ("two different programs" as may appear to an end user).
I would assume that by design, Drupal is not decoupled because it does have built in JavaScript (quick edit for a node, for example) but by design is it headless?
Comment: "_Drupal is not decoupled because it does have built in JavaScript almost anywhere_"
Comment: @leymannx isn't at least one case of using JavaScript in Drupal GUI would mean lack of decoupling backend from frontend.
Answer: Headed means there is a GUI (Graphic User Interface). Headless means a system without that.
Drupal can be run headless - there are headless distributions out there that can be used as the back-end for apps or a React site or whatnot. However, by default it's headed - Drupal core has a GUI out of the box.
Decoupling refers to separating the head (GUI) and the back-end. Drupal is decoupled in that it separates the front end from the back-end.

Drupal is by design not decoupled because it does have built in
JavaScript almost anywhere

Drupal is decoupled, and it does have an extensive, powerful JavaScript API that ships with core: https://www.drupal.org/docs/drupal-apis/javascript-api/javascript-api-overview
Answer: Drupal can be used decoupled, and as new features are added to Drupal 9, support for decoupling is given high priority under the API-First Initiative (ensure APIs are provided that allow programmers to select the parts of Drupal they want to use, and replace other parts as needed with custom solutions).
Historically, Drupal 7 + older versions are NOT decoupled (although older versions can e used headlessly with contributed modules), but starting from Drupal 8, decoupled use is supported by Drupal core itself.
Yes, Drupal does provide a frontend-- but this frontend is provided through modules that can be disabled.  So Drupal can be used decoupled because it does not force you to use its UI; you can disable the Drupal UI and replace it with something else, like a React or Angular app.
What does headless use actually look like?
Contenta is a headless Drupal distribution that can give you an idea of how to set up Drupal for headless use.
To actually get at your content, Drupal provides support for JSON:API and REST in Core, and GraphQL is available via a contributed module.  The JSON:API support is particularly great because it lets you expose all your content with Drupal permissions intact with very little additional configuration.
However, this is a pretty complex topic; there's a whole book on it:

Decoupled Drupal in Practice

There's also a great series of tutorials available at Drupalize.me.

Is by design, Drupal headless?


Why is there a little gap between my navbar and both sides of my page?

Question: little gap
this is my html and css:

body {
  background-color: green;
}

.navbar {
  overflow: hidden;
  background-color: #333;
  text-align: center;
  width: 100%;
}

.navbar a {
  float: left;
  font-size: 18px;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.dropdown {
  float: left;
  overflow: hidden;
}

.dropdown .dropbtn {
  font-size: 18px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

.navefix:hover, .dropdown:hover, .dropbtn {
  background-color: red;
  cursor: pointer;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #ddd;
}

.dropdown:hover .dropdown-content {
  display: block;
}

        <button class="dropbtn" onclick="location.href='index.html'">Index
        </button>

          page1
          page2
          page3

      page4

See you can see it in the code snipped, the navbar should stretch outside the window so there is no green space between the navbar and the page sides.
Comment: body { margin: 0 }
Comment: thank you so much.. it was so easy and I couldn't find it... it actually worked I feel so stupid right now
Comment: Spend some time learning to use your browser's developer tools (usually accessed with F12). This will allow you to physically find styling issues easily.
Comment: Since by default now there is a margin in the body tag is defined So to overcoome that you need to define margin:0
Answer: Just add a margin: 0px CSS property to your body. There is a default 8px padding on the body which is causing the issue.

body {
  background-color: green;
  margin: 0px;
}

.navbar {
  overflow: hidden;
  background-color: #333;
  text-align: center;
  width: 100%;
}

.navbar a {
  float: left;
  font-size: 18px;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.dropdown {
  float: left;
  overflow: hidden;
}

.dropdown .dropbtn {
  font-size: 18px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

.navefix:hover, .dropdown:hover, .dropbtn {
  background-color: red;
  cursor: pointer;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #ddd;
}

.dropdown:hover .dropdown-content {
  display: block;
}

        <button class="dropbtn" onclick="location.href='index.html'">Index
        </button>

          page1
          page2
          page3

      page4

Answer: Always try using this in starting of ur project will help u save a lot of headache and time. Here * means all elements (a universal selector) so we are setting all elements to have zero(0) margins and 0 paddings.
*{
    margin: 0px;
    padding: 0px;
    box-sizing: border-box;
}

* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}
body {
  background-color: green;
}

.navbar {
  overflow: hidden;
  background-color: #333;
  text-align: center;
  width: 100%;
}

.navbar a {
  float: left;
  font-size: 18px;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.dropdown {
  float: left;
  overflow: hidden;
}

.dropdown .dropbtn {
  font-size: 18px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

.navefix:hover, .dropdown:hover, .dropbtn {
  background-color: red;
  cursor: pointer;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #ddd;
}

.dropdown:hover .dropdown-content {
  display: block;
}

        <button class="dropbtn" onclick="location.href='index.html'">Index
        </button>

          page1
          page2
          page3

      page4


What's it called when the band repeats the lyrics from the lead singer?

Question: For example, in Level by The Raconteurs:

.
Answer: Call and response is the technique of trading off lyrical or musical lines in a piece. This can take several forms:

imitation
question and answer
statement and commentary
affirmation
surprise

Simply repeating the call in the response is imitation.
Comment: The middle link is worth following by the way, lots of good commentary and examples of call & response.
Comment: Awesome, that's what I was looking for.


When should the "translatable" tag be added to a query?

Question: I noticed that a Drupal core function is using the following code.
$categories = db_select('contact', 'c')
  ->addTag('translatable')
  ->fields('c', array('cid', 'category', 'recipients', 'selected'))
  ->orderBy('weight')
  ->orderBy('category')
  ->execute()
  ->fetchAll();

When should a module add that tag to the query it is executing?
I take that adding that query tag has some effect.
Answer: On its own, that tag doesn't much (yet). This is the so called Dynamic data translation feature, an idea that was born from Prepare Drupal core for dynamic data translation.
Basically, you define in your hook_schema() (See contact_schema() for an example) which fields can be translated, and then add the "translatable" tag to all queries which fetch the data. Use 'translated' => TRUE' for all those columns.
Then, what is supposed to happen is that a contributed module can maintain separate tables per language for your translatable columns, automatically join these tables, and replace the selected columns with those from translated table.
However, as far as I know, nobody has yet attempted to write such a module.


Using Firestore's snapshot.forEach to create a table

Question: I'm trying to output an array filled with Firestore objects onto a table, but just displays the last object above the table

            List of Available Shows

Is it the way I'm going about the td code lines?
Comment: I think you missed `+`  in `showList.innerHTML += '' + array[i] + '';`
Answer: assuming this markup:

then it works about like this:
firebase.firestore().collection('TV Shows').get().then(snapshot => {
    var showList = document.getElementById('showList');
    var html = '

';

    html += 'List of Available Shows	';
    /* add further columns into here, alike the one above. */

    html += '

';
    snapshot.forEach(doc => {
        html += '
';

        html += '' + doc.data().show.name + '	';
        /* add further columns into here, alike the one above. */

        html += '
';
    });
    html += '

';
    showList.append(html);
});

Comment: This actually just has all that raw code display instead
Comment: @SalimElouafi Use `showList.insertAdjacentHTML("beforeend", html);` instead of `showList.append(html);`
Answer: You're resetting the entire showList element with every iteration of the loop:
showList.innerHTML = '' + array[i] + '	';

I suspect you mean to append to it each time instead or resetting it entirely each time.  Maybe try building a string with each iteration, then set the whole thing after the loop is over.
Comment: @MartinZeitler If showList was actually undefined at runtime, don't you think it would generate an error rather than show the last element?
Comment: within the scope of the provided script, it is `undefined`... except globally defined.


Como enviar notificações push/php com janela do site fechada?

Question: De uns tempos para cá (acho que 2014 em diante), o facebook tem feito notificações via browser usando a API Notifications do HTML5. O curioso, é que facebook consegue mandar notificações, mesmo a sua página estando fechada.
Pesquisando na internet, não encontrei uma maneira sequer de fazer isso em conjunto com o PHP. Por isso estou apelando para o stackoverflow .
Sei que existem soluções como o PushLead, e o PushCrew. Mas de nada servem se quero usar meu próprio sistema. Usar somente exemplo do frontend, o script em si é inútil, sem uma linguagem que atue no servidor para enviar novidades aos usuários do site. Sobre tópicos semelhante já criado, nada servem para minha dúvida específica: Como enviar notificações push/php com janela do site fechada?
Comment: Como pretende receber notificações se o browser está fechado? Nesse caso as notificações seriam visualizadas onde?
Answer: Para implementar este recurso utilize a Push API do Html5. Fique atento com a compatibilidade com os browsers.
Outro cuidado que deve ter é que o PHP não é uma linguagem boa para implementar daemons, isto é, implementar websockets é um tiro no pé. O PHP foi feito para que os processos iniciem e tenham um fim, manter um processo sempre ativo vai aumentar muito o uso de memória e processamento de seu servidor. Como o PHP não possui maneiras de gerenciar memória terá que contar apenas com o garbage collector, o que é uma péssima ideia. (Caso tenha alguma dúvida sobre isso, aqui uma explicação https://software-gunslinger.tumblr.com/post/47131406821/php-is-meant-to-die)
Apesar da Push API não utilizar websockets, tenha isso em mente, é melhor usar outra linguagem se deseja um sistema de notificações em tempo real. E tambem pense na situação que por trabalhar com workers, você receberá chamadas em tempos curtos de todos os usuários que habilitar este recurso, o que pode pesar em seu servidor devido ao alto número de processos que serão abertos conforme o número de usuários do seu site/sistema aumenta.
Por exemplo:
Se seu sistema possui 100 usuários e as notificações são conferidas de 5 em 5 segundos, o mínimo de requisição que terá é 100/s e 6000/m some isso a média de número de visitas em seu site por minuto e terá o total de processos executados. Chegará a conclusão que não é uma boa deixar esse tipo de recurso na mão do PHP, pois o processamento utilizado é muito alto.
Por isso irá encontrar poucos exemplos em PHP sobre recursos como notificações.
Algumas implementações PHP

https://github.com/web-push-libs/web-push-php
https://pusher.com/
https://github.com/pusher-community/html5-realtime-push-notifications
http://www.howopensource.com/2014/12/introduction-to-server-sent-events/
https://github.com/licson0729/libSSE-php
https://gauntface.github.io/simple-push-demo/

Referências:

https://w3c.github.io/push-api/
https://www.binpress.com/tutorial/building-useful-notifications-with-html5-apis/163
https://developers.google.com/web/fundamentals/engage-and-retain/push-notifications/
https://developer.mozilla.org/en-US/docs/Web/API/Push_API
https://stackoverflow.com/questions/27221203/send-desktop-notifications-in-chrome-or-firefox-from-a-closed-web-app
Comment: Meu objetivo era criar um novo sistema de notificação para vloggers. Então acho que um sistema que envia uma notificação por dia seria o suficiente. Recentemente descobri que poderia fazer isso em AJAX (ainda sim consumindo recursos do servidor).
Sua ajuda contribui muito amigo. Ainda aceito sugestões.
Comment: Esse post me deixou com uma dúvida, será que dá pra juntar PHP + Cron do Linux pra empurrar as mensagens ao invés de deixar isso só com o PHP?


SPLUNK HOSTING ON DIFFERENT

Question: How do we check the availability of each host on Splunk
Answer: You should configure and user the Splunk distributed monitoring console, which will monitor the performance and availability of all Splunk instances and forwarders. I would also suggest you configure some alerts to be notified if anything goes wrong.
https://docs.splunk.com/Documentation/Splunk/8.0.5/DMC/DMCoverview

SPLUNK HOSTING ON DIFFERENT


My android app starts service before display the layout

Question: I'm writing android app, here is the code
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    startService(new Intent(getBaseContext(), ttt.class));
}

ttt is class extends Service that keeps displaying a Dialog every 15 mins
when it starts, it first wait 15 mins and show the dialog, then it will display the layout.
the setContentView(R.layout.activity_main); is before startService(new Intent(getBaseContext(), ttt.class));
why it don't display the layout first, but start the service first?
How can I display the layout first, then after 15 mins and display the dialog?
Comment: You should not use Service to deal with UI elements (a Dialog).
Answer: Firstly please rename your service ttt to some proper name. You can start a AlarmManager inside your onCreate.
Intent intent = new Intent(getBaseContext(), ttt.class);
PendingIntent pintent = PendingIntent.getService(getBaseContext(), 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 15*60*1000, pintent);

Answer: You can use a handler for this.
try something like :
new Handler().postDelayed(new Runnable() {
                  @Override
                  public void run() {

                      Intent i=new Intent(MainActivity.this,ttt.class);
                      startActivity(i);
                  }
              }, 900000);

Hope it helps


Lasso regression solutions

Question: In the ridge regression $\hat{\beta}^{ridge}=argmin\left \{ \frac{1}{2}\sum_{i=1}^{N}(y_i-\beta_0-\sum_{j=1}^{p}x_{ij}\beta_j)^2 +\lambda \sum_{j=1}^{p}\beta_j^2 \right \}$ the ridge regression solutions can be computed form $\hat{\beta}^{ridge}=(X^tX+\lambda I)^{-1}X^ty$
But for the lasso regression case: $\hat{\beta}^{lasso}=argmin\left \{ \frac{1}{2}\sum_{i=1}^{N}(y_i-\beta_0-\sum_{j=1}^{p}x_{ij}\beta_j)^2 +\lambda \sum_{j=1}^{p}|\beta_j| \right \}$
With which matrix form formula can I compute the lasso regression solutions? I looked in the Elements of Statistical Learning book and that wasn't anywhere, only the beta solutions for ridge.
Comment: There are no closed form solutions for LASSO, which is why you didn't find them in the book!  LASSO is solved using iterative approximations (coordinate descent) or an exact calculation called LARS which does not lend itself to a simple closed for expression.
Comment: No, there isn't.
Answer:
With which matrix form formula can I compute the lasso regression solutions?

As @Matthew Drury points out there is no closed form solution to the multivariate lasso problem. To understand why this is the case you must first familiarise yourself with the closed form solution to the univariate lasso problem which is derived here:

Univariate Lasso problem
Computing the subdifferential of the Lasso cost function and equating to zero to find the minimum:
\begin{aligned}
 \partial_{\theta_j} RSS^{lasso}(\theta)  &=  \partial_{\theta_j} RSS^{OLS}(\theta) + \partial_{\theta_j} \lambda || \theta ||_1
 \\
 0 & = -\rho_j + \theta_j z_j + \partial_{\theta_j} \lambda || \theta_j ||
 \\
 0 & =     \begin{cases}
       -\rho_j + \theta_j z_j  - \lambda & \text{if}\ \theta_j < 0 \\
        [-\rho_j  - \lambda ,-\rho_j + \lambda ] & \text{if}\ \theta_j = 0 \\
       -\rho_j + \theta_j z_j +  \lambda  & \text{if}\ \theta_j > 0
    \end{cases}
\end{aligned}
For the second case we must ensure that the closed interval contains the zero so that $\theta_j = 0$ is a global minimum
\begin{aligned}
     0  \in [-\rho_j  - \lambda ,-\rho_j + \lambda ]
\end{aligned}
Solving for $\theta_j$ gives:
\begin{aligned}
     \begin{cases}
       \theta_j = \frac{\rho_j + \lambda}{z_j}  & \text{for} \ \rho_j < - \lambda \\
       \theta_j = 0 & \text{for} \ - \lambda \leq \rho_j \leq \lambda \\
       \theta_j = \frac{\rho_j - \lambda}{z_j}  & \text{for} \ \rho_j > \lambda
    \end{cases}
\end{aligned}
We recognize this as the soft thresholding function with a normalizing constant.
Multivariate Lasso problem
$$ min_{\theta} \ \frac{1}{2} \ || \mathbf{y - X \theta}||_2^2 + \lambda || \theta||_1$$
Taking the subdifferential and ensuring that the zero is contained in the closed interval (i.e. stationary conditions for global minimum) gives:
$$ 0 \in \mathbf{X^T(y - X \theta) + \partial (\lambda || \theta||_1)}$$
Re-arranging we get
$$ \mathbf{X^T(y - X\theta)} \in \lambda || \theta ||_1$$
Where $\theta$ appears on both sides of the equation. You can only solve this explicitely if $X^TX = I$ which means that $X$ is orthonormal, since you could then use the soft-thresolding function to write explicit solutions for each component in $\theta$
Comment: There is no closed form solution in that case
Comment: I think that in general X is not orthonormal. What is the LASSO solution in this case?
Comment: So, can i ask where I can find a possible solving algorithm, in that case?
Comment: I suppose you could find research papers on optimization that describe various attempts to solve the lasso problem: https://en.wikipedia.org/wiki/Proximal_gradient_methods_for_learning#Lasso_regularization
Comment: But the simple answer is that you use coordinate descent which ensures X is orthogonal
Comment: I thought X was fixed.

Lasso regression solutions


Possible metric space

Question: $d_m$ is defined on $\Bbb R^2$  as such:
$d_m(x,y) = max \lbrace|x_1 - y_1| , |x_2 -y_2| \rbrace $ where $x=(x_1,x_2) , y = (y_1 ,y_2)$
Which I have the task of proving whether or not the above s a matric.
I am having some difficultly  with one of the properties of a metric, namely
$d(x,y) \leq d(x,z) + d(z,y)$  the famous triangle inequality.
I have a idea on how this could be proved
I thought of using the elementary properties of the modulus function i.e.:
for $i =1 , 2 $
$|x_i -  y_i| = |x_i -z_i +z_i -y_i|\\
              \leq |x_i -z_i|+|z_i -y_i|$
However , I am unsure how to show that this implies that
$d_m(x,y) \leq d_m(x,z) +d_m(z,y)$
I apologise for my horrible formatting
Comment: @DonAntonio Sorry about that. I fixed it
Comment: This suggests the following interesting generalization, which you may want to investigate (I don't know whether it's true or not): If $(X,d)$ is a metric space, then $D((x_1,y_1),(x_2,y_2))=\max\{d(x_1,x_2),d(y_1,y_2)\}$ is a metric on $X^2$.
Answer: You are on the right track. Note that (using the inequality you already derived in my first inequality)
$$
d(x,y) = \max\{|x_1-y_1|,|x_2-y_2|\} \le \max\{|x_1 - z_1| + |z_1-y_1|,|x_2-z_2| + |z_2-y_2|\} \le \max\{|x_1 - z_1|,|x_2-z_2|\} + \max\{|z_1-y_1|,|z_2-y_2|\} = d(x,z) + d(z,y).
$$
Comment: Yes! I corrected it.
Comment: How is $\max\{|x_1 - z_1| + |z_1-y_1|,|x_2-z_2| + |z_2-y_2|\} \le \max\{|x_1 - z_1|,|x_2-z_2|\} + \max\{z_1-y_1|,|z_2-y_2|\}$ ?
Comment: On the left side you choose the maximum between $|x_1 - z_1| + |z_1-y_1|$ and $|x_2-z_2| + |z_2-y_2|$. On the right side you compare the first terms in both expressions and take the highest of those. Similarly you take the highest of the second terms. If you add the two chosen higher terms, then this is bigger than both $|x_1 - z_1| + |z_1-y_1|$ and $|x_2-z_2| + |z_2-y_2|$.
Comment: I am not sure if that is clear?
Comment: Ahh!I see it now

Possible metric space


Triangle Tonnetz vs. Hexagon Tonnetz

Question: I have just started to learn about Tonnetz and I've run across two very representations of the same information in different types of Tonnetz.
In the first one shown below the triangles represent a chord while the points represent a note:

In the second one shown below the hexagons represent a note while the points represent a chord:

It seems like they both state the same exact information, but in different ways. Is there a reason to use/prefer one over the other or is there a situation where one is more appropriate then the other?
Answer: These two diagrams form what mathematicians might call a dual graph, in that they are sort of mirror images of each other. I'll describe this briefly for the benefit of others.
In the first image, the nodes represent pitches (well, pitch classes), while in the second image, the nodes represent chords. To construct the second image from the first, place a point in the center of each triangle, label it with the name of the chord formed by the surrounding three pitches, and connect it to the centers of the three neighboring triangles. To construct the first image from the second, simply repeat this process: place a point in the center of each hexagon, label it with the name of the pitch that is common to the six surrounding chords, and connect it to the centers of the six neighboring hexagons. For example, the hexagon (c-C-a-F-f-A♭) represents the pitch C, and if you go one hexagon above it (g-G-e-C-c-E♭) this represents the pitch G. The line connecting these two hexagons is the same as the edge C-G in the first image.
Thus all of the intervalic relationships in the first diagram exist in the second diagram, but in a slightly less easy-to-see form (lines between centers of shapes rather than edges). Similarly, in the second diagram, the edges represent transitions between two chords that share two notes in common. But this same information can be seen in the first diagram by crossing an edge from one triangle to an adjacent one.
You might think that, since the second diagram focuses more on chords (by making them be the nodes), it would be better-suited for analyzing chord progressions. However, here we see the downside of the second diagram: not all chords are represented in the diagram, only major and minor triads. There are no diminished or augmented chords, much less suspensions, or sevenths, or other combinations. Furthermore, if you look at any pair of adjacent nodes as being a chord progression, they are always chords that differ by a single note.
On the other hand the first diagram is capable of displaying any possible combination of tones, regardless of whether it is a major or minor triad. However, chord progressions do become rather abstract, as one shape morphs into another.

To summarize:
Triangles

Nodes: All pitch classes
Edges: Intervals, but only consonant ones (m3/M6, M3/m6, P4/P5)
Shapes: Chords (any possible combination of nodes)

Hexagons

Nodes: Chords, but only major/minor triads.
Edges: Chord progressions, but only if they share two common tones.
Shapes: Pitch classes (common tone of surrounding chords).

Given the clear limitations of the hexagon based diagram (which are easily overcome in the triangle diagram) I'm not sure why someone would choose it over the triangle diagram, given the choice (historically, I think it was developed first, though). Honestly, I'm having a hard time thinking of any cases where you can clearly and easily do something on the hex grid that you absolutely can't do on the triangle.
This agrees with the fact that it's more natural to think of a chord as a combination of multiple pitches, rather than to think of a pitch as the overlapping of multiple chords.
Answer: To expand on Caleb's and N1hk's excellent answers, I would just like to add my picture of the two tonnetze superimposed and rotated to show their relationship.

Interestingly, the hexagonal tonnetz as drawn in the question, has an enharmonic change of spelling which in my opinion further limits its usefulness since it obfuscates harmonic motion and chord progression analysis.
If a chord tonnetz is required I much prefer the 'chord lattice' of W.A. Mathieu

It shares some similarities with the hexagonal tonnetz while retaining the horizontal fifths/vertical thirds orientation of the triangular one, which in my opinion makes it easier to read.
I would also like to mention the 'five-limit lattice' which is more or less identical to the 'triangular' tonnetz but with a different orientation: drawn on a system of staves it has a slight slant to it but more importantly it is upside down.

My experience with lattices/tonnetze is mostly limited to simple harmonic analysis and singing practise over a drone. For these applications I've only ever used the five-limit lattice/triangular tonnetz.
(Image source: Harmonic Experience: Tonal Harmony from Its Natural Origins to Its Modern Expression, W.A. Mathieu)
Answer: I've never seen before the sort of Tonnetz you've provided with your second example! The first Tonnetz, however, is the kind I've encountered most often.
My immediate impression is that the first is much more navigable. The intervallic relationships are easily apparent: bottom-left to top-right are minor thirds, top-left to bottom-right are major thirds, and horizontally are the perfect intervals.
The second example obfuscates this intriguing logic with its edges: the intervals are either alternating between major and minor thirds or unisons. The consequence of these unisons is that there is a lot of redundancy, something the first example has much less of. Its enharmonicism also eliminates the potential for an infinite web of pitches with successively more accidentals, which the first example would do were it more expansive. With respect to the first example, you're right: there doesn't seem to be any reason to prefer the second one.
Slight digression: Hexagons are semantically relevant to study of transformational theory, which Tonnetze are a large part of. But the hexagons of the second example have little to do with the hexagonal "hexatonic systems" proposed by Richard Cohn in his landmark article "Maximally Smooth Cycles, Hexatonic Systems, and the Analysis of Late-Romantic Triadic Progressions" (1996).

Triangle Tonnetz vs. Hexagon Tonnetz


Criar e manter um loadbar enquanto uma função é chamada

Question: Preciso criar um loadbar e deixa-lo ativo até a função terminar. Consigo fazer isso no angular?
$scope.getPosts = function () {
    $http({
        method: 'POST',
        url: '/getPosts',
    }).then(function(response) {
        return response.data;
    }, function(error) {
        console.log(error);
    });
};

Comment: Como assim um loader?
Comment: @FelipeDuarte, um Loadbar.
Comment: Já respondi algo parecido, em vez de intercalar em cada rota, basta intercalar na chamada https://pt.stackoverflow.com/questions/225936/qual-a-melhor-forma-de-implementar-um-loading-bar
Answer: Sim, é possível.
Basicamente você vai controlar o "loader" usando a diretiva ng-if.
Veja um exemplo:

angular.module('app', []).controller('mainController', mainController);

function mainController($http) {
  let ctrl = this;
  ctrl.loading = false;

  ctrl.iniciar = () => ctrl.loading = true;
  ctrl.parar = () => ctrl.loading = false;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

    Carregando

  <button ng-click="main.iniciar()">Iniciar</button>
  <button ng-click="main.parar()">Parar</button>

Comment: Poderia mostrar um exemplo em que apenas com o clique de botão o loader aparece?
Comment: @AntonioBrazFinizola Pronto


How can i apply upto three level of OrderbyChild in firebase Android

Question: I need three level orderbychild in firebase Android
I already apply two level of orderbychild
mFirebaseDatabase.getReference("childs").orderByChild("busNo").equalTo(no);

DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("childs");
mDatabase.orderByChild("childPosition").addValueEventListener(new ValueEventListener() {  }

No such Error but finding the way to do it.
Comment: Firebase Database queries can only order/filter on a single property. In many cases it is possible to combine the values you want to filter on into a single (synthetic) property. So in your case that could be a property `"busNo_childPosition": "value1_value2"` that you then order/filter on. For a longer example of this and other approaches, see my answer here: http://stackoverflow.com/questions/26700924/query-based-on-multiple-where-clauses-in-firebase
Answer: Firebase doesn't support ordering by multiple queries.

Queries can only order by one key at a time. Calling orderByChild()
  multiple times on the same query throws an error.

Try ordering by a simple query an then filter the data, sample:
Query searchAllQuery = usersRef
            .orderByChild("fullname")
            .startAt(searchBoxInput.toUpperCase())
            .endAt(searchBoxInput.toLowerCase() + "\uf8ff" )

searchAllQuery.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
        // filter your data here by username and country
        User user = dataSnapshot.getValue(User.class);
        if (user.getUsername().contains('wei')  || user.getCoutnry().contains('usa')) {
            // add the user to your list maybe?
        }
        }
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});