Como chamar um método de uma classe em outra classe

Question: Havia postado mais cedo mas não consegui editar, tentarei ser mais clara dessa vez. Estou fazendo (tentando)um code pra conta telefonica. Tenho a classe tempo, ligação e contadaligacao. na classe conta ligacao eu chamo um campo tipo tempo(classe) para converter o tempo em minutos e exibi-lo chamando da classe tempo um construtor.Tenho também na classe ligação um outro campo que retorna o valor do minuto. O que eu gostaria de fazer é chamar tanto o método que me retorna o valor, quando o que retorna os minutos, para dentro da classe condadaligacao. A questão, é que não estou conseguindo chamar essas funções, e como sou iniciante nem ao menos sei o que estou fazendo de errado.
Seguem abaixo minhas classes:
public class Ligacao
{
    private String nrOrigem, localOrig, nrDest, localDest;
    private float valor;
    private Tempo inicio, termino;

    public Ligacao(String nrOrigem, String localOrig, String nrDest, String localDest, float valor, Tempo inicio, Tempo termino){
    this.nrOrigem=nrOrigem;
    this.localOrig=localOrig;
    this.nrDest=nrDest;
    this.localDest=localDest;
    this.valor=valor;
    this.inicio=inicio;
    this.termino=termino;
   }

   public String getnrOrigem(){
    return nrOrigem;
    }
   public void setnrOrigem(String numOrigem){
       this.nrOrigem=numOrigem;
    }

   public String getlocalOrig(){
   return localOrig;
    }
   public void setlocalOrig(String localOrigem){
   this.localOrig=localOrigem;
   }
   public String getnrDest(){
    return nrDest;
    }
   public void setnrDest(String numDest){
    this.nrDest=numDest;
    }
   public String getlocalDest(){
    return localDest;
    }
    public void setlocalDest(String localDest){
    this.localDest=localDest;
    }

    public float getvalor(){
    return valor;
    }
    public void setvalor(float valor){
        this.valor=valor;
    }
    public Tempo getinicio(){
        return inicio;
    }
    public Tempo gettermino(){
        return termino;
    }
    public int calcularDuracao(){
        int inicioSeg,terminoSeg,durSeg,durMin,resto;

        inicioSeg=inicio.tempoEmSegundos();
        terminoSeg=termino.tempoEmSegundos();

        durSeg=terminoSeg-inicioSeg;
        durMin=durSeg/60;
        resto=durSeg%2;
        if(resto>0){
            durMin++;
        }
        return durMin;
    }

    public boolean verificaNumero(String numero){
        return ((nrOrigem.equals(numero))||(nrDest.equals(numero)));

    }

}

public class Tempo
{
   private int hora, minuto, segundo;
   private float tempoTotal;

  public Tempo (int hora, int minuto, int segundo){
      this.hora=hora;
      this.minuto=minuto;
      this.segundo=segundo;
    }
    public int tempoEmSegundos(){
        return hora*3600 + minuto *60 + segundo;
    }
   public int gethora(){
    return this.hora;
    }
   public void sethora(int hora){
    this.hora = hora;
    }
    public int getminuto(){
    return this.minuto;
    }
    public void setminuto(int minuto){
    this.minuto=minuto;
    }
    public int getsegundo(){
    return this.segundo;
    }
    public void setsegundo(int segundo){
        this.segundo=segundo;
    }

}

public class ContaTel
{
    private int mes, ano, contrato;
    private Ligacao[] listaligacoes;
    private Tempo inicio,termino;

    public ContaTel(int mes,int ano, int contrato, int tamanho){
    this.mes=mes;
    this.ano=ano;
    this.contrato=contrato;
    this.listaligacoes = new Ligacao[tamanho];

    }
    public void setmes(int mes){
    this.mes= mes;
    }
    public int getmes(){
    return mes;
    }
    public void setano(int ano){
    this.ano = ano;

    }
    public int getano(){
    return ano;
    }
    public void setcontrato(int contrato){
    this.contrato = contrato;
    }
    public int getcontrato(){
    return contrato;
    }
    public Ligacao[] getlistaligacoes(){
    return this.listaligacoes;
    }
    public void addligacao(Ligacao lig){
        int i=0;
         for(i=0;i<listaligacoes.length;i++){
            if (listaligacoes[i]==null){
                listaligacoes[i]=lig;
                break;
            }
            else {
                break;
            }
        }
    }

Não quero a resposta, quero aprender, fiquei o dia todo nisso.
Answer: Você tem a lista (vetor) de tudo dentro da ContaTel. Para você acessar essas funções você precisa primeiro acessar cada elemento da Ligacao[].
public class ContaTel
{
    private int mes, ano, contrato;
    private Ligacao[] listaligacoes;
    private Tempo inicio,termino; // Desnecessário esses atributos

    ...

    public void doItAnywway(){

        for(int i = 0; i < listaligacoes.lenght; i++){

            Ligacao ligacao = listaligacoes[i]; // peguei um elemento
            Tempo t1 = ligacao.getinicio(); // peguei o Tempo deste elemento
            Tempo t2 = ligacao.gettermino(); // peguei o outro tempo deste elemento

            /**
            * Agora eu posso acessar todas as funções que eu precisar!!!!
            * VIVAAA!!!!
            */

            t1.tempoEmSegundos(); // usei essa!
            t1.gethora(); // peguei a hora!

            ligacao.calcularDuracao(); // essa parece boa!
            ligacao.getlocalDest(); // preciso ver para onde esse povo ligou!!!

        }

    }

    ...

Sei que você ainda está aprendendo mas precisa dar uma melhorada nessa modelagem sua.
Espero ter ajudado.
Comment: Com modelagem vc diz a identação do código? se sim, onde eu posso ver mais sobre a padronização? E muito obrigada pela resposta!
Comment: @MarcelaBraga modelagem, é o que você fez. Você criou uma classe `ContaTel` que poderia ter mais de uma ligação, e que a ligação dependia de um Tempo para existir. Você criou as "regras". Porém, tem uns buracos... Tipo... a classe ContaTel não tem porque ter o atributo Tempo. Esse Tempo faz parte da ligação e não da conta. Entendeu?
Comment: @MarcelaBraga pesquise sobre UML e diagrama de classes.
Comment: Certo, de todo modo, eu estou tentando e está me retornando uma excessão aqui:
    java.lang.NullPointerException
 at ContaTel.valorConta(ContaTel.java:52)
Comment: @MarcelaBraga ai já é outro problema! Mas você já consegue acessar as funções. Pesquise sobre esse erro no google.
Answer: Não consegui entender muito bem o que você quer fazer, mas como você falou que quer aprender vou tentar explicar de um jeito meio genérico. Tem dois meios de você chamar métodos de uma classe:
1 - Instanciado ela
Classe classe = new Classe();
classe.metodo(parametrosSeHouver);

2 - Tornando o método da classe estático
2.1 - Declarando um metodo estatico
public static String retornaString(String str){
return str;
}

2.2 - Chamando um método estático:
Classe.retornaString("Uma string qualquer");

--- edit
public int calculaValorLigacao() {
    return calcularDuracao() * 1;
}

Comment: Então, quero calcular o valor de uma ligação, a partir dos minutos. por exemplo, 200 minutosx1 real=200 reais. Não deve ter ficado muito claro, mas eu criei uma variável com o tipo da classe tempo, que recebe horas minutos e segundos, converte em minutos etc, e um método que armazena o valor da ligação. somente.
Comment: acho que entendi, veja a minha resposta atualizada, você já tinha na classe ligação um método que calculava a duração, então só criei um novo e multipliquei pelo valor do minuto


Why does a catcher throw to the third baseman after strikeout?

Question: I saw a baseball catcher throw to the third baseman after each strikeout.
Is there any particular reason for this?
Is it just a custom?
Answer: The catcher throws to third to give the fielders something to do after a strikeout (in which they had nothing to do).  See this article:

After a strikeout, it is common for catchers to throw the ball to third base. In any given baseball game there's a lot of standing around in the dugout. Throwing the ball around shakes things up for the fielders and helps keep them on their toes.
Throwing the ball to third also keeps the infielders' arms loose for throwing. The routine can even provide relief for the pitcher and give them a quick but much needed break. The catcher uses this routine throwing tactic to keep everyone on the same page in regards to the current number of outs.
Standing around can be very fatiguing, especially in the summer, but the catcher can regain players' focus and keep players mentally sharp. It's important every player is prepared for what is going to happen next, and it can be easy to lose train of thought when the game seems to be at a standstill.
The catcher almost only throws the ball to third base when there aren't any runners on base.
Chicago Cubs third baseman Kris Bryant says he thinks catchers throw the ball to third after a strikeout to allow the pitcher time to walk around the mount and refocus.

The word for this is throwing "around the horn":

Around the Horn

If a strikeout occurs and no one is on base, it's common to see the catcher throw the ball to either first base or third base. This starts the team throwing the ball around the infield, which is known as "around the horn." The ball will often go to the third baseman, second baseman, shortstop, then back to the third baseman. Sometimes, the ball goes from first base to shortstop, second base and third base. Almost always when you see a team go around the horn, the third baseman gets the ball last before giving the ball back to the pitcher. This is usually done to help keep the infielders warm and ready in case the next batter hits the ball to them.


Is there a good replacement for WCF UDP Discovery in ASP.NET Core?

Question: I am looking for UDP service discovery functionality in ASP.NET Core.  This functionality is available in .NET Framework WCF via System.ServiceModel.Discovery (e.g., UdpDiscoveryEndpoint that uses WS-Discovery).
The intended result is to allow clients on a LAN to discover an ASP.NET Core WebAPI without needing to know the server's name/IP and port.
I see some service discovery frameworks available like Consul, but they don't seem to support UDP broadcasts.
I could write my own using code similar to the solution in How to do Network discovery using UDP broadcast, but I have to question whether something better is available already.
Comment: You are aware udp without realys only works in VERY Limited scenarios. LAN is not even one - a LAN can do routing (and does in any sane larger company). This is one reason they fell out of use.
Comment: It's potentially coming in v3 https://github.com/dotnet/wcf/issues/211
Answer: Could be using Ocelot, http://ocelot.readthedocs.io/en/latest/features/servicediscovery.html
An example of how this could potentially be implemented can be found here: https://www.c-sharpcorner.com/article/building-api-gateway-using-ocelot-in-asp-net-core-service-discoveryeureka/
Comment: It looks like Ocelot leverages Consul or Eureka.  Both of these solutions still require you to know the host name of the discovery registry server.  I was looking for a way to discover services without this piece of info.


Convergence of $\sum_{n=1}^{\infty}(-n)^{\lfloor\alpha\rfloor}\frac{\sin^3\left(\frac{1}{n}\right)}{\left(\log(n)\right)^{\alpha-1}}$

Question: Convergence of the following series as $\alpha\in\mathbb{R}$
 $$\sum_{n=1}^{\infty}(-n)^{\lfloor\alpha\rfloor}\frac{\sin^3\left(\frac{1}{n}\right)}{\left(\log(n)\right)^{\alpha-1}}$$
As $n \to +\infty$ we have that $\frac{\sin^3\left(\frac{1}{n}\right)}{\left(\log(n)\right)^{\alpha-1}} = \mathcal{O}\left(\frac{1}{n^3\log^{\alpha-1}(n)}\right)$
How to handle $(-n)^{\lfloor\alpha\rfloor}$ with that result?
Comment: i think you should take two cases, for $\lfloor\alpha\rfloor$ to be odd or even
Comment: @F.inc Please recall that if the OP is solved you can evaluate to accept an answer among the given, more details [HERE](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)
Answer: Yes the key point is that
$$\frac{\sin^3\left(\frac{1}{n}\right)}{\left(\log(n)\right)^{\alpha-1}} \sim \frac{1}{n^3\log^{\alpha-1}n}$$
then we need to distinguish the cases, for example for $0\le \alpha <1$ we have $\lfloor\alpha \rfloor=0$ and then
$$(-n)^{\lfloor\alpha\rfloor}\frac{\sin^3\left(\frac{1}{n}\right)}{\left(\log(n)\right)^{\alpha-1}} \sim \frac{\log n}{n^3}$$
which converges by limit comparison test with $\sum \frac1{n^2}$.
And you can proceed similarly for the others values.


AngularJs resetar para option padrão com ngOption

Question: Ao acionar o metodo addAgent o item é adicionado mas a option selecionada continua e deveria voltar a ficar selecionado o option default.
Controller
$scope.addAgent = function (selectedAgent) {

    if (null == selectedAgent) {
        alert('Selecione um Agente para adicionar.');
        return;
    }

    $scope.agents.push(selectedAgent);
    //mesmo resetando aqui, o último option selecionado continua marcado
    $scope.selectedAgent = '';
};

View

Agentes
 <select class="form-control"
        ng-model="selectedAgent"
        ng-options="option as option.name
        group by option.type for option in availableAgents track by option.id">

<option value="" ng-selected="selectedAgent ==''">Selecione</option>

</select>

Exemplo Formato dos dados do ngOption

var availableAgents =  [
 {id:1, name:"aaaa", "type":"A"},
 {id:2, name:"aaaa2", "type":"A"},
 {id:3, name:"bbbb", "type":"B"},
];

Answer: Você declarou a variável $scope.agents como um Array?  Eu copiei seu código para o Plunker e a única alteração que eu fiz foi declarar a variável como um Array.
Controller:
angular.module('app', []).controller('appController', function($scope) {
  $scope.agents = [];
  $scope.availableAgents = [{
    id: 1,
    name: "aaaa",
    "type": "A"
  }, {
    id: 2,
    name: "aaaa2",
    "type": "A"
  }, {
    id: 3,
    name: "bbbb",
    "type": "B"
  }, ];

  $scope.addAgent = function(selectedAgent) {
    if (null == selectedAgent) {
      alert('Selecione um Agente para adicionar.');
      return;
    }

    $scope.agents.push(selectedAgent);
    //mesmo resetando aqui, o último option selecionado continua marcado
    $scope.selectedAgent = null;

  };

})

Html:
<select class="form-control"
        ng-model="selectedAgent"
        ng-options="option as option.name
        group by option.type for option in availableAgents track by option.id">

<option value="" ng-selected="selectedAgent ==''">Selecione</option>

</select>

Adicionar

Plunker
Comment: o seu plunker não está completo.
Comment: @CelsomTrindade testa agora. Obrigado por avisar.
Comment: Só para visualizar melhor o funcionamento https://plnkr.co/edit/eO3qJk0T4MZGFzBSddeL?p=preview mas realmente, se a solução era só adicionar o $scope.agents, perfeito =D


How can we know whether an arbitrary sentence corresponds to a sentence in the language of arithmetic or not?

Question: From what I came to understand from Godel's work is that a consistent effectively generated theory $T$ can have its consistency statement $Con(T)$ written in the language of $T$ itself! and that this wouldn't be provable in $T$ should $T$ be strong enough to formulate basic arithmetic. Now also I came to understand from this answer, that this statement being in the language of $T$ itself would be coded as a "natural number" which is of course the Godel number for that sentence. But at the same time there is an arithmetical sentence $Con(T)^{arith}$ that is TRUE in the standard model $\mathbb N$ of arithmetic! So we have $Con(T)$ being equivalent to the syntactical meta-theoretic statement $``T \text{ is consistent}"$ and also we have $Con(T)^{arith}$ being equivalent to that meta-theoretic consistency statement. This is a form of correspondence whereby a sentence is the language of $T$ corresponds to a sentence in the language of arithmetic, and not just to a term in that language.

Question: is there a general way to determine whether an arbitrarily given sentence $\phi$ in the language of $T$ corresponds to a sentence in the language of arithmetic or just correspond to some natural number?
Answer: It seems like you're a little confused about the way Gödel's proof works. Let me try to clarify this, which I hope will shed some light on the whole question:

If $T$ is an effectively generated first-order theory, then there is a sentence in the language of arithmetic, $\text{Con}(T)^{\text{arith}}$ (adopting your notation), expressing the consistency of $T$.
If $T$ is strong enough to formulate basic arithmetic - and let's be precise about this by assuming $T$ interprets PA, though this is stronger than what's actually required - then $\text{Con}(T)^{\text{arith}}$ can be translated into a sentence $\text{Con}(T)$ in the language of $T$.
If $T$ is consistent, then $T$ cannot prove $\text{Con}(T)$.

It's the second point that's most relevant to your question. The sense in which $\text{Con}(T)$ (as a sentence in the language of $T$) corresponds to a sentence in the language of arithmetic is no more or less than the fact that it's the translation of $\text{Con}(T)^{\text{arith}}$ via the interpretation of PA in $T$.
Taking this as the meaning of "corresponds to a sentence in the language of arithmetic", the answer to your question is yes: the question of whether a sentence of the language of $T$ corresponds to a sentence in the language of arithmetic is algorithmically decidable.
But it's really not very interesting. For most set theories $T$, the interpretation of PA in $T$ will amount to taking the domain to be $\omega$ and the arithmetic operations to be the usual ordinal arithmetic operations on $\omega$. Then a sentence in the language of $T$ is in the image of this interpretation just when it is built up from equations involving only the ordinal arithmetic operations, using Boolean connectives and quantifiers that are explicitly bounded to $\omega$. That is, if it obviously expresses a (first-order in the language of arithmetic) property of the natural numbers!


Como acessar nó filho no Firebase?

Question: Eu tenho a seguinte árvore no Firebase:
Como eu faço para acessar para poder listar os dados que estão dentro do nó "furos"?
Estou usando o seguinte método de listagem de dados:
public void recuperaFuros(){
    DatabaseReference furosRef = firebaseRef
            .child(idUsuario.toString())
            .child("vhykFsTJMhaCd6jkBd3oXpmYoiH2Thu Jan 10 22:54:24 GMT-02:00 2019")
             .child("furos")
            .child("Thu Jan 10 22:54:51 GMT-02:00 2019");

    furosRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            furos.clear();
            for(DataSnapshot ds: dataSnapshot.getChildren()){

                furos.add(ds.getValue(Furo.class));

                //System.out.println("PROJETO" + ds.getValue());
            }
            adapterFuros.notifyDataSetChanged();
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}

porém, meu retorno está sendo:
 Can't convert object of type java.lang.String to type geoapp.cursoandroid.com.geoapp.model.Furo

na linha
furos.add(ds.getValue(Furo.class));

Minhas regras estão assim:
{
  "rules": {
      ".read" : true,
      ".write" : true
    }
}

Answer: O que acontece é que,  no laço de repetição for, a cada iteração ele pega uma propriedade do objeto, então o valor de ds.getValue é o valor da propriedade alvoFuro, ou seja, "alv"
Tente remover a última chamada ao método child
//...
DatabaseReference furosRef = firebaseRef
        .child(idUsuario.toString())
        .child("vhykFsTJMhaCd6jkBd3oXpmYoiH2Thu Jan 10 22:54:24 GMT-02:00 2019")
         .child("furos");

furosRef.addValueEventListener(//...

Comment: O erro desapareceu, porém, meu recycler não trás os dados
Comment: Se eu apago a linha que dá erro e debugo com o System.out.println(ds.getValue) ele trás meus dados
Comment: Então esse problema foi resolvido e você pode aceitar a resposta. Faça outra pergunta se não conseguir resolver o outro problema!
Answer: Amigo, primeiramente você deve estruturar melhor o seu BD.
Ao invés de usar um Id seguido da hora da solicitação, tente a seguinte saida:
idUsuario
(idProjeto)
// Você vai setar com
myRef.child("Usuarios").child(user.getUid()).push().child("Timestamp").setValue(ServerValue.TIMESTAMP);
//Demais dados
O push fará que você tenha um ID único. E o timestamp logo abaxo, você substitui pela "dataHoraCadastro".
O timeStamp será um dado que você conseguirá converter facilmente quando necessário. Ao invés de tratar essa hora e data que você está utilizando. O TimeStamp te dá data completa, até os milisegundos.
//Dentro de furos, você fará a mesma coisa. Ao invez de ser a data completa como id, você pode usar o push() ou o timestamp.
myRef.child("Usuarios").child(user.getUid()).push().child("furos).child("Timestamp").setValue(ServerValue.TIMESTAMP);
//Demais DAdos
E para evitar redundância na parte "dataHoraCadastro", você pode usar no firebase, o datasnapsho.getKey(). (Que ao invés de pegar o dado, você terá acesso a chave, que seria seu Timestamp, ou data, se preferir manter).
public void recuperaFuros(){
    DatabaseReference furosRef = firebaseRef
            .child(idUsuario.toString())
            .child("vhykFsTJMhaCd6jkBd3oXpmYoiH2Thu Jan 10 22:54:24 GMT-02:00 2019")
             .child("furos")
            .child("Thu Jan 10 22:54:51 GMT-02:00 2019");

    furosRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            furos.clear();
           if(dataSnapshot.exist())`{
                furos.add(dataSnapshot.getValue(Furo.class));
}
                //System.out.println("PROJETO" + ds.getValue());
            }
            adapterFuros.notifyDataSetChanged();
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}

// Você está usando o forEach para pegar dados únicos. Se a classe estiver com as mesmas variáveis que estão no BD, elas serão atribuídas normalmente.

Como acessar nó filho no Firebase?


comma separated cck multivalues in a view

Question: I've created a cck field and called it authors so the machine name is field_authors. To print this field in a view template, i'm doing this - print $fields['field_authors_value']->content;
In case is there 2 or 3 values it prints each value on separate line, and i want something like author1, author2, author3. (comma separated)
Tried to do this way in template.php:
function mytheme_content_view_multiple_field($items, $field, $values) {
  $output = '';
  switch($field['field_name']) {
    case 'field_authors_value':
      $output .= '
'. implode(', ', $items) .'
';
      break;

    default:
      foreach ($items as $item) {
        if (!empty($item) || $item == '0') {
      $output .= '
'. $item .'
';
    }
      }
      break;
  }
  return $output;
}

but it has no effect. What im doing wrong?
Answer: Per the following on drupal.org:
http://drupal.org/node/1018198#comment-3993646

You can do this by copying "views-view-field.tpl.php" into your theme's directory, under
  a name the view will recognize it selectively. Put the following code in it:

print preg_replace('/<\/div>
]+>/i', ', ', $output);

In your case, I think it would be:

views-view-field--VIEWNAME--field_authors_value.tpl.php
Comment: Thanks that worked. But it is possible to do that a more Drupl way? :)


Why is this regret a good choice for a multi-armed bandit?

Question: The regret in a multi-arm bandit model is given by
$$\underset{j}{\max}\sum_{t=1}^{T}x_j(t) -G_{A}$$
where $$G_A=\sum_{t=1}^{T}x_{it}(t)$$ is the total reward achieved by the learner, based on an action $i$, taken at each time interval $t$, i.e $i_{t}\in {1,2,...,K}$ and $x_j(t)$ is the reward assosciated with action $j$, at time $t$ with $K$, being the total number of actions available.
In a stochastic multi-arm bandit setting where each arm is modeled by a population distribution:
a) What is the connection between the sequential decisions taken by a chosen learner that guarantees a minimization of the expectation of the above regret?
I ask this, as I do not see the expectation of the best arm being accounted for- directly in the given form of the regret. Instead, is there a bound that connects this regret to the population mean parameters?
I looked at the expected regret being $$\mathbb{E}\left[\underset{j}{\max}\sum_{t=1}^{T}x_j(t)\right]-\mathbb{E}G_A $$ and want to have a connection between the steps in any chosen multi-arm-bandit algorithm and the minimization of the expected regret. Is it done directly- or is it based on the minimization of say, an indirect upper bound?
Comment: Isn't the first term reflecting the best strategy, and therefore the best arm, over the period? To take the mean, you'd just multiple by 1/T, but you would need to multiply both terms by that to equivalize them. I'm not sure where you're stuck.
Comment: The probabilities are allocated to the actions at time t+1 based on the actions in 1...t by a chosen Reinforcement Learner. The connection between these sequential actions to a minimization of the above regret alludes me. To dig in further- the Exp3 method introduced in Auer, Bianchi, Yoav Freund and Rob Schapire's work has a sequential probability allocation mechanism at each time step t. They construct a bound over the expected regret. Exp3 does not make distributional assumptions. I am interested if there are such connections between a stochastic(parametric) technique to the expected regret
Comment: @PraneethVepakomma No need to mark this post as *edited* directly in the title; we have access to edit history (near your user badge) for that.
Answer: I have understood this far- recently-looking for the difference between
$\mathbb{E}[ \max_j \sum_{j=1}^T x_j(t) - G_A(T) ]$ and
$\max_j  \mathbb{E}[ \sum_{j=1}^T x_j(t) - G_A(T) ]$  obviously, the
first one is greater.
This is because $\mathbb{E}[\max_{j} Z_{j}] \ge \max_j \mathbb{E}[ Z_j ]$
Thus, if we prove that an algorithm controls the first "expected
regret" then it will obviously control the second one (control the
regret== To prove an upper bound for the regret).
Answer: As Michelle said, the first term is the utility of the omniscient learner, and the second term is the utility of your agent. Your goal is to devise a policy---a rule to select an action $i$ at time $t$---to minimize the difference, which we call the regret.
The crux of the problem is that you don't know the optimal arm at a particular time until you play it, and that's where the expectations come in. So the problem reduces to one of estimating the best arm at any moment based on the available information.
Comment: @PraneethVepakomma It is an old monograph and I don't know whether or not it formally addresses your issue but have you seen Don Berry's book "Bandit Problems"? I think it was published by Chapman and Hall.
Comment: Thanks for the pointer. I will search for this material.


Solve k in this ODE: mv′(t)=mg−kv^2(t)

Question: I have this question about finding the air resistance using the following differential equation:
<code>*mv′(t)=mg−k(v^2)(t)*
</code>
where m is the mass of the downward-falling object, gravitational acceleration is g= 9.82, and k is a constant which describes the air resistance.
According to the question, after many trials it was deduced that the constant fall speed is : 3.7√(m/A)m/s where m is mass in kg and A is the cross-section area in m^2.
So what is the value of k?
The only thing I know is that this equationis seprable but I am completely lost in this problem so any hint will be appreciated. Where should I start?
Thank you so much!
Comment: Hint: "*constant* fall speed"
Comment: Possible duplicate of [How to solve initial value problem $m\dot{v} = mg - kv^2$ for $v(t)$ when $v(0) = 0$](https://math.stackexchange.com/questions/1272173/how-to-solve-initial-value-problem-m-dotv-mg-kv2-for-vt-when-v0)
Answer: We first look at the stationeries states:
$v'(t)=0\Rightarrow k{v_0}^2=mg$. You can from here deduce $k$ since the constant fall speed $v_0$ is given.
Resolution: Now we put this expression into ODE. It comes:  $mdv=k({v_0}^2-v^2)dt\Rightarrow \frac{dv}{v^2-v_0^2}=-\frac{k}{m}dt$ then:
$$\int_{0}^{v}{\frac{dv}{v^2-v_0^2}}dv=\int_{0}^{\tau}{\frac{-k}{m}}dt$$ $\Rightarrow$
$$\frac{1}{v_0}arctanh {({\frac{v}{v_0}})}=\frac{k}{m}t$$ $\Rightarrow$ $$v=v_0\tanh(\frac{kv_0}{m}t)$$
Answer: As a general rule, don't try to solve a differential equation if you don't need to.
When the object is falling at its constant fall speed, its acceleration (by definition) is zero. You've been told $v$ and $g$. You now know $v'$. The only unknowns remaining in the question are $k$ and $m$. In principle, that's a problem if you're expecting a fixed number for $k$; the correct response to that issue is usually to just try to solve for $k$ in terms of $m$, and hope the $m$'s cancel out.
Comment: The m did cancel out and I got a value of k in terms of A. The next question is to solve the equation. I did solve it but I'm not sure of my answer as I got v'=-0.04. Is it possible to get the answer as a number, Isn't the answer of an ODE not a value but an equation?? Or did they mean to solve it without entering the value of k? Any Hints?? Thank alot!
Comment: The answer certainly shouldn't be a number; sometimes a value can be a correct answer to an ODE (if the solution is just a constant function) but not in this case. What concerns me particularly, though, is that your answer is about v' instead of v. Treat it the same way you would treat any separable differential equation; write v' as dv/dx, multiply both sides by dx, and then divide both sides by the part involving v. Note that that means dividing by (mg - kv^2).

Solve k in this ODE: mv′(t)=mg−kv^2(t)


Print a text if a view result is equal to a certain value

Question: In a template file, how can I use PHP to print some text if a view has a certain value?
The view uses the node ID, so I guess this argument needs to be passed to the view (as it would be if the view was embedded onto the page).
Here is my attempt:
<?php
  $view = views_get_view('hide_weight_2');
  if ($view->execute_display('default', $args) == 'Yes' ):
?>

Result of view was yes

<?php endif; ?>

Answer: If I understand well your question, I guess that you can make this in a rough way from a template View. Inside this template file you can add the respective conditional to show your text.
Here is the part of views-view-unformatted.tpl.php when each result is printed:
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes[$id]; ?>">
    <?php print $row; ?>

<?php endforeach; ?>

Then, you can parse $row to catch the respective value and print a message. You can use preg_match() to match the value For example, instead of <?php print $row; ?> you could use:
<?php
  if (preg_match("/(here text to match)/i", $row)) {
    print "Aha!:" . $row;
  }
  else {
    print $row;
  }
?>

I guess you can improve this seeking per target fields.


Nullable struct vs class

Question: I have a simple struct which contains two fields; one stores an object and the other stores a DateTime. I did this because I wanted to store objects in a Dictionary but with a DateTime stamp as well.
I've got a method which returns my structure, and I've now decided the method should also be able to return null, so I made my structure nullable. I'm now wondering if I should just make my structure a class so it's a reference type?
Answer: In this case, yes, it's probably clearer to make your structure a class.
As far as justification goes, you're essentially creating a specialized Tuple.  It's interesting to note that the library designers have opted to make the .Net 4 Tuple a class rather than a struct.  (That page is the tuple creator and links to the various tuple instance classes)
Comment: The "tuple as a class" is probably mainly to keep things consistent when you get to Tuple<,,,,,,,> (8 args) - which would almost certainly be oversized as a struct - especially if any of the T are non-trivial.
Comment: @Marc: That's a good point.  I hadn't noticed until just now that the Tuples are immutable.
Answer: Either should be fine, in reality (as long as the struct is immutable). A DateTime and a reference shouldn't be enough to make it oversized.
I assume you are using it as the value (not the key) in the dictionary? If used as the key you would need to override Equals and GetHashCode(), regardless of struct vs class.
Comment: (maybe I didn't phrase it well... those methods are only important [in this context] when used as a key)
Comment: Yep, am using it as value, not key, so am overriding those methods.
Comment: Yes, I understand - not needed for me. You mean if you're using the class as a key, as someone explained in one of the answers here http://stackoverflow.com/questions/689940/hashtable-with-multidimensional-key-in-c

Nullable struct vs class


Lavaan mediation + moderation + 2 X's

Question: I'm trying to build a SEM that looks like the picture shown below:

Where:

$X$ and $X^2$ are the independent variables
$Y$ is the dependent variable
$M_1$ and $M_2$ are the mediators
$W$ is a moderator

None of the default mediation packages that I've tried so far support such a structure so I'm using lavaan SEM instead. I've been reading up on Hayes and have figured out the model without the moderator:
  # direct effect
  Y ~ cprime1*X + cprime2*X2 + controls

  # mediator 1 paths
  M1 ~ a1*X+a2*X2  + controls
  Y ~ b1*M1

  # mediator 2 paths
  M2 ~ a1prime*X + a2prime*X2 + d*M1 + controls
  Y ~ b2*M2

  # indirect effect (a*b) using the Hayes2010 formula (Table 1)
  ab :=  (a1 + 2*a2*X)*b1 + (a1prime + 2*a2prime + (a1+2*a2*X)*d ) * b2

  # total effect
  cprime := (cprime1+2*cprime2)
  total := cprime + (ab)

I'm aware of how to moderate with 1 input variable, for instance for M1 you'd have something like:
M1 ~ a1*X1 + a2*W + a3*X1:W + controls

But it's unclear to me how one would add the moderators for X2 in these and the other parts of the model.
Comment: I am quite unsure about your indirect effect. You are looking to 2 indirect effects and the equation only compute a single one.
Comment: I'm following Hayes to compute the total indirect effect as the sum of the individual indirect effects.
Answer: I simulated some irrelevant data:
library(lavaan)

dat <- as.data.frame(MASS::mvrnorm(5e2, rep(0, 6), matrix(.25, 6, 6) + .75 * diag(6)))
colnames(dat) <- c("X", "X2", "M1", "M2", "W", "Y")
dat$X2 <- dat$X ^ 2
head(dat)
#            X         X2         M1         M2          W          Y
# 1 -1.2556613 1.57668526  0.9558917 -0.6155703 -0.4540778 -0.3747208
# 2 -0.8463471 0.71630340  0.2066086 -0.1680590 -0.9181445 -0.2819832
# 3  0.1081230 0.01169059 -0.1934604  1.2662057  0.4817797 -0.5342619
# 4  0.6180336 0.38196555  0.3301925 -0.1277026  1.3222274  0.3626635

Given these data, this is the model code you want:
summary(sem(
  "M1 ~ a11 * X + a12 * X2 + w10 * W + w11 * X:W + w12 * X2:W
  M2 ~ a21 * X + a22 * X2 + w20 * W + w21 * X:W + w22 * X2:W + d * M1
  Y ~ c1 * X + c2 * X2 + w30 * W + w31 * X:W + w32 * X2:W + b1 * M1 + b2 * M2
  a11db2 := a11 * d * b2
  a12db2 := a12 * d * b2
  a11b1 := a11 * b1
  a12b1 := a12 * b1
  a21b2 := a21 * b2
  a22b2 := a22 * b2",
  dat), rsquare = TRUE)

With this, you can work out the exact combinations that get you the total indirect, direct and total effects. The nature of W makes things a bit difficult. Right now, the computed effects at the bottom are for when W = 0. You might want to play around with the computed effects depending on the type of variable W is.
Comment: I think `library(MASS)` is required for running `mvrnorm`.
Comment: Thank you, this is very helpful! How would one get the effect size for one standard deviation above/below the value of a continuous W?
Comment: @ciri standardize W before adding it to the model. Then add its interaction coefficient wherever it might be of interest.
Comment: I have [requested](https://gitlab.com/georgy.m/semopy/-/issues/30) the developers of `semopy` to reproduce this example.
Answer: Moderation is basically the product of the IVs ($X_i$) with the moderator ($W$). Since you have two IVs, you have two products $X_1W$ and $W_2W$, you just have to do it once for each predictor $X_i$ on each outcome ($M_1,M_2,Y$), since you want the moderator on each of them.
I used the notation in the graph for the code,
Y ~ cprime1*X + cprime2*X2 + w3_1*X1:W + w3_2*X2:W + controls
M2 ~ aprime1*X1 + aprime2*W + w2_1*X1:W + w2_2*X2:W + + d*M1 + controls
M1 ~ a1*X1 + a2*W + w2_1*X1:W + w2_2*X2:W + controls

plus your indirect effects.
You can also consider a triple interaction X1:X2:W. You would have to add the double interaction of $X_1X_2$ and the triple interaction $X_1X_2W$. At this point you would have an IV and two moderators (conceptually speaking; statistically, it is arbitrary because there is no difference between the variables). I don't think it is what you want though.
Comment: Could you further clarify the full model? What would the implication be of adding a triple interaction?
Comment: I edited my answer.

Lavaan mediation + moderation + 2 X's


Prove that there doesn't exist a polynomial $P$ with integer coefficients such that $P(2)=P(-2)=2$ and $P(0)=0$.

Question: Stumbled upon this problem in a math competition. Couldn't figure it out. Thanks
Comment: Hint: What are the known roots of the polynomial $Q(x)=P(x)-2$? What does this tell you about possible factors of $Q(x)$?
Comment: Please show attempt
Answer: Since $P(0)=0$ we have $P(X)=XQ(X)$. Then $P(2)+P(-2)=4$ which is equivalent to $Q(2)-Q(-2)=2$.
Now recall that $m-n\mid Q(m)-Q(n)$. For $m=2$ and $n=-2$ we get $4\mid 2$, a contradiction.
Answer: We might also make an argument using function symmetries.  Since $ \ P(0) \ = \ 0 \ , $ the polynomial has zero "constant term", so it may be written as $$ P(x) \ \ = \ \ a_nx^n \ + \ a_{n-1}x^{n-1} \ + \ a_{n-2}x^{n-2} \ + \ \cdots \ + \ a_2x^2 \ + \ a_1x \ \ ,  $$
with the coefficients taken to be integers.
We are given the values of the function $ \ P(2) \ = \ P(-2) \ = \ 2 \ \ . \ $ If $ \ P(x) \ $ has even symmetry, then we have
$$ P(\pm 2) \ \ = \ \ a_n·2^n \ +  \ a_{n-2}·2^{n-2} \ + \ \cdots \ + \ a_2·2^2   \ \ = \ \ 2  \ \ , \ \ n \ \ \text{even} $$
$$ \Rightarrow \ \   a_n·2^{n-1} \ +  \ a_{n-2}·2^{n-3} \ + \ \cdots \ + \ a_2·2 $$ $$ =   \ \  2  ·  [ \ a_n·2^{n-2} \ +  \ a_{n-2}·2^{n-4} \ + \ \cdots \ + \ a_2 \ ]    \ \  = \ \ 1 \ \ ,  $$
with the left side of the equation being some integer multiple of $ \ 2 \ \ , $ which is clearly not possible.  (It becomes clear why the constant term was "removed" for this problem.)
Must $ \ P(x) \ $   be an even function? If we write the polynomial function as a sum of even- and odd-symmetry functions, $ \ P(x) \ = \ P_e(x) + P_o(x) \ \ , $ then of course $ \ P_o(0) \ = \ 0 \ \ , $ but also $ P_o(-2) \ = \ -P_o(2) \ = \ 0 \ \   $ [the odd-symmetry function makes zero contribution at these values of $ \ x \ \ ; $ this is related to TonyK's comment on the OP]. Hence,
$$ P_o(-2) \ \ = \ \ a_{n-1}·(-2)^{n-1} \ +  \ a_{n-3}·(-2)^{n-3} \ + \ \cdots \ + \ a_1·(-2)     $$
$$ = \ \ -P_o(2) \ \ = \ \ -[ \ a_{n-1}·2^{n-1} \ +  \ a_{n-3}·2^{n-3} \ + \ \cdots \ + \ a_1·2 \ ]  \ \ = \ \ 0  \ \   \ \ (n \ \ \text{even}) \ \ .  $$
This requires that $ \ a_{n-1} \ = \ -a_{n-1} \ \ , \  \ a_{n-3} \ = \ -a_{n-3}  \ \ , \ \ \cdots \ \ , \ \  a_1 \ = \ -a_1 \ \ , $ so all of the odd coefficients of $ \ P(x) \ $ are zero.  Thus, $ \ P(x) \ $ is  an even function and the argument in the previous paragraph stands.  [We can see that the proposition may be generalized as:  there is no polynomial $ \ P(x) \ $ with integer coefficients for which $ \ P(k) \ = \ P(-k) \ = \ k \ $ and $ \ P(0) \ = \ 0 \ , \ $ with $ \ k \ $ being an integer.]


Adding shadow to circular view

Question: I'm trying to add a shadow behind a circular view, but my attempts have led me to only a shadow on my view's border—and this shadow doesn't appear all the way around the view either (just the top).  Here's my code:
<code>-(void)drawRect:(CGRect)dirtyRect{
    CGContextRef ctx=UIGraphicsGetCurrentContext();
    CGRect bounds=[self bounds];

    // Figure out the centre of the bounds rectangle
    CGPoint centre;
    centre.x=bounds.origin.x+0.5*bounds.size.width;
    centre.y=bounds.origin.y+0.5*bounds.size.height;

    // Clip context
    CGPathRef path = CGPathCreateWithEllipseInRect(bounds, NULL);
    CGContextAddPath(ctx, path);
    CGContextClip(ctx);

    // Add black outline
    path = CGPathCreateWithEllipseInRect(bounds, NULL);
    CGContextAddPath(ctx, path);
    [[UIColor blackColor] setStroke];
    CGContextSetLineWidth(ctx, 3.0);

    // Specify shadow
    CGSize offset=CGSizeMake(1,4);
    CGColorRef colour=[[UIColor darkGrayColor] CGColor];
    CGContextSetShadowWithColor(ctx, offset, 2, colour);

    // Draw image
    UIImage *littleImage=[UIImage imageNamed:@"image.png"];
    [littleImage drawInRect:bounds];

    CGContextStrokePath(ctx);

}
</code>
Thanks for reading.
Answer: I think you're clipping the shadow. Try making the clipping path rect a little bigger or the ellipse rect a little smaller.
You can test this by turning off the clipping and see if the shadow appears.
Comment: Thanks for the reply.  That would explain why the shadow doesn't go all around, but the problem of the shadow appearing inside the view itself (as though the view was transparent and showing the shadow behind) would still remain... Any ideas on this one?
Comment: I think it's behaving properly because you don't fill the ellipse. It's displaying the line's shadow. If you fill the path with a solid color you won't see it.
Answer: OK, there were a couple things that needed doing to fix this.  I think that this code could likely be reduced by a few lines, but here's what worked:
<code>-(void)drawRect:(CGRect)dirtyRect{
    CGContextRef ctx=UIGraphicsGetCurrentContext();

    // Create bounds and path for rectangle slightly smaller than view (Thanks, Andrew T., for this!)
    CGRect bounds=[self bounds];
    CGFloat smallerBy=20.0;
    CGRect smallBounds=CGRectMake(bounds.origin.x+smallerBy/2, bounds.origin.y+smallerBy/2, bounds.size.width-smallerBy, bounds.size.height-smallerBy);
    CGPathRef path = CGPathCreateWithEllipseInRect(smallBounds, NULL);
    CGContextAddPath(ctx, path);

    // Add black outline with shadow to bounds
    [[UIColor blackColor] setStroke];
    CGContextSetLineWidth(ctx, 5.0);
    CGSize offset=CGSizeMake(3,4);
    CGColorRef colour=[[UIColor lightGrayColor] CGColor];
    CGContextSetShadowWithColor(ctx, offset, 8, colour);
    CGContextStrokePath(ctx);

    // Draw opaque white circle (to cover up shadow that was leaking "inside" image)
    [[UIColor whiteColor] setFill];
    CGContextSetLineWidth(ctx, 0.0);
    CGContextFillEllipseInRect(ctx, smallBounds);

    // Draw shadowless black outline over white circle (the circle had bitten into the original outline)
    CGContextSetShadowWithColor(ctx, offset, 3, NULL);
    CGContextAddPath(ctx, path);
    [[UIColor blackColor] setStroke];
    CGContextSetLineWidth(ctx, 5.0);
    CGContextStrokePath(ctx);

    // Clip context to bounds
    CGContextAddPath(ctx, path);
    CGContextClip(ctx);

    // Draw image
    UIImage *newImage=[UIImage imageNamed:@"image.png"];
    [newImage drawInRect:smallBounds];

}
</code>

Adding shadow to circular view


In univariate linear regression if you are already using Ordinary Least Square, is cost function still neccesary?

Question: I have a question regarding cost function and Ordinary Least Square (OLS) in univariate linear regression.
From my understanding, in linear regression, OLS is used to find the the slope and y-intercept that minimises the sum of squared differences between the dependent and independent variables.
While for cost function, my understanding is that it is also somewhat used to find a line of best fit, by measuring the relationship performance between the dependent and independent variables.
Then if that's the case, do we still need to use cost function when we are already using OLS to plot our line? Thank you.
Answer: There are at least two roles for cost/loss functions in machine learning: in training and in evaluation. OLS is an estimator that corresponds to square cost in training. So if you choose OLS, you know your training cost. You may still need to specify evaluation cost for evaluating your model, and evaluation cost may differ from training cost. For a more in-depth review, see "Why is using squared error the standard when absolute error is more relevant to most problems?".


Alternative to 3 Synchronized CStringList's

Question: I have 3 CStringList's:

parameterNameList
parameterValueList
parameterID

The lists are synchronized, which means that the value (found in parameterValueList) of a named parameter (found in parameterNameList) are located in the same position (index\POSITION) in their respective StringLists. The same goes for parameterID.
Im looking for an alternative to having 3 StringLists and thought about using a CMap with parameterID as key and create a class to hold name and value.
Question: What would be the best solution for replacing my 3 CStringList objects ?
Additional: The collection\list\map must be fairly easy to sort and be serializable
Answer: Just use a std::map
<code>struct DATA
{
    CString strName;
    CSTring strValue;
};

typedef std::map<CString,DATA> MYDATAMAP;
</code>
It is sorted and easy to iterate. Createing a serializer is easy too.
Comment: Per would be suitable, but better? From my point of view such DATA blocks are more redable and understandable than using pair. But yes. std::pair will work too!
Comment: isn't std::pair better than the struct in this case?


antiderivative of $f(x)=(3x^2-1)^2$

Question: It is easy to calculate $\int(3x^2-1)^2dx$: $\int(3x^2-1)^2dx=9x^4-6x^2+1dx=\frac{9}{5}x^5-2x^3+x+c$ $c\in\mathbb{R}$.
Now, one of my friends calculated the antiderivative of f with a similar method to subsitution, but which I have never seen before and which I don't understand, he named this method "backwards subsitution".
He get $F(x)=\frac{1}{3}(3x^2-1)^3\frac{1}{6x}$ as an antiderivative of f.
It is $F'=f$, but x has to be nonzero. It seems to be a different result as $\frac{9}{5}x^5-2x^3+x$, but I don't understand what is wrong. Is $F(x)=\frac{1}{3}(3x^2-1)^3\frac{1}{6x}$ an antiderivative of f?
Regards
Comment: http://www.wolframalpha.com/input/?i=antiderivative+of+%283x%5E2-1%29%5E2
Comment: $F(x)$ is an antiderivative of $f(x)$ if $F'(x) = f(x)$. But $F'(x) = \frac{(3x^2-1)^2(15x^2+1)}{18x^2}$, which is clearly not $f(x)$
Comment: Your friend's method only works when a function's argument is a linear polynomial in x but not in case of a quadratic.
Comment: @Brenton oh, I forgot to use the product rule. Thank you! @A Googler, thanks!Good to know!
Answer: One fundamental principle in calculus is that you don't (or your friend doesn't) get to make up new rules and expect them to work. His method is incorrect and doesn't follow at all from the rule of substitution.

antiderivative of $f(x)=(3x^2-1)^2$


Need to stop LDAP reflection attack. Will only allowing LAN IPs for LDAP break active directory/domain functionality?

Question: Back story: I've got a domain controller exposed to the internet (I know, it shouldn't be, was put together piecemeal). Unfortunately, we just discovered that it's being used in LDAP reflection attacks. We're only using this for active directory, not much DNS work going on.
I can't make many changes to the physical infra at this stage and just want to limit requests hitting port 389 via UDP/TCP to LAN IPs only. I'm trying to limit issues and downtime as it's a high traffic environment.
I did notice in Resource Monitor > Network > TCP Connections, the public IPs for the other servers in the domain showing on port 389. I was under the impression communication to the AD was via the 10.1.1.x.
Questions:
Can I add only the LAN IP range 10.1.1.0/24 to the firewall rule for port 389 without breaking other AD/DC functionality?
Why would I see connections to the AD from other servers with their public IP?
Comment: Are all your servers connecting to the public DC multihomed with internal and public IPs? AD (almost) always uses its interal DNS zone to connect the servers/ services. I think all you can do is restrict your servers to register the public IP in DNS, so AD will only connect to LAN. If you just block the connections no matter what, you may break AD. (Manually) Clean up DNS, check your service connections etc. for public IPs, block public IPs. Could work.
Comment: All multihomed with public and internal IPs. The DNS looks OK with all servers showing up properly with correct internal IPs. If I block connections to 389, it will break it as I monitor the connections while logging in on another server, also LDAP uses the first connection to dish out ephermal ports (I think). I guess if it breaks and I immediately roll back, could there be delays/caching of those settings? Thanks.
Answer: So it's OK to only allow internal IPs in firewall for LDAP TCP/UDP (port 389) and Secure LDAP (port 636) by adding the internal IP range.

My AD is using 10.1.1.0/24
After changing the firewall, my network activity went from 50-90Mbps to 1Mpbs over time.
Note: In some cases, it can take a while for the outgoing connections to remove themselves. I'm guessing this is down to the issue of ephermals ports and a certain time period or continued activity.


Does adding more processing power increases Drupal Page Load Speed

Question: I have a site hosted on Acquia Cloud.all the unnecessary modules are uninstalled. The site has only couple of nodes (300 almost)and lot of imported registered accounts.
Below optimizations are enabled already
http://www.goodykitchen.com

memcache
varnish
CDN - Cloudfront
Page Caching (Drupal's Default)
CSS / JS aggregation

RAM : 1.7GB
CPU : 1 ECU
Problem:
My comparison site is bbcgoodfood.com in terms of page load. I have gone through some research and they are using most of above mentioned optimizations. Is there a way to find out why their page load is so smooth. OR should i just increase the Cloud size and see my site page load. (currently i do not have many users on the site)
any clues ?
thanks
Answer: APC might be your answer
Best APC settings to reduce page execution time
There's a lot here on Drupal speed and performance generally ...


How could I stop ssh offering a wrong key?

Question: (This is a problem with ssh, not gitolite)
I've configured gitolite on my home server (ubuntu 12.04 server, open-ssh). I want an special identityfile to administer the repositories, so I need to access throught ssh to my own host ussing two different identity keys.
This is the content of my .ssh/config file:
Host gitadmin.gammu.com
User            git
IdentityFile    /home/alvaro/.ssh/id_gitolite_mantra

Host git.gammu.com
User            git
IdentityFile    /home/alvaro/.ssh/id_alvaro_mantra

This is the content of my hosts file:
# Git
127.0.0.1      gitadmin.gammu.com
127.0.0.1      git.gammu.com

So I should be able to communicate with gitolite this way to access with the "normal" account:
$ssh git.gammu.com

and this way to access with the administrative account:
$ssh gitadmin.gammu.com

When I try to access with the normal account, all is ok:
alvaro@mantra:~/.ssh$ ssh git.gammu.com
PTY allocation request failed on channel 0
hello alvaro, this is gitolite 2.2-1 (Debian) running on git 220.127.116.11
the gitolite config gives you the following access:
    @R_ @W_    testing
Connection to git.gammu.com closed.

When I do the same with the administrative account:
alvaro@mantra:~$ ssh gitadmin.gammu.com
PTY allocation request failed on channel 0
hello alvaro, this is gitolite 2.2-1 (Debian) running on git 22.214.171.124
the gitolite config gives you the following access:
    @R_ @W_    testing
Connection to gitadmin.gammu.com closed.

It should show the administrative repository. If I launch ssh with verbose option:
ssh -vvv gitadmin.gammu.com
...
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /home/alvaro/.ssh/id_alvaro_mantra (0x7f7cb6c0fbc0)
debug2: key: /home/alvaro/.ssh/id_gitolite_mantra (0x7f7cb6c044d0)
debug1: Authentications that can continue: publickey,password
debug3: start over, passed a different list publickey,password
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/alvaro/.ssh/id_alvaro_mantra
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Server accepts key: pkalg ssh-rsa blen 279
...

It's offering the key id_alvaro_mantra, and it shouldn't!!
The same happens when I specify the key with the -i option:
ssh -i /home/alvaro/.ssh/id_gitolite_mantra -vvv gitadmin.gammu.com
...
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /home/alvaro/.ssh/id_alvaro_mantra (0x7fa365237f90)
debug2: key: /home/alvaro/.ssh/id_gitolite_mantra (0x7fa365230550)
debug2: key: /home/alvaro/.ssh/id_gitolite_mantra (0x7fa365231050)
debug1: Authentications that can continue: publickey,password
debug3: start over, passed a different list publickey,password
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/alvaro/.ssh/id_alvaro_mantra
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Server accepts key: pkalg ssh-rsa blen 279
debug2: input_userauth_pk_ok: fp 36:b1:43:36:af:4f:00:e5:e1:39:50:7e:07:80:14:26
debug3: sign_and_send_pubkey: RSA 36:b1:43:36:af:4f:00:e5:e1:39:50:7e:07:80:14:26
debug1: Authentication succeeded (publickey).
...

What's happening?  I'm missing something, but I can't find what.
These are the contents of my home dir:
-rw-rw-r--  1 alvaro alvaro  395 nov 14 18:00 authorized_keys
-rw-rw-r--  1 alvaro alvaro  326 nov 21 10:21 config
-rw-------  1 alvaro alvaro  137 nov 20 20:26 environment
-rw-------  1 alvaro alvaro 1766 nov 20 21:41 id_alvaromaceda.es
-rw-r--r--  1 alvaro alvaro  404 nov 20 21:41 id_alvaromaceda.es.pub
-rw-------  1 alvaro alvaro 1766 nov 14 17:59 id_alvaro_mantra
-rw-r--r--  1 alvaro alvaro  395 nov 14 17:59 id_alvaro_mantra.pub
-rw-------  1 alvaro alvaro  771 nov 14 18:03 id_developer_mantra
-rw-------  1 alvaro alvaro 1679 nov 20 12:37 id_dos_pruebasgit
-rw-r--r--  1 alvaro alvaro  395 nov 20 12:37 id_dos_pruebasgit.pub
-rw-------  1 alvaro alvaro 1679 nov 20 12:46 id_gitolite_mantra
-rw-r--r--  1 alvaro alvaro  397 nov 20 12:46 id_gitolite_mantra.pub
-rw-------  1 alvaro alvaro 1675 nov 20 21:44 id_gitpruebas.es
-rw-r--r--  1 alvaro alvaro  408 nov 20 21:44 id_gitpruebas.es.pub
-rw-------  1 alvaro alvaro 1679 nov 20 12:34 id_uno_pruebasgit
-rw-r--r--  1 alvaro alvaro  395 nov 20 12:34 id_uno_pruebasgit.pub
-rw-r--r--  1 alvaro alvaro 2434 nov 21 10:11 known_hosts

There are a bunch of other keys which aren't offered... why id_alvaro_mantra is offered and not the other keys? I can't understand.
I need some help, don't know where to look....
Answer: This is expected behaviour according to the manpage of ssh_config:
 IdentityFile
         Specifies a file from which the user's DSA, ECDSA or DSA authentica‐
         tion identity is read.  The default is ~/.ssh/identity for protocol
         version 1, and ~/.ssh/id_dsa, ~/.ssh/id_ecdsa and ~/.ssh/id_rsa for
         protocol version 2.  Additionally, any identities represented by the
         authentication agent will be used for authentication.

         [...]

         It is possible to have multiple identity files specified in configu‐
         ration files; all these identities will be tried in sequence.  Mul‐
         tiple IdentityFile directives will add to the list of identities
         tried (this behaviour differs from that of other configuration
         directives).

Basically, specifying IdentityFiles just adds keys to a current list the SSH agent already presented to the client.
Try overriding this behaviour with this at the bottom of your .ssh/config file:
Host *
IdentitiesOnly yes

Comment: Also, you can specify it on the host level, that's what I've done finally:
`Host git.gammu.com`
        `User                    git`
        IdentityFile    /home/alvaro/.ssh/id_alvaro_mantra
        IdentitiesOnly  yes`
Comment: @AlvaroMaceda is correct. Adding `IdentitiesOnly yes` to the gitadmin.gammu.com and git.gammu.com `Host` entries is enough. You don't have to make a wildcard entry that will affect other hosts.
Comment: Thanks a lot, that worked. I'd completly forgotten ssh-agent!
Comment: Finally I found the solution, thanks! This should be enabled by default.
Comment: I found that the 'wrong' key was still offered regardless, and I _also_ needed to omit the problematic host from *, like `Host * !bitbucket.org`, per https://superuser.com/a/859719/73736
Answer: For me the solution was to add a key to a list of ssh keys, with a command:
ssh-add ~/.ssh/id_name_of_my_rsa_key

so it could be offered when connecting to the server. After adding a ssh, it was automatically recognized the correct one.
Edit:
But recently I think the better solution, and more permanent one, is to go to ~/.ssh/config and add IdentitiesOnly yes in your configuration file like this:
Host github.com
  HostName github.com
    User git
      IdentityFile ~/.ssh/id_rsa
      IdentitiesOnly yes

Comment: Thank you, your second approach was exactly what I should do. Side notes: HostName is excessive in your example since its value equals Host's, indentation more than one level has no means since there's grouping by Host and Match in ssh_config only.
Comment: The second approach was the only one that worked for me on OS X Catalina.


Initializing two threads with the same instance of a runnable

Question: Is it bad programming to initialize two threads with the same instance of a runnable? What difference would it make to initialize with separate instances of a runnable, and does sharing memory locations at all for the same instance of a runnable have anything to do with performance?
public static void main(String[] args)throws Exception {
   H h = new H();
   H h2 = new H();
   Thread j = new Thread(h);
   j.setName("11");

   Thread jj = new Thread(h);//instead of new H()
   jj.setName("22");
   j.start();
   jj.start();
}

class H implements Runnable {
    public void run() {
        while(true) {
           System.out.println(Thread.currentThread().getName());
        }
    }
}

Answer: It's absolutely fine to do it so long as the code you're running is designed to support that. Not only will it save some memory by having a single instance instead of multiple instances, but if those threads are trying to communicate via shared data, then it may be absolutely required!
Admittedly communicating via shared state is where threading often gets tricky, so this needs to be done carefully, but from the point of view of the threading system itself, there's absolutely no problem in having two threads call the run method of a single Runnable instance.
Answer: Since H doesn't have any instance state, using multiple instances won't matter. You need to take care when the Runnable instances start storing state.
public class Main implements Runnable {
    volatile int i;
        public void run() {
        for (i = 0; i < 100; i++) {
            System.out.println(i);
        }
    }

    public static void main(String[] args) {
        Main a = new Main();
        Thread t1 = new Thread(a);
        Thread t2 = new Thread(a);
        t1.start();
        t2.start();
    }
}

What gets printed? When you do need to share state between threads, it's a good idea to use the classes in java.util.concurrent. They were written primarily by an expert in multithreading (Doug Lea, author of Concurrent Programming in Java) and tested by many people. Save yourself some heartache. :)
Comment: woo, its all screwed up. very interesting
Answer:
Is it bad programming to initialize two threads with the same instance of a runnable?

Not specifically.  However, if the Runnable instance has instance fields, then you'll need to make sure that all access to the fields by the thread is properly synchronized, and this will make the code more complicated.

What difference would it make to initialize with separate instances of a runnable, and does sharing memory locations at all for the same instance of a runnable have anything to do with performance?

The memory saved by sharing a Runnable instance between multiple threads is insignificant ... unless the Runnable holds a significant amount of instance data.  (And if it does, the chances are that this will make the instance non-shareable.)

Your H class is an example where sharing instances is safe, but pointless since the memory saving is insignificant.  (A Runnable object with no instance fields occupies roughly 8 to 16 bytes, depending on the platform.)
Answer: To make understand easily(based on the comment of Stephen), added the below program block about the impact of accessing the instance variable from a non-synchronized block with the same instance of Runnable displays the unexpected results.
public class SynchronizedInstanceMethod implements Runnable{

private int counter;

public SynchronizedInstanceMethod(int counterValue){
    this.counter = counterValue;
}

private synchronized void displayMessage(){
    System.out.println(" Display Message ");
}

private void modifyCounter(){
    this.counter++;
    System.out.println("Value -- "+ this.counter);
}

@Override
public void run() {
    this.displayMessage();
    this.modifyCounter();
}

public static void main(String[] args) {
    SynchronizedInstanceMethod instance = new SynchronizedInstanceMethod(5);
    new Thread(instance).start();
    new Thread(instance).start();
}
}


rsyslog won't start - pid already exist

Question: I was trying to configure rsyslog to forward logs from a specific file to a syslogserver and I ended up purging the whole configuration (the rsyslog service was stuck - wouldn't start) ..
so I purged everything, and installed everything from scratch again ...  and now it fails when I try to start it.
here is the OS version:
~# cat /etc/os-release
PRETTY_NAME="Debian GNU/Linux 10 (buster)"
NAME="Debian GNU/Linux"
VERSION_ID="10"
VERSION="10 (buster)"
VERSION_CODENAME=buster
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"

here is the rsyslog version
~# rsyslogd -v
rsyslogd  8.2212.0 (aka 2022.12) compiled with:
    PLATFORM:               x86_64-pc-linux-gnu
    PLATFORM (lsb_release -d):
    FEATURE_REGEXP:             Yes
    GSSAPI Kerberos 5 support:      No
    FEATURE_DEBUG (debug build, slow code): No
    32bit Atomic operations supported:  Yes
    64bit Atomic operations supported:  Yes
    memory allocator:           system default
    Runtime Instrumentation (slow code):    No
    uuid support:               Yes
    systemd support:            No
    Config file:                /etc/rsyslog.conf
    PID file:               /var/run/rsyslogd.pid
    Number of Bits in RainerScript integers: 64

See https://www.rsyslog.com for more information.

Here is my rsyslog.conf
~# cat /etc/rsyslog.conf
#  /etc/rsyslog.conf    Configuration file for rsyslog.
#
#           For more information see
#           /usr/share/doc/rsyslog-doc/html/rsyslog_conf.html

#################
#### MODULES ####
#################

module(load="imuxsock") # provides support for local system logging
module(load="imklog")   # provides kernel logging support
#module(load="immark")  # provides --MARK-- message capability

# provides UDP syslog reception
#module(load="imudp")
#input(type="imudp" port="514")

# provides TCP syslog reception
#module(load="imtcp")
#input(type="imtcp" port="514")

###########################
#### GLOBAL DIRECTIVES ####
###########################

#
# Use traditional timestamp format.
# To enable high precision timestamps, comment out the following line.
#
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat

#
# Set the default permissions for all log files.
#
$FileOwner root
$FileGroup adm
$FileCreateMode 0640
$DirCreateMode 0755
$Umask 0022

#
# Where to place spool and state files
#
$WorkDirectory /var/spool/rsyslog

#
# Include all config files in /etc/rsyslog.d/
#
$IncludeConfig /etc/rsyslog.d/*.conf

###############
#### RULES ####
###############

#
# First some standard log files.  Log by facility.
#
auth,authpriv.*         /var/log/auth.log
*.*;auth,authpriv.none      -/var/log/syslog
#cron.*             /var/log/cron.log
daemon.*            -/var/log/daemon.log
kern.*              -/var/log/kern.log
lpr.*               -/var/log/lpr.log
mail.*              -/var/log/mail.log
user.*              -/var/log/user.log

#
# Logging for the mail system.  Split it up so that
# it is easy to write scripts to parse these files.
#
mail.info           -/var/log/mail.info
mail.warn           -/var/log/mail.warn
mail.err            /var/log/mail.err

#
# Some "catch-all" log files.
#
*.=debug;\
    auth,authpriv.none;\
    news.none;mail.none -/var/log/debug
*.=info;*.=notice;*.=warn;\
    auth,authpriv.none;\
    cron,daemon.none;\
    mail,news.none      -/var/log/messages

#
# Emergencies are sent to everybody logged in.
#
*.emerg             :omusrmsg:*

and lastly the systemd service (which is a soft link to /lib/systemd/system/rsyslog.service)
~# cat /etc/systemd/system/syslog.service
[Unit]
Description=System Logging Service
Requires=syslog.socket
Documentation=man:rsyslogd(8)
Documentation=man:rsyslog.conf(5)
Documentation=https://www.rsyslog.com/doc/

[Service]
Type=notify
ExecStart=/usr/sbin/rsyslogd -n
StandardOutput=null
Restart=on-failure

# Increase the default a bit in order to allow many simultaneous
# files to be monitored, we might need a lot of fds.
#LimitNOFILE=16384

[Install]
WantedBy=multi-user.target
Alias=syslog.service

when I run /usr/sbin/rsyslogd -n I am getting
~# /usr/sbin/rsyslogd -n
rsyslogd: pidfile '/var/run/rsyslogd.pid' and pid 6260 already exist.
If you want to run multiple instances of rsyslog, you need to specify
different pid files for them (-i option).
rsyslogd: run failed with error -3000 (see rsyslog.h or try https://www.rsyslog.com/e/3000 to learn what that number means)

service status says:
~# systemctl status rsyslog.service
● rsyslog.service - System Logging Service
   Loaded: loaded (/lib/systemd/system/rsyslog.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Thu 2022-12-22 08:05:56 CET; 8s ago
     Docs: man:rsyslogd(8)
           man:rsyslog.conf(5)
           https://www.rsyslog.com/doc/
  Process: 6464 ExecStart=/usr/sbin/rsyslogd -n (code=exited, status=1/FAILURE)
 Main PID: 6464 (code=exited, status=1/FAILURE)

Dec 22 08:05:56 TW-3CXNFA-B systemd[1]: rsyslog.service: Main process exited, code=exited, status=1/FAILURE
Dec 22 08:05:56 TW-3CXNFA-B systemd[1]: rsyslog.service: Failed with result 'exit-code'.
Dec 22 08:05:56 TW-3CXNFA-B systemd[1]: Failed to start System Logging Service.
Dec 22 08:05:56 TW-3CXNFA-B systemd[1]: rsyslog.service: Service RestartSec=100ms expired, scheduling restart.
Dec 22 08:05:56 TW-3CXNFA-B systemd[1]: rsyslog.service: Scheduled restart job, restart counter is at 5.
Dec 22 08:05:56 TW-3CXNFA-B systemd[1]: Stopped System Logging Service.
Dec 22 08:05:56 TW-3CXNFA-B systemd[1]: rsyslog.service: Start request repeated too quickly.
Dec 22 08:05:56 TW-3CXNFA-B systemd[1]: rsyslog.service: Failed with result 'exit-code'.
Dec 22 08:05:56 TW-3CXNFA-B systemd[1]: Failed to start System Logging Service.

I am a bit stuck here ... I googled the "pid already exist" message and many others but it led me nowhere :(
I would appreciate a bit of nudge here please :( Any ideas what I need to do?
----------- EDIT ------------
I tried this according to the tips from you guys ...
edited (r)syslog.service and add -iNONE as a param
~# cat /etc/systemd/system/syslog.service
[Unit]
Description=System Logging Service
Requires=syslog.socket
Documentation=man:rsyslogd(8)
Documentation=man:rsyslog.conf(5)
Documentation=https://www.rsyslog.com/doc/

[Service]
Type=notify
ExecStart=/usr/sbin/rsyslogd -n -iNONE
StandardOutput=null
Restart=on-failure

#Increase the default a bit in order to allow many simultaneous
#files to be monitored, we might need a lot of fds.
#LimitNOFILE=16384

[Install]
WantedBy=multi-user.target
Alias=syslog.service

reloaded the daemon -> systemctl daemon-reload (no error messages)
stopped both systemctl stop syslog.socket rsyslog.service
checked the status of both
~# systemctl status syslog.socket rsyslog.service
● syslog.socket - Syslog Socket
   Loaded: loaded (/lib/systemd/system/syslog.socket; static; vendor preset: disabled)
   Active: inactive (dead) since Thu 2022-12-22 14:57:32 CET; 18s ago
     Docs: man:systemd.special(7)
           https://www.freedesktop.org/wiki/Software/systemd/syslog
   Listen: /run/systemd/journal/syslog (Datagram)

Dec 22 10:17:58 TW-3CXNFA-B systemd[1]: Listening on Syslog Socket.
Dec 22 14:57:32 TW-3CXNFA-B systemd[1]: syslog.socket: Succeeded.
Dec 22 14:57:32 TW-3CXNFA-B systemd[1]: Closed Syslog Socket.

● rsyslog.service - System Logging Service
   Loaded: loaded (/lib/systemd/system/rsyslog.service; enabled; vendor preset: enabled)
   Active: inactive (dead) since Thu 2022-12-22 14:57:32 CET; 18s ago
     Docs: man:rsyslogd(8)
           man:rsyslog.conf(5)
           https://www.rsyslog.com/doc/
  Process: 22681 ExecStart=/usr/sbin/rsyslogd -n -iNONE (code=exited, status=0/SUCCESS)
 Main PID: 22681 (code=exited, status=0/SUCCESS)

Dec 22 14:56:59 TW-3CXNFA-B systemd[1]: Starting System Logging Service...
Dec 22 14:57:32 TW-3CXNFA-B systemd[1]: rsyslog.service: Succeeded.
Dec 22 14:57:32 TW-3CXNFA-B systemd[1]: Stopped System Logging Service.

both are inactive .. I then checked if there is any active PID (all good)
~# ps axu | grep rsyslog
root     22747  0.0  0.0   6072   888 pts/0    S+   14:59   0:00 grep rsyslog

verified if there is the pid file ls /var/run/ | grep syslog (none)
I then started the service which resulted in the timeout message
~# systemctl start rsyslog
Job for rsyslog.service failed because a timeout was exceeded.
See "systemctl status rsyslog.service" and "journalctl -xe" for details.

checking the status
~# systemctl status rsyslog.service
● rsyslog.service - System Logging Service
   Loaded: loaded (/lib/systemd/system/rsyslog.service; enabled; vendor preset: enabled)
   Active: activating (start) since Thu 2022-12-22 15:03:16 CET; 1min 26s ago
     Docs: man:rsyslogd(8)
           man:rsyslog.conf(5)
           https://www.rsyslog.com/doc/
 Main PID: 22896 (rsyslogd)
    Tasks: 4 (limit: 1136)
   Memory: 824.0K
   CGroup: /system.slice/rsyslog.service
           └─22896 /usr/sbin/rsyslogd -n -iNONE

Dec 22 15:03:16 TW-3CXNFA-B systemd[1]: Starting System Logging Service...

plus journal:
~# journalctl -xe
-- A stop job for unit rsyslog.service has finished.
--
-- The job identifier is 25478 and the job result is done.
Dec 22 15:03:16 TW-3CXNFA-B systemd[1]: Starting System Logging Service...
-- Subject: A start job for unit rsyslog.service has begun execution
-- Defined-By: systemd
-- Support: https://www.debian.org/support
--
-- A start job for unit rsyslog.service has begun execution.
--
-- The job identifier is 25478.
Dec 22 15:04:46 TW-3CXNFA-B systemd[1]: rsyslog.service: Start operation timed out. Terminating.
Dec 22 15:04:46 TW-3CXNFA-B systemd[1]: rsyslog.service: Failed with result 'timeout'.
-- Subject: Unit failed
-- Defined-By: systemd
-- Support: https://www.debian.org/support
--
-- The unit rsyslog.service has entered the 'failed' state with result 'timeout'.
Dec 22 15:04:46 TW-3CXNFA-B systemd[1]: Failed to start System Logging Service.
-- Subject: A start job for unit rsyslog.service has failed
-- Defined-By: systemd
-- Support: https://www.debian.org/support
--
-- A start job for unit rsyslog.service has finished with a failure.
--
-- The job identifier is 25478 and the job result is failed.
Dec 22 15:04:46 TW-3CXNFA-B systemd[1]: rsyslog.service: Service RestartSec=100ms expired, scheduling restart.
Dec 22 15:04:46 TW-3CXNFA-B systemd[1]: rsyslog.service: Scheduled restart job, restart counter is at 2.
-- Subject: Automatic restarting of a unit has been scheduled
-- Defined-By: systemd
-- Support: https://www.debian.org/support
--
-- Automatic restarting of the unit rsyslog.service has been scheduled, as the result for
-- the configured Restart= setting for the unit.
Dec 22 15:04:46 TW-3CXNFA-B systemd[1]: Stopped System Logging Service.
-- Subject: A stop job for unit rsyslog.service has finished
-- Defined-By: systemd
-- Support: https://www.debian.org/support
--
-- A stop job for unit rsyslog.service has finished.
--
-- The job identifier is 25554 and the job result is done.
Dec 22 15:04:46 TW-3CXNFA-B systemd[1]: Starting System Logging Service...
-- Subject: A start job for unit rsyslog.service has begun execution
-- Defined-By: systemd
-- Support: https://www.debian.org/support
--
-- A start job for unit rsyslog.service has begun execution.
--
-- The job identifier is 25554.
Dec 22 15:05:01 TW-3CXNFA-B CRON[22955]: pam_unix(cron:session): session opened for user root by (uid=0)
Dec 22 15:05:01 TW-3CXNFA-B CRON[22956]: (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 1 1)
Dec 22 15:05:01 TW-3CXNFA-B CRON[22955]: pam_unix(cron:session): session closed for user root

wth am I missing?
Comment: have you tried to kill the process through "kill -9 PID".
kill all the pids related to rsyslog and start it again.
Comment: didn't help.. see the comment below pls for more details
Answer: The default PID file location for rsyslog is /var/run/rsyslogd.pid (as described in the man rsyslogd). cat that file to know what's inside.
Check if that PID is really rsyslogd (something like ps axu | grep $(cat /var/run/rsyslogd.pid) and ps axu | grep rsyslogd). If it is running, kill it as suggested and remove a PID file. This is the problem with the service manager thinking the service is not running, while it is (for example, it was failed to stop).
If PID exists but it is not rsyslogd, don't kill it. It is probably unrelated and that action will likely cause harm rather than good. Just remove the rsyslog PID file. This could have happened because rsyslog created the file, put its PID there and then stopped, the system later reused that PID for something else.
Now, when the service is clearly not running and there is no misleading PID file, try to start it again using service manager, observing the startup in /var/log/daemon.log and other log files (messages, syslog) and checking for any errors during the startup.

Interesting is that since Debian 11 it is configured to not to write any PID file (the startup like is /usr/sbin/rsyslogd -n -iNONE).
Comment: I did find the pid and it was rsyslog `/usr/sbin/rsyslogd -n` ... however after killing it and removing the pid file... when I tried `systemctl start rsyslog` it stuck for a while and then said:  'Job for rsyslog.service failed because a timeout was exceeded. See "systemctl status rsyslog.service" and "journalctl -xe" for details.' .. the
 `/var/log/daemon.log` is empty ... `messages` says: `Dec 22 08:48:30 TW-3CXNFA-B rsyslogd: [origin software="rsyslogd" swVersion="8.2212.0" x-pid="8052" x-info="https://www.rsyslog.com"] start`  .. and the syslog says the same
Comment: So well, log file seems to show it is successfully started, is it really running now, or not?
Comment: no .. in the status is says: `Active: activating (start) since Thu 2022-12-22 08:59:04 CET; 40s ago` but will never start ...
Comment: btw I noticed the `-iNONE` in D11 .. bec on the other machine (D11) the rsyslog is running just fine ..
Answer: I think this is a bug reported via link below:
https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=815862
This appears counter-intuitive...but the actual steps to perform is you have to stop TWO systemd units, and not just the rsyslog.service or killing the PID of rsyslog:
systemctl stop syslog.socket rsyslog.service

Comment: well I figured that too during debugging ... the problem is .. even if I stop them both, they won't start ... specifically -> rsyslog won't start (syslog.socket will) .. after stopping both, they seem to be dead (when checking the status) .. but when I try to start the rsyslog .. the socket is active and fine .. but the rsyslog is "activating (start)" but will never become active
Comment: @Mr.P You are correct. Let me tell you what's happening. as I described when you stop the rsyslog service, it starts itself. So already a PID is used, but in parallel you have started another instance of it manually, which is the second PID of the same service (without -i option). that's why its throwing an error. but you may resolve it by using -i switch "/usr/sbin/rsyslogd -n -iNONE" which causes not to write the PID to any file.
Comment: so I modified the `/lib/systemd/system/rsyslog.service` which is soft-linked to the /etc/systemd/system/syslog.service ... added the -iNONE as you mentioned (and as is in the D11) ... I reloaded the daemon `systemctl daemon-reload` .. stopped both `systemctl stop syslog.socket rsyslog.service` and started the rsyslog `systemctl start rsyslog` but am still getting the "timeout was exceeded" message :( checking service status for both, socket is running fine but the rsyslog.service ain't (activating)
Comment: in the logs - all seems to be fine (start)..
Comment: @Mr.P in your logs it says:
/usr/sbin/rsyslogd -n
rsyslogd: pidfile '/var/run/rsyslogd.pid' and pid 6260 already exist.
Comment: exactly :) that's why this is so weird ... see the updated question pls (it won't format nice here)

rsyslog won't start - pid already exist


Qual o formato a imagem é convertida ao ser solicitada pelo navegador?

Question: Isso é mais uma curiosidade, dei uma rápida pesquisada e não encontrei algo que explicasse como isso funciona.
Na prática quando desenvolvemos, temos alguns métodos para solicitar uma imagem ao servidor e exibir na tela do browser no cliente. Um jeito dependendo do caso pode ser bom usar, que é deixar a imagem convertida na base64, tem pessoas que não gostam assim, eu acredito que dessa forma é bom pra se utilizar imagens pequenas, diminuindo a quantidade de arquivos nos diretorios. O google imagens funciona dessa forma, emoticons do whats app versao web tambem funciona assim.

A outra maneira, a mais tradicional é preencher o src com o caminho da localidade da imagem. E ai surge a curiosidade, qual o método  utilizado pelo servidor para converter a imagem para enviar-la ao cliente (navegador/browser)?
exemplo:

Comment: A princípio, não há conversão alguma - ou a imagem existe no servidor com o nome requisitado, ou não existe; e independentemente do nome, o servidor pode especificar o formato no *mime type* e/ou o *browser* pode inspecionar a imagem para descobrir seu conteúdo (não sei exatamente o que acontece quando o *mime type* não corresponde ao formato do arquivo). A propósito, o base64 [aumenta em 33% o tamanho dos dados](http://pt.stackoverflow.com/a/53107/215), não sendo uma boa opção para arquivos grandes, mas como você apontou de fato para arquivos pequenos economiza um *round-trip* ao servidor.
Comment: acho que ele quis usar algum outro termo ao invés da palavra "converter".. essa palavra muda todo o sentido da questão...
Comment: comentando um pouco mais, parte da descrição da pergunta já responde a própria pergunta.. rsrsr.. esse esquema aplicando data:image é mais para imagens pequenas. Imagine 50 imagens pequenas numa única página. São 50 requisições ao servidor.. Num serviço de alto tráfego, isso se converte num custo significativo $$.
Comment: Hum sim, então cada imagem tem uma requisição nova ao servidor. A minha duvida é só como o servidor envia a imagem na solicitação normal como dado no exemplo, é em array de bytes? ou algum outro tipo de dados ? é mais uma curiosidade.
Answer: Nenhum tipo de conversão ocorre: a imagem é simplesmente serializadas em um array de bytes e este é enviado no corpo da resposta HTTP.


Can we switch integral and expectation by Fubini's theorem?

Question: From Itō isometry Wikipedia page:

Can we switch the expectation and integral in the RHS by Fubini's theorem?
I'm actually not quite sure how Fubini's theorem is used outside basic Calculus.
The fact that my professor did not discuss Riemann integration of a random variable suggests that it is possible otherwise the $\int_0^T X_t^2 dt$ probably wouldn't make sense.
Answer: You can switch expectation and integral by Tonelli's theorem since $X_s^2\geq 0$.
Comment: @BCLC: yes, which is still a rectangle. Easier said, the two integral are decoupled
Comment: Thanks Alex R. Do we ever have to adjust the region of integration as is done for non-rectangular regions in R2 for riemann integration in basic calculus?
Comment: @bclc: no, the region is rectangular
Comment: Is it? One is from 0 to T while the other is not over an interval but rather over $\Omega$
Comment: Never mind. I'll ask about that in another question sometime. Thanks anyway
Answer: I believe this is a result from Itô isometry in Stochastic Calculus, where LHS is the variance of the Random Variable $\int_{0}^{T}X_tdW_t$, reduced to ordinary expectation w.r.t $ds$ on RHS.
Comment: What do you mean? My question is about RHS: is it equal to int (e(x^2))dt? Then the answer appears to be yes by fubini's or tonelli's theorem


What are the scalability concerns with pub/sub servers?

Question: I'm looking into setting up a pub/sub service with websockets. From what I can tell the scalability bottlenecks will mainly be with memory, which affects how many sockets can be opened at a time, so therefore I would think it wise to split this off of the other servers running services such as APIs. Is this correct? I would imagine memory is more expensive than compute power when it comes to hosting, so are there any best practices when it comes to optimizing this type of server for scalability and cost?
The goal is to provide the user of this web application with real-time updates as systems in the field check-in with new data, without having to poll the backend periodically. But we don't want to double our server costs or it might not be worth it. We are using AWS EC2 with load balancing and auto-scaling for our current API servers.
Answer: The actual memory usage of a single socket isn't that much.
What does eat up memory is the state associated with which client is interested in which updates, and which client has already received a particular update.
In a primitive implementation (i.e. using the OS network stack), the latter state is kept in the form of outgoing buffers -- so if an update is sent to 10,000 clients, the data is copied 10,000 times, each of the copies appended to an outgoing queue, where it is augmented with the requisite headers (that contain per-connection state), and then a descriptor is built for the hardware that instructs it to send a packet that is a concatenation of the headers and the payload.
The per-client copy of the payload is kept in memory until it is acknowledged by the client, and that is where the memory requirements come from. This memory cannot be paged out, so it creates memory and cache pressure on other applications.
There are implementations that implement parts of the network stack inside the server program itself, and these can avoid the copies by reference counting or recreating payloads on-demand, that allows you to get away with a lot less memory usage, but involves a lot of tricky coding to be truly scalable, especially multi-socket servers pose some interesting issues there that the OS network stack already knows how to work around.
The options you have

run the pub/sub service on the same server as the app
run the pub/sub service on a dedicated server with OS networking
run the pub/sub service on a dedicated server with custom networking
run the pub/sub service on multiple dedicated servers

are your escalation strategy as the service grows. Moving from shared to dedicated does not require much planning, and can be done as needed; once that has happened, it is time to prepare the further stages.
Scaling up to multiple servers is going to introduce nondeterminism into your system, as clients may receive updates in different order, so for this scaling step to be successful, your clients need to be aware of this and be able to present a consistent view -- whether that is trivial or difficult depends on your actual application.
tl;dr: no need to optimize prematurely. Split out the service so the first scaling step is a simple configuration change, and start optimizing as soon as that has happened.


What is igrid server - port 19000?

Question: Recently our monitoring tools is reporting a port as down, the port number is 19000.
I have never seen this port before and I don't find out good information. Doing some tests, I've seen I can telnet it using localhost, but not ipaddres/hostname:
[root@server01 ~]# telnet 10.122.96.60 19000
Trying 10.122.96.84...
telnet: connect to address 10.122.96.60: Connection refused
[root@server01 ~]# telnet localhost 19000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

Also, it is used by some java process and informix database:
[root@server01 ~]# lsof -iTCP:19000

COMMAND   PID     USER   FD   TYPE    DEVICE SIZE/OFF NODE NAME
java    14492 java_user   93u  IPv6 133689854      0t0  TCP localhost:38902->localhost:igrid (ESTABLISHED)
oninit  25235 informix   12u  IPv4 133689855      0t0  TCP localhost:igrid->localhost:38902 (ESTABLISHED)
oninit  25277 informix    3u  IPv4  33431811      0t0  TCP localhost:igrid (LISTEN)
oninit  25277 informix    6u  IPv4 133689855      0t0  TCP localhost:igrid->localhost:38902 (ESTABLISHED)
oninit  25278 informix    7u  IPv4 133689855      0t0  TCP localhost:igrid->localhost:38902 (ESTABLISHED)
oninit  25280 informix    4u  IPv4 133689855      0t0  TCP localhost:igrid->localhost:38902 (ESTABLISHED)
oninit  25281 informix    4u  IPv4 133689855      0t0  TCP localhost:igrid->localhost:38902 (ESTABLISHED)
oninit  25282 informix    6u  IPv4 133689855      0t0  TCP localhost:igrid->localhost:38902 (ESTABLISHED)
oninit  25283 informix   11u  IPv4 133689855      0t0  TCP localhost:igrid->localhost:38902 (ESTABLISHED)
oninit  25284 informix    6u  IPv4 133689855      0t0  TCP localhost:igrid->localhost:38902 (ESTABLISHED)
oninit  25285 informix    6u  IPv4 133689855      0t0  TCP localhost:igrid->localhost:38902 (ESTABLISHED)
oninit  25286 informix    6u  IPv4 133689855      0t0  TCP localhost:igrid->localhost:38902 (ESTABLISHED)
oninit  25289 informix    6u  IPv4 133689855      0t0  TCP localhost:igrid->localhost:38902 (ESTABLISHED)
oninit  25290 informix   12u  IPv4 133689855      0t0  TCP localhost:igrid->localhost:38902 (ESTABLISHED)
oninit  25291 informix   12u  IPv4 133689855      0t0  TCP localhost:igrid->localhost:38902 (ESTABLISHED)
oninit  25292 informix   12u  IPv4 133689855      0t0  TCP localhost:igrid->localhost:38902 (ESTABLISHED)
oninit  25315     root    5u  IPv4  33431811      0t0  TCP localhost:igrid (LISTEN)
oninit  25319     root   22u  IPv4 133689855      0t0  TCP localhost:igrid->localhost:38902 (ESTABLISHED)

What is this? How can I allow this port for remote connections (our monitoring tool)? Recently the server has migrated from physical machine to virtual machine and now the monitoring tool cannot reach this port.
The /etc/services has:
igrid           19000/tcp               # iGrid Server
igrid           19000/udp               # iGrid Server

Answer: You can try to use ss and ps commands to check further. Example of output, replace 12345 with your PID:
$ sudo ss -lntp | grep :19000
LISTEN  0  128  127.0.0.1:19000  0.0.0.0:*  users:(("program-name",pid=12345,fd=62))

$ sudo ps aux | grep 12345
oioki  12345  0.4  1.9 5132596 238256 ?  Sl  09:33  3:06 /full/path/to/your/program-name

What is igrid server - port 19000?


Retrieve/recover cert pfx from Azure Application Gateway

Question: I want to retrieve/download the original pfx certificate that was uploaded onto our Application Gateway.
So far I have done the following in PowerShell:
$appGw = Get-AzApplicationGateway -Name "appgatewayname" -ResourceGroupName "appgatewayresourcegroup"

$certs = Get-AzApplicationGatewaySslCertificate -ApplicationGateway $appGw

$certBase64 = $certs[0].PublicCertData
$certBytes = [System.Convert]::FromBase64String($certBase64)

[io.file]::WriteAllBytes("C:\directory\newcert.pfx", $certBytes)

However, it doesn't seem to be a valid certificate, especially when I try to upload it onto our KeyVault.
Is anyone familiar, and is this even possible? Should I use the Data property instead of the PublicCertData?
Answer: .pfx file can't be retrieved after you uploaded it to an application gateway listener. I have checked Azure resource explorer, there is no API provided by Azure to retrieve it. And I also double-checked with the Azure product team.
Though seems we can use Get-AzApplicationGatewaySslCertificate PS command to get certs, but actually, it provides you with PublicCertData only, there is no PrivateCertData of .pfx file. I also have tested on my side, the value of Data property is empty.
So if you want to upload this .pfx file to Azure KV, I am afraid the only way is uploading the original pfx certificate to Azure KV directly.
Comment: Yeah, I think you are right. The Data property is definitely null.
Comment: @AnimaSola Thanks for your reply. So please mark this answer if your confusion has been solved, thanks!


CSS não carrega na versão mobile ao instalar certificado SSL grátis

Question: Instalei um certificado SSL https://zerossl.com/ em um site. O certificado está funcionando normal. O problema é que na versão mobile do site o CSS não é carregado, por outro lado, na versão desktop o CSS é carregado normalmente. Desconfio que o problema seja no htaccess. Segue o código do .htaccess que estou usando para redirecionar para HTTPS:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Usei esse mesmo htaccess em outro site que também instalei o mesmo certificado, e o CSS carregou certinho em ambos os dispositivos. Gostaria de saber se alguém passou por algo parecido e pode me ajudar na resolução desse problema.
Comment: Pode mandar o link do site em questão?
Comment: Olá Vinícius, obrigado pela atenção. Segue o link: https://www.camarapicui.pb.gov.br
Answer: Você está usando o caminho absoluto dos arquivos .css, .js.
E por isso, o navegador acusa que tem conteúdo misturado http com https
Use caminhos relativos.
<link rel="stylesheet"  href="/mdl/material.min.css">
<link href="/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="/css/style.css?style=2.9" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="/shadowbox-master/source/shadowbox.css">
<link rel="stylesheet" type="text/css" href="/slick-1.5.9/slick/slick.css">
<link rel="stylesheet" type="text/css" href="/slick-1.5.9/slick/slick-theme.css">

Comment: Muito obrigado amigo, deu certo!. Eu estava utilizando uma urlbase para o site. Usando a sua sugestão deu certo!


Endomorphisms of $V$ and the dual space

Question: I was told that $V\otimes V^{*}\simeq\mbox{End}\left(V\right)$. I can't find the isomorphism itself though. Can anyone tell me what it is with a proof?
Thanks!
Comment: There's some discussion of this [here](http://math.stackexchange.com/questions/57189/understanding-isomorphic-equivalences-of-tensor-product/57191#57191).
Comment: Are you assuming $V$ is finite-dimensional?
Answer: We'll assume that $V$ is finite-dimensional. Let's think about what elements of $V \otimes V^*$ are, to understand how these can be thought of as elements in $\operatorname{End}(V)$. If you give me a gadget like $v \otimes f$, I need to be able to take in an arbitrary $w \in V$ and give you something else. There's really only one thing I can do in this situation: I can apply $f$ to $w$, and scale $v$ by that amount:
$$
v \otimes f: w \mapsto f(w)*v.
$$
You can instantly see that any such endomorphism has rank 1. To get endomorphisms with larger rank, we'll have to move away from pure tensors. Let's pick a basis $e_1, \dots, e_n$ that comes with a dual basis $e_1^*, \dots, e_n^*$. When we apply $A \in \operatorname{End}(V)$ to a basis vector $e_i$, we get the $i^{th}$ column of $A$, $Ae_i$. This is represented by the element $e_i^*\otimes Ae_i$. So we can write $A$ in this form as
$$
A \mapsto \sum_{i=1}^n Ae_i\otimes e_i^*
$$
We can go one step further if we write $Ae_j$ in terms of the basis we choose. We have $Ae_i = \sum_{j =1}^n a_{ij}e_j$, so that in the basis $\{e_i^* \otimes e_j\}$ of $V^*\otimes V$ that we have constructed, we see that the coefficient on $e_i^* \otimes e_j$ of $A$ is just $a_{ij}$:
$$
A \mapsto \sum_{i,j}a_{ij} e_j \otimes e_i^*
$$
At this point, the fact that we have an isomorphism of vector spaces is very easy to show: we just observe that the above correspondence is a linear bijection.
Comment: Note the implicit assumption that $V$ has finite dimension.
Comment: Yes, I should make that more obvious.

Endomorphisms of $V$ and the dual space


Different apps from the same code base

Question: I have developed a generic app, which can ne customized for clients. Each app should be available in the app store.
Any idea what is the best way to deploy the different apps? This is of course also necessary on app updates.
Only the package name, some graphics and some settings change for different Apps. The Code will be the same for all.
Comment: If they're all in the same Xcode project, you could make multiple targets each with their own `xcassets` and `info.plist`.  If each app should be in its own project, I recommend packaging your code as a framework that the apps import and immediately execute.
Answer: Consider deploying your app as a framework, static library or CocoaPod. The clients should be able to use your framework/pod to customize the appearance (and anything else) and publish their apps.
CocoaPods: If your project is in progress and your client is using it, I wouldn't recommend it. Pods are great way for managing dependencies mostly if dependencies are not going to change on nightly basis. Also you'll have to make a few decisions about how to integrate it with your source control. If you and your clients will be working on their client app and pods simultanously. They'll most likely have to get your pods in a workspace, which defeats the purpose of pods. (If somebody knows a better way around editing pods and project simultanously, please let me know as well.)
Static Library/Frameworks: Rey Wenderlich has a good tutorial for creating frameworks. http://www.raywenderlich.com/65964/create-a-framework-for-ios

Different apps from the same code base


Why is ISql100DatabaseEncryptionKey blocking Schema Compare

Question: I am trying to do a Schema Compare in Visual Studio 2010 on some SQL Server 2008 databases. But I get the following error. What does it mean and how can I ignore?
<code>An error was received from SQL Server while attempting to reverse engineer elements of type Microsoft.Data.Schema.Sql.SchemaModel.ISql100DatabaseEncryptionKey: The user does not have permission to perform this action.
</code>
Update: "Write Updates" does actually work. But I can't "Export to editor".
Answer: I ran into the same problem. The only fix I found so far is to run the comparison as a user with the sysadmin Server Role. Even selecting to ignore Database Encryption Keys gives this error which seems broken to me. I filed a bug on connect: https://connect.microsoft.com/VisualStudio/feedback/details/552986/schema-compare-permission-error-for-database-encryption-keys-even-though-the-type-is-set-to-be-ignored
Comment: Thank you for reporting this to Microsoft. It is troublesome when like me is having the database on a web host where I can not change the user roles.
Comment: Microsoft closed it as won't fix, however they did give some details on specific permissions that need to be granted to avoid this error (I haven't had a chance to try it yet) - check out the connect link above for details.

I think they should have made it workable with a default setup and a login that has db_owner to the database you are working with but I guess they disagree.
Comment: The user I'm connecting with has the sysadmin server role, and it's still producing the error.
Comment: @MegaMatt Steve Campbell notes that VS 2010 SP1 resolves the issue. Give that a try if you haven't already.
Comment: I'm still encountering the issue on VS 2010 SP1, and the Connect link now appears to be broken. Here's the archive: http://web.archive.org/web/20110819201500/https://connect.microsoft.com/VisualStudio/feedback/details/552986/schema-compare-permission-error-for-database-encryption-keys-even-though-the-type-is-set-to-be-ignored
Answer: I found a work around that works for me.
http://www.richardmaxwell.name/blog/2011/3/2/work-around-isql100databaseencryptionkey-blocking-schema-com.html
Answer: VS2010 sp1 fixed this issue for me.
Comment: Sure does! The Error is a Warning now, permitting you to continue your work.
Answer: As mentioned "Write Updates" works and after you update target database you will be able to generate script using "Export To Editor".