Por que devo usar apenas um "return" em cada função?

Question: É comum vermos a recomendação de usar apenas um return por função/método. Mas isso parece algo sem sentido e deixa o código mais confuso em muitos casos.
Veja os exemplos:
Forma como eu costumo fazer:
if (cond)
    return 0;
else
    return 1;

Forma como é recomendado:
int resultado;
if (cond)
    resultado = 0;
else
    resultado = 1;
return resultado;

Por que há essa recomendação? O que se ganha em usar um único return?
Comment: Considero as vezes melhor haver apenas um return porque você pode depurar o resultado do método facilmente. Verificando o que sai em `resultado` neste caso (pois se não for assim, você precisará de colocar duas inspeções ou mais, uma para cada return, para ver aonde o método está entrando). Em compensação isso as vezes aumenta a complexidade ciclomática também.
Answer: Não deve, faça o que for melhor para a legibilidade do código
Basicamente essa regra é chamada de Single Entry, Single Exit (SESE) e é uma recomendação importante em linguagens que usam gerenciamento explícito (ou manual) de memória. Especialmente em linguagens que não contam com tratamento de erros por exceções.
É importante perceber que o uso de SESE quase sempre torna o código mais complexo.
Em linguagens como C, por exemplo, quando você precisa explicitamente liberar recursos alocados no final da execução da função, há a necessidade de replicar a liberação desses recursos antes de cada return e corre-se o risco de haver confusão quando existem vários deles. Se houver qualquer confusão, o código da função acaba terminando a execução da mesma sem fazer a liberação ou fazendo de forma indevida.
Gerenciamento de recursos e exceções
Em linguagens que fazem uso de exceções, SESE já faz ainda menos sentido já que qualquer função chamada potencialmente pode gerar uma saída da função atualmente em execução. Mesmo que você possa se valer da documentação para saber se uma função usada pode emitir uma exceção, terminando a função atual, você tem em mãos uma dificuldade de entendimento do código de manutenção futura.
Em C++, por exemplo, onde exceções existem, é fundamental o uso de gerenciamento automático ou semi-automático de recursos através da técnica chamada RAII (Resource Acquisition Is Initialization). Em Java e C# existem construções como try-finally e using para lidar com liberação de recursos.
Já que o programa pode ter vários pontos de saída implícitos, através do lançamento de exceções, onde você nem sabe de onde vem, não adianta tentar unificar a saída explícita em um único ponto. Você vai criar um fluxo confuso no código e não vai resolver qualquer problema.
Em linguagens com tratamento de exceção você tem duas situações:

a existência de recursos que facilitam a chamada "saída limpa" liberando todos os recursos aconteça o que acontecer;
a ineficácia da técnica já que sempre pode existir vários pontos de saída invisíveis em qualquer função chamada que emita um throw ou raise.

Então a técnica SESE se tornou desnecessária e até não recomendada já que em muitos casos o fluxo do programa acaba sendo complicado em nome da confiabilidade da saída única.
Infelizmente ainda há quem ache isso importante em qualquer linguagem e dissemina uma informação que é parcialmente obsoleta, como ocorre em muitos outros casos de "boas práticas" propagandeadas.
A legibilidade do código e a facilidade de manutenção são mais importantes que um guia que não traz nenhum benefício em linguagens que possuem ferramentas próprias para gerenciamento e liberação de recursos. É comum  termos a complexidade ciclomática reduzida quando utilizamos vários return fazendo que a execução da função termine o quanto antes.
É evidente que fazer uso correto do return e manter uma lógica coerente ainda é necessário não importando quantas vezes ele aparece no corpo da função.
Uso legítimo
Mas vejamos um caso em que o uso do SESE seria legítimo e solucionaria um problema existente, como é comum acontecer na linguagem C:
void funcao1() {
  resource recurso = acquire_resource();  //talvez possa ser um malloc() aqui
  if( funcao2(recurso) )
    return; // esqueceu do código de liberação antes do return e o recurso vazou
  .
  .
  .
  funcao3(recurso);
  release_resource(recurso);  //poderia ser um free()
  return;
}

Com SESE:
void funcao1() {
  resource recurso = acquire_resource();  //talvez possa ser um malloc() aqui
  if( funcao2(recurso) )
    goto saida; // manda para o ponto onde o recurso é liberado e termina a função
  .
  .
  .
  funcao3(recurso);
saida:
  release_resource(recurso);  //poderia ser um free()
  return;
}

Em linguagens assim você tem algumas opções:

Repetir o código de liberação do recurso
Solução horrorosa e facilita a criação de erros, fere o DRY

Colocar um goto para o trecho do código que faz a liberação de recursos
O código de liberação deve ser a última parte da função e é um dos melhores usos para o goto

Criar uma variável local para ajudar o controle de fluxo do programa
É bem mais complicado controlar o fluxo desta forma do que usando controles da linguagem que guardam o estado para o controle do fluxo implicitamente.

Como essas linguagens trazem essas dificuldades, foi criada a técnica do SESE que manda existir apenas um ponto de saída, ou seja um único return.
Fica bem mais fácil padronizar esta técnica. Se o programador tem na cabeça que sempre deve fazer isto, como se fosse obrigado pela linguagem, a chance dele esquecer de fazer a liberação é bem menor.
Conclusão
Precisamos usar técnicas apropriadas para cada linguagem. Tentar usar uma técnica criada para uma linguagem em outras acabam criando as interpretações erradas do tipo "goto nunca deve ser usado" e "comentários devem estar espalhados por todo programa detalhando tudo o que o programa faz", etc.
Certamente este post não encerra o assunto e seria interessante ver informações adicionais. Deixei alguns pontos de fora para dar oportunidade de outras pessoas complementarem.
Coloquei no Github para referência futura.

Esta resposta é baseada na encontrada em Where did the notion of "one return only" come from?
Comment: Eu nunca engoli essa história que "goto é sempre ruim", mas nunca tinha visto um caso prático em que ele fosse claramente útil e sem boas alternativas. +1
Comment: @bigown realmente esse preconceito de que isso ou aquilo não deve ser usado cai sempre no mesmo: desconhecimento. É como discutir se com ou sem OOP é melhor, se if sem { } pode ou não, etc. O bom programador usa o que é melhor na hora que é melhor, o programador mediano só usa o pouco que domina, e o mau programador repete o que ouve da maioria, pois não tem como discernir.
Comment: Esse exemplo de `goto` não me convenceu. É só fazer `if ( !funcao2(recurso) ) { funcao3(recurso); } release_resource(recurso); return;` que o `goto` pode ser dispensado, ficando até mais evidente qual é a lógica por trás do fluxo da função. Se não houver um exemplo melhor, só vejo o `goto` sendo indispensável em assembly e bytecode. Não à toa, BASIC é considerada uma linguagem ruim para iniciantes em programação e Java priva o uso da palavra-chave `goto`.
Comment: Quando eu fizer a pergunta sobre o `goto` você verá que não é bem assim. Não quis dar um exemplo completo porque esta questão não é sobre `goto`.
Comment: Os casos em que os benefícios do uso de `goto` supera seus malefícios são muito restritos. Tão restritos que se você disser que "`goto` é sempre ruim", você provavelmente vai estar errado _menos de 1% das vezes_. :)
Comment: @Marciano.Andrade Ninguém falou que é sempre ruim, só 99% das vezes. :) O problema é que esse `LABEL` pode estar em *literalmente qualquer lugar*, acima ou abaixo do `goto`, talvez em um ponto totalmente desconexo do fluxo que você estava acompanhando quando chegou no `goto`, por exemplo em uma outra função. Código-espaguete é quase sinônimo de código com muitos `goto's`. O problema não é o programador saber ler um `goto` esporádico, e sim querer perpetuá-lo em novos códigos de maneira desenfreada. Em 99% dos casos existem estruturas de controle melhores e mais previsíveis para se usar.
Comment: O problema de usar `goto` é que ele dificulta a manutenção do código pois ele fragmenta os "fluxos de execução de código". Um código com vários gotos pode ter fluxo do código que começa em cima, vai para baixo, volta pro meio... Isso geralmente é indesejável. Como no exemplo já dado pelo @Piovezan, nesse exemplo é possível refatorar o código para ter uma condição `if/else` muito mais legível e fácil de dar manutenção.
Comment: qual o problema em: ler um `goto LABEL` e procurar tal `LABEL`, seguindo a leitura a partir dela? Existem tantas pessoas que são tão limitadas na nossa área? Um programador que se preze precisa entender o que o `goto` faz e entender como ler um programa usando ele. Coisa ridícula isso de que `goto é sempre ruim`.
Comment: @Marciano.Andrade 1 `goto` é uma barbadinha de entender. O problema é quando a gente pega um código espaguete que fica jogando o fluxo pra lá e pra cá o tempo inteiro. Fica quase impossível saber quais variáveis foram inicializadas e qual o valor delas.
Comment: Realmente nunca havia visto um exemplo prático mostrando um benefício da utilização do goto. +1
Comment: Outro exemplo prático são os usados pelo csc onde loops e instruções de fluxo são substituídos por goto's.
Comment: _"SESE quase sempre torna o código mais complexo"_, _"Temos a complexidade ciclomática reduzida quando fazemos o fluxo terminar o quanto antes"_ - no tópico em inglês o único argumento para essas afirmações é quando se adiciona uma variável local e **a usa para fazer controle de fluxo**. Não acho que seja o caso em todas as situações.
Comment: Tem desenvolvedor que evita lógica negativa (`if (!condição)`) por achar difícil de ler. Isso sugere uma deficiência/comodismo em lógica de programação e leva a uma tendência a espalhar `return`'s pela função quando a condição negativa é invertida para uma positiva. Evitar lógica negativa não deveria ser desculpa para não aplicar SE.
Comment: Eu exemplifiquei o uso de `goto` em casos como este [nesta resposta](http://stackoverflow.com/a/3339958/176769), anos atrás.
Comment: @bigown Ok. Quando postar, por favor informe o link.
Comment: _"Em linguagens que fazem uso de exceções, SESE faz menos sentido"_ - em uma manutenção você pode querer acrescentar código imediatamente antes do (preferencialmente único) ponto de retorno, por exemplo uma chamada a função de log ou outra função qualquer.
Comment: Sempre discordei deste único return, pelo menos agora tenho um bom argumento. Ainda mais hoje em dia em que existem muitos IDEs onde se depura código e pode-se ver o ciclo
Answer: Atenção: A resposta do @Maniero (para a pergunta do @Maniero :) está claramente correta. Minha resposta é mais curta e direta, mas meramente complementar, com o objetivo de salientar um ponto que considero importante.
Para linguagens em um nível mais alto (com gerenciamento automático de memória: C#, Java, JavaScript, Python etc.) na verdade chega até a haver um consenso em não utilizar o formato descrito na pergunta como "recomendado".
Só dar uma olhada, por exemplo, nas respostas a esta pergunta do programmers.stackexchange (em Inglês).
Manter um único return tende a tornar o método mais complexo, com vários níveis de ifs e elses. Já o "early returning", pelo contrário, permite ao programador "se livrar" de condições mais fáceis de identificar, que exigem menos processamento (normalmente associadas a pré-condições de erro, ou que não permitam a execução completa da rotina). Logo, facilitando a escrita.
Isso também deixa o código mais simples de compreender, pois o método acaba se dividindo naturalmente em duas partes: um início composto de pré-condições de saída rápida, e o código que efetua o processamento propriamente dito, quando as condições de entrada forem satisfeitas. Logo, facilitando a manutenção.
Uma forma ainda melhor seria justamente utilizar pré-condições explícitas, ou programação-por-contrato, em linguagens que tenham suporte a isso (tais como Eiffel, por exemplo).
Comment: Excelente complemento! Ao estilo Eric Lippert :)
Comment: Perfeito. Muita gente (eu me incluo) sempre tomou como base a prática SESE para qualquer que fosse a linguagem de programação usada.
Answer: Discutindo questão paralela...
MEDOS
Como a pergunta refere-se a qualquer linguagem, qualquer situação... Me recordei de situações onde o problema não era estilo, elegância, legibilidade, etc. mas o comportamento lógico da função. O uso mal pensado do return, ou a visão de um monte de returns, dá um certo "medo de errar", de surgirem bugs misteriosos...
Me recordo de três situações típicas:

Quando o algoritmo é complexo, cheio de ramificações, e desejo "provar" que ele termina (problema clássico da Computação)... Aí creio que devemos nos lembrar também da regra do "para todo IF um ELSE", que ajuda a verificar algebricamente se tem return para todas as situações.

Quando existe recorrência: como vai ficar a pilha de recorrência?

Quando a linguagem não estabelece com clareza a "encerramento de tudo" após o return.
Comment: Excelente complemento.
Answer: resposta rápida seria em relação a Manutenibilidade do código, o fato de existir apenas um return ajuda a mapear com facilidade o fluxo dentro do método ou função
Comment: Aumentar a complexidade ciclomática facilita mapear o fluxo?


How do I free pVect so that memory can be used again?

Question: The code is
Vect::~Vect()
/*
PRE:  None
POST: free pVect
*/
{
    cout << "(__||  - DELETE (unlock the memory for): " << (*this) << endl;
    // Put code below ....

}

Basically, I need it to correctly free pVect so that my other fuctions can work.
Also there is a .h file with this
double* pVect;
Comment: Welcome to Stack Overflow. Please read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly please learn how to [edit] your questions to improve them (like removing totally unrelated tags, like the C language tag).
Comment: No don't post the same question again, instead **[edit]** your current question to add information.
Comment: We can't possibly help given only the information in the question.
Comment: I'll post another question in 2 hours with all the information
Comment: Alright I just edited it :D
Comment: After you add a destructor you may get into a problem of double deletes. You probably want to read about this:  [https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three)
Answer: It would have been nice if you'd provided a full but minimally-producable example to start with. Let's try this:
class Vect {
public:
    ~ Vect();
private:
    double *pVect = nullptr;
};

Vect::~ Vect() {
    delete [] pVect;
}

Make sure you keep pVect equal to a nullptr unless it contains a valid address. Which means you absolutely should give it a default value like I did.


Solve the equation: $ 3(\sin^3 x + \cos^3 x) + 4(\sin^7 x + \cos^7 x) = 7(\sin^5 x + \cos^5 x) $

Question: Problem

Solve the equation in $[0, \pi]$
$$
3(\sin^3 x + \cos^3 x) + 4(\sin^7 x + \cos^7 x)
= 7(\sin^5 x + \cos^5 x)
$$

This problem is from the algebra round of a local high school competition that has ended.

I have not been able to get very far for this question, I can only see that we might try to use sum of cubes to simplify the first term into $3(\sin x + \cos x)(1 - \cos x \cdot \sin x)$. Could I receive some help for this question? Thank you.
Answer:
$$
3(\sin^3 x + \cos^3 x) + 4(\sin^7 x + \cos^7 x)
= 7(\sin^5 x + \cos^5 x).
$$

$$\begin{align}
3(\sin^3 x + \cos^3 x)-3(\sin^5 x + \cos^5 x)
&= 4(\sin^5 x + \cos^5 x)- 4(\sin^7 x + \cos^7 x) \\
\\
3(\sin^3 x \cos^2x+ \cos^3 x\sin^2x)&= 4(\sin^5 x \cos^2x+ \cos^5 x\sin^2x) \\
\\
3\sin^2 x\cos^2 x(\sin x + \cos x)&= 4\sin^2 x\cos^2 x(\sin^3 x + \cos^3 x)
\end{align}$$
so we get:
$$\sin x=0, ~~\cos x=0,~~\sin x + \cos x=0,~~3=4(\sin^2x+\cos^2x-\sin x \cos x)$$
which is equivalent to
$$\sin x=0, ~~\cos x=0,~~\sin x + \cos x=0,~~\sin(2x)=\frac{1}2$$
Solution:
$$\boxed{x=0,~~x=\frac{\pi}{12},~~x=\frac{\pi}2,~~ x=\frac{3\pi}4,~~x=\frac{5\pi}{12},~~ x=\pi}$$
Comment: Congratulations! I like your answer very much! (+1)
Comment: Thank you very much :)
Comment: It's also equivalent to $\sin2x\in\left\{-1,\,0,\,\frac12\right\}$. This may be why the problem specifies a range of width $\pi$.
Answer: Let $\sin x=s$ and $\cos x=c$.
$$(3s^3-7s^5+4s^4)+(3c^3-7c^5+4c^7)=0$$
$$s^3(3-7s^2+4s^4)+c^3(3-7c^2+4c^4)=0$$
$$s^3(4c^4-c^2)+c^3(4s^4-s^2)=0$$
$$4s^3c^4+4c^3s^4-(s^3c^2+c^3s^2)=0$$
$$4s^3c^3(s+c)-s^2c^2(s+c)=0$$
$$s^2c^2(s+c)(4sc-1)=0$$
And we conclude as Mathfail did.
Answer: Hint
If you use the linearization of the powers of the sine and cosine functions
$$4(\sin ^3(x)+\cos ^3(x))= 3 \sin (x)-\sin (3 x)+3 \cos (x)+\cos (3 x)$$
$$16(\sin ^5(x)+\cos ^5(x))= 10 \sin (x)-5 \sin (3 x)+\sin (5 x)+10 \cos (x)+5 \cos   (3 x)+\cos (5 x)$$
$$64(\sin ^7(x)+\cos ^7(x))=5 \sin (x)-21 \sin (3 x)+7 \sin (5 x)-\sin (7 x)+35\cos (x)\\
+21 \cos (3 x)+7 \cos (5 x)+\cos (7 x)$$
So
$$\text{rhs - lhs}=\frac{1}{4}\, \sin ^2(2 x) \,(\cos (3 x)-\sin (3 x))$$


onChange event firing incorrectly after being loaded programmatically

Question: I have an APEX application where there are many drop down items. I've bound change event handlers to them using the bind function of jQuery.
Now when I load the content of a drop-down programmatically using $('#ELEMENT').trigger('apexrefresh'), the drop-down reloads but the change event handler fires automatically.
How do I prevent this from happening? I tried avoiding binding the event handler using bind and instead adding the onChange attribute to the element. The incorrect behaviour was still present.
Here is the skeletal code:
$(document).ready(function()
{
   $('#P7021_MSG_DEF').bind('change', function(e)
   {
      console.log('bound function onChange() msg_def');
      updateStartWord();
   }
   );
});

function updateMsgDef()
{
   console.log('function  updateMsgDef() ');

      $('#P7021_MSG_DEF').one('apexafterrefresh', function()
      {
         if( $x('P7021_RESTORE_CHK').value == 'Y')
         {
            setdefault('P7021_MSG_DEF', vJson.msg_def);
         }
         updateStartWord();
      }
      ).trigger('apexrefresh');
}

In the above code, when the updateMsgDef is called from another function the function updateStartWord() gets called twice - once by updateMsgDef() itself and again by the onChange handler that was bound to P7021_MSG_DEF item.
If anyone could help on this?
Comment: Any particular reason not to use dynamic actions?
Comment: Yeah. Page logic is too complicated to implement using a declarative logic like DAs. Tried it but had to give up after maintaining it became a nightmare.
Comment: Could you post the code?
Answer: Calling $('#ELEMENT').trigger('apexrefresh') is going to trigger the change event. Short of going back to the drawing board altogether, the solution is going to be a hack whatever you do. You could poke about in (and quite possibly break) Oracle's javascript. You could write your own AJAX to populate the select list.
The easiest way might be to check in your onChange event which element currently has focus, eg:
onChange = "if($( document.activeElement).attr('id')=='YOUR_PAGE_ELEMENT')
                { $( document.activeElement).trigger('apexrefresh'); };"

If the user has changed the select list, it should still have focus. There's no guarantee that will work in all browsers, but I think it should be ok in current Chrome and IE versions.
I've been in a similar situation to yours, and have come to accept that if the page logic is too complicated to implement using DAs, maintaining it is likely going to be a nightmare whatever happens. Much as I like "proper" programming, Apex is really all about the declarative controls.


clearing cache to call hooks in .module file

Question: I have created a token in .module file. that gives current node title.
But every-time I change the title of node, I have to rebuilt cache so that updated title get reflected in my token.
Of-course clearing cache again and again on every page refresh is not a good idea.
Any other way to call hook_token_info and hook_tokens automatically on every page load?
PS: I also installed "token" module and this module is using hook_module_implements_alter(&$implementations, $hook).
@edit:
function hook_token_info() {
    $info = array();
    $info['tokens']['etf']['node-title'] = array(
    'name' => t('Node Title'),
    'description' => t("Provides current node title."),
    'type' => 'etf',
    );
    return $info;
}

function hook_tokens($type, array $tokens, array $data = array(), array $options = array(), BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();

  $url_options = array('absolute' => TRUE);
  if(isset($options['langcode'])) {
      $url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']);
      $langcode = $options['langcode'];
  }
  else {
      $langcode = NULL;
  }
  $request = \Drupal::request();
  $route = $request->attributes->get(RouteObjectInterface::ROUTE_OBJECT);
  $title = \Drupal::service('title_resolver')->getTitle($request, $route);
  if ($type == 'etf') {

    foreach ($tokens as $name => $original) {
      switch ($name) {
              case 'node-title':
              $replacements[$original] = $title;
//              drupal_flush_all_caches();
//              sleep(2);
              break;
       }
    }

  }
  return $replacements;
}

All code is written in .module file
Comment: Your question sounds a bit fishy, I'm not sure you can do what you want to do with tokens. Can you explain a bit what you mean by current node and how you use the token?
Comment: I agree with @googletorp, here. It's not totally clear what your code is doing. As far as I see, modules implementing tokens don't need to clear any cache, to get their tokens updated. Also, it's not clear how the part about your module implementing `hook_module_implements_alter()` matters for the answer.
Comment: I have edited the question with code i'm trying to implement. When using token [etf:node-title], this token gets replaced with current node's title. But for this, I have to re-built cache every time.
Answer: Short
This is wrong use of tokens, it can never work.
Long
So what you are doing is incorrect usage of tokens. The idea with tokens, is that you have some data object, like a Node, a User etc and based on that you can output something from that object, like the label, uri etc.
Tokens aren't designed to load data from somewhere and display it. For Drupal 8 with all the new caches, it's even more tricky, but even for Drupal 7 this would not work. The reason is that the result of token replacement is cached, since the idea with tokens is that it will always be the same (as long as the data objects which are used for to make the tokens do not change.
To achieve this feature, you would need to load the current node and make it available in the texts where you want to use it as a token, and for Drupal 8 you would also need to add cache context of the url. If I knew what you are using this for, I might be able to give a more precise advise on what the best way would be to achieve this.
Comment: @SugandhKhanna You might have been using it in a such a way, that you avoided the issue, but this is definitely a misuse of tokens. Like I said, to really help you we need to know what you actually want to achieve.
Comment: Thanks @googletorp but the approach of using hook_token_info in .module file worked fine in Drupal 7. Without clearing cache, everything is running perfect. and the same approach is used by https://www.drupal.org/project/token  (token) contibuted module, which is also running smooth.
Answer: The node title already has a token, you can see this, if you install the token module: https://www.drupal.org/project/token
This is only an alpha version, but it is OK to use it.
Go to the help page of the module and you will see that the node title is already there:
[node:title]

You can use this token only in a node context. If you use it outside of this, for example in a block, you have to add a cache context in this block:
$build['#cache']['contexts'][] = 'url.path';

And a cache tag to invalidate the block if the node is changed:
$build['#cache']['tags'][] = 'node:N';

or if any node is changed:
$build['#cache']['tags'][] = 'node_list';


How to merge array field values in php?

Question: My array is like this:
Array
(
    [0] => Array
        (
            [id] => 1
            [name] => a
            [hardware_type] => keybord
        )

    [1] => Array
        (
            [id] => 2
            [name] => b
            [hardware_type] => mouse
        )

    [2] => Array
        (
            [id] => 1
            [name] => a
            [hardware_type] => mouse
        )

    [3] => Array
        (
            [id] => 1
            [name] => a
            [hardware_type] => moniter
        )

    [4] => Array
        (
            [id] => 2
            [name] =>b
            [hardware_type] => keyboad
        )

)

required out put like this i want only merge hardware type
Array(
    [0] => Array

        (
            [id] => 1
            [name] => a
            [hardware_type] => keybord, mouse, moniter
        )
[1] => Array
    (
            [id] => 1
            [name] => b
            [hardware_type] => keyboard, mouse
        )

 )

Comment: Do you want merge Hardware types for each & every element?
Comment: yes i want merge only Hardware type
Comment: Your example shows that the same ID corresponds to the same name; Any chance there will be an ID corresponds to different names in your real data?
Answer: Where $array is the input array you described, where $newarray is the output array you desire, and assuming every value of id has the same name as in your example input:
$temp = array();

foreach ($array as $item) {
  $temp[$item['id']] = array('id' => $item['id'], 'name' => $item['name']);
  if (empty($newarray[$item['id']]['hardware_type']))
    $temp[$item['id']]['hardware_type'] = $item['hardware_type'];
  else
    $temp[$item['id']]['hardware_type'] .= ', ' . $item['hardware_type'];
}

$newarray = array_values($temp);

If you want the hardware_type to be an array instead of a comma-separated list of strings, do this instead:
$temp = array();

foreach ($array as $item) {
  $temp[$item['id']] = array('id' => $item['id'], 'name' => $item['name']);
  $temp[$item['id']]['hardware_type'][] = $item['hardware_type'];
}

$newarray = array_values($temp);

How to merge array field values in php?


What is the reason for ArrayIndexOutOfBoundsException in my code?

Question: I am implementing Graham Scan Algorithm for convex hull in Java.
I am getting this error while running the code. For input string: "10 18"
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at Graham.SelectMin(Graham.java:110)
    at Graham.GrahamScan(Graham.java:78)
    at Graham.main(Graham.java:41)

Can anyone help me out to solve this error?
Thanks
Comment: It would be helpful to us if you could provide some code.
Comment: You provided the error message.  What's the code that you wrote that's producing that output?
Comment: What does "10 18" mean? Does it mean 1 point with coordinates 10 and 18?
Comment: look at http://stackoverflow.com/questions/5554734/java-lang-arrayindexoutofboundsexception
Comment: 10 18 is the 1st line from .txt file
Answer:
java.lang.ArrayIndexOutOfBoundsException: 0

This means that you're trying to access an element of an empty array. (An array of size 0.)
You need to have a non-negative size of the array to be able to access element at index 0.
For reference, this code for instance, produces the same error:
int initialSize = 0;
int[] arr = new int[initialSize];
System.out.println(arr[0]);

Comment: Yeah. Check your `SelectMin` method and before accessing the array, check if `arrayName.length > 0` before doing anything. I would also suggest that you change the first letter of the name of every one of your methods to lowercase.
Comment: /**
  *
  *
  *
  */
 public class Point {
  public int x;
  public int y;
  public int getX() {
   return x;
  }
  public void setX(int x) {
   this.x = x;
  }
  public int getY() {
   return y;
  }
  public void setY(int y) {
   this.y = y;
  }
  public Point(int x_,int y_){
   x = x_;
   y = y_;
  }

  public String toString(){
   StringBuffer sb = new StringBuffer();
   sb.append(x);
   sb.append(",");
   sb.append(y);
   return sb.toString();
  }
 }
Comment: import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.io.*;
Comment: public class Graham {
 private Point p[];
 private int size;
 private List list = new ArrayList();

 public static void main(String[] args) {
  List list2 = new ArrayList();
  Graham g = new Graham();
  BufferedReader br ;
  try{
   br = new BufferedReader(new FileReader(args[0]));
   String buf = br.readLine();
   while (buf!=null&&buf!=""){
         StringTokenizer st = new StringTokenizer(buf,",");
      int x = Integer.parseInt(st.nextToken());
      int y = Integer.parseInt(st.nextToken());
      list2.add( new Point(x,y));
      buf = br.readLine();
   }
Comment: }catch(Exception e){
    System.out.println(e.getMessage());
   }
      g.setSize(list2.size());
      Point[] p = new Point[list2.size()];
      Iterator it1 = list2.iterator();
      int i=0;
      while(it1.hasNext()){
       p[i++]= (Point)it1.next();
      }
Comment: g.setP(p);
   g.GrahamScan();

  List list = g.getList();
  Iterator it = list.iterator();
  while(it.hasNext()){
   Point point = (Point)it.next();
   System.out.println(point);
  }

 }

   public List getList() {
  return list;
 }

 public void setList(List list) {
  this.list = list;
 }

 public Point[] getP() {
  return p;
 }

 public void setP(Point[] p) {
  this.p = p;
 }

 public int getSize() {
  return size;
 }

 public void setSize(int size) {
  this.size = size;
 }
Comment: boolean GrahamScan () {
      SelectMin();  SortPoints();
      if( size > 2){
          int stk[] = new int[size];
       int top = 2;
       stk[0] = 0; stk[1] = 1; stk[2] = 2;
       for (int i = 3; i < size; i++) {
         while (Area(p[stk[top-1]], p[stk[top]], p[i]) < 0)
      top--;
         stk[++top] = i;
       }
       for (int i = 0; i <= top; i++)
         list.add(p[stk[i]]);
      }else{
       for (int i=0;i< size;i++){
        list.add(p[i]);
       }
      }
      return true;
    }
Comment: static int Area (Point p0, Point p1, Point p2) {
      int dx1 = p1.x - p0.x, dy1 = p1.y - p0.y;
      int dx2 = p2.x - p0.x, dy2 = p2.y - p0.y;
      return dx1 * dy2 - dx2 * dy1;
    }

       void SelectMin () {
      int ym = p[0].y;
      int m = 0;
      for (int i = 1; i < size; i++) {
        if (ym > p[i].y || (ym == p[i].y && p[m].x > p[i].x)) {
        ym = p[i].y; m = i;
        }
      }
      SwapPoints(0, m);
    }
Comment: // It Sorts the points
   void SortPoints () {
      for (int i = 1; i < size - 1; i++)
        for (int j = i + 1; j < size; j++)
   if (Area(p[0], p[i], p[j]) < 0)
     SwapPoints(i, j);
    }
   void SwapPoints (int i, int j) {
      Point tmp;
      tmp = p[i]; p[i] = p[j]; p[j] = tmp;
    }

}
Comment: I added Graham.java in # of comments 1 by 1.
Comment: 2 2 and 3 3 o/p is 1 1 and 3  3
Answer: it means that on line 110 of Graham.java you are trying to access an array index that is either < 0 or that is > the length of your array, can't tell exactly which array without code.
Also Graham.SelectMin(Graham.java:110) shows that you are naming method calls in a non-idiomatic Java way. In Java method calls should be in lowerCamelCase, such as Graham.selectMin();
In Java UpperCamelCase is reserved for ClassNames.
Comment: This is my code :    /**
  *
  *
  *
  */
 public class Point {
  public int x;
  public int y;
  public int getX() {
   return x;
  }
  public void setX(int x) {
   this.x = x;
  }
  public int getY() {
   return y;
  }
  public void setY(int y) {
   this.y = y;
  }
  public Point(int x_,int y_){
   x = x_;
   y = y_;
  }

  public String toString(){
   StringBuffer sb = new StringBuffer();
   sb.append(x);
   sb.append(",");
   sb.append(y);
   return sb.toString();
  }
 }

Also==========================
Comment: file name: case1.txt1 1
2 2
3 3


Call marker icon

Question: I want to check if my google maps marker has a certain image ressource like this:
if (marker.getIcon() == BitmapDescriptorFactory.fromResource(R.drawable.imagefile)) {
}

But marker.getIcon does not work, so how can I call the icon of a marker?
Answer: you can't get the icon, and the equals will not be valid anyway (it's not the same object if you get from BitmapDescriptorFactory.
Anyway, you can try to use String ids for markers instead of icons
Answer: You can use a HashMap to store the type of Icon for each Marker that is added to the map.
I just got a simple example working to give the general idea, using a HashMap that maps the Marker ID to the color of the Icon currently set for the Marker.
If you are using custom Drawables, you could use HashMap<String, Integer> instead of HashMap<String, Float> as I have in this simple example.
If you change the Marker Icon color or Drawable resource, you should also update the HashMap as well.
Class code:
public class MainActivity extends AppCompatActivity {

    HashMap<String, Float> markerIcons = new HashMap<>();

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setUpMapIfNeeded();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    private void setUpMap() {

        mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {

            Float markerColor;
            @Override
            public boolean onMarkerClick(Marker marker) {
                markerColor = markerIcons.get(marker.getId());
                if (markerColor == BitmapDescriptorFactory.HUE_MAGENTA){
                    Toast.makeText(MainActivity.this, "HUE_MAGENTA", Toast.LENGTH_LONG ).show();
                }
                else if (markerColor == BitmapDescriptorFactory.HUE_AZURE){
                    Toast.makeText(MainActivity.this, "HUE_AZURE", Toast.LENGTH_LONG ).show();
                }
                else if (markerColor == BitmapDescriptorFactory.HUE_CYAN){
                    Toast.makeText(MainActivity.this, "HUE_CYAN", Toast.LENGTH_LONG ).show();
                }

                return false;
            }

        });
        Marker marker = null;
        marker = mMap.addMarker(new MarkerOptions().position(new LatLng(2, 2)).title("Marker Magenta").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
        markerIcons.put(marker.getId(), BitmapDescriptorFactory.HUE_MAGENTA);

        marker = mMap.addMarker(new MarkerOptions().position(new LatLng(3, 3)).title("Marker Azure").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
        markerIcons.put(marker.getId(), BitmapDescriptorFactory.HUE_AZURE);

        marker = mMap.addMarker(new MarkerOptions().position(new LatLng(4, 4)).title("Marker Cyan").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
        markerIcons.put(marker.getId(), BitmapDescriptorFactory.HUE_CYAN);

    }
}

Result after clicking on each Marker:

Call marker icon


How to find out if an OpenSSL certificate was created by a certain private key?

Question: I have an OpenSSl certificate. I also need the private key. I was told it is located somewhere on the server, and true enough, I found multiple SSL key files.
Before I try them all by brute force: Is there a way I can find out on terminal if a private key was used to create the certificate?
Answer: The classic reference for this is this FAQ in the online Apache docs.
In that document, an md5 of the modulus is used because

As the public exponent is usually 65537 and it's difficult to visually check that the long modulus numbers are the same, you can use the following approach

This gives:
$ openssl rsa -noout -modulus -in key.pem.decrypted | openssl md5
(stdin)= 9fxxfoobar558d9xx0045a89467d2bxx

$ openssl x509 -noout -modulus -in crt.pem | openssl md5
(stdin)= 9fxxfoobar558d9xx0045a89467d2bxx

I'm proposing the use of process substitution to avoid visual comparison of the modulus:
$ diff \
    <(openssl x509 -noout -modulus -in cert.pem) \
    <(openssl rsa -noout -modulus -in key.pem.decrypted)

If the output is empty, the private key matches the certificate.
This is just a more convenient way to compare the strings than the one in Andrew Schulman's answer, which is, of course, also valid.
Another reference here.
Comment: The modulus is the important part of the public key. So comparing just the modulus should give you the same result as comparing the entire public key.
Comment: Are you saying that the comparison of the pub key is not enough or is it merely a more convenient way to compare the cert and the key?
Comment: By "*comparison of the pub key*", do you mean just comparing the two keys themselves?
Answer: To check that a certificate file certifies the public key associated with a given private key file, compare the public keys associated with each:
openssl rsa -in KEYFILE -pubout
openssl x509 -in CERTFILE -pubkey -noout

The certificate and private key are matched if and only if the public keys are identical.


Como remover o nome do aplicativo "app_name" da toolbar?

Question: Estou começando no mundo Android, e estou desenvolvendo um projeto pessoal pra apromorar meu conhecimentos, mas me deparei com um problema, eu defini o thema do meu app para:


I accidentally disabled the web interface for DD-WRT

Question: I accidentally disabled the web interface for my DD-WRT router, but I can still SSH in. How can I fix it so I can admin with the GUI again?
Comment: How did you disable the gui?
Comment: I though I was disabling the remote access, but it was local :)
Comment: Answer from @charnley at http://superuser.com/a/263296 helped quite a lot. Also, I would suggest this question to be merged with the answers from [here](http://superuser.com/q/263295).
Answer: From the dd-wrt wiki:

If for some reason you completely lost
  web access to the router, the web
  server (HTTP daemon) may be shut down.
  To regain access try starting the web
  server. SSH or telnet into the router
  and enter the following commands:

httpd -h /www
This forum thread gives all to gory details about enabling/disabling the web interface.
Answer: You can try restarting the HTTP daemon since you can still SSH in.  If that doesn't work, you may have to resort to a full reset/reboot.
Comment: Ah nice. A reboot didn't work because it was diabled in the nvram. httpd -h /www worked perfectly. Thank you!
Answer: It's a quite old question.
You can simply restart the HTTP daemon with:
startservice httpd


AppleScript : Search safari tab and open tab

Question: I would like to find a safari tab, and focus on this tab
This is not working, however the tab is found alright, I just can't open this tab.
tell application "Safari"
    repeat with t in tabs of windows
        tell t
            if name starts with "facebook" then open tab
        end tell
    end repeat
end tell

Also I wonder can I found some text from a another tab without focus on this tab ?
to getInputByClass75(theClass, num)
    tell application "Safari"
        set input to do JavaScript "
document.getElementsByClassName('" & theClass & "')[" & num & "].innerHTML;" in document 1
    end tell
    return input
end getInputByClass75
getInputByClass75("Order", 0)
set theText to Unicode text
set theSource to getInputByClass75("Order", 0)

property leftEdge75 : "Display"
set saveTID to text item delimiters
set text item delimiters to leftEdge75
set classValue to text item 2 of theSource
set text item delimiters to rightEdge75
set OrderLink to text item 1 of classValue
set text item delimiters to saveTID
OrderLink

Answer: The right phrase to bring a tab to foreground is
tell window x to set current tab to tab y
Try this
tell application "Safari"
    repeat with w in windows
        if name of w is not "" then --in case of zombie windows
            repeat with t in tabs of w
                if name of t starts with "facebook" then
                    tell w to set current tab to t
                    set index of w to 1
                end if
            end repeat
        end if
    end repeat
end tell

--
You can execute javascripts in background tabs. Specify the tab like this:
tell application "Safari"
    do JavaScript "document....." in tab 1 of window 1
end tell

Comment: Thank you, that's great. The first script (find tab) work fine but always have a error "Safari got an error: Can't get every tab of item 2 of every window."
Comment: This could be a zombie window. I've updated the answer.
Comment: just one little thing, how would you save the tab number as a variable instead ? I tried with if name of t contains "google" then set tabNumber to t but then the result look like "item 5 of every tab of item 1 of every window of application "Safari""


TYPO3 + DCE - display image thumbnail in backend

Question: I am using TYPO3 6.2 and the extension DCE (dynamic content elements).
Everything works fine, except that I wasn't able to display a thumbnail for the custom content elements in the backend.
For the frontend I use this fluid template:
    <f:for each="{dce:fal(field:'image', contentObject:contentObject)}" as="fileReference" iteration="iterator">
        <f:if condition="{iterator.isFirst}">
            <f:image src="{fileReference.uid}" alt="" treatIdAsReference="1" width="140px"/>
        </f:if>
    </f:for>

It works fine. But if i use the same code for the backend (in the field "Bodytext preview template (fluid)") it doesn't output anything. What could be the reason for this?
By the way, what is a more elegant way to output just the first image? I guess I wouldn't have to use this for loop then?
Answer: For some reason you need to refer to "fields" instead of "field" in the backend previews

<f:if condition="{fields.image}">
  <f:for each="{fields.image}" as="fileReference">
    <f:image src="{fileReference.uid}" alt="" treatIdAsReference="1" width="140px"/>
  </f:for>
</f:if>


Update problems when updating to Varbase

Question: I updated a Drupal 8 site to Varbase release 16. After running update.php I get the following error.

Symfony\Component\Routing\Exception\RouteNotFoundException: Route "content_lock_timeout.settings_form" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName() (line 190 of core\lib\Drupal\Core\Routing\RouteProvider.php).

Has anybody a idea how to proceed?
Answer: The https://www.drupal.org/project/varbase/issues/2953417 shows Varbase is using Content locking module, which is causing the reported error. Try temporarily disabling it to proceed.


What kind of services does ESXI SLP port advertise to locally connected hosts?

Question: I got enthusiastic about the last exploitations of ESXI CVE-2021-21974 (heap overflow exploitation). After researching the SLP service, which is the weak point in this CVE, I tried to turn it off, after which everything still was working perfectly fine, so I had a logical question, what kind of services SLP port on ESXI advertises about?
In addition, I would like to ask how is it possible to send an SLP request manually.
Answer: you can download SLP software from https://www.openslp.org for a number of OSs (including Windows and Linux). That includes a CLI tool called slptool which you can use to send SLP discovery messages.
ESXi uses SLP to announce its CIM monitoring service.


How do I find all the databases and related schemas on a Postgres cluster?

Question: I want to list out all the databases and schemas within a Postgres cluster, how do I get that list?
I have run below queries (I am using pgAdmin)
SELECT * FROM pg_database; --This lists all the databases in the cluster

SELECT distinct table_catalog, table_schema
FROM information_schema.tables
ORDER BY table_schema; --This lists all the schemas in the current database I am in.

I tried to combine them (below query) but it just gives result from information_schema and is limited to one database only.
select distinct db.datname, t.table_schema from pg_database db
inner join information_schema.tables t on db.datname = t.table_catalog
order by db.datname, t.table_schema

Answer: Databases are (logically) strictly separated in PostgreSQL; you cannot get information about objects in one database (e.g. schemas) with queries in another database.
You'll have to connect to all databases in turn and query each for its schemas.
Comment: Aahh, that sucks. Thanks for answer though.


Simple Twinfield API request with Postman

Question: I want to connect sales invoices with javascript/ google apps script. Therefore I want to test some things with Postman. I know, that the API works with XML and to get data you need to use the so called Browse code 100. But I am stucked with creating a working request to get sales invoice data :(
What I did so far:

Read the Twinfield API documentation
Created a login in the developer portal
Managed to request authorization code with Postman: I did a workaround to adjust the parameters in Postman and then paste the request URL into the browser
Managed to request access token
Determine cluster

I did a lot of research but couldn't find any examples I could understand. Examples like

how should a request URL in Postman look like
what parameters do I need
is it possible to have a handy request in javascript to get open sales invoices

I would be very grateful for any help!
Answer: Try this
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Header>

            <AccessToken>{{Accescode}}</AccessToken>
            <CompanyCode>{{Company}}</CompanyCode>

    </soap:Header>
    <soap:Body>
        <ProcessXmlDocument xmlns="http://www.twinfield.com/">
            <xmlRequest>
                <columns code="100">
                    <column xmlns="">
                        <field>fin.trs.head.yearperiod</field>
                        <operator>between</operator>
                        <from>2021/01</from>
                        <to>2022/01</to>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.head.code</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.head.shortname</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.head.number</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.head.status</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.head.date</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.line.dim2</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.line.dim2name</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.head.curcode</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.line.valuesigned</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.line.basevaluesigned</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.line.repvaluesigned</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.line.openbasevaluesigned</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.line.invnumber</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.line.datedue</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.line.matchstatus</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.line.matchnumber</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.line.matchdate</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.line.openvaluesigned</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.line.availableforpayruns</field>
                        <visible>true</visible>
                    </column>
                    <column xmlns="">
                        <field>fin.trs.line.modified</field>
                        <visible>true</visible>
                    </column>
                </columns>
            </xmlRequest>
        </ProcessXmlDocument>
    </soap:Body>
</soap:Envelope>

EDIT:
Lets start with the beginning, first I'm assuming you are able to get the access code.
With the access code you need to do a Postmand get request to the following url: https://login.twinfield.com/auth/authentication/connect/accesstokenvalidation?token={{Accescode}}
from the results you need to copy over the clusterUrl for me it looks like this:
"twf.clusterUrl": "https://api.accounting2.twinfield.com"

Next we need to find the companyID's this is also something we can get from Postman with the following post to the url: https://api.accounting2.twinfield.com/webservices/processxml.asmx?wsdl
as you can see this has the cluserURL from before so you've to replace this with the one you find.
The XML envelope you need to send with this request is the following:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:twin="http://www.twinfield.com/">
    <soapenv:Header>
        <twin:Header>
            <twin:AccessToken>{{Accescode}}</twin:AccessToken>
        </twin:Header>
    </soapenv:Header>
    <soapenv:Body>
        <twin:ProcessXmlString>
            <twin:xmlRequest><![CDATA[<list><type>offices</type></list>]]></twin:xmlRequest>
        </twin:ProcessXmlString>
    </soapenv:Body>
</soapenv:Envelope>

this will result in a list with ID's you can collect the data from.
To get the sales invoices you need to use the following url again:
https://api.accounting2.twinfield.com/webservices/processxml.asmx?wsdl
but this time we change the envelope to the first one I posted above, just the whole thing into the raw body, this should result in a list of invoices.
if you need more info I can try to get a collection working for you but I hope this will help enough to get you started
Edit 2:
Regarding your second question, you need to set the header to accept the xml input, see below
Comment: Thank you! Is the CompanyCode the same as the organisationId? If not, where can I find the Company code? And what kind of request URL should I put into postman?  Or how can I test your xml request? Sorry for those questions, but I am completely new to this :(
Comment: No worries, everyone has to start somewhere. I've edited my post to get a more complete answer for you. I hope this will help you more then my first answer. Please let me know if you need more info :)
Comment: Thank you so much for your patience and for editing your answer!!! I now can understand it better!
But when I make the POST request in postman with the url (for me it's https://api.accounting.twinfield.com/webservices/processxml.asmx?wsdl) and the envelop you posted, I get this error: "The server cannot service the request because the media type is unsupported."
Do you maybe know what could cause this error?
Comment: A small adjustment should fix this, you will need to set the header to accept the xml input, see the screenshot I've added to the answer


Apply CSS based on text length of

Question: If a href is longer than 40 chars I want apply a class to the previous LI element.
How can I do this in jQuery?
Answer: Try this:
$('li a').filter(function () {
    return $(this).attr('href').length > 40;
}).closest('li').addClass(...);

Demo here: http://jsfiddle.net/BPQBe/1
Further reading:

filter()
Comment: You don't need to use the `each` method, you can directly work on the result set from the `filter` call (I've updated my jsfiddle demo with an example).

Apply CSS based on text length of


Binary tree not inserting to right of any node that is the left child of another node

Question: My current insert method for my binary tree is not inserting to the right of any node that is the left child of its parent.
current code:
private BinaryTreeNode insert(BinaryTreeNode current, String word) {
    if (current == null) {
        current = new BinaryTreeNode(word);
    } else {
        if (word.compareToIgnoreCase(current.value) < 0) { // if smaller than current node
            if (current.left != null) {
                if (word.compareToIgnoreCase(current.left.value) < 0) {// check next node for lesser than,
                    current.left = (insert(current.left, word));
                }
            } else {
                current.left = new BinaryTreeNode(word);// iff current node is end of tree
                System.out.println(word + "left");
            }
        } else {
            if (current.right != null) { // if larger than current node
                current.right = (insert(current.right, word));
            } else {
                current.right = new BinaryTreeNode(word); // if current node is end of tree
                System.out.println(word + "right");
            }
        }
    }
    return current;
}

Answer: Your problem lies here:
if (word.compareToIgnoreCase(current.left.value) < 0) {// check next node for lesser than,
    current.left = (insert(current.left, word));
}

What are you expecting this to do? You already know you should be inserting to the left of the current node, but why are you re-checking the next node down here?
Comment: Thank you for pointing that out, I am not sure as to why I had that line in there. I have removed it, Waiting now for the test case to finish running.
Answer: You should recurse instead of reaching down to compare to the left:
private static BinaryTreeNode insert(BinaryTreeNode current, String word) {
    if (current == null) {
        current = new BinaryTreeNode(word);
    } else {
        int test = word.compareToIgnoreCase(current.value);
        if (test < 0) {
            current.left = insert(current.left, word);
        } else if (test > 0) {
            current.right = insert(current.right, word);
        }
        // else word already at this node!
    }
    return current;
}

Note that the function should be static, since it doesn't depend on this.
Comment: (To be picky: The OP should "employ recursion", and the `insert` method should "recur".  I'm guessing that the OP has done enough cursing on this project already that he doesn't need to "recurse".)
Answer: I think there were some errors... I would do something like this:
private void insert(BinaryTreeNode current, String word) {
    if (current == null) {
        current = new BinaryTreeNode(word);
    } else {
        if (word.compareToIgnoreCase(current.value) < 0) {

            if (current.left != null) {
                insert(current.left, word);
            } else {
                current.left = new BinaryTreeNode(word);
                System.out.println(word + "left");
            }

        } else {

            if (current.right != null) {
                insert(current.right, word);
            } else {
                current.right = new BinaryTreeNode(word);
                System.out.println(word + "right");
            }

        }
    }
}


How can I measure the local sparsity of neighbourhood of a pixel (x,y) after homography transform

Question: Example Image
Let say I am rectifying a planar surface in the image.
The object is represented by finite discrete number pixel. Once it get projected to a rectified coordinate by a $3x3$ homography matrix $H$, the pixels of the far corner of the desk in the example image become sparse because the information does not exists in the original image. Two neighbouring pixel in the original image become more separate after projection.
Normally in computer vision, we solve this by interpolating nearby pixel. But I am measuring coordinate of some object in the original image. I want to get a sense of "uncertainty" after projected to rectified coordinate.
Answer: I'm not sure if this is anything like an established concept, but I would use Tissot's indicatrix as inspiration here: consider a circlein the original image and investigate the rectified version of that.
You could make the original circle have one pixel radius, or half a pixel, or a square pixel area, or infinitesimal radius. I guess unless your original image is really low resolution or your transformation really extreme, there should not be much practical difference between these.
You can use the ratio of rectified area to original area as a measure of how much rectified area an original pixel represents. You could also measure things which relate to the eccentricity or aspect ratio in order to see how direction-dependent this effect is.
While these things can be expressed conceptually in terms of circles and their transformed conics, I would assume that if you do the math on the symbolic level, you probably can come up with expressions that don't have much relation to the original circle. The pixel size independent version with infinitesimal radius should lead to the simplest expressions as it is scale invariant.
I haven't done the math, though. So if you do and get stuck, feel free to update your question and send me a comment and I can have a look. Or ask a follow-up question and add a comment here.


What is the point of having two different names for the same parameter?

Question: func mapEachElement (inArray arr: [Int],  withFunc aFunc: (Int))

Why would there be "inArray and then "arr"...what's the point?
Same for "withFunc and "aFunc", it makes it more code complicated and also messier to read, why are they even used?
Answer: inArray is external name which the caller of the function should use when passing parameters. arr is the internal name which the function implementer uses in the implementation to refer to the parameter. You don't have to supply external name.It makes it more readable. It is more like to make swift function names and parameters readable as Objective-C functions are.
Comment: so inArray is passed from the argument in the function call to the function?
Comment: Thank you so much, Its very clear for me now. You're awesome!!
Comment: Glad, my explanation helped.
Comment: part of this function header confuses me a little, here is the part: func mapEachElement   (inArray arr:  [Int],   withFunc  aFunc:  (Int) -> Int) ->  [Int] {
Comment: The types are what confuse me, the (int)'s and the [int]
Comment: That's passing a closure (code block) as a parameter. Read up on closures in the Apple Swift language book. It explains it pretty well.
Comment: The part before -> says it's a closure that accepts an int as an argument, and the part after -> says the closure returns and array of type int.
Comment: I did read up on it and it says that basically this function is accepting a funciton of type int that has a return type of int and then this  function returns an array of type int......oh lol I see now @DuncanC
Comment: functions and closures are types in swift. They can be stored in a variable and passed around.
Answer: I'm not sold on the issue of having different internal and external names either.
Having or not having external names makes sense to me.
object.BeepXTimes(6) doesn't need an external name for it's parameter because the function name implies the meaning of the parameter.
The rationale, I think, is that sometimes the naming of a function's external parameters is phrased to make sense to the caller in a sentence:
someView.animateInWithDuration(0.25, withTimingFunction: .easeIn)

The external name withTimingFunction makes the function call read like a sentence, but withTimingFunction makes a lousy internal parameter name. You would probably want your parameter name to be just timingFunction. Having separate internal and external parameter names lets you do that.
For me, though, the extra complexity this requires in the function definition doesn't seem worth it. The good news is that the default is to create parameters using the same name for both internal and external parameter names, so the standard syntax is simple and easy to read.
Comment: yes the # before the parameter name, that is much more efficient and easier to see also, thanks a lot!
Comment: The # before the parameter name is deprecated in Swift 2.0 and produces a warning.
Comment: Sorry. I was referring to Swift 2.0. I wish Apple would release Swift 2.0 so we could only have to worry about a single syntax.
Answer: These are internal and external parameter names.
Just like in Obj-C, you might have
- (void)calculateFoo:(id)foo withBar:(id)bar ...

[object calculateFoo:var1 withBar:var2];

in Swift, we use
func calculateFoo(foo: AnyObject, withBar bar: AnyObject) ...

object.calculateFoo(var1, withBar: var2)

The internal names foo and bar are only accessible inside the function/method. The external names provide the argument labels which you use to call the function.
In your case, you need to use the internal name nibBundle. That's the one accessible inside the function body.


Judging how good your guesses are

Question: Suppose you have a set of objects and you have to guess whether each is A or B. Each object has a known probability of being A and a known probability of being B.

How would you evaluate how "well" you are guessing when you go down the list of objects and assign each A or B.

How would you evaluate how well you are guessing when you go down the list of objects and assign each a probability of being A or B.

Thanks for your help!
Comment: Hi, these are some rather standard starting concepts in decision theory or probability. Is this a homework question or practice problem? If so, please tag as [tag:self-study]. What do you think the answers to your questions are, and where are you stuck?
Comment: It's neither for homework or a practice problem - I'm trying to evaluate how well my friends and I are at predicting certain things in some games we play.  is there an appropriate tag for this use case?
Comment: Do you have any features of A and B that you are using to make your guess?
Answer: Fun question.
In the first question, you are labelling objects as either A or B, making a definitive choice.  If you do this for a sequence of objects, you can construct what is known as a confusion matrix
<code>           Actually A Actually B
Assigned A          a          b
Assigned B          c          d
</code>
From this matrix, we can compute a whole host of metrics.  Accuracy is probably the one people think of most often, but sensitivity and specificity are two other measures of how well one can guess.
In the second question, you would be assigning probabilities (p% this object is class A, q% this object is class B, etc).  In that case, calibration of your probabilities is a measure you would want to examine.  In brief, say you had 20 objects which you p[predicted all have 95% probability of being class A.  If you are well calibrated for predicting the probability of class membership, then 19 of those 20 should actually belong to class A (that is 95% of the 20 actually belong to class A).
As Arya mentions, these are quite standard topics in the realm of classification and probabilistic modelling respectively.  I will leave you to understand them further.
Comment: Thanks for your help!  Will do some reading on the concepts you referenced. :)
Comment: I'm reading about confusion matrices and I have a follow up question:

Suppose you objects x and y, both class A.

In one scenario from the POV of the guesser x has 90% chance of being A and y has 80% chance of being A.

In another (also from the POV of the guesser) x and y both have 50% chance of being A.

Is there a method where the guesser still guesses in a binary way but we can distinguish between the two?  For example using the example someone that guesses A, A in scenario two would have done a "better" job than the person who guessed A, A in scenario 1.

Thanks for your help!
Comment: @Cloner5942 I'm not sure I understand.  You're going to have to make your question more concrete.
Comment: Suppose an object is in class A. Before making their guesses, guesser one's has information saying that the object has a 30% chance of being in class A and guesser two has information saying that the object is 90% in class A. Intuitively if both guess that the object was in class A I would think that the first guesser would be classified as a "better guesser", especially if we repeat the scenario a bunch.  Is there some tool or technique to describe or formalize this? Sorry if still not clear.
Comment: Here's an example that might help clarify
Sam has to guess whether each of 100 objects is in class A or B. He has a list of probabilities each is in A, something of the form (50, 20, ...).  He guesses.

The next day Sam has to guess again, this time with 80 objects. He has another list of probabilities each is in A, maybe (25, 40, ...). He guesses.

How do we analyze which day he did better on?  How do we analyze how he's done overall?  My understanding is confusion matrices don't care about the set of probabilities the guesser is working with but just looks at whether he's right or not.
Comment: @Cloner5942 Sam should compute his Brier Score.  Another thing for you to look up.
Comment: Thank you so much!  Looking into that along with more on scores and binary classifiers in general.  One clarification: The list of probabilities aren't Sam's guesses - they're provided to him.  You can imagine his friend next to him telling him "this object has a 25% chance of being A" and then Sam going "Okay I think it's A" etc.  I think the Brier score assumed that the list of probabilities were his guesses themselves.
Comment: @Cloner5942  There is no differentiation between if Sam makes his own guess or if it is given to him.  Brier score is a scoring rule for whatever probabilities are used.
Comment: Sorry maybe I'm misunderstanding something.  My understanding is that Brier score is for measuring accuracy of answers to things of the form "here's a weighted coin, what percent of the time do you think it will land heads"  and not "here's a 60/40 coin, I'm going to flip it, do you think it will land heads or tails". In the former the guess takes the form of a probability while in the latter the answer is just heads or tails.  Maybe an even better example is a bag of 4 red socks and 1 blue sock, I secretly remove one, I want to evaluate Sam's ability to guess whether it's red or blue.

Judging how good your guesses are


Complex numbers and conjugates.

Question:
Given that $|z|=√3$, solve the equation $$2\overline{z}+\frac3{iz}=\sqrt{15}.$$

How to solve this question without a calculator?
Comment: Could you edit your question using [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)? It's unclear what you're asking and where the division symbol should be.
Comment: @Vittal Kamath, so what is the answer did you get?
Answer: HINT
Multiplying by $z$ we obtain
$$2\bar z+\frac3{iz}=\sqrt{15} \implies 2\bar zz+\frac3{iz}z\frac i i=\sqrt{15}z$$
then recall that $\bar z z=|z|^2$.
Comment: ,what are the next steps to arrive at final answer?
Comment: @DhamnekarWinod What did you obtain from here $2\bar zz+\frac3{iz}z\frac i i=\sqrt{15}z$?
Comment: ,I got $6+ \frac{3}{i}=\sqrt{45}$
Comment: @DhamnekarWinod Why that? We have $\bar z z=|z|^2$ and here we are ok, then $\frac 3 i =-3i$ but at the RHS we should have $\sqrt{15}z$.
Comment: because|z|=$\sqrt{3}$. If this is wrong,then $z=\frac{6-3i}{\sqrt{15}}$
Comment: @DhamnekarWinod Exactly, we can obtain z form that. And you can check that |z| is indeed $\sqrt 3$.
Answer: WLOG $z=\sqrt3e^{it}\implies\bar z=\sqrt3e^{-it}$ where $t$ is real
$$\sqrt{15}=2\sqrt3e^{-it}+\dfrac3{i\sqrt3e^{it}}=\sqrt3(2-i)e^{-it}$$
$$\iff e^{it}=\dfrac{2-i}{\sqrt5}$$
We are done.
We can go even further.
$$e^{it}=e^{-i\arcsin\dfrac1{\sqrt5}}$$
$$\implies t=2n\pi -\arcsin\dfrac1{\sqrt5}$$ where $n$ is any integer
Comment: ,what is WLOG z means?
Comment: https://artofproblemsolving.com/wiki/index.php?title=Without_loss_of_generality
Comment: I know $e^{i\pi}=-1$. So what is $e^{it}?$ and why did you multiply it by z?
Comment: https://math.stackexchange.com/questions/2660361/how-do-i-interpret-eulers-formula

Complex numbers and conjugates.


Codeigniter like Database class

Question: I am moving onto making some open source software for kicks, from scratch (not using a framework) and I was building my own database class to use, so queries would be simpler and all run through the same methods.
Ideally it would work like codeigniters database class:
<code>$db->where("field", "value");
$db->get();
</code>
So on and so forth, and decided I may as well not reinvent the wheel if there is already something out there like it, though google searching didn't bring me much.
Any ideas? Thanks guys.
Comment: umm... CI is open source right? ... :|
Answer: Check out Idiorm, a fluent query builder for PHP5+.
https://github.com/j4mie/idiorm

Codeigniter like Database class


Reducing ZFS stream size for offsite backup

Question: NOTE: My understanding of this question has changed significantly since I first asked it (see Edit 2 below) but I've left the original version intact.
We've put together an offsite backup system (still testing in-house) that does its data transfer via ZFS send/receive.  Machines on both ends are FreeBSD 8.2.  Overall, the setup works well.
However, there's clearly something I don't understand about ZFS snapshot stream sizes.  I've had a hard time finding information on this, so I'm hoping someone with some more experience can enlighten me.
On the source machine, I have a filesystem of about 47GB for which I need to transfer snapshots:
# zfs list -t snapshot -r -s creation stg/serverx
NAME                   USED  AVAIL  REFER  MOUNTPOINT
(.......)
stg/serverx@20110620  2.88M      -  47.1G  -
stg/serverx@20110621  2.89M      -  47.1G  -
stg/serverx@20110622  2.88M      -  47.1G  -
stg/serverx@20110623  5.44M      -  46.6G  -

I have the snapshot from 6/22 already on the remote server, so I send it the stream generated by
zfs send -i stg/serverx@20110622 stg/serverx@20110623

This is received on the other end with no trouble; however, the stream generated is over 80 gigabytes—nearly twice the size of the entire source filesystem.
Am I misinterpreting the meaning of the "USED" column generated by zfs list?  I'd have expected this snapshot stream to be 5.44M plus a certain amount of overhead.  It seems I don't quite understand what constitutes overhead.
Possibly useful information: We backup (via rsync) each server to its own filesystem. This particular one seems to generate the largest streams (relative to filesystem and snapshot size). I suspect it may be related to the fact that it's a mail server, so some of its content is pretty dynamic.  However, I'd expect this to show up in the snapshot "used" size too.
Obviously, we can save quite a bit by compressing the stream (it can probably be reduced to 12-20% of its original size).  Even then, bandwidth will be our limiting factor, so we'd like to understand what makes these streams so large and whether we can do anything to mitigate it.
EDIT: I had forgotten that we have zfs compression enabled on the source filesystem.  So the 47-ish gigabytes used does indeed translate to nearly 80 gigabytes of "real" filesystem data.  I suppose that's a partial explanation, but I still don't see why the incremental stream from zfs send would be so large.

EDIT 2:
Further investigation of this backup and a couple of others has led to the conclusion that the large transfers were in fact to be expected (due to some upgrades that had taken place).  However, I don't see any indication of that large amount of data in the output from zfs list.
I've been through documentation, and I understand that there are a lot of complexities in computing the space used by a snapshot.  The zfs man page says the following in the description of the used property:

When snapshots . . . are  created,  their space is initially shared between the snapshot and the file system, and possibly with previous snapshots. As the file system  changes, space  that  was  previously shared becomes unique to the snapshot, and counted in the snapshot's space  used.

This makes sense to me.  However, I would expect to see a much larger snapshot created at the end of the day the server was upgraded.  In fact, it's only a few megabytes.  There is no deduplication here (zpool version 15).  However, the incremental stream generated by zfs send -i is quite large, and contains all the upgrade information.
Can someone explain this apparent inconsistency? The related question, then, is: How can I get a reasonable estimate of the size of an incremental stream (from, for example, zfs list output)?
Answer: I know this is a really old question, but I've seen it a few difference places. There's always been some confusion about the value expressed in zfs list as it pertains to using zfs send|recv. The problem is that the value expressed in the USED column is actually an estimate of the amount of space that will be released if that single snapshot is deleted, bearing in mind that there may be earlier and later snapshots referencing the same data blocks.
Example:
zfs list -t snapshot -r montreve/cev-prod | grep 02-21
NAME                                      USED  AVAIL  REFER  MOUNTPOINT
montreve/cev-prod@2018-02-21_00-00-01     878K      -   514G  -
montreve/cev-prod@2018-02-21_sc-daily     907K      -   514G  -
montreve/cev-prod@2018-02-21_01-00-01    96.3M      -   514G  -
montreve/cev-prod@2018-02-21_02-00-01    78.5M      -   514G  -
montreve/cev-prod@2018-02-21_03-00-01    80.3M      -   514G  -
montreve/cev-prod@2018-02-21_04-00-01    84.0M      -   514G  -
montreve/cev-prod@2018-02-21_05-00-01    84.2M      -   514G  -
montreve/cev-prod@2018-02-21_06-00-01    86.7M      -   514G  -
montreve/cev-prod@2018-02-21_07-00-01    94.3M      -   514G  -
montreve/cev-prod@2018-02-21_08-00-01     101M      -   514G  -
montreve/cev-prod@2018-02-21_09-00-01     124M      -   514G  -

In order find out how much data will need to be transferred to reconstitute a snapshot via zfs send|recv, you'll need to use the dry-run feature (-n) for these values. Taking the above-listed snapshots try:
zfs send -nv -I montreve/cev-prod@2018-02-21_00-00-01 montreve/cev-prod@2018-02-21_09-00-01
send from @2018-02-21_00-00-01 to montreve/cev-prod@2018-02-21_sc-daily estimated size is 1.99M
send from @2018-02-21_sc-daily to montreve/cev-prod@2018-02-21_01-00-01 estimated size is 624M
send from @2018-02-21_01-00-01 to montreve/cev-prod@2018-02-21_02-00-01 estimated size is 662M
send from @2018-02-21_02-00-01 to montreve/cev-prod@2018-02-21_03-00-01 estimated size is 860M
send from @2018-02-21_03-00-01 to montreve/cev-prod@2018-02-21_04-00-01 estimated size is 615M
send from @2018-02-21_04-00-01 to montreve/cev-prod@2018-02-21_05-00-01 estimated size is 821M
send from @2018-02-21_05-00-01 to montreve/cev-prod@2018-02-21_06-00-01 estimated size is 515M
send from @2018-02-21_06-00-01 to montreve/cev-prod@2018-02-21_07-00-01 estimated size is 755M
send from @2018-02-21_07-00-01 to montreve/cev-prod@2018-02-21_08-00-01 estimated size is 567M
send from @2018-02-21_08-00-01 to montreve/cev-prod@2018-02-21_09-00-01 estimated size is 687M
total estimated size is 5.96G

Yikes! That's a whole heck of a lot more than the USED values. However, if you don't need all of the intermediary snapshots at the destination, you can use the consolidate option (-i rather than -I), which will calculate the necessary differential between any two snapshots even if there others in between.
zfs send -nv -i montreve/cev-prod@2018-02-21_00-00-01 montreve/cev-prod@2018-02-21_09-00-01
send from @2018-02-21_00-00-01 to montreve/cev-prod@2018-02-21_09-00-01 estimated size is 3.29G
total estimated size is 3.29G

So that's isolating the various blocks that were rewritten between snapshots, so we only take their final state.
But that's not the whole story! zfs send is based on extracting the logical data from the source, so that if you have compression activated on the source filesystem, the estimates are based on the uncompressed data that will need to be sent. For example, taking one incremental snapshot and writing it to disk you get something close to the estimated value from the dry-run command:
zfs send -i montreve/cev-prod@2018-02-21_08-00-01 montreve/cev-prod@2018-02-21_09-00-01 > /montreve/temp/cp08-09.snap
-rw-r--r--  1 root root    682M Feb 22 10:07 cp08-09.snap

But if you pass it through gzip, we see that the data is significantly compressed:
zfs send -i montreve/cev-prod@2018-02-21_08-00-01 montreve/cev-prod@2018-02-21_09-00-01 | gzip > /montreve/temp/cp08-09.gz
-rw-r--r--  1 root root    201M Feb 22 10:08 cp08-09.gz

Side note - this is based on the OpenZFS on Linux, version :
- ZFS: Loaded module v0.6.5.6-0ubuntu16
You will find some references to optimisations that can be applied to the send stream (-D deduplicated stream, -e more compact), but with this version I haven't observed any impact on the size of the streams generated with my datasets.
Comment: Massive kudos for such a detailed response to an ancient question! I've long since left that job and that system, but I believe you've managed to answer the question. Thanks!
Comment: Hopefully it will be useful to others as well. It's non-obvious until you've had to dive into the details like I had to recently. :-)
Answer: What type of email system and what type of "store" technology? If the mail store is already compressed in any way, then each incremental may actually be a full as its compressed data stream may be dynamically changing due to its compression.
Also is dedup in play across either system? It sounds like there may be a remote chance that it might be on the source system. That might account for the size difference.
Comment: No deduplication--this is zpool version 15 on both sides.  +1 for suggesting compression-related issues; that turns out to be a partial explanation.  See also my edit 2 above. (Sorry to be slow in follow-up here.)
Comment: What is the actual data format being backed up from your email server? File-based individual message files (Unix-style), Exchange EDB, backup format from a backup application??? It seems like the "zfs send" may not be moving the data in "native zfs," but possibly expanding it back to its original format and then letting the receiving system "recode" things back into "zfs" storage/format.
Comment: It's not just the mail being backed up, it's the entire server.  Anyway, the mail is in plain old mbox format. The `zfs send` command is surely removing the zfs compression when it creates the stream, but that size difference isn't near enough to account for what I'm seing.
Comment: OK, so what is the ratio (text vs. binary vs. compressed stream) of the data being backed up? The zfs compression ratios are directly impacted by the data it is working with - example: text is more compressible than binary, where an already compresses zip file may no longer be compressed any further.


Why isn't my PHP installation recognized by Apache on Windows XP?

Question: I have done the procedure below given in http://www.ricocheting.com/server/php.html for installing PHP and Apache. When I start the Apache server, it is displaying "invalid command PHPIniDir". How can I fix this problem?
I wanted to learn PHP. When I started installing I came with this problem.

Editing Apache Conf File
Using Notepad open httpd.conf (should be start-menu shortcut "Apache HTTP Server 2.2 > Configure Apache Server > Edit the Apache httpd.conf Configuration File"). Either at the very beginning or end of the file add the following lines: (NOTE: be sure to change BOTH C:/php parts to the directory you installed PHP to)

LoadModule php5_module "C:/php/php5apache2_2.dll"
AddType application/x-httpd-php .php
PHPIniDir "C:/php"

Comment: Not a direct answer to your question, but have you considered installing an Apache distribution? I have found XAMPP to be very easy to set up and use: http://www.apachefriends.org/en/xampp.html
Comment: Any reason why not on Linux OS? Will be much more easier.
Comment: I have only windows xp
Answer: I would recommend you using XAMPP. It is a complete package of Apache, PHP, MySQL and so on... You don't have to configure and you can easily stop the processes so that you don't have an open webserver running on your computer all the time which can be risky if accessible over the Internet.
Try: XAMPP
Comment: what you don't like pain?
Comment: I tried upgrading xampp from 1.7.3 to 1.7.7 and everything broke. yay
Answer: I vaguely remember having this problem as well. If I remember correctly you might need to add a trailing / to the PHPIniDir
PHPIniDir "C:/php/"

Answer: The only other alternative that I know of to XAMPP is to install WAMP. I've used WAMP many times but I haven't tried XAMPP. They are full LAMP stacks (well WAMP stacks) that contain Apache, MySQL and PHP.
Answer: As an alternative, drop the PHPIniDir command and place the php.ini in the same directory as the Apache.exe application.
Answer: I created a new file called php.conf. In that file I placed the following:

php.conf

Loadfile "C:\php\php5ts.dll"

LoadModule php5_module "C:\php\php5apache2_2.dll"

PHPIniDir "C:\php"

AddHandler application/x-httpd-php .php
AddHandler application/x-httpd-php-source .phps

Then I went to my httpd.conf file and included the php.conf file:

httpd.conf

Include conf/extra/php.conf

I included the line above, right before these lines in my httpd.conf file, where all the other include lines are.
<IfModule ssl_module>
    SSLRandomSeed startup builtin
    SSLRandomSeed connect builtin
</IfModule>

Answer: Be careful when you copy and paste from webpages on the web, i had to change the quote
marks to  "C:/PHP72" (straight)  from  "C:/PHP72" (curly) to get the service to restart in windows.
Like most web page they are sensitive to the littlest of differences.


how to calculate the phase shift in the formula that has sin in both side?

Question: Given formula
$asin ( x ) = b sin( x + \phi)$
where $a$ and $b$ are constants. I want to calculate $\phi$.
Comment: Is $x$ a given number, or do you want this to be an identity which holds for all $x$?
Comment: x is a variable. Please see my comment to Dr. Sonnhard
Comment: In that case, you are asking too much! If $a$ and $b$ are given, there will usually not exist such a number $\phi$. Exceptions occur if $a=b$ (in which case $\phi=0$ will do) and if $a=-b$ (then $\phi=\pi$ works).
Answer: we obtain for $b\ne 0$
$\frac{a}{b}\sin(x)=\sin(x+\phi)$
$\arcsin\left(\frac{a}{b}\sin(x)\right)-x=\phi$
Comment: thanks very much for the answer. But according to your solution, the value of the phase shift phi will be depent on the value of x? Actually the real formula I have is this: a*sin(2*pi*t)+b*sin(2*pi*t+phi)=c*sin(2*pi*t) These are actually 3 sinwave signals. By adjusting the phase shift in signal 'b', I will be able to match the sum of signal (a+b) to signal c. So, should phi be independent to variable x?


Codility PermMissingElem

Question: My solution scored only 40% correctness on Codility.
What am I doing wrong?
Here is the test result (https://codility.com/demo/results/trainingU7KSSG-YNX/)
Problem:
A zero-indexed array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.
Your goal is to find that missing element.
Solution:
function solution(A) {
    var output = 1;
    var arrayLength = A.length;

    if(!arrayLength){
        return output;
    }

    if(arrayLength == 1) {
        return A[0] + 1;
    }

   var sorted = A.sort(sortingFn);

    for(var i = 0; i  1) {
            output =  A[i] + 1;
            break;
        }
    }

    return output;
}

function sortingFn(a, b) {
    return a - b;
}

Result
Answer: Your algorithm find the missing element by comparing neighboring elements in the array. This means it is incapable of handling cases where the first or last element is missing, as these only have a single neighbor.
Consider as an example [1, 2, 3]. The missing element would be 4. But since 4 has precisely one neighbor (3), it can't be found by the algorithm, and 1 will be returned.
In addition your algorithm is rather inefficient, as sorting takes O(n lg n), while the problem is solveable in O(n):
find_missing(arr):
    s  = sum(arr)
    s' = (len(arr) + 1) * (len(arr) + 2) / 2

    return s' - s

This code works by summing up all elements in the array and comparing it to expected sum, if all elements were present. The advantage of this approach is that it only requires linear operations and will find the missing element with relative simplicity.
Comment: @m.rufca That the first or last element in the array is missing. I.e. in `[2, 3, 4]` the first element is missing, as the range always starts with `1`. On the other hand in `[1, 2, 3]` `4` is missing, as the "original" range was `[1, 2, 3, 4]` ("original" ranges are always `[1, N + 1]`, where `n` is the number of elements in the input-array) . Your code is still incapable of handling the case of the first element missing. It is considered bad algorithm-design to add specific handling for edge-cases. Where possible **always** avoid this and use a single approach to solve the problem.
Comment: @AlexeySh. `[4]` is not a valid input. Only one number can be missing.
Comment: When I read the problem description I didn't understand that if there is no real missing element, the output should be N + 1.
I added a conditional to verifies is is the last element and didn't find missing element, returns correctly but still 40% correctess (https://codility.com/demo/results/trainingG52Z9N-GN6)
Comment: I don't really understand what is the criteria of _missing first_ or _missing last_
Comment: Just to clarify, I was curious about the reason algorithm is not working, I know there are better solutions. I did not noticed that sequence must start with number 1 as said on _each element of array A is an integer within the range [1..(N + 1)]_.
Comment: Handling edge cases works. Thanks :) https://codility.com/demo/results/trainingEYF8S3-QUA/
Answer: Try this in c#:
using System;
using System.Linq;

private static int PermMissingElem(int[] A)
    {
        if (!A.Any() || !A.Any(x => x == 1)) { return 1; }
        var size = A.Length;
        var numberTwoList = Enumerable.Range(1, size);
        var failNumber = numberTwoList.Except(A);
        if (!failNumber.Any()) { return A.Max() + 1; }
        return failNumber.FirstOrDefault();
    }

Answer: Well, when the last element is missing, you obviously return 1, since your if statement's condition is always false. Same for first element.
Take as example this input:

1 2 3 4 5

the difference will be always 1, but element 6 is missing.
The reason for this incapability of your algorithm to catch these cases, is that it examines neighboring elements (A[i + 1] and A[i]).
Answer: JS solution #1
function solution(A) {
  if (A.length === 1) {
    return A[0] > 1 ? 1 : 2;
  }
  const map = {};
  let max = 0;
  for (let i = 0, len = A.length; i < len; i++) {
    map[A[i]] = A[i];
    if (A[i] > max) {
        max = A[i]
    }
  }
  for (let i = 0, len = A.length; i < len; i++) {
    if (!map[i + 1]) {
      return i + 1;
    }
  }
  return max + 1
}

JS solution #2
function solution(A) {
    const s  = A.reduce((a, b) => {return a + b}, 0);
    const s2 = (A.length + 1) * (A.length + 2) / 2
    return s2 - s;
}

try this arrays (like the end test):

[1,2,3] -> must return 4;
[1] -> must return 2;
[2] -> must return 1;
[2,3] -> must return 1;
[1, 3] -> 2

But for #2 solution [4] returns -1 and for [123] returns -120. The test will show 100 points. But actually, it doesn't work as expected on my opinion.
Both solutions work with the same performance.
Answer: Try this javascript function:

function solution(A) {
    let givenSum = 0;
    let expectedSum = 0;
    let size = A.length;

    for(let i = 1; i <= size +1; i++){
        expectedSum = expectedSum + i;
    }

    for(let i = 0; i < size; i++){
        givenSum += A[i];
    }

    return expectedSum - givenSum;
}

Answer: here is my solution:
https://app.codility.com/demo/results/trainingMZWVVT-55Y/
function solution(A) {
    A = A.sort((a,b)=>a-b)
    if(A[0]!==1) return 1
    for(let i = 0; i < A.length; i++)
    {
        if(A[i+1]-A[i]!==1) return A[i] + 1
    }
    return A[A.length] + 1
}

Answer: Tested on Codility with 100% score see here
The solution i implemented is using set difference. since the question guaranties exactly one element is missing.
def solution(A):
    # write your code in Python 3.6
    N = len(A)
    difference = set(range(1, N+2)) - set(A)
    return difference.pop()

Codility PermMissingElem


Getting JSON exchange rate from fixer.io to HTML

Question: I'm trying to get the current USD to EUR rate from fixer.io into a single line in a HTML file and replace the "." in the USD value with a ",".
Can somebody help me?
LINK: https://api.fixer.io/latest?symbols=USD
{
  "base": "EUR",
  "date": "2017-12-04",
  "rates": {
    "USD": 1.1865
  }
}

What i need in a HTML file:
1,1865

EDIT:
This is what i tried so far (literally never done this before):
HTML:

JS:
$(document).ready(function(){
  var url= "https://api.fixer.io/latest?symbols=USD"
  $.getJSON(url,function(data){
    document.getElementById("rate_usd").innerHTML = data.rates.USD;

  });
});

Comment: this link will help you [link]https://openexchangerates.github.io/money.js/#basic-install
Comment: I don't know what to do with that. Sorry.
Answer: Try the below, it includes all the HTML, JS and jQuery dependency you were referencing.
You were pretty close, here we are taking the number returned by the API, converting it to a string with toString() and then replacing the . with , as requested.

    <title>USD Rate</title>

Comment: Thank you! Works perfectly.
Answer: Also you can give a try to the Java API for fixer.io:
https://github.com/lico/jFixer
These API encapsulate the call to the web service.


Some questions about Gradle for Android Development

Question: I have some questions about Gradle.

What is the difference between buildscript.dependencies and
dependencies ?
What is the difference between classpath and compile?
What does apply plugin: mean?
Answer: Just check their docs, they have described it well. But here is it:
1:

If your build script needs to use external libraries, you can add them
  to the script's classpath in the build script itself. You do this
  using the buildscript() method, passing in a closure which declares
  the build script classpath.

This is good for external dependencies (for example from internet repos which are in buildscript part too.)

2:
Docs with table and descriptions for each.
compile will get dependencies during compiling. (for example you can set 'runtime' and these dependencies will be used during runtime, or testCompile will be used only during compiling tests). This is very important! Read their docs. Of course you can try to compile everything everytime, but this is really bad idea. Good example are JUnit tests, you need JUnit only during compiling tests co then you use compileTest:
 testCompile "junit:junit:X.YZ"

3:
It means that you applied plugin :) You apply java, or when you need spring or spring boot, then you simply can tell Gradle, hey Gradle, I am going to using this, so aplly it. More here.
Answer: I suggest you download the full Gradle distribution, only because it provides a PDF version of the User Guide (I don't know of any other way to get the user guide PDF).  Read it from top to bottom, skipping chapters that are clearly irrelevant to you.  You will get answers to all of these questions, and more that you haven't asked yet.
However, I'll give you some brief answers.
Q1: Gradle has dependencies for the build script, and dependencies for the code you're building.  They are separate.
Q2: Classpath is a runtime notion used by Java, which Gradle utilizes in different ways.  Compile is a "configuration" which you can add dependencies to, which affects the eventual runtime classpath.
Q3: "apply plugin" is applying a Gradle plugin.  Read the user guide.
Comment: The on-line User Guide is here: https://docs.gradle.org/current/userguide/userguide.html


How to verify that exception was thrown by a mock when it was caught within the code under test?

Question: In Java/Junit/Mockito, it is fairly easy to simulate an exception (doThrow() etc.), and fairly easy to verify when an exception is thrown and not caught (assertThrows() etc.). But what if exception was successfully simulated using doThrow, but then subsequently caught in the main code - how the test can know that it was ever thrown?
Consider following code snippet:
public void doFullOpeartion() {

    try {
        optionalService.blink();
    }
    catch (IOException exception) {
        // No operation needed
    }

And the following test code:
doThrow(IOException.class).when(mockOptionalService).blink();

classUnderTest.doFullOperation();

// ??? - how do we know that IOException was thrown

If in the catch block in the main code we had some code that could be verified, the problem becomes moot. But what if we don't?
Comment: It sounds like a strange problem. Doesn't the test only care that an exception was thrown or not thrown? Which is what `assertThrows` does. You want your test to assert that an exception was thrown, caught and not rethrown?
Comment: Can't you do `verify(mockOptionalService, times(1)).blink()` in combination with `doThrow`? That would imply not just that *if* it's called, it should throw, but also that it must be called (and thus throw). The exception or lack of exception in the test is the indication whether or not it was caught.
Comment: "You want your test to assert that an exception was thrown, caught and not rethrown?" - yes, pretty much. The overall purpose of this test is to verify that this particular execution path does not break the code. I know I can verify unused doReturn (or verify that they were called once) - but is it possible to verify unused doThrow?
Answer: I prefer tddavies' answer (just verify that the mock was called - because you know that calling it means it throws). But here's another solution which perhaps makes what you're trying to assert a bit more explicit.
doAnswer is the more general purpose Mockito primitive, which can either return a value or throw. In there you can just maintain a counter.
AtomicInteger blinkIOExceptions = new AtomicInteger();
doAnswer(invocation -> {
    blinkIOExceptions.incrementAndGet();
    throw new IOException();
}).when(mockOptionalService).blink();

assertEquals(1, blinkIOExceptions.get());

Answer: I don't think that you can check that the exception is actually thrown, but you can verify that the method you stubbed to throw an exception was actually called. See the example below, where we control whether the method is called, and a test fails when it doesn't get called:
package org.example;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.io.IOException;

import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;

class ToTest {
    private final InjectedClass injectedClass;

    ToTest(InjectedClass injectedClass) {
        this.injectedClass = injectedClass;
    }

    public void doIt(boolean callMethod) {
        try {
            if (callMethod) {
                injectedClass.mightThrow();
            }
        } catch (IOException e) {
            // ignore (this seems like a bad idea...
        }
    }
}

interface InjectedClass {
    void mightThrow() throws IOException;
}

@ExtendWith(MockitoExtension.class)
public class AppTest {
    @Mock
    InjectedClass injectedClass;
    @InjectMocks
    ToTest toTest;

    @Test
    public void passingTest() throws IOException {
        doThrow(IOException.class).when(injectedClass).mightThrow();
        toTest.doIt(true);
        verify(injectedClass).mightThrow();
    }

    @Test
    public void failingTest() throws IOException {
        doThrow(IOException.class).when(injectedClass).mightThrow();
        toTest.doIt(false);
        verify(injectedClass).mightThrow();
    }
}