Testing for Stochastic Dominance - Mann Whitney with Unequal Variance

Question: I've been looking for methods like Mann Whitney, but without homogeneity of variance. So far, I found that I suppose to test for stochastic dominance instead - i.e. modifying the null hypothesis. Could anybody refer books or any literature for me to study further? Thanks.
Comment: `like Mann Whitney, but without homogeneity of variance`. M-W tests for the stochastic dominance. It does not require homogeneity of variance.
Comment: @AndyW Looking around, since "P(X>Y)=P(Y>X)" is often called "stochastic equality", it looks like some people have occasionally taken to calling "P(X>Y)>P(Y>X)" stochastic dominance. It appears not to be very widespread though. Mann and Whitney's original 1947 paper uses the term "stochastically larger", which would seem to be a better term.
Comment: There have been many, many good discussions of `Mann-Whitney` and its direct extension `Kruskal-Wallis` tests on this site. May I recommend you to search and browse though them first?
Comment: Moreover, M-W knows nothing about specifically variances. It is rank-based nonparametric test.
Comment: However, the Mann-Whitney can be considered a test for the more strict case of stochastic dominance (as given at the link AndyW gave) -- one could accompany the minimal assumptions of the test with say the assumption of equality under the null and a dominance alternative -- as long as you can add those assumptions it will work fine. The test is somewhat sensitive to other kinds of differences, so if you can't make those additional assumptions it wouldn't be suitable.
Comment: Would using the K-S test and then just plotting the CDF's be a reasonable test for this? Did you really mean to say M-W tests for stochastic dominance @ttnphns - I'm pretty sure you can construct situations in which the CDF's cross but M-W would still be significant.
Comment: That depends on how you define "stochastic dominance". That cdf curves cross does not preclude the non-0.5 probability that an observation randomly taken from one population is greater than such observation taken from the other population.
Comment: That is not [stochastic dominance](https://en.wikipedia.org/wiki/Stochastic_dominance) ttnphns! Stochastic dominance is a much more strict null. (The third order definition on the Wikipedia page is the *only* definition I have ever come across in statistical texts, so if you are thinking of another could you provide a source?)
Comment: @AndyW, I've once seen that wiki page. Perhaps you are correct, I won't object sharply. Or maybe that definition is too narrow? M-W test, when it was formulated, was - I suppose - not tied with that definition which, probably, appeared later. [I myself think that one is entitled to give/understand definitions of whatewer things as he likes it.] M-W tests for location difference, wherein I define "location" broader than "shift".
Comment: @AndyW I've several times seen  "Prob(A>B) > Prob(B>A)" described as "stochastic dominance" -- but it might not have been in the context of utility theory.
Comment: @Glen_b P(A>B) > P(B>A) is NOT stochastic dominance, which is a well-known concept (one CDF always smaller than the other, and strictly so somewhere). This is a common misconception about Mann-Whitney. I don't know what you mean by a "dominance alternative" but the fact is unless you make strong assumptions about the shape of the distributions, M-W will not test correctly for dominance and will reject far too often. Andy W is correct in this regard, but not about using KS and then examining CDFs to test dominance. You may reject the null, but you should not conclude dominance this way.
Comment: Yes, this wasn't the correct term for the thing being described for the Mann-Whitney. I can point to some authors that use the term in exactly that way (which is where I first picked it up) but later learned that usage wasn't very widespread and conventionally it means something else. (I did fix at least one other post though.) ... I will see what  I can do to rephrase, though your comment is at least sufficient to make it clear there's an error.
Answer: First, let me point out that Mann-Whitney does not test stochastic dominance. It tests the null hypothesis $P(X > Y) = P(X < Y)$. If $X$ is uniform on $[0,1]$ and $Y$ is 1 with probability 0.9 and 0 with probability 0.1, then the null is false but neither variable stochastically dominates the other. Stochastic dominance is a stronger condition.
There's plenty of literature on testing for dominance, though it is highly technical and requires some understanding of empirical processes. A Google Scholar search for "test stochastic dominance" will work. A famous reference is, e.g., Barrett and Donald (2003), Econometrica, 71, 1, "Consistent Tests for Stochastic Dominance".
Comment: (+1) But see [Glen_b's comment](https://stats.stackexchange.com/questions/220703/testing-for-stochastic-dominance-mann-whitney-with-unequal-variance#comment417604_220703). The necessary assumptions can often be reasonable ones - more so than a location-shift alternative - & gross violations are apparent from examination of the empirical distribution functions.


NoobProgramer = "Need explanation on this JQUERY smoothscrolling code"

Question: What does the below Javascript do? Could someone explain what each line in this smooth scrolling API does?
    $('a').click(function(){        //when you click 'a' run this function
       $('html, body').animate({              // animate what is in the html and body?
         scrollTop: $( $(this).attr('href') ).offset().top //grab coordinates?
      }, 800);                               // scroll speed?
       return false;                        // not sure what this means
     });

Comment: `return false;` cancels the click action. Documentation on animate: http://api.jquery.com/animate/ Jquery multiple selectors https://api.jquery.com/multiple-selector/
Comment: Almost all good...`$('html, body')` are dom selectors(I think that html do not to be included)...and `return false` prevents the `a` to work as expected(you are implementing a custom behavior when you click on an `a` element, so you don't need the default behavior)
Comment: `return false` works the same as `function(ev) { ev.preventDefault();`, as @epascarello said, it just makes it so when you click the link it won't redirect to the `href=""`
Answer: Ok let's start, the first 2 lines are correct from your investigation
$('a').click(function(){        //when you click 'a' run this function
   $('html, body').animate({     // animate the actual body and html element?

The next line is a bit tricky. Let's break it down
$(this).attr("href")

the clicked element's (a) href attribute value (in this case it could be something like #test1 or #test2
$($(this).attr("href")

if the above has the value '#test1' the selector becomes $('#test1') which mathces all elements with id=test1
$().offset().top

you get the offset method that has the coordinates of the element to the document. One of the variables is top which is the distance from the top of the document.
And so the next line will find the total amount of pixels that is needed to scroll
     scrollTop: $( $(this).attr('href') ).offset().top
  }, 800);         // this is the scroll speed
   return false;    // this will stop the anchor element from executing the default functionality, which is actually navigating to the href specified.
 });

I hope this helps :P


Node.js: How to add event handler to Connect/Express Server?

Question: I want handle EADDRINUSE how it is described in API Doc nodejs but connect/express did not call the error event handler.
here is a example:
var connect = require('connect');
var app = connect();

app.use(function(req, res){
    res.end('hello world\n');
});

app.on( 'error' , function(e) {
    console.log('error event handler called');
});

app.listen(3000);

if I start the server two times, I got
throw arguments[1]; // Unhandled 'error' event
I tested it with connect 2.7.2.
Answer: Since version 2.x, connect() is no more a constructor for a net.Server.
The 'net.Server' will be returned by the function listen(...).
So to get the example working, it should look like this:
var connect = require('connect');
var app = connect();

app.use(function(req, res){
    res.end('hello world\n');
});

app.listen(3000).on( 'error' , function(e) {
    console.log('error event handler called');
});

see also connect issue #749


Comparar Duas datas e hora

Question: Bom dia galera, estou tentando comparar duas datas mas não estou obtendo sucesso. Eu tenho 2 datas: dataAtual e dataPedido. O que eu quero fazer é que se a dataAtual for igual a dataPedido e se a hora atual for maior que 11:00 AM aparece uma mensagem. Tentei fazer isso mas nao deu certo:
public void getDateTime(Date dataPedido, Date dataSistema) {
        try {
            DateFormat dateFormat = new SimpleDateFormat("HH:mm");
            Date horaAtual = new Date();
            String horaMaxima = "11:00";
            dateFormat.format(horaAtual);

            Date horaMax = null;
            horaMax = dateFormat.parse(horaMaxima);

            if (horaAtual.getTime() > horaMax.getTime() && dataPedido.compareTo(dataSistema) == 0) {
                System.err.println("HORA ATUAL MAIOR, nao pode fazer");
                horarioComparacao = false;

            } else {
                System.err.println("HORA ATUAL Menor, pode fazer");
                horarioComparacao = true;

            }
            System.err.println("HORA MAXIMA: " + horaMax);

        } catch (ParseException ex) {
            Logger.getLogger(frmPedidos.class.getName()).log(Level.SEVERE, null, ex);

        }

    }

Answer: Se você usar a classe Calendar tudo fica mais simples.
Escreva um método para converter um objecto Date em Calendar com a opção de "zerar" a parte do Time.
public static Calendar DateToCalendar(Date date, boolean setTimeToZero){
    Calendar calendario = Calendar.getInstance();
    calendario.setTime(date);
    if(setTimeToZero){
        calendario.set(Calendar.HOUR_OF_DAY, 0);
        calendario.set(Calendar.MINUTE, 0);
        calenario.set(Calendar.SECOND, 0);
        calendario.set(Calendar.MILLISECOND, 0);
    }
    return calendario;
}

Suponho que quando diz "se a dataAtual for igual a dataPedido..." está a considerar que elas são iguais independente da hora.
Escreva um método para testar as condições:
public boolean possoProcessarPedido(Date dataPedido) {

    Calendar dataAtualTimeZero = DateToCalendar(new Date(), true);
    Calendar dataPedidoTimeZero = DateToCalendar(dataPedido, true);

    if(dataAtualTimeZero.compareTo(dataPedidoTimeZero) != 0){
        // A data do pedido e a data atual são diferentes: pode processar
        return true;
    }

    Calendar dataAtual = DateToCalendar(new Date(), false);
    Calendar dataAtualAs11Horas  = DateToCalendar(new Date(), true);
    dataAtualAs11Horas.set(Calendar.HOUR_OF_DAY, 11);

    if(dataAtual.after(dataAtualAs11Horas){
        //As datas são iguias mas já passa das 11 horas: não pode processar
        return false;
    }
    // As datas são iguais e é antes das 11 horas: pode processar
    return true;
}

Use o método da seguinte forma:
if(possoProcessarPedido(dataPedido){
    // código para processar pedido
}

Comment: Alterei o código para simplificar a condição que verifica se já passou das 11 horas
Answer: Apenas para complementar as respostas anteriores, a partir do Java 8 você pode usar a API java.time.
Há alguns detalhes a se considerar ao trabalhar com a API antiga (java.util.Date) e a nova simultaneamente, pois alguns conceitos são diferentes. Segue então uma breve explicação sobre Date, para que possamos entender a conversão desta para as classes do java.time.
Sobre java.util.Date
java.util.Date, apesar do nome, não é exatamente uma data propriamente dita, pois ela não representa um único valor de dia, mês e ano. Ela representa na verdade um timestamp: um número gigante (do tipo long) contendo a quantidade de milissegundos desde o Unix Epoch (1970-01-01T00:00Z, ou "1 de janeiro de 1970, à meia noite, em UTC").
O timestamp é um valor, digamos, "universal". Neste exato momento, em qualquer lugar do mundo, o timestamp é o mesmo. Em Java, basta chamar System.currentTimeMillis() e você terá o timestamp correspondente ao instante atual. Eu rodei agora e o valor retornado foi 1534249967760. E este valor é o mesmo no mundo todo: qualquer computador, em qualquer fuso horário do mundo, obteria este mesmo número se chamasse System.currentTimeMillis() no mesmo instante que eu.
Só que este valor (1534249967760) pode representar uma data/hora diferente em cada fuso horário. Em São Paulo, este timestamp equivale a 14 de agosto de 2018, às 09:32:47.760 da manhã. Em Londres, equivale ao mesmo dia (14 de agosto), mas neste mesmo instante o horário lá é 13:32 (1 da tarde). E em Samoa já são 01:32 (1 da manhã) do dia 15.
Podemos ver melhor isso imprimindo o Date (com System.out.println ou com qualquer API de log). Ao imprimí-lo, este é convertido para o timezone default da JVM, por isso o resultado contém uma data e hora específicas. Mas o valor do Date não muda. No código abaixo eu uso a classe java.util.TimeZone para mudar o timezone default:
// código rodado quando o timestamp atual é 1534249967760
Date date = new Date();
TimeZone.setDefault(TimeZone.getTimeZone("America/Sao_Paulo"));
System.out.println(date.getTime() + "=" + date);
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
System.out.println(date.getTime() + "=" + date);
TimeZone.setDefault(TimeZone.getTimeZone("Pacific/Apia"));
System.out.println(date.getTime() + "=" + date);

Eu mudei o timezone default 3 vezes, para São Paulo, Londres e Apia (que é o timezone de Samoa) e imprimi o Date e o valor de getTime() (que retorna o valor do timestamp). O resultado é:
1534249967760=Tue Aug 14 09:32:47 BRT 2018
1534249967760=Tue Aug 14 13:32:47 BST 2018
1534249967760=Wed Aug 15 01:32:47 WSST 2018

Repare que o timestamp não muda, mas a data e hora sim. Isso acontece porque ao imprimir o Date, ele converte o timestamp para o timezone default, resultando em uma data e hora diferentes em cada caso. Mas estes valores de data e hora não fazem parte do Date, somente o timestamp.
Por isso, para converter um Date para uma data (um dia, mês e ano específicos), você deve escolher um fuso horário (que a API chama de timezone). O que acontece com Calendar é que internamente ele usa o timezone default da JVM e já calcula os valores para o dia, mês, ano, horas, minutos, segundos etc.
Mas no java.time isso não acontece automaticamente e você deve especificar qual timezone deve ser usado.
Com isso, podemos prosseguir para a conversão de Date para as classes do java.time.
Converter Date para uma data e hora específicas
Primeiro convertemos o Date para java.time.Instant, que é a classe que representa um timestamp. Para isso foi adicionado o método toInstant() (disponível a partir do Java 8):
Date data = new Date();
// criar Instant (com o mesmo valor do timestamp de Date)
Instant instant = data.toInstant();

A partir do Instant, podemos convertê-lo para um timezone qualquer, usando a classe java.time.ZoneId (que representa um timezone). O resultado será um java.time.ZonedDateTime (uma classe que representa uma data e hora em um timezone específico). Exemplo:
Date data = new Date();
ZonedDateTime zdt = data.toInstant()
    // converter o Instant para um timezone
    .atZone(ZoneId.of("America/Sao_Paulo"));

O nome do timezone (America/Sao_Paulo) segue a nomenclatura da IANA, que é a base de dados usada pela JVM para obter informações do timezone (como início e fim do horário de verão, por exemplo, assim ela consegue saber exatamente a data e hora correspondente ao timestamp).
Se você quiser usar o timezone default da JVM (e assim simular o que Calendar faz), pode usar ZoneId.systemDefault(). Fica a seu critério.
Para obter a data atual, basta usar o método now():
ZonedDateTime agora = ZonedDateTime.now();

Isso cria um ZonedDateTime contendo a data e hora atual, no timezone default da JVM. Se quiser usar um timezone específico, basta passar o ZoneId:
ZonedDateTime agora = ZonedDateTime.now(ZoneId.of("America/Sao_Paulo"));

Com isso você obtém os valores corretos para a data e hora no timezone que quiser, sem depender da configuração da JVM (que pode mudar sem você saber, pois qualquer parte do código pode chamar TimeZone.setDefault, afetando todas as aplicações que rodam na mesma JVM).
Para fazer as comparações necessárias, basta usar o método equals (para verificar igualdade) e isAfter (para saber se um determinado instante ocorre depois de outro).
A primeira comparação leva em conta apenas a data (ignorando a hora), então você deve usar o método toLocalDate(), que retorna um java.time.LocalDate (uma classe que só possui dia, mês e ano), assim a comparação é feita ignorando o horário.
Depois, para a segunda comparação, basta usar o método toLocalTime(), que retorna um java.time.LocalTime (uma classe que só possui hora, minuto, segundo e frações de segundo). Em seguida comparamos com outro java.time.Localtime cujo valor é 11:00.
Aliás, esta é outra característica do java.time: várias classes especializadas para cada situação (uma que só representa data, outra só para as horas, outra para data e hora com timezone, etc).
Enfim, o código ficaria assim (assumindo que você quer usar o timezone default da JVM):
public boolean possoProcessarPedido(Date dataPedido) {
    ZonedDateTime pedido = dataPedido.toInstant().atZone(ZoneId.systemDefault());
    ZonedDateTime dataAtual = ZonedDateTime.now();

    // comparar somente a data (ignora o horário)
    if (! dataAtual.toLocalDate().equals(pedido.toLocalDate())) {
        // data do pedido e data atual são diferentes - pode processar
        return true;
    }
    // se não entrou no if acima é porque as datas são iguais

    // verificar se já passou das 11:00
    if (dataAtual.toLocalTime().isAfter(LocalTime.of(11, 0))) {
        // passou das 11:00 - não pode processar
        return false;
    }

    // não passou das 11:00 - pode processar
    return true;
}

Se ao invés do timezone default, você quiser usar um timezone específico, basta usar o ZoneId correspondente, conforme já explicado anteriormente.
Java 6 e 7
Para Java 6 e 7, você pode usar o ThreeTen Backport, um backport do java.time. Basicamente, possui as mesmas classes (Instant, LocalDate, ZoneId, etc) e métodos do Java 8, com uma diferença: no Java 8 as classes estão no pacote java.time, e no backport elas ficam em org.threeten.bp.
Outra diferença é que no Java 6 e 7 a classe Date não possui o método toInstant() e a conversão deve ser feita pela classe org.threeten.bp.DateTimeUtils:
Date date = new Date();
Instant instant = DateTimeUtils.toInstant(date);

O restante do código ficaria igual.
Java <= 5
Para Java <= 5, é possível usar o Joda-Time. Esta API é o "predecessor" do java.time, e muitos conceitos são parecidos (até alguns nomes de classes são os mesmos), embora ela não seja 100% igual.
O código fica bem parecido: ao invés de ZonedDateTime, usamos a classe org.joda.time.DateTime - aliás, todas as classes abaixo (LocalDate, Localtime, etc), embora tenham os mesmos nomes do java.time, estão no pacote org.joda.time:
public boolean possoProcessarPedido(Date dataPedido) {
    DateTime pedido = new DateTime(dataPedido);
    DateTime dataAtual = new DateTime();

    // comparar somente a data
    if (!dataAtual.toLocalDate().equals(pedido.toLocalDate())) {
        // data do pedido e data atual são diferentes - pode processar
        return true;
    }
    // se não entrou no if acima é porque as datas são iguais

    // verificar se já passou das 11:00
    if (dataAtual.toLocalTime().isAfter(new LocalTime(11, 0))) {
        // passou das 11:00 - não pode processar
        return false;
    }

    // não passou das 11:00 - pode processar
    return true;
}

Este código usa o timezone default da JVM para converter o Date para DateTime. Se quiser usar um timezone específico, use a classe org.joda.time.DateTimeZone:
DateTimeZone timezone = DateTimeZone.forID("America/Sao_Paulo");
DateTime pedido = new DateTime(dataPedido, timezone);
DateTime dataAtual = new DateTime(timezone);

O método forID recebe o nome do timezone, também seguindo a nomenclatura da IANA.
Answer: Acho melhor vc usar a classe calendar
Calendar dataAtual = new GregorianCalendar();
    Calendar dataMAxima = new GregorianCalendar();
    dataAtual.setTime(new Date());
    dataMAxima.set(Calendar.HOUR_OF_DAY, 11);
    dataMAxima.set(Calendar.MINUTE, 0);
    dataMAxima.set(Calendar.SECOND, 0);

nela vc tem metodos de comparação, acima eu explico com passar uma data e como setar uma data importante é setar hora, minuto e segundo

Comparar Duas datas e hora


What does "aspect model" refer to in machine learning

Question: Hopefully this is the right place to ask my question.
I am reading this paper about cold-start recommendations: http://dl.acm.org/citation.cfm?id=1352837
the expression "aspect model" is used a lot : in the abstract (sentence before last sentence), and at the beginning of section2.
Is anyone able to shed some light here ?
Thanks
Answer: So ! I did so more research and found the signification of "aspect model", in the paper of the  author Mr Hoffman who coined the expression in this paper : http://cs.brown.edu/~th/papers/Hofmann-SIGIR99.pdf
The definition is at the top of page 2 (section 2).
Enjoy :)
Comment: Link is now a 404. New link: https://arxiv.org/pdf/1301.6705.pdf (Probabilistic Latent Semantic Analysis)


Parse output of lastlog?

Question: I want to withdraw the fourth field of the output of lastlog -u 'user' however using cut -d' ' -f4 I can only withdraw the first field otherwise whitespace is output.
Username         Port     From             Latest
auser            pts/31   c-73-123-11-86.h Sun Jan 19 13:52:08 -0800 2014

I want to remove 'Sun Jan 19 13:52:08'. How can I do this considering there are multiple spaces in the line I want and using cut with specific subscript locations will produce erroneous results when usernames of different length are input. How can I solve this problem?
Comment: See [How to make the 'cut' command treat several sequential delimiters as one?](http://stackoverflow.com/questions/4143252/how-to-make-the-cut-command-treat-several-sequential-delimiters-as-one)
Answer: I believe this will do what you are asking for
lastlog -u 'user' |  grep -v Latest | awk '{$1="";$2="";$3="";print $0 }'

In your example, this will output
Sun Jan 19 13:52:08 -0800 2014

Comment: This works but the output Latest
   Sun Jan 19 13:52:08 -0800 2014 containts latest which is in the fourth column on the top. How could i modify to not grab latesT?
Comment: You could add a `grep -v Latest` or a `tail -n 1`.
Answer: It seems that using any delimiter to separate lastlog output is problematic, since some of the fields may be empty:

ubuntu@ubuntu:~$ lastlog -u ubuntu
Username         Port     From             Latest
ubuntu                                     **Never logged in**
ubuntu@ubuntu:~$

Alternatively you can just cut at the right number of characters, though this could be problematic too if the output ever changes in a new version:

ubuntu@ubuntu:~$ lastlog -u ubuntu | { read; cut -c44- ;}
**Never logged in**
ubuntu@ubuntu:~$

Note the read simply reads and discards the first/header line of lastlog output.
Comment: With read, it will remove other records, if this user has several sessions.
Comment: @BMW - can you elaborate?  In this case, there is just one invocation of `read` - no while loops or anything.  So exactly one line will be read from stdin of the {} command grouping.  Then the remaining lines will be read by `cut`.  Or am I missing something?
Answer: You could count the length of the lines up to the string Latest and cut at that point:
$ lastlog -u $USER | (
    IFS= read -r line1
    IFS= read -r line2
    length=${#line1}
    echo "${line2::$((length - 6))}"
)

For my user this returns:
abcdef           tty1

(I don't have a "From" value for this user)

Parse output of lastlog?


Estilo não propagar para os parents

Question: Tenho vários elementos um dentro do outro e quando passo o mouse com o hover ele adiciona uma borda para identificação do elemento, porém, como todos tem a mesma classe, todos os items pegam a borda.
Eu quero que apenas o elemento posicionado com o mouse conseguisse a borda, isso é possível?
Segue exemplo do problema:

.test
{
    width: 100%;
    float:left;
    padding-top: 20px;
    padding-left: 20px;
    padding-bottom: 20px;
}

.test:hover
{
    outline: #000 1px solid;
}

    teste

        teste2

            teste3

Answer: O que você pretende não é possível dessa maneira.
Em parte por que o CSS funciona assim, note que a primeira letra de CSS quer dizer "Cascata", ou seja as regras são aplicadas de parente para descendente; e em parte porque está a fazer de maneira que não ajuda.
Se quiser usar esse HTML vai ter de fazer isso com javascript. O melhor seria usar listas, que são feitas/pensadas para esse tipo de código.
Exemplo utilizando JavaScript:

$(function(){
    var testes = $('.test');
    testes.on('mouseover mouseout', function (event) {
        event.stopPropagation();
        testes.removeClass('ativo');
        $(event.target).addClass('ativo');
    });
});
.test {
    width: 100%;
    float:left;
    padding-top: 20px;
    padding-left: 20px;
    padding-bottom: 20px;
}
.ativo {
    outline: #000 1px solid;
}

teste

teste2

teste3

Comment: é, eu sei como funciona e recorri aqui por precisar usar e não conhecer nada parecido, talvez quem sabe, mas, enfim, vou ir pro JavaScript mesmo... Valeu
Comment: @CaioGomes ok. Pois é, enquanto houver parentes/descendentes com a mesma classe esse problema vai surgir. Juntei uma sugestão com JavaScript/jQuery caso lhe seja útil.

Estilo não propagar para os parents


How to access related data in view ASP.NET Core MVC

Question: I'm struggling to figure out how to access related data in my view. I think my issue has something to do with collection vs reference navigation properies, but I can't figure out what the problem is.
This app is to keep track of prototype testing, with Test and Prototype entities having a one-to-many relationship.
Test model(attributes removed):
public int Test_ID { get; set; }
public string Test_Name { get; set; }
public string? Test_Procedure { get; set; }
public string? Test_Notes { get; set; }

public ICollection<Prototype>? Prototype{ get; set; }

Prototype model:
public int Prototype_ID { get; set; }
public string Prototype_Name { get; set; }
public string Prototype_Model { get; set; }
public int Trials { get; set; }

public Test Test { get; set; }

I want to be able to view the Prototypes associated with each Test, which I've tried to do in my PrototypeController.cs:
public async Task<IActionResult> Index(int? id)
        {
            var test = _db.Tests
                .AsNoTracking()
                .Include(t => t.Prototypes);
            return View(await test.ToListAsync());
        }

And finally in my view:
@model IEnumerable<TortureChamber.Models.Test>
...

                @foreach (var test in Model)
                {

                        @test.Test_Name
                        @*Below is where my errors are*@
                        @test.Prototypes.Prototype_Name
                        @test.Prototypes.Prototype_Model
                        @test.Prototypes.Cycles

                }

In my view I get the error:
"CS1061 'ICollection' does not contain a definition for 'Prototype_Name' and no accessible extension method 'Prototype_Name' accepting a first argument of type 'ICollection' could be found (are you missing a using directive or an assembly reference?)"
I realize I've probably forgotten an important step. Can anyone point me to what it is?
Comment: Use nested `for`/`foreach` loop for `Prototypes` property.
Answer: Prototypes is a ICollection<Prototype> but you're accessing it as though it's an instance of Prototype; it isn't, you haven't indexed into it. You probably want to either take the first member, or iterate over its contents and print a table row for each one.


lavacharts' doesn't display chart size properly using tab (first tab is ok, second tab not ok)

Question: I'm using a package caled lavacharts from https://github.com/kevinkhill/lavacharts.
To display the simple chart, I do the following in my Controller with the method show():
   public function show($id)
   {
    $product = Product::findOrFail($id);

    $prices = \Lava::DataTable();

    $prices->addDateColumn('Month')
        ->addNumberColumn('Retailer Price')
        ->addNumberColumn('Consumer Price')

        ->addRow(array('2014-10-1', 67, 65))
        ->addRow(array('2014-10-2', 68, 65))
        ->addRow(array('2014-10-3', 68, 62))
        ->addRow(array('2014-10-4', 72, 62))
        ->addRow(array('2014-10-5', 61, 54))
        ->addRow(array('2014-10-6', 70, 58))
        ->addRow(array('2014-10-7', 74, 70))
        ->addRow(array('2014-10-8', 75, 69))
        ->addRow(array('2014-10-9', 69, 63))
        ->addRow(array('2014-10-10', 64, 58))
        ->addRow(array('2014-10-11', 59, 55))
        ->addRow(array('2014-10-12', 65, 56))
        ->addRow(array('2014-10-13', 66, 56))
        ->addRow(array('2014-10-14', 75, 70))
        ->addRow(array('2014-10-15', 76, 72))
        ->addRow(array('2014-10-16', 71, 66))
        ->addRow(array('2014-10-17', 72, 66))
        ->addRow(array('2014-10-18', 63, 62))
        ->addRow(array('2014-10-19', 63, 55))
        ->addRow(array('2014-10-20', 63, 56))
        ->addRow(array('2014-10-21', 63, 55))
        ->addRow(array('2014-10-24', 63, 33))
        ->addRow(array('2014-10-29', 63, 64))
        ->addRow(array('2014-10-30', 63, 63));

    $linechart = \Lava::LineChart('Price_History')
        ->dataTable($prices)
        ->title('Price history for: '.$product->name)
        ->legend(\Lava::Legend(array('position' => 'in')));

   // dd($product);
    return view('admin.products.show', compact('product'));
    }

In order to display from the controller in the view blade, I just put the following code in blade:

{!! \Lava::render('LineChart', 'Price_History','price_history_chart') !!}

So, I put the display code in the tabs like below (using with bootstrap):

                                        First Tab

                                                        First Tab

                                                            {!! \Lava::render('LineChart', 'Price_History','price_history_chart') !!}

                                        Second Tab

                                                        Second Tab

                                                            {!! \Lava::render('LineChart', 'Price_History','price_history_chart') !!}

PROBLEM:
http://postimg.org/image/o9gsju91f/
Screenshot 1-on first tab loaded / clicked: (display correctly)
http://postimg.org/image/k18bhfsnd/
Screenshot 2-on second tab clicked: (display incorrectly; the chart becomes smaller.)
Any idea how to fix this?
EDIT
    I thought of calling $(window).trigger('resize'); like below but it doesn't work
$('#tab2').on('click',function(){

    $(window).trigger('resize');
 });

Answer: When a Google Chart is rendered, its size is determined by the size of the element it is inside.  Since the second tab is hidden when the second chart is drawn, it is defaulting to the standard size.  You'll need to re-size the chart when that tab is selected.  Also, if you want to have the chart respond when the window changes size, you'll have to re-size it again.  Check out Google chart redraw/scale with window resize for how to re-size the chart.
Comment: Hi, just to clarify back the code actually doesn't work. I was too confident that it actually work. the trigger('resize') never done anything. It was my clicking movement on 2nd tab which actually faster than before the chart rendered . That's why I thought it work. For the temporary, I just display this chart on the first tab. If you have the solution, please let me know. Thanks.
Answer: I had the same issue with bootsrap modal.
The fix is through config in php code although mine was in 3.0 version
Your code :
$linechart = \Lava::LineChart('Price_History')
        ->dataTable($prices)
        ->title('Price history for: '.$product->name)
        ->legend(\Lava::Legend(array('position' => 'in')));

New code :
$linechart = \Lava::LineChart('Price_History')
        ->dataTable($prices)
        ->title('Price history for: '.$product->name)
        ->width(800)//add appropriate width
        ->legend(\Lava::Legend(array('position' => 'in')));

In 3.0 the code would have been
$datatable = \Lava::DataTable();
     \Lava::LineChart('Price_History',$datatable,[
        'title'=>'Price history for: '.$product->name,
        'width'=>800
    //and you other configs
     ]);

Comment: but unable to set width in percentage :(
Answer: Lavacharts Dev here :) So the charts should already be responsive, and resize on window resize. This was an issue that was brought up before and as far as I know, it is working. As for being resized when brought into view in the tab, I'm not certain how to handle that. I suppose adding an endpoint to the lava.js module for manually resizing, so the user could use the bootstrap event of the tab showing to activate the resize.
Thoughts?
PS: I'm fairly new here, so I can't comment, even though I know this isn't an "answer" to the question.
Answer: Dispatch an resize event works for me, hope this help
$("your-tab").on("click", function(){
    window.dispatchEvent(new Event('resize'));
});

Comment: After 5 years, I think something has been updated. Haven't used laravel for a long time


Distribution of minimum distance in a iid Gaussian sample

Question: $X_1,...,X_n$ denotes an iid sample with the same Gaussian distribution. I am interested in the distribution of the following quantity.

We first pick $i \in [n]$
Then we extract $j^* \in argmin_{j\neq i} |X_i-X_j| $

Do we have information on $(X_i-X_j^*)$ and $(X_i-X_j^*)^2$ ?
Thanks!
Answer: Yes we have some information using the theory of spacings of order statistics.
Let $X_{(1)}\le \dots \le X_{(n)}$ be the Gaussian sample sorted, the so-called order statistics. What you are asking about is information on $X_{(i+1)}-X_{(i)}$ (may be linked to this post), well more precisely you can rewrite the quantity you are interested in as
$$ \Delta=\min(X_{(i+1)}-X_{(i)},X_{(i)}-X_{(i-1)}) $$
and you are interested about information on this quantity.
Now, Gaussian order statistics are not the easiest ones, and typically to handle this sort of things, the easiest way is to reduce the problem to exponential order statistics because exponential order statistics are well known. To do that, you can consider the function $U=F_{exp}^{-1} \circ \Phi$ where $F_{exp}$ is the cdf of an exponential with parameter $1$ and $\Phi$ the cdf of a standard Gaussian. By the Probability integral transform, you have that if $X\sim \mathcal{N}(0,1)$ then  $U(X)\sim Exp(1)$ and because $U$ is increasing,
$$U(X_{(1)})\le \dots \le U(X_{(n)}) $$
Denote $E_i=U(X_i)$, we have that $E_{(1)},\dots,E_{(n)}$ are exponential order statistics ! Now, it is known from order statistics theory that $$i(E_{(i+1)}-E_{(i)})\sim Exp(1)$$
Good, now that we have a handle on this, we come back to the original sample by mean value theorem:
\begin{align*}
X_{(i+1)}-X_{(i)}&=U^{-1}(U(X_{(i+1)}))-U^{-1}(U(X_{(i)}))\\
&\le \left(U(X_{(i+1)})- U(X_{(i)})\right)\sup_{x \in [U(X_{(i)},U(X_{(i+1)}]} U^{-1}(x)\end{align*}
and so on.
For example, this reasoning allow you to get concentration inequalities for $\Delta$, this is the technique that was used for example in the article Concentration inequalities for order statistics by Stephane Boucheron and Maud Thomas.
To go further you can also see wikipedia or the article Spacings Around An Order Statistic by H. N. Nagaraja, Karthik Bharath, Fangyuan Zhang.
Comment: Thanks a lot for all those pointers :)


Laravel Custom FormRequest in PHPUnit env

Question: Okay so, I've tried searching for a while now for solutions on how and why this is happening, here it goes.
On production environment, this chunk of code works just fine.
public function store(Add $request) {
        $data = $request->validated();
        //....  some other stuff
}

Add is a class that extends Illuminate\Foundation\Http\FormRequest, it has some rules only (that I've checked and doesn't influence the error, being the reason for not being posted)
On my test schema, I've got a couple scenarios, mostly Acceptence tests to make sure everything is created (or not) according to different data input. These make calls such as $this->call($uri, $body, $headers) and they work as expected, simulating the production environment.
However, I'm trying to write a test specific to the Controller and it keeps on giving me this error:
$userController = new UserController();
$request = Add::create('/test', 'POST', $body);
$userController->store($request);

This outputs an error:
 Error: Call to a member function validated() on null
 vendor/laravel/framework/src/Illuminate/Foundation/Http/FormRequest.php:188

I've tried to output what dd($request->validated()); returns but this is where it crashes.

What is the solution?
Why it happens?
Comment: `$this->call($uri, $body, $headers)` The second parameter is the `$body` but you are passing the method of the form in `Add::create('/test', 'POST', $body);`. Maybe this could be the issue?
Comment: $this->call is a laravel testcase function to call URIs with http,  Add::create is a class derivant of FormRequest that represents the body of a HTTP request, they're different things
Answer: When creating a new instance of the request there are some properties set to null, you will have to populate the container, redirector and validator yourself before you can use the request properly in the controller.
Something like this should work:
$userController = new UserController();

// create the request and set the container and redirector
$request = Add::create('/test', 'POST', $body)
    ->setContainer($this->app)
    ->setRedirector($this->app['redirect']);

// resolve the validator
$request->validateResolved();

$userController->store($request);


Feeds for the module information of drupal.org

Question: http://simplytest.me/ has a nifty autocomplete option for the module suggestions. Screenshot attached.

I did a little digging and figured it out that ajax call being made is to the following url.

http://simplytest.me/simplytest/projects/autocomplete?string=views

I could be use the same end point but I need to get the permission and also the data available is not sufficient for my use case. I wanted to know if Drupal.org provides any authentic feeds of modules so that I will be able to list other details, say the download url for the tarball file.
Comment: Checkout update module of core. May be you will get an idea from there.
Answer: The official Drupal.org feeds available can be found at https://www.drupal.org/api/rss.  There is a feed for projects, but to get the information about releases you'll need to parse the JSON of an API request like
https://www.drupal.org/api-d7/node.json?field_project_machine_name=media
You can read more about the APIs available and how to use them at https://www.drupal.org/api
UPDATE:  If the goal is to a list of all projects and pull their releases, this cannot be done with just an official "feed".  It requires scraping the list of projects from Drupal.org and writing code to get the release into, but the code to do that already exists.  Lin Clark's ScraperWiki code still works (http://lin-clark.com/blog/2011/07/22/writing-scripts-clone-contrib-projects-gitdrupalorg/).  Export the scrapper output as SQL, import that into a custom table, write some code to loop those the projects calling Drupal.org's API to get the release information you are looking for, and save that response.  Not as easy as just pulling the information from a feed provided by Drupal.org, but it can be done.
Comment: @Gokul N K unfortunately a full list of projects doesn't exist in feed form, but you can scape the project names from Drupal.org using Lin Clark's ScraperWiki code.  After forking that code to Morph.io, you can tweak it as needed.  It currently returns 6454 full D7 projects.  Good luck!
Comment: There is a feed only for latest modules, you can't search modules by name
Comment: I'm only answering the question as it was asked "if Drupal.org provides any authentic feeds of modules".  If the goal is to get a dump of all projects, that can be done with git... but it's a very different question.
Comment: @kreynen Thanks for the answer. Your answer seems to be the most relevant till now. I will wait to see if somebody can provide a feed that can be filtered as well :)
Answer: The URL used when creating a new issue https://www.drupal.org/node/add/project-issue requires a project name in it's first step.
This is https://www.drupal.org/project/autocomplete/issue/project so issuing https://www.drupal.org/project/autocomplete/issue/project/gra gives a list of the first 10 items in json format.
Answer: There's over 9,000 d7 modules up on drupal.org, and I'm not sure if they put out an rss feed that provides every single module there is. I know drush does a fairly good job of keeping track of modules, so you might want to have a look at that.
There's also an internal function called module_list, not sure how much use that would be to you.
Comment: module_list() just returns a list of currently active modules on the website, not on drupal.org :)
Answer: Well, good question.
I wonder why there is no elegant and easy way to get machine-readable list of all Drupal modules and their data.
What i have found so far for humans are:

Modules search on Drupal.org
Modules search on Drupalmodules.com
Modules index on Drupal.org
Index of Drupal.org git repositories

But non of them provides rss or json out of the box.
If you need just a list of all Drupal modules - i would suggest you to parse Modules index on Drupal.org - there are titles and links of all the modules on one page - quite handy.
But if you need more detailed list which you want continuously keep up-to-date - the only solution so far is to parse on your own this page: Modules search on Drupal.org.
For example do it with import.io service and then integrate into your site with Feeds module - here is a good tutorial: "Scraping websites into Drupal using Feeds and Import.io"


How to avoid manually deleting the content of an EditTextPreference when the user want to change its content?

Question: I have the following preference screen on my API 29 app :
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

    <PreferenceCategory app:title="@string/sample_header">

        <EditTextPreference
            app:key="sample_id"
            app:title="@string/sample_id_title"
            app:useSimpleSummaryProvider="true" />

    </PreferenceCategory>
</PreferenceScreen>

The EditTextPreference is set to numeric input :
public void onBindEditText(@NonNull EditText editText) {
   editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
}

When the user opens the sample_id preference, the text is set to the old numeric value, as expected, and the cursor is placed at the beginning of the text. It's important for the application that the current value is shown to the user.
To change that value, the user has to first scroll to the end of the text or select it, delete the old content, and then enter the new numeric text.
I would like to have the following behavior: The old text get deleted when the user types in a new text.
One implementation would be to have the text content already selected. Therefore it would be replaced as soon as the user types in a new text.
I haven't found a way to force the selection of the text on edit.
Another sub-optimal solution would be to have the cursor placed at the end of the text on edit. Just pressing a couple of backspace is more convenient than having to fist move to cursor to the end or to select the old text content.
My question is :
How to avoid the need to first delete the old content to enter a new one ?
Comment: You can do all you want with a ' i think.
Answer: You can overide the focus so when that editText is focus'd it can either clear the text or change the value to hint.
setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus & v instanceof EditText){
                        ((EditText) v).setText("");
                }
            }
        });

Set to hint
.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus & v instanceof EditText){
                String value = ((EditText) v).getText().toString();
                    ((EditText) v).setText("");
                    ((EditText) v).setHint(value);
            }
        }
    });


Qual é a finalidade do método mágico __clone?

Question: No PHP temos o método mágico __clone. Ele serve para definir um comportamento quando você clona um objeto, através da palavra chave clone.
Até aí tudo bem. Porém não entendi muito bem por que ter esse método mágico, já que a palavra clone por se só já clona um objeto.
Exemplo 1:
 $a = new ArrayObject(['nome' => 'Wallace']);

 $b = clone $a;

Outro detalha que eu queria entender é que eu já vi algumas bibliotecas em PHP usarem esse método mágico para operações parecidas com essa abaixo:
Exemplo 2:
  class X {
       public function __construct (Y $y) {
          $this->y = $y;
       }

       public function __clone() {
          $this->y = clone $this->y;
       }
  }

Baseando-se nas observações acima, pergunto:

Existe algum caso onde é, realmente, necessário definir um comportamento para a clonagem de um objeto?
Por que algumas bibliotecas utilizam __clone para clonar uma propriedade correspondente à uma instância de um objeto (como no exemplo 2)?
Comment: Mas ele é mágico mesmo?
Comment: http://i.stack.imgur.com/YkZbv.jpg
Comment: Ele também serve para privar a sua classe de ser clonada. Quando você torna o método 'private'. É muito utilizado em design pattern de padrão do tipo singleton.
Comment: Sim, ele é Mágico, Mágico
Comment: http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=205960&type=card
Comment: @IvanFerrer boa observação, isso é bom.
Comment: Esse é um método que nunca entendi pra que serve efetivamente
Answer: Deep clone
Porque a clonagem, em geral, envolve copiar todo o conteúdo do objeto de forma profunda (deep). Ou seja, copia também os objetos referenciados dentro desse objeto. Eventualmente pode-se querer até que toda árvore de objetos seja clonada, se for possível (os objetos referenciados precisam ser capazes de serem clonados profundamente).
Como a maneira de copiar esses objetos pode variar bastante, você tem que escrever o código que vai fazer isto. Isso ocorre muito quando você segura recursos externos na classe, como arquivos e objetos GUI, mas não se limita a estas coisas. Qualquer coisa que precise de independência total dos dados precisa de uma clonagem profunda.
Shallow clone
Se não criar esse método o PHP irá clonar de forma rasa (shallow), ou seja, copiará só o objeto, seus membros por referência terão apenas as referências copiadas que apontará para o mesmo objeto que seu objeto original apontava. Isso pode ser o que deseja em alguns casos, mas não em todos.
Aí muita gente começa se perder criando classes. A maioria dos programadores não entendem todas implicações de se criar um classe. Costuma dar certo porque em geral as classes não fazem nada sofisticado, ou mesmo elas nem eram necessárias de fato. Na verdade só não dá um monte de problema porque os códigos PHP são o que eu sempre falo, apenas scripts simples. Se fossem aplicações complexas de fato muita classes começaria explodir. Em geral seu uso é muito contido e clonagens profundas não costumam ser necessárias. Onde elas são necessárias costuma ser escritas por programadores que possuem mais noção do funcionamento da computação como um todo.
Clonar != Copiar
Note que clonar, mesmo a rasa, é diferente de copiar o objeto, a cópia pura só copia a referência do objeto, e não o objeto.
Exemplos
No exemplo da pergunta $b terá um objeto igualzinho a $a, mas será outro objeto. Eles serão completamente independentes, cada um com sua vida própria, mudar um não muda o outro. Você clonou e não simplesmente copiou. Se a clonagem será rasa ou profunda depende do tipo do objeto da variável $a. Até onde eu sei o ArrayObject não clona de forma profunda, pelo menos não tem nada que diga isto na documentação.
Na classe X está fazendo isto com o seu membro, garantindo que uma cópia do membro seja feita e não só a referência.
$x = new X(new Y());
$y = clone $x;

Nesse caso já sabe que $x e $y serão independentes. Mas o mais importante é que internamente o membro y, acessado pelo $this também será independente em cada um dos objetos, ou seja, este membro será copiado também. Se não tivesse essa clonagem. Tanto $x.y, quanto $y.y apontariam para o mesmo objeto, e mudando em um, mudaria no outro, eles não seriam independentes. Provavelmente não era o que queria.
class A {
    public $b;

    public function __construct(B $b) {
        $this->b = $b;
    }
}

class B {}

class C extends A {
    public function __clone() {
        $this->b = clone $this->b;
    }
}

$a = new A(new B);
$aa = clone $a;
$b = $a;
$c = new C(new B);
$cc = clone $c;
echo "CÓPIA\n";
var_dump($a === $b); //é igual, ambos apontam para o mesmo objeto
var_dump($a->b === $b->b); //continua igual, é o mesmo objeto, não pode ser diferente
echo "SEM __CLONE\n";
var_dump($a === $aa); //é diferente, copiou o objeto
var_dump($a->b === $aa->b); //é igual, o membro continua sendo o mesmo objeto apontado
echo "COM __CLONE\n";
var_dump($c === $cc); //é diferente, copiou o objeto
var_dump($c->b === $cc->b); //é diferente, copiou o objeto referenciado pelo membro

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
O método mágico __clone() sempre é chamado pelo comando clone da linguagem, quando o método estiver disponível para aquele objeto, se não estiver disponível, a clonagem será rasa.
Documentação.
Answer: Sumário
Basicamente o método mágico __clone() serve como um "callback" após uma clonagem.
Quando um objeto é clonado o compilador busca pelo método mágico __clone() e, se existir é invocado.
Instâncias independentes e atribuição por referência
Um objeto clonado é independente do original de onde foi clonado.
No entanto, você pode querer copiar ou fazer atribuições por referência dos membros do objeto original. Para isso existe o método mágico __clone() onde poderá realizar essas cópias.
O motivo de não ocorrer uma cópia profunda e completa de todo um objeto é que nem sempre se precisa de uma cópia profunda do objeto inteiro. Pelo menos não dentro da principal finalidade de uso que fazemos do PHP.
No manual do PHP tem exemplos suficientemente bons para compreender: http://php.net/manual/pt_BR/language.oop5.cloning.php
Sobre as duas questões no final

Existe algum caso onde é, realmente, necessário definir um
comportamento para a clonagem de um objeto?
Por que algumas bibliotecas utilizam __clone para clonar uma propriedade
correspondente à uma instância de um objeto (como no exemplo 2)?

É complicado tentar responder pois o motivo/razão/circunstância depende de um contexto.
Sem entender o contexto torna-se inviável responder.
Answer:
Depois que a clonagem se completa, se um método __clone() estiver definido, o objeto recém criado terá seu método __clone() chamado, permitindo que qualquer propriedade seja alterada.
http://php.net/manual/pt_BR/language.oop5.cloning.php

Nothing more, nothing less.
// Force a copy of this->object, otherwise
// it will point to same object.
$this->object1 = clone $this->object1;

Comment: Achei que aqui era SO-PT...
Comment: Desculpem a sinceridade, mas esse +2 foi mal votado. Realmente, a resposta não explica nada, apenas faz uma referência ao manual (que por sua vez nunca explica nada direito).
Comment: A resposta é simplista e responde à pergunta feita no título da questão, mas ignora o conteúdo da pergunta, onde o AP já demonstra saber que a rotina é chamada e procura conhecer um caso de uso prático da mesma. Comparada com as demais ela é incompleta, porém ela foi dada antes, portanto não acho que mereça tantos negativos.
Comment: Não entendi o restante da resposta depois da parte tirada do Manual.


Android webview : Show the default JS popup for web page access authentication

Question: This is a screenshot from google chrome. When I try to access a page with basic authentication, this authentication dialog is shown. I want this feature be enabled in my android Webview as well and let the user enter their username and password. But instead it just shows the 401 unauthorized page without showing this popup. How would I achieve this in the Webview? I have tried adding these snippets but still unable to show this popup.
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setBuiltInZoomControls(true);
    webview.getSettings().setSupportZoom(true);
    webview.getSettings().setLoadWithOverviewMode(true);
    webview.getSettings().setUseWideViewPort(true);
    webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    webview.getSettings().setSupportMultipleWindows(true);
    webview.getSettings().setDomStorageEnabled(true);
    webview.getSettings().setDatabaseEnabled(true);
    webview.getSettings().setAppCacheEnabled(true);
    webview.getSettings().setSaveFormData(true);
    webview.getSettings().setMixedContentMode(MIXED_CONTENT_ALWAYS_ALLOW);
    webview.getSettings().setAllowFileAccess(true);
    webview.getSettings().setAllowFileAccessFromFileURLs(true);
    webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
    webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

Answer: You need to override WebViewClient.onReceivedHttpAuthRequest() to handle the authentication. Your code is responsible for showing the authentication dialog or retrieving saved username/password. This will not be done for you.
This is the code that worked in my app. I remove some parts of it for clarity.
    @Override
public void onReceivedHttpAuthRequest(final WebView view,
                                      final HttpAuthHandler handler,
                                      final String host,
                                      final String realm) {
    if(handler.useHttpAuthUsernamePassword()) {
        String[] creds = view.getHttpAuthUsernamePassword(host,realm);
        if(creds!=null) {
            handler.proceed(creds[0],creds[1]);
            return;
        }
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
// set up the input for user name and password here
// ... removed for clarity ...
    builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            String name = nameEdit.getText().toString();
            String pass = passEdit.getText().toString();
            view.setHttpAuthUsernamePassword(host,realm,name,pass);
            handler.proceed(name,pass);
        }
    });
    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
          handler.cancel();
        }
    });
    AlertDialog dialog = builder.create();
    dialog.show();
}

Comment: Any example? Because I tried this method too but gave me 401
Comment: I edited my answer to include some code. It works in my app.


Do I need identical servers for load balancing?

Question: I am new to using AWS and web hosting in general.
Let's say I currently have a single server running a website, and the traffic starts to grow to a point I need to use load balancing.
Assuming my current server is running on an EC2 instance with Ubuntu, and an Apache server with all the website files inside the /var/www/ folder. If I want to add load balancing, do I need to create an EC2 instance with the same website files copied to it? Or I just need to create an empty EC2 instance and the rest is done automatically? A bit confused as to how it would work.
Answer: Yes, you will need to create an identical (in configuration only) ec2 instance which contains the same files in /var/www as the main instance and when you make changes, you have to make sure that the changes are applied in both servers.
I think the best method to keep both server site configuration identical is to set-up a git repository which contains all your site files, and clone it in both servers in addition to setting a cron job which will run git pull every hour or so.
Another thing you can do, is to create an Elastic File System and mount it in both servers. Info about this process can be found here.
Comment: *"The load balancer will know which server and port to send the request to based on cpu / networking stats"*  ...I don't believe CPU/networking stats are ever considered by any AWS load balancer.  Can you cite a source for this assertion?
Comment: You're right, with the configuration at hand, there cannot be load balancing based on stats. It is doable though using an alb with a target group attached to an auto-scaling group configured with scaling policies. I've edited my answer. Thanks
Answer: Each server needs all the content, and you need to set up the server and content. It's not automatic.
Options for keeping content in sync between the servers:

Version control (git is pretty standard)
Golden AMI (though this means every code change means replacing all your servers)
Use Amazon Elastic File System to host the code / resource (consider latency)
rsync (some content may be stale)

You may also need to consider where the database lives. AWS RDS is a good option in many cases. You can of course continue to use one server as the database server, or even cluster the database servers, but RDS is easy and scales (manually).
Your servers within the cluster should be the same size as traffic is distributed to them equally. You could probably use ALB to send specific traffic to specific servers, doing a kind of manual load balance, but this doesn't give you any redundancy.
You should look at auto scaling. This will run the number of servers you need for the current load. With this scenario you're often better off with more, smaller servers rather than a small number of large servers, to give finer grained control of the server required. For this to work you need good automation, such as an AMI that has all your software on it and ideally reasonably recent code. When the server boot you can have the code updated.


Most efficient way to reverse a numpy array

Question: Believe it or not, after profiling my current code, the repetitive operation of numpy array reversion ate a giant chunk of the running time. What I have right now is the common view-based method:
reversed_arr = arr[::-1]

Is there any other way to do it more efficiently, or is it just an illusion from my obsession with unrealistic numpy performance?
Comment: Er... `arr[::-1]` just returns a reversed view. It's as fast as you can get, and doesn't depend on the number of items in the array, as it just changes the strides. Is what you're reversing actually a numpy array?
Comment: Hmmm... Well, on my laptop it takes about 670 nanoseconds regardless of the length of the array. If that's your bottleneck, you may need to switch languages... I'm pretty sure you won't find a faster way of reversing a numpy array. Good luck, at any rate!
Comment: Well, do you necessarily have to run it inside a loop? In some cases, it's better to make a numpy array with millions of items and then operate on the entire array. Even if you're doing a finite difference method or something similar where the result depends on the previous result, you can sometimes do this. (Emphasis on sometimes...) At any rate, if speed is the primary goal, fortran is still king. `f2py` is your friend! It's often worthwhile to write performance critical parts of an algorithm (especially in scientific computing) in another language and call it from python. Good luck!
Comment: @berto. It is slower since it's a wrapper for `arr[::-1]`: https://github.com/numpy/numpy/blob/master/numpy/lib/twodim_base.py. Search for `def flipud`. The function is literally four lines long.
Comment: @berto. That is not a good idea if you expect your link to be up for more than a couple of days. Line numbers in the master branch change *very* frequently.
Comment: yes, indeed, `arr` is a numpy array.
Comment: 670 nanosec per hit is about the same number I got. The total time for running the whole function is about 2~3 seconds, in which the reversion takes about 1/3, i.e., 1 second. Since I'm gonna run this function for millions of times, I regard this as a bottleneck. If this is indeed the best I can get, presumably I can only decide to live with it. Thanks!
Comment: I just learned about `numpy.flipud()`, not sure how it compares to the performance of `arr[::-1]`
Comment: Thanks @MadPhysicist (by the way, on github, click the line number and then copy the link to get: https://github.com/numpy/numpy/blob/master/numpy/lib/twodim_base.py#L85)
Answer: reversed_arr = arr[::-1]

gives a reversed view into the original array arr.  Any changes made to the original array arr will also be immediately visible in reversed_arr. The underlying data buffers for arr and reversed_arr are shared, so creating this view is always instantaneous, and does not require any additional memory allocation or copying for the array contents.
See also, this discussion on NumPy views: How do I create a view onto a NumPy array?

Possible solutions to performance problems regarding views
Are you re-creating the view more often than you need to?  You should be able to do something like this:
arr = np.array(some_sequence)
reversed_arr = arr[::-1]

do_something(arr)
look_at(reversed_arr)
do_something_else(arr)
look_at(reversed_arr)

I'm not a numpy expert, but this seems like it would be the fastest way to do things in numpy.  If this is what you are already doing, I don't think you can improve on it.
Comment: Actually I just tested it and don't see any difference with the slice object created outside of the loop.  (Oh wait, it's very slightly faster.  Repeatably 43.4 ms vs 44.3 ms for a 1000000 loop)
Comment: What is `look_at` function suppose to do?
Comment: @mrgloom It is supposed to represent any task that looks at the data.  The point of the example was to show that the view `reversed_arr` is still usable after the underlying data was changed.  Writing new values into the array does not invalidate the view.  Actually you could also use the view for writing new values into the array.  `reversed_arr[0] = 99` would set the last element in the array to 99, the same as `arr[-1] = 99` would.
Comment: Does it help to create a slice object and then reuse it on many arrays?
Comment: Interestingly, though, using a view seems to cause scipy's `lombscargle` function to fail in some previous (but recent, in my case 1.8.1) versions. E.g., `pgram = signal.lombscargle(x[::-1], y, w)` gives an error: `TypeError: Invalid call to pythranized function \`_lombscargle(float64[:] (is a view), float64[:], float64[:])'`. This is a bug that should be solved in newer versions, though: [Github issue](https://github.com/scipy/scipy/issues/15964).
Answer: a[::-1]

only creates a view, so it's a constant-time operation (and as such doesn't take longer as the array grows). If you need the array to be contiguous (for example because you're performing many vector operations with it), ascontiguousarray is about as fast as flipud/fliplr:

Code to generate the plot:
import numpy
import perfplot

perfplot.show(
    setup=lambda n: numpy.random.randint(0, 1000, n),
    kernels=[
        lambda a: a[::-1],
        lambda a: numpy.ascontiguousarray(a[::-1]),
        lambda a: numpy.fliplr([a])[0],
    ],
    labels=["a[::-1]", "ascontiguousarray(a[::-1])", "fliplr"],
    n_range=[2 ** k for k in range(25)],
    xlabel="len(a)",
)

Comment: perfplot requires at least Python 3.6 because it uses f-strings (Literal String Interpolation)
Answer: Because this seems to not be marked as answered yet... The Answer of Thomas Arildsen should be the proper one: just use
np.flipud(your_array)

if it is a 1d array (column array).
With matrizes do
fliplr(matrix)

if you want to reverse rows and flipud(matrix) if you want to flip columns. No need for making your 1d column array a 2dimensional row array (matrix with one None layer) and then flipping it.
Answer: np.fliplr() flips the array left to right.
Note that for 1d arrays, you need to trick it a bit:
arr1d = np.array(some_sequence)
reversed_arr = np.fliplr([arr1d])[0]

Comment: `reversed_arr = np.flipud(arr1d)` seems to work directly.
Comment: A 1D array is deemed one column, not one row, therefore [np.flipud](https://numpy.org/doc/stable/reference/generated/numpy.flipud.html) (up-down) is to be used, not [fliplr](https://numpy.org/doc/stable/reference/generated/numpy.fliplr.html#numpy.fliplr) (left-right).
Answer: I will expand on the earlier answer about np.fliplr(). Here is some code that demonstrates constructing a 1d array, transforming it into a 2d array, flipping it, then converting back into a 1d array. time.clock() will be used to keep time, which is presented in terms of seconds.
import time
import numpy as np

start = time.clock()
x = np.array(range(3))
#transform to 2d
x = np.atleast_2d(x)
#flip array
x = np.fliplr(x)
#take first (and only) element
x = x[0]
#print x
end = time.clock()
print end-start

With print statement uncommented:
[2 1 0]
0.00203907123594

With print statement commented out:
5.59799927506e-05

So, in terms of efficiency, I think that's decent. For those of you that love to do it in one line, here is that form.
np.fliplr(np.atleast_2d(np.array(range(3))))[0]

Comment: Timing something with such a small array is pretty useless. If you want to compare things it'd be better to use something that takes a while, like 3000 or maybe even more elements.
Answer: The slice notation based analog to np.flip would be [::-1,::-1]
a = np.array([[1., 2.], [3., 4.], [5, 6]])
print(a)

out: [[1. 2.]
      [3. 4.]
      [5. 6.]]

b=a[::-1,::-1]
print(b)

out: [[1. 2.]
      [3. 4.]
      [5. 6.]]

Answer: Expanding on what others have said I will give a short example.
If you have a 1D array ...
>>> import numpy as np
>>> x = np.arange(4) # array([0, 1, 2, 3])
>>> x[::-1] # returns a view
Out[1]:
array([3, 2, 1, 0])

But if you are working with a 2D array ...
>>> x = np.arange(10).reshape(2, 5)
>>> x
Out[2]:
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])

>>> x[::-1] # returns a view:
Out[3]: array([[5, 6, 7, 8, 9],
               [0, 1, 2, 3, 4]])

This does not actually reverse the Matrix.
Should use np.flip to actually reverse the elements
>>> np.flip(x)
Out[4]: array([[9, 8, 7, 6, 5],
               [4, 3, 2, 1, 0]])

If you want to print the elements of a matrix one-by-one use flat along with flip
>>> for el in np.flip(x).flat:
>>>     print(el, end = ' ')
9 8 7 6 5 4 3 2 1 0

Comment: I think you could also use x [...,::-1] to create a reversed view of a multidimensional array without resorting to np.flip, as demonstrated here https://stackoverflow.com/questions/7416170/numpy-reverse-multidimensional-array
Answer: In order to have it working with negative numbers and a long list you can do the following:
b = numpy.flipud(numpy.array(a.split(),float))

Where flipud is for 1d arra


java.lang.IllegalArgumentException: API Key must not be empty

Question: I am trying to implement a google maps API on my android project (inside a basic activity named BasicMapActivity.java) however I keep getting an error saying my API Key must not be empty.
My Logcat says the error is on this line of the code
Places.initialize(BasicMapActivity.this, getString(R.string.google_maps_api));
Inside my AndroidManifest, I have the meta-data tag with my google maps API key as follows:
<meta-data android:name="com.google.android.geo.API_KEY" android:value="AIza*********************dNq4" />
which is enclosed inside the application tag.
Inside my strings.xml I have the string resource <string name="google_maps_api" />
which relates to my API key.
I seem to have done everything correctly so I'm not sure why I get this error. All help is appreciated.
Answer: <meta-data android:name="com.google.android.geo.API_KEY"
android:value="AIza*********************dNq4" />

I think you forgot to add api key
Strings.xml
<string name="google_maps_api">AIza*********************dNq4</string>


$_SERVER['SERVER_NAME'] returns nginx reverse proxy port/name

Question: I am running WordPress under the following configuration:
Varnish (Port 80) -> nginx (Port 8080)
This is all working great except when some plugin or other tries to get my server name using $_SERVER['SERVER_NAME']. When that happens, it is getting back _:8080 as my server name and port. This is what the nginx config has:
server {
listen 8080;
server_name _;

What I need it to return is domain.com but if I change the nginx config, obviously, it stops listening on the port it needs to be (8080) (but changing the server_name works fine).
How can I have nginx listen on 8080 but have $_SERVER['SERVER_NAME'] return the correct port (or rather, not append the wrong port)?
Answer: _:8080 is the correct value for $_SERVER['SERVER_NAME'] in this configuration. It's explicitly defined to return the value of server_name. From the documentation:

The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.

It sounds like you are looking for $_SERVER['HTTP_HOST']. Note that you also need to have not configured Varnish to alter the Host: request header.
Comment: Well, you can't control them directly, but if they're trying to look at SERVER_NAME then that's a pretty serious bug. Plugins should call `get_site_url()` to find the site URL, and parse it if necessary. You can always report bugs. You can't guarantee a developer will fix bugs, though...
Comment: I agree... but I can't control what plugin developers are using to get my server name. Which is why I am looking for a work-around to set it to what they are looking for. I'll check into what we are or are not doing with Host in varnish. Thanks!
Comment: And that's exactly what they did! I am updating the site now to test it out.
Answer: You can override the default value of $_SERVER['SERVER_NAME'] by adding a fastcgi_param directive after the include fastcgi_params; statement.
For example:
location ~ \.php$ {
    include fastcgi_params;
    fastcgi_param  SERVER_NAME  $http_host;
    ...
}

The value defined in the include file will be silently overwritten with the value of $http_host.
Comment: Excellent! I'll try this for the other plugin that does this (see below, one of the devs already updated their code)!
Comment: Keep in mind that this might not fix a broken plugin that is inappropriately depending on SERVER_NAME. For instance, this value will never have anything useful on a WP multisite subdomain install. The developer will still need to fix the bug in that case.


How db_set_active works with other db?

Question: Is db_set_active() need to work with a Drupal database or can I use it with a database that doesn't contain any drupal tables ?
Comment: It's not a duplicate question. Here I asked about "how it's work" not about "how to use it". The nuance is important to use it properly.
Answer: db_set_active() is used for connecting to another database. The other database does not need to be Drupal at all.
Just don't forget to switch back to default DB when you are done. If you don't, Drupal will try to perform all subsequent queries in the other database, which will result in a lot of errors and potentially mess up the data in the other database.
Here's example code:
// Connect to your other database.
db_set_active('your_other_db');
// Run any queries you want.
db_query("...");
// Switch back to the default database of your installation.
db_set_active();

You can read more about db_set_active() here.
Another note, per Neograph734's reminder: the argument you would pass to the db_set_active() needs to be the same key you used for adding another DB access info in settings.php file.
Here's an example:
$databases = array (
  'default' => array (
    'default' => array (
      'database' => 'your_default_database',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'your_other_db' => array (
    'default' => array (
      'database' => 'your_other_database',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Comment: Thank you, your first sentence answers the question because in the documentation never talks about database format :)

How db_set_active works with other db?


Uncaught TypeError: $(...).lightGallery(...).destroy is not a function

Question: I am using the light gallery plugin fro my website , while running the
 $('#categoryImages').lightGallery().destroy(true);
I getting the console error

Uncaught TypeError: $(...).lightGallery(...).destroy is not a function

the below mentioned code snippet is my website code which am using for light gallery.
    $subcategory) { $subcategoryImage= scandir($dir.strtolower($getCategory)."/".$subcategory); unset($subcategoryImage[array_search('.', $subcategoryImage, true)]); unset($subcategoryImage[array_search('..', $subcategoryImage, true)]); foreach ($subcategoryImage as $key => $value2) { $data['subcategoryImages'][]= $dir.strtolower($getCategory)."/".$subcategory."/".$value2;?>

Jquery code
$('body').on('click', '.category', function() {
    $('#categoryImages').lightGallery().destroy(true);
});

Comment: see my answer below
Comment: Does this answer your question? [TypeError: $(...).lightGallery(...).destroy is not a function](https://stackoverflow.com/questions/32650578/typeerror-lightgallery-destroy-is-not-a-function)
Answer: As the documentation it should be like that : http://sachinchoolur.github.io/lightGallery/docs/api.html#methods
var cI = $('#categoryImages');
cI.lightGallery();
$('body').on('click', '.category', function() {
    cI.data('lightGallery').destroy(true);
});

Update fiddle : http://jsfiddle.net/n5w7eoxh/11/
Comment: Thanks for your reply , I have used which you shared "Uncaught TypeError: gal.destroy is not a function"
Comment: Please submit your full code in fiddle, maybe i can help you
Comment: Hi Jagjeet Singh: Thanks for your reply. I have used the light gallery for my website, initial page load its working fine, on click multiple checkbox using ajax am fetching the images related to the category. If I selected more than one category the light gallery is not working. But its not displaying any errors in the console.
Comment: Don't submit your code here, please provide fiddle http://jsfiddle.net/
Comment: Hi Jagjeet Singh: jsfiddle.net/gireesht14/n5w7eoxh this link will open my code but its related to dyanamic php code included
Comment: Yes but where are you try to use destroy method
Comment: Updated, check my answer
Comment: Hi Jagjeet Singh: this below code is working fine for me . Thanks for your help

var gal = $('#categoryImages');
gal.lightGallery();
/...
request.done(function(data) {
//...
$('.ajxcategoryImages').html(subcategoryImages1); //append the results
  gal.data('lightGallery').destroy(true);//destroy the current gallery
  gal.lightGallery();//create a new one
/..
Answer: You need to save a reference to your initialized plugin and then call destroy on that after the ajax is complete, after you call destroy you reinitialize the plugin
var gal = $('#categoryImages');
gal.lightGallery();
/...
request.done(function(data) {
//...
$('.ajxcategoryImages').html(subcategoryImages1); //append the results
  gal.data('lightGallery').destroy(true);//destroy the current gallery
  gal.lightGallery();//create a new one
/..


Advice as to what voice or in which section I should sing in choir

Question: Need help!
So I am a male of 25. My tessitura sits comfortably at F3 - G5. My voice sits quite high and light (meaning I cannot sing the normal tenor line with the tenors; however my voice can comfortably blend in with the alto and soprano sections).
My voice also blends well if in a trio with two girls (soprano and alto) I sing the countertenor/high tenor melody. In an all male ensemble I naturally sing either the same higher tenor line (I still havent figured it out). In a trio with a male and a female (tenor and alto) I normally sing the soprano line.
My lows
(E3) F3 - C4: decent at my age now as my voice has matured, yet not fully dropped the normal octave, but I sit well in the range.
My middle
C4 - D5: I consider this part of my voice my normal voice. In this range my voice is strong and balanced.
My mid-highs
D5 - G5: my voice blossoms as I have found my chest voice. I didnt have it a few years ago as I heavily leaned towards a more heady sound; I have since found my chest/mixed voice.
Head or falsetto?
E5 - Bb5: when the choral music appeals to me and I sing the soprano line, going beyond that my voice just stops. I take it as my limit, but I know I can reach higher with the right training.
Any advice as to where I should sing and maybe tips to break through to my limit?
Thank you in advance
Comment: The answer depends on what you like singing, what the ensemble needs in that moment, and what the piece is. It is not uncommon to switch too. There is no reason to pigeonhole yourself.
Answer: Note that "what voice type am I?" questions are a tad bit to specific for this site (it is of little use a different person to know what your exact type is). In this case this question is a bit different, and might be phrased as such. In your case your voice type is a rounded mezzo as a male. These things happen, in German there is the term perverse permutation (so perverted permutation (= voice breaking)) for this.
Basically as a male due to Testosterone you'll grow a differently shaped larynx with longer vocal cords, meaning a lower voice. In ancient times you had castrati, where boys would be castrated to inhibit Testosterone so that the voice keeps high. Now, occasionally it happens that a males larynx develops more as a female one, and the other way round.
So essentially you are a male with a more female-like larynx ant thus with a high voice. And as long as you feel comfortable doing so and the voice blends well there is no reason you should not sing Soprano II or Alto I in choir.
Comment: "as long as you feel comfortable doing so and the voice blends well": this the critical point.  People often fail to take this into account, especially young singers.  Range is only a small part of the story, perhaps the smallest.
Answer:
tips to break through to my limit?

If you're serious about it, find an experienced teacher.
Keep in mind that being able to sing A5 doesn't mean that you should be singing soprano parts, however.  Have a look at He shall feed his flock from Messiah, which opens with the alto soloist, after which the soprano sings the same tune a fourth higher.  What's comfortable?  From your description, I suppose it's the first section.
A baritone who can squeeze out an A4 won't be comfortable singing tenor and won't sound much like a tenor while trying.  A soprano with a nice C4 will not likely have much volume down there and will tire quickly trying to sing alto -- adult women tend to dislike singing even boy soprano parts.
Mozart's Figaro sings Non più andrai, which ranges from C3 to F4; the tenor part of the Hostias from Mozart's Requiem ranges from F3 to F4.  Should baritones be singing it?  Generally not.  What's the difference?  Non più andrai spends most of its time below G3, with only occasional forays above C4.  The Hostias tenor part spends almost all of its time above B♭3.
If you're not comfortable singing tenor, sing alto.  Work on your technique and see where it takes you.  If you become comfortable singing soprano -- or tenor -- great.  If not, go that's great too.  There's no point in having an unusually large range if you're uncomfortable, much less if your audience is uncomfortable.


Angular 2 - cannot get base class instance with ViewChild nor ContentChild

Question: answer:

dont use exportAs
use @ViewChild('myContent') myContent; to get the instance of the parent class
it will only work if the view is initialized, so better use ngAfterViewInit

this concerns inheritance !
base class (component)
    |
inherited class (component)

I have a base class component exported with exportAs
@Component({
    selector: 'my-content',
    exportAs: 'myContent',
    ...
})

the inherited class component uses a reference to the base class template
in its own template
<my-content #myContent>
  ...

in the inherited component's code I try to get its instance
@ViewChild('myContent') myContent;

or
@ContentChild('myContent') myContent;

some say this should work but myContent is alway undefined
how do I solve this ?
thanks
Comment: Can you reproduce in Plunker?
Answer: To get the instance of the child component within the parent template you can use the Component class directly, without any references, like so
@ViewChild(MyComponentClass) myContent;

Where MyComponentClass is the exported name of the child component class.
As a side note, make sure that you are referenceing the myComponent variable after the views have been checked / initialized (using ngAfterViewInit) rather than on ngOnInit, since during the init stage, the child components would not have been created yet.
Here's a working plunkr :
https://plnkr.co/edit/Q53I4EIDOL0ZrUEo2jRN?p=preview
Comment: it's the other way around, I want to call the parent function from the child
Comment: I tried with ngAfterViewInit instead of ngOnInit but still the reference in undefined
Comment: Fixed your plunkr to work.  Changed ContentChild to ViewChild, and removed the exportAs decleration.
Answer: @ViewChild(MyParentComponent) myParent:  MyParentComponent
you can instance the Parent Component like this.myParent
plunker:
import { Component, ViewChild } from '@angular/core';

@Component({...})

export class InheritedComponent extends BaseClassComponent {

    @ViewChild(BaseClassComponent) myBaseclass: BaseClassComponent;

    doSomeOperations()
    {
        this.myBaseclass.toggle();
        console.log(this.visible);
    }

}

Comment: then why calling the variable myChild ? it should be myParent or something.I tried your solution, it does not work
Comment: still the reference in undefined  ?
Comment: I'm getting True in console. UPDATED
Comment: you should get FALSE

I already tried that, does not work it gives UNDEFINED for the baseClass variable..

I updated the plunker https://plnkr.co/edit/jjN9An8G2QKzqFqk3dnp?p=preview you can see for yourself

I tried in Chrome and Firefox


Taxonomy term view with number of items for parent and child terms

Question: For my shop, I need a taxonomy tree view with 2 levels, the number of items should be shown in brackets for every parent and child term.
My problem: it works for the child terms, but not for their parents.
This should my view look like:
parent-term-1 (15)
- term-1.1 (7)
- term-1.2 (8)
parent-term-2 (15)
- term-2.1 (6)
- term-2.2 (9)
But it looks like this:
parent-term-1 (0)
- term-1.1 (7)
- term-1.2 (8)
parent-term-2 (0)
- term-2.1 (6)
- term-2.2 (9)
My view
Vocabulary Name = Category
Relationships
Taxonomy Term: Parent term (Identifier = Parent)
Taxonomy Term: Content with term (Identifier = node)
Use aggregation: Yes
Fields
Taxonomy Term: Term ID (Exclude from display)
(Parent) Taxonomy Term: Term ID (Exclude from display)
Taxonomy Term: Name
(node) COUNT (Content: Nid)
Filter criteria
Taxonomy vocabulary: Machine Name=(Category)
Format
Format: Tree (Main field: 1st Term ID, Parent Field: 2nd Term ID)
Field Settings: 3rd + 4th field inline
Any ideas?
Answer: I now have worked out a solution. You need to implement the taxonomy edge module. With that you can define a new relationship: Taxonomy term: child term. After that it's possible not only to count the number of nodes tagged with one term, but also the number of nodes tagged with the child terms of this term.
My nodes are always tagged with terms from the deepest level. So I have to consider the number of nodes tagged with the considered term OR the number of nodes tagged with the childs terms of the considered term (if available).
Completing my initial post, I add two relationships:
Taxonomy term: Child terms (Identifier = Childs)
(Childs)Taxonomy Term: Content with term (Identifier = node_childs)

I further add one field:
(node_childs) COUNT (Content: Nid)

In the field settings, i set these fields inline:

Taxonomy Term: Name
(node) COUNT (Content: Nid)
(node_childs) COUNT (Content: Nid)

The field (node) COUNT (Content: Nid) is excluded from display.
In the field (node_childs) COUNT (Content: Nid) I set the No-results-behavior to the token [nid].
The effect is that either the considered term has child-terms, then the number of nodes tagged with the child terms is counted. Or the considered term has no childs, than the number of nodes tagged with the considered term is counted.
Comment: I'm trying to follow the steps from your answer but can't get the (Childs) relationship in the step you added those two relationships, it just dislpays the parent relationship, how can I get that (Childs) relationship? (I know (Childs) is just your identifier, I set this as well, but it doesn't work for me).


Limsup on boundary implies bound on modulus

Question: I am working on the following problem:

Suppose $f$ is analytic on a bounded domain U and that
$$\limsup_{U\ni z\to w} |f(z)| \leq K \quad (\dagger)$$
for each $w \in \partial U$. Show that $|f(z)| \leq K$ for each $z \in U$.

I came up with the following: Let $L>K$ and consider $V = \{z \in U : |f(z)| >L\}$. Then, since $V \subseteq U$, so $\bar{V} \subseteq \bar{U}$. But suppose that $w \in \bar{V} \cap \bar{U}$, then $\exists (z_n)_{n=1}^{\infty} \in V$ such that $(z_n)_{n=1}^{\infty} \to w$, implying $\forall \epsilon > 0 \> \exists y \in B_{\epsilon}(w)$ such that $f(y) \geq L>K$, contradicting the assumption $(\dagger)$, implying $\bar{V} \cap \bar{U} = \emptyset$, thus $\bar{V} \subseteq U$.
Since $f$ analytic, so continuous, $V$ open. Let $W$ be a connected component of $V$.  Then $f(\partial W)=L < f(z)$ for any $z \in W$, contradicting the maximum modulus principle.
My questions are: Is my proof correct? The exercise also provides the following hint:

Show that $\bar{V}$ is a compact subset of $U$.

Which I believe follows from the fact that $\bar{V} \subseteq U$ and that $\bar{V}$ is compact in $\mathbb{C}$. This would imply that $f$ achieves its exterma on $\bar{V}$, but I am not sure how to finish this line of argument. Could someone help with finishing this argument?
Comment: Looks good to me! Maybe the author had in mind the same proof as you but in a different order. I.e., notice that there is an extremum at some point $x_0 \in \overline{V}$ first then let $W$ be a connected component of $V$ such that $x_0 \in \overline{W}$. By the maximum principle, we must have $x_0 \in \partial W$. But, as you noted, this is impossible since for all $z\in W$ we have $f(z) > L = f(\partial W)$.
Answer: In the light of @Quoka's comment, I will finish the proof using the compactness of $\bar{V}$.
Since $\bar{V} \subseteq U$ and is a closed, bounded subset of $\mathbb{C}$, thus it is a compact subset of $U$. Further, since $f$ is analytic, so continuous on $U$, $f$ achieves its maximum on $\bar{V}$, say at a point $z_0 \in \bar{V}$ - i.e. $f(z_0) > L$. Let $W$ be a connected component of $V$, such that $z_0 \in \bar{W}$. Then by the maximum modulus principle $z_0 \in \partial W$, but as noted in the original post, $f(\partial W)=L$, contradicting $f(z_0) >L$.


when appending the  text as html, it's not load into the DOM

Question: I am trying to append the html in the DOM using innerHTML method. When </> content was inside the string html content which i want to append in DOM, It will not load in DOM. it's automatically removed.
ex:
   document.getElementById("container").innerHTML = "
</>
";

   console.log(document.getElementById("container").innerHTML);

   result:  "

"

I don't know why. Can anyone clarify this for me please.?
Thanks in advance.!
Comment: Because `` isn't valid HTML? (At least that's my understanding... please correct me if I'm wrong)
Comment: What are you trying to achieve by using ``?
Comment: I think your problem might be because you're trying to put `` inside a ``. If you put other text instead of `` then your code should work, as long as you don't have any other syntax errors.
Comment: Does this answer your question? [How to display HTML tags as plain text](https://stackoverflow.com/questions/6817262/how-to-display-html-tags-as-plain-text)
Comment: If you just want to put `` into the container, you could just do -> `innerText = ''`
Comment: What purpose would it serve to have it in there? A DOM node has children for which the docs say "Child nodes include elements, text and comments" ([source](https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes)). Trying to add `` apparently resolves to neither of those three, and it seems to get discarded instead.
Answer: To print </> as text inside HTML, use the respective HTML codes.
< = < and > = >:

document.getElementById("container").innerHTML = "
</>
";
console.log(_.escape('</>'));

Common libraries like underscore/lodash has _.escape method that'll do the conversion for you. See comment by @Keith below for a custom implementation.
Comment: For people that wanna know: `lt` means `lesser than` and `gt` means `greater than`
Comment: If you want to do the escape the html in code, you can use the DOM to do it for you..  eg.  `const escHtml = s => { const a = document.createElement('div'); a.innerText = s; return a.innerHTML; }`
Comment: @Reyno it's `less than` https://stackoverflow.com/questions/5068951/what-do-lt-and-gt-stand-for  https://ell.stackexchange.com/a/821/55055


Does Windows XP connection limit apply to Sql Server connections?

Question: I have installed Sql Server 2005 on Windows XP acting as server in a small workgroup. Since XP has as limit of 10 computers connecting at the same time, my question is, does this limit also apply to concurrent connections over TCP/IP to the Sql Server? Or does this limit only apply to connections to shares, printers and so on?
Answer: This article states maximum of 10 connections.

For Windows XP Professional, the maximum number of other computers that are permitted to simultaneously connect over the network is ten. This limit includes all transports and resource sharing protocols combined. For Windows XP Home Edition, the maximum number of other computers that are permitted to simultaneously connect over the network is five. This limit is the number of simultaneous sessions from other computers the system is permitted to host

Although

The connection limit refers to the number of redirector-based connections and is enforced for any file, print, named pipe, or mail slot session. The TCP connection limit is not enforced, but it may be bound by legal agreement to not permit more than 10 client

These people seem to have copied or created a tcpip driver that enables up to 50 connections.
It is not clear to me if they took TCPIP.SYS from another microsoft operating system or if they somehow wrote their own.
Comment: In other words: yes the limit applies, but it won't be enforced and will probably work anyway?
Comment: That is my impression.


Stata error: "panels are not nested within clusters"

Question: I have an unbalanced panel data set with more than 400,000 observations over 20 years. My panel variable is a person id and my time series variable is the year. The persons are from all over Germany which means that they are from different regions. To account for possible correlations between the persons within the same regions, I would like use clustered standard errors in my fixed effects regression. The Stata code looks like this:
xtreg depvar var1 var2 ... varN if year > 1990, fe vce(cluster clustvar)

First, I used the variable "region" which is a numeric variable indicating in which region the observation (person) lives as the cluster variable (clustvar). Of course, I got the error "panels are not nested within clusters" because I forgot that people move across regions such that they appear in more than a single region. To fix this problem, I wanted to use a region-year variable which is a numeric variable indicating the year as well as the region. To visualize the variable, the follwing extract from my dataset including the variable "region-year" may help:
region year region-year
1      1991 2000
1      1992 3000
2      1991 2500
2      1992 3500
2      1993 4500

Note that this extract does not contain the person id. The values of "region-year" are chosen arbitrarily in this example. In my opinion, it is just important that all observations belonging to the same region in the same year have the same number no matter how this number looks like. Am I right?
Running the regression
xtreg depvar var1 var2 ... varN if year > 1990, fe vce(cluster region-year)

also causes the error "panels are not nested within clusters". But I don't know why.
Comment: The clustering should not be on region-year pairs since, for example, the error for Bavaria in 2014 is presumably correlated with the error for Bavaria in 2013.
Answer: Question 1:

In my opinion, it is just important that all observations belonging to the same region in the same year have the same number no matter how this number looks like. Am I right?
Answer: No.
Question 2.  The error message.
It's very easy to think of a likely data configuration that would generate the error message. Consider the following data extract for one individual (panel)
id  region year  cluster
 1     1    2000   1
 1     1    2001   2

Here id = 1 is observed in more than one year but stays in the same region. If so, the panel for  id =1 will span two years, meaning two different "clusters". You can't escape the error.
There are apparently no natural clusters that would justify use of vce(cluster) for your problem. Moreover, there's no reason to use that option, as  good alternatives are available: vce(jackknife), vce(bootstrap), and vce(robust).  For most calculations, each panel is considered a cluster.  See also the contributed command ivreg2 for Stata, which is available on SSC.


magento cleaning my category to 2000 products

Question: After updating my category or subcategory products disappearing from it. Strange because always are just 2000 products left. Cache, indexing not helping. If this make more sense actually category disappearing from product.
Comment: please provide a little more information, such as your code or the tables
Comment: can you please tell me which table and for which part of code from where thanks
Answer: Open your logs, there is a PHP error about max_input_vars.