Fetchall() limitado em python

Question: Estou fazendo um código que faz uma consulta no postgres e retorna em uma lista, porém isso está dando erro de memória. A parte do código que faz isso:
c = conn.cursor()
c.execute("SELECT latitude, longitude, gid FROM pontos")
records = c.fetchall() #pega todos os resultados do select e armazena em uma tupla
e = conn.cursor()
e.execute("SELECT precipitacaoh, gidgeo_fk FROM historico")
records2 = e.fetchall()

Como faço pra pegar, por exemplo, os 100 elementos da consulta e armazenar no disco, e depois pegar os próximos 100 elementos, até armazenar toda a consulta? Pra não sobrecarregar o sistema.
Comment: Pelo seu comentário abaixo, seu erro não tem nada a ver com a quantidade de dados - inclua a mensagem de erro que acontece efetivamente.S e o código já mudou, pode ser melhor fazer outra pergunta.
Comment: Na verdade, nao apresenta erro, o sistema simplesmente trava. Já deixei o código rodando uma noite inteira, tive que reiniciar o computador e não tinha incluído nenhum registro no novo banco.
Answer: É possível fazer isso sim - eu me pergunto se será útil simplesmente armazenar os valores em um arquivo texto: em geral recuperar os dados desejados no banco de dados e processa-los diretamente é melhor do que pear os mesmos dados de um arquivo texto, onde não temos ferramenta de indexação, formas de fazer busca, etc...
me causa muito estranhamento você estar tendo um "erro de memória" com registros tão simples como esses - mesmo milhões de registros não deveriam exaurir a memória de um sistema com RAM na casa dos gigabytes.
Agora, voltando especificamente ao que você pergunta - os conectores de banco de dados do Python  - todos - implementam além do fetchall, o fetchmany - que retorna somente o número solicitado de registros.
Então, um jeito de transferir uma query para um arquivo local (que não considero que seja algo útil - a não ser que seja tudo o que você quer fazer com os dados) seria:
import csv
c = conn.cursor()
c.execute("SELECT latitude, longitude, gid FROM pontos")

with open("arquivo_destino.csv", "wt") as file_:
    writer  = csv.writer(file_)
    writer.writerow(("latitude", "longitude"))
    records = True
    while records:
        records = c.fetchmany(100)
        writer.writerows(records)
...

O próprio cursor da conexão também pode ser usado como um iterador,
retornando um resultado da query por vez se for usado numa query - essa forma de usar é melhor se você for consumir seus dados, em vez de simplesmente grava-los num arquivo local:
c = conn.cursor()
c.execute("SELECT latitude, longitude, gid FROM pontos")
for record in c:
      # do things with row result

(mas eu já vi implementações bugadas de coenxões ao banco em que interar o cursor dessa forma ficava muito lento - se for o caso, melhor fazer uma combinação com o fetchmany também).
Comment: Fiz a seguinte modificação no meu codigo, mas continua travando. Estou tentando migrar um banco de dados relacional para um banco de dados em grafo.

http://pastebin.com/rG3kMxuv
Comment: No código que você linkou você cria os arquivos num comando "with"  - e cria os escritores (writers) CSV - só que a idéia do comando "with" é justamente _Garantir_ que o arquivo seja fechado assim que você sai dele. Então os seus writes ficam com uma referência a arquivos fechados - não vai funcionar mesmo.

O With é algo que funciona melhor em trechos críticos de programa em que vários arquivos vão ser abertos (centenas ou milhares de vezes) para evitar vazemtno de recursos do sistema operacional caso alguns não sejam fechados.

Nesse caso, abra os arquivos com "open"  mesmo, sem o "with".
Comment: mas ainda não entendi por que você não pode fazer o insert na nova base de dados imediatamente após ler do SQL - por que precisa do CSV intermediário?
Comment: Na verdade, o que eu queria era pegar os registros do banco de dados, por exemplo de 100 em 100 registros, e inserir no novo banco, e continuar até que todos os dados fossem inseridos. Porque se eu fizer o que faço no código original: records = c.fetchall(), isso trava totalmente o sistema. Então já queria pegar de 100 em 100 e já ir inserindo. Entendeu?

Fetchall() limitado em python


Como criar uma só caixa de pesquisa para o Google e a Wikipédia?

Question: Criei uma caixa de pesquisa com dois buttons, um para a Pesquisa Google e outro para a Pesquisa da Wikipédia. O button para o Google funciona muito bem mas não consigo fazer o mesmo para a Wikipédia. Segue o código...

<!DOCTYPE html>

<title>Search Box Example 1</title>
<meta name="ROBOTS" content="NOINDEX, NOFOLLOW" />

  <form id="tfnewsearch" method="get" action="https://www.google.com/search" target="_blank" >

   <input type="text" class="tftextinput" name="q" id="google-search" size="21" maxlength="120">

   <input type="submit" value="Pesquisa Gooogle" class="tfbutton">

   <button type="submit" class="tfbutton" name="q" id="wikipedia-search" formaction="http://pt.wikipedia.org/wiki/Special:Pesquisar/">Pesquisa Wikipedia</button>
  </form>

Comment: O nome do *input* de pesquisa deve ser `search`, em vez de `q`, para funcionar com o *Wikipedia*
Answer:
OPÇÃO 01

no seu input altere o name para search
ficando assim: name="search"

OPÇÃO 02 (COMO PHP)

Então você pode utilizar o php pra isso. com um simples formulário! eu usei o bootstrap, mas dai e só adicionar ao seu código.

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0-12/css/all.css" integrity="sha256-qQHUQX+gGGYfpC7Zdni08sr+h0ymXr0avmIASucY4FM=" crossorigin="anonymous" />

    <title>Formulario!</title>

          <form action="resultado_caixadebusca.php" target="_blank" method="post">

              Sua pesquisa abaixo
              <input type="text" name="termo_pesquisa" class="form-control" placeholder="Oque deseja ?">

            <button type="submit" name="tipo_pesquisa" value="1" class="btn btn-primary"> Pesquisa Gooogle</button>
            <button type="submit" name="tipo_pesquisa" value="2" class="btn btn-primary"> Pesquisa Wikipedia</button>
          </form>

E no resultado_caixadebusca.php voce adiciona o:
if ($_POST['tipo_pesquisa'] === '1') {
  $linkpesquisa = "https://www.google.com/search?q=".$_POST['termo_pesquisa']."";
  header('Location: '.$linkpesquisa.'');
}
if ($_POST['tipo_pesquisa'] === '2') {
  $linkpesquisa = "https://pt.wikipedia.org/w/index.php?sort=relevance&search=".$_POST['termo_pesquisa']."";
  header('Location: '.$linkpesquisa.'');
}

Assim ele vai pegar o $_POST enviado pelo formulário adicionar a URL e redirecionar.
Comment: Você também pode usar metado $_GET, só alterar.
Comment: Obrigado Matheus Vitor, mas não consigo colocar a funcionar... aparece isto: "Warning: Cannot modify header information - headers already sent by (output started at /home2/wid/corampopulo.pt/resultado_caixadebusca.php:6) in /home2/wid/corampopulo.pt/resultado_caixadebusca.php on line 10"
Comment: E alguma coisa em seu server que não está permitindo o $_POST, tente mudar pra o $_GET mesmo.
Comment: na pagina do php deixei somente assim: http://prntscr.com/ospuir
Comment: Como e php eu não consigo ver.. somente com o arquivo consigo ver, você tem team View ?
Comment: Mude tudo $_POST para $_GET
Comment: Mude no PHP e no HTML para GET
Comment: Mudei para "get" na pagina html e no php e vai para uma nova pagina mas não mostra nada, nem sequer aparece o endereço de busca no website do google ou da wikipedia.
Answer: Não precisa usar uma linguagem back-end para tal. Com JavaScript é possível fazer o que desejas.
Isso pode ser feito tratando o evento "click" dos botões. Dessa forma podemos criar um elemento, do tipo âncora , temporário e ativá-lo de forma automática.
Exemplo:

/**
 * Captuar o elemento responsável por
 * capturar o valor digitado pelo usuário
 */
const inputSearch = document.querySelector('input[name="q"]')

/**
 * Aplica um evento, do tipo "click", nos botões de pesquisa.
 * Para evitar incompatibilidades, você pode substituir o `forEach`
 * por um `for` "simples"
 */
document.querySelectorAll('#google-search, #wikipedia-search')
  .forEach(btn => btn.addEventListener('click', search))

/**
 * Função responsável por identificar o botão pressionado,
 * e enviar o usuário para o site correto.
 *
 * @param {EventTarget} event
 * @return void
 */
function search(event) {
  event.preventDefault()

  const anchor = document.createElement('a')
  anchor.target = "_blank"
  anchor.href = `${event.target.getAttribute('formaction')}${encodeURI(inputSearch.value)}`
  anchor.click()
}
#tfheader {
  background-color: #c3dfef;
}

#tfnewsearch {
  float: left;
  padding: 20px;
}

.tftextinput {
  margin: 0;
  padding: 5px 65px;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 14px;
  border: 1px solid #0076a3;
  border-top-left-radius: 5px 5px;
  border-bottom-left-radius: 5px 5px;
  border-top-right-radius: 5px 5px;
  border-bottom-right-radius: 5px 5px;
}

.tfbutton {
  margin: 0;
  padding: 5px 15px;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 14px;
  outline: none;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  color: #ffffff;
  border: solid 1px #0076a3;
  border-right: 0px;
  background: #0095cd;
  background: -webkit-gradient(linear, left top, left bottom, from(#00adee), to(#0078a5));
  background: -moz-linear-gradient(top, #00adee, #0078a5);
  border-top-left-radius: 5px 5px;
  border-bottom-left-radius: 5px 5px;
  border-top-right-radius: 5px 5px;
  border-bottom-right-radius: 5px 5px;
}

.tfbutton:hover {
  text-decoration: none;
  background: #007ead;
  background: -webkit-gradient(linear, left top, left bottom, from(#0095cc), to(#00678e));
  background: -moz-linear-gradient(top, #0095cc, #00678e);
}

/* Fixes submit button height problem in Firefox */

.tfbutton::-moz-focus-inner {
  border: 0;
}

.tfclear {
  clear: both;
}

  <form id="tfnewsearch">

    <input type="text" class="tftextinput" name="q" size="21" maxlength="120">

    <button type="button" class="tfbutton" id="google-search" formaction="https://www.google.com/search?q=">
      Pesquisa Google
    </button>

    <button type="button" class="tfbutton" id="wikipedia-search" formaction="http://pt.wikipedia.org/wiki/Special:Pesquisar?search=">
      Pesquisa Wikipedia
    </button>
  </form>

Aqui, no StackOverflow, não vai funcionar devido à restrição.
Comment: Obrigado Valdeir Psr você é fantástico... funciona mesmo.


Erro "cannot find symbol" ao criar um objeto

Question: Estou tentando instanciar um novo objeto "Caneta" na classe principal, mas está dando um erro: "Cannot find symbol".

Classe principal(Aula02):

//pasta em que o código está inserido
package aula02;

//a classe DEVE ser escrita em maiúscula
public class Aula02 {

    //Classe principal:
    public static void main(String[] args){

        //instanciando o objeto Caneta
        Caneta c1 = new Caneta();
        //adicionando um estado ao atributo cor
        c1.cor = "Azul";
        //f após o valor -> número real
        c1.ponta = 0.5f;
        c1.tampada = false;

    }

}

Devido ao "package aula02;", os dois códigos estão na mesma pasta.

Classe Caneta:

//pasta em que se encontra o código
package aula02;

//Declaração da classe
public class Caneta{

    //Declarando os atributos da classe
    String modelo;
    String cor;
    float ponta;
    int carga;
    boolean tampada;

    //metódos da classe Caneta
    void status() {
        System.out.println("Uma caneta" + this.cor);
    }

    void rabiscar() {
    }

    void tampar() {

    }

    void destampar(){

    }

}

Mensagem de erro:

Aula02.java:4: error: cannot find symbol
        Caneta c1 = new Caneta();
        ^
  symbol:   class Caneta
  location: class Aula02
Aula02.java:4: error: cannot find symbol
        Caneta c1 = new Caneta();
                        ^
  symbol:   class Caneta
  location: class Aula02
2 errors

Além disso, compilei a "classe Caneta" antes da classe principal e continua aparecendo o mesmo erro. Alguém pode me dizer como resolver esse problema?
Comment: Segui exatamente esses passos: criei os 2 arquivos, compilei `javac aula02/Caneta.java` e depois `javac aula02/Aula02.java` e funcionou. Talvez o problema seja a forma como vc tentou compilar (foi na linha de comando? usou alguma ferramenta? como tentou compilar? etc). Pior é a resposta aceita abaixo, que não faz sentido, pois se duas classes estão no mesmo pacote, não precisa de `import` (ou seja, precisaria saber exatamente como vc está compilando, pois esta é a causa do problema - usar `import` no mesmo pacote é uma gambiarra desnecessária, o ideal é corrigir a causa de fato)
Answer: Você deve importar a classe Caneta no arquivo da classe Aula02:
package aula02;

import aula02.Caneta;

public class Aula02 {
    // ...
}

Comment: _Importei a classe e no VSCode deu o seguinte erro:_
`Aula02.java:3: error: cannot find symbol
import aula02.Caneta;
             ^
  symbol:   class Caneta
  location: package aula02
Aula02.java:7: error: cannot find symbol
        Caneta c1 = new Caneta();
        ^
  symbol:   class Caneta
  location: class Aula02
Aula02.java:7: error: cannot find symbol
        Caneta c1 = new Caneta();
                        ^
  symbol:   class Caneta
  location: class Aula02
3 errors`.
Answer: confere no VSCode se tanto o arquivo Aula02.java quanto o arquivo Caneta.java estão no Package aula02. Não precisa dar o import aula02.Caneta; pois eles teoricamente estão no mesmo Package.


LINQ - how to remove duplicate rows in table

Question: After certain proccess, I wan to remove duplicates from the table and commit the changes, so only single values remain.
I have three criteria for removal:

Name
date
status (is always 1)

So if there are records with same Name, and same date and same status... remove one. Does not matter which one.
I have:
dbContext.tbl_mytable
Comment: So you are using `Linq To SQL`, right? Does the table have primary keys?
Comment: Yes. I use Linq to SQL. Table has primary keys.
Answer: Since you are talking about deleting records, you need to test this first.

So if there are records with same Name, and same date and same status... remove one. Does not matter which one.

I'm assuming you want to remove all but one, ie, if you have three records with the same details, you remove two and leave one.
If so, you should be able to identify the duplicates by grouping by { Name, date, status} and then selecting all except the first record in each group.
ie something like
<code>var duplicates = (from r in dbContext.tbl_mytable
                  group r by new { r.Name, r.date, r.status} into results
                  select results.Skip(1)
                 ).SelectMany(a=>a);

 dbContext.tbl_mytable.DeleteAllOnSubmit(duplicates);
 dbContext.SubmitChanges();
</code>


How do I secure pages and related media files?

Question: I would like to password protect Drupal pages (solved) and media files related to these pages (solved, but not optimally).  Currently the Drupal pages are secured via Drupal and the media files via htaccess.  The problem with this is the users then have to authenticate twice to get to the media content.  I've been told that the way to solve this is to create a role and restrict access to both Drupal pages and media using Private files download permission module.
I'm quite new to Drupal and am wondering if this is the normal way that people solve this problem; or is another method better/more common/etc..
Answer: Try to use Secure Site for this.

This module allows you to authenticate users with a browser-based password (HTTP Auth). You can restrict access to the site by role and choose to secure restricted pages or the entire site. This means the site will be inaccessible to search engines and other crawlers, but you can still allow access to certain users.


bodyWithEdgeLoopFromRect Assertion failed

Question: I'm receiving the following error when trying to set up a physics world in my iOS7 Sprite kit project.
Assertion failed: (count >= 3), function CreateLoop, file /SourceCache/PhysicsKit/PhysicsKit-4.6/PhysicsKit/Box2D/Collision/Shapes/b2ChainShape.cpp, line 35.

The strange thing is the code I'm using worked before I added new scenes to my project. I reverted my project back to the last known time that it ran correctly and it still does not work. The project will build once I remove the physics world.
(SKNode*) myWorld = [SKNode node];
[self addChild:myWorld];

map = [SKSpriteNode spriteNodeWithImageNamed:@"background1"];
map.position = CGPointMake(0.0, 0.0);
[myWorld addChild:map];

//Setup physics
self.physicsWorld.gravity = CGVectorMake(0.0, 0.5);
self.physicsWorld.contactDelegate = self;

CGRect worldFrame = CGRectMake(map.frame.origin.x, map.frame.origin.y-1150, map.frame.size.width, map.frame.size.height + 2000);

myWorld.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:map.frame];
myWorld.physicsBody.categoryBitMask = wallCategory;

The program terminates when it tries to execute…
myWorld.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:map.frame];

If I put this code into a new project, It works just fine. Any thoughts of what is going on with my project and how to fix it?
Comment: Add symbolic breakpoints for NSException, and see why it is terminating. Also, add a breakpoint at the line that is crashing and look at the values of all the objects you have created. Why have you created worldFrame, if you aren't using it?
Answer: Check that map is non-nil. The error indicates that there aren't enough vertices (3 minimum) which can only happen with a rect if you pass in a zero rect, either because map is nil or the frame has no width/height.
Comment: I was inadvertantly setting the scale of map to zero in another method. Thanks bro!


concatenar variável em link - javascript

Question: Meu problema está na passagem de parâmetro no link, porque lá na página que recebe, está chegando como valor as variáveis ao invés dos valores.
Acredito que o problema esteja realmente na concatenação das variáveis na formação do link.
As variáveis serão números decimais ou inteiros.
var ins = 123.46;
var newcostumer = 456889;

Comment: Ficou meio obscuro o que vc quer. Qual o objetivo afinal?
Comment: André, tem que melhorar a pergunta para que possamos ajudar. Da onde provém as variáveis? Copie e cole o código completo para entendimento. Esses valores estão em campos input hidden ou foram enviados por GET para essa página?
Comment: Veja se a resposta te ajuda.
Answer: Você pode usar document.write para construir a URL passando variáveis:

Note que foi preciso fazer duas concatenações scr'+'ipt para que o JavaScript não crie um script dentro do outro, resultando em erro.


Modules that allow an infinite exact sequence on them

Question: I'm looking for a characterization of modules that fit the following property:
(*) There's an infinite exact sequence with $\phi_i \neq 0 \space \forall i\in I $
$\require{AMScd}$
\begin{CD}\cdots @>{\phi_i}>>\mathbb{M} @>{\phi_i+1}>> \mathbb{M}  @>{\phi_i+2}>> \cdots \\\end{CD}
I thought about the case of vector spaces and about factor rings $\mathbb{Z}/n\mathbb{Z}$:

For vector spaces V with $dim(V)=1$ it's impossible, but possible for $dim(V)>1$ (Might hold for free modules in general)
For $\mathbb{Z}/n\mathbb{Z}$ it's possible with 1 function, if n is square, with 2 functions as long as n ist not prime and impossible if n is prime.

But that's far from general... I'm also interested if the number of different functions has a deeper meaning.
Thanks in advance.
Comment: You're asking to characterize a rather wild type of module. Normally you ask to characterize well-behaved things... I guess there's still a chance something nice is true.
Answer: For any two nonzero $R$-modules $A$ and $B$, the maps
$$f(a,b)=(a,0), \quad g(a,b)=(0,b) $$
compose to zero, and moreover the sequence
$$ \cdots \to A \oplus B \xrightarrow{f} A \oplus B \xrightarrow{g} A \oplus B \xrightarrow{f} A \oplus B \to \cdots $$
is exact. This works for any ring, so indeed, if you allow rank at least $2$, this can always happen. Now if you want rank $1$, as you note, you can't allow $R$ to be a field. Indeed if $R$ is even an integral domain, there is no hope of composing two nonzero maps $R\to R$ to get zero. On the other hand, if $R$ is commutative but has zero divisors, you can still concoct an infinite exact sequence.


Como utilizar .directive, modularização e divisão de camadas? AngularJS

Question: OBS: Até entendi o tudo, o problema é que não consigo fazer com esse código as informações que me passaram, tipo nada. E quando faço não funciona. Alguém pode me ajudar por favor??
Olá, eu estou com um sério problema em entender como funcionam esssas coisas citadas em um texto. Gostaria de criar uma .directive, fazer a modularizarão fazendo parte do código ser utilizada em serviços e efetuar a divisão de camadas nesse código. Estou começando agora a aprender então estou tendo muita dificuldade nessa parte do processo de criação Angular.

angular.module('TarefApp', []);

// Code goes here
angular.module('TarefApp')

.controller('TarefasController', function($scope) {
  $scope.categorias = [];
  $scope.tarefas = [];
  $scope.categoriaTarefa = {
    tarefa: {}
  };

  $scope.addTarefa = function(tarefa) {
    if (!$scope.categoriaSelecionada) {
      alert("Selecione uma categoria!")
      return;
    }

    var c = $scope.categoriaSelecionada;

    if (!$scope.categoriaTarefa.tarefa[c])
      $scope.categoriaTarefa.tarefa[c] = [];
    else {
      var itemDuplicado = false;
      angular.forEach($scope.categoriaTarefa.tarefa[c], function(item, index) {
        itemDuplicado = (item.nome === tarefa.nome);
        if (itemDuplicado) {
          alert("Tarefa para categoria já existe!");
          return false;
        }
      });
    }

    if (!itemDuplicado) {
      $scope.categoriaTarefa.tarefa[c].push(tarefa);
      $scope.tarefa = {};
    }
  };

  $scope.delTarefas = function() {
    angular.forEach($scope.categorias, function(item) {
      var c = item.nome;
      var oldTarefas = $scope.categoriaTarefa.tarefa[c];
      $scope.categoriaTarefa.tarefa[c] = [];

      angular.forEach(oldTarefas, function(tar) {
        if (!tar.selecionado) $scope.categoriaTarefa.tarefa[c].push(tar);
      });
    });
  };

  $scope.addCategoria = function(categoria) {
    for (var i = 0; i < $scope.categorias.length; i++) {
      if ($scope.categorias[i].nome === categoria.nome) {
        alert("A categoria já existe!");
        return;
      }
    }
    $scope.categorias.push(angular.copy(categoria));
    delete $scope.categoria;
  };
});
        .container {
          margin-top: 2%;
        }
        .apgfiltro {
          margin-top: 5%;
          margin-bottom: 2.9%;
        }
        a:hover {
          text-decoration: none !important;
        }
        .done-true {
          text-decoration: line-through;
          color: #ccc;
        }
        .col-xs-9.edit {
          margin-top: 3%;
        }

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

Adicionar Categoria

                        <form role="form" class="ng-pristine ng-valid">

                                <input type="text" class="form-control ng-pristine ng-valid" ng-model="categoria.nome">

                            <button class="btn btn-info btn-block ng-pristine ng-valid" ng-click="addCategoria(categoria)" ng-model="infoIgual" ng-disabled="!categoria.nome" disabled="disabled">Adicionar</button>
                        </form>

Adicionar Tarefa

                        <form role="form" class="ng-pristine ng-valid">

                                <input type="text" class="form-control ng-pristine ng-valid" ng-model="tarefa.nome">

                                <select class="form-control" id="category" ng-options="item.nome as item.nome for item in categorias" ng-model="categoriaSelecionada">

                                </select>

                            <button class="btn btn-info btn-block ng-pristine ng-valid" ng-click="addTarefa(tarefa)" ng-model="infoIgual" ng-disabled="!tarefa.nome" disabled="disabled">Adicionar</button>
                        </form>

                    <button class="btn btn-danger btn-block" ng-click="delTarefas()">Apagar tarefas selecionadas</button>

{{categoria.nome}}

                            <input type="checkbox" ng-model="tarefa.selecionado" ng-click="tarefaFeita()">
                            {{tarefa.nome}}

Comment: Você quer muita coisa em uma única pergunta, nesta caso, eu recomendo que você faça o curso até a fase gratuita que o próprio AngularJS oferece [ http://campus.codeschool.com/courses/shaping-up-with-angular-js/ ] , com ele você terá toda a base necessária para começar a criar cada um desses elementos.
Comment: Para mais informações, consulte a documentação: https://docs.angularjs.org/api
Answer: Vamos lá:
Antes de mais nada você precisa entender o que é um controlador, um serviço e uma diretiva no angular
Controlador (Controller)
Entenda item como sendo um controlador dos componentes que estão em tela. Em outras palavras, aqui vão ficar todas as rotinas que envolvem interação usuário com a página HTML em sí. Além disso também partem daqui as requisições a outros componentes como por exemplo o serviço.
Serviço (Service)
Esse é o cara responsável por compartilhar recursos entre os controladores e também aqui geralmente ficam as rotinas que envolvem as chamadas http. É comum o pessoal usar esse cara para efetuar chamadas rest por exemplo. Desse modo você tem um serviço de pessoa por exemplo que pode incluir, alterar, excluir um pessoa.
Serviço Genérico
App.factory("$comum", function($http, $q, $injector) {
    function ajax(url, parametros, metodo) {
        var requisicao = $http({
            method: metodo,
            url: url,
            data:parametros
        });

        var promessa = requisicao.then(
            function(resposta) {
                return(resposta.data);
            },
            function(resposta) {
                return($q.reject("Something went wrong"));
            }
        );
        return promessa;
    }
    return({
        ajax:ajax
    });
});

Serviço Histórico Venda
App.factory("$historicovenda", function($comum) {
    var historico;
    return {
        buscar : function(filtro) {
            var promessa = $comum.ajax("/fusion/services/roi/history/search", filtro, "POST");
            promessa.then(function(req) {
                historico = req;
            })
            return promessa;
        },
        cache : function() {
            return historico;
        }
    };
});

Controlador Histórico Venda
App.controller("HistoricoVendaController", function($scope, $historicovenda) {
    $scope.buscar = function(regerar) {
        var filtro = "1";
        $historicovenda.buscar(filtro).then(function(req){
            console.log(req)
        });
    };
});

E agora vamos a sua pergunta:
Divisão de camadas
A divisão em camadas é justamente separar as responsabilidades de cada um. Um exemplo prático: Você tem um cadastro de pessoa, nesse caso podemos dividir a rotina em dois componentes. Um controlador (camada 1) responsável por executar a ação quando o usuário clicar no botão salvar e validar os dados. Além disso esse componente também irá compilar o objeto a ser salvo e em seguida irá passar a bola para o serviço (camada 2) que irá efetuar a chamada http para efetivar o usuário no banco de dados. Nesse caso temos duas camadas com baixo acoplamento. Caso necessite consultar uma pessoa em outro controlador pode usar mesmo serviço. E ai está a sacada de separar as responsabilidades, você pode compartilhar o recursos.
Diretiva (Directive)
A diretiva é utilizada quando você quer determinar um comportamento em determinado elemento HTML. Também pode ser utilizado para você criar suas próprias tags. Existem muitas bibliotecas no angular que fazem o uso de tal elemento para dar um comportamento especifico. Exemplo:
No Js:
angular.module('App', [])
.directive('sonClick', function () {
    return {
        restrict: 'A',
        link: function(scope,element,attrs){
            element.bind('click',function(){
                scope.$eval(attrs.sonClick);
            })
        }
    };
})
.controller('CtrlApp', function ($scope) {
    $scope.executa = function(){
        alert("scope");
    };
});

No html:

    <button son-click="executa()">clique aqui</button>

Modularização
Esse é o mais simples e considero tão quanto os outros. Trata-se de separar em arquivos diferentes cada componente. Um arquivo para controlador, outro para serviço, outro para diretiva e assim por diante.
Answer: Resumidamente, vou explicar como funciona as diretivas.
1) para criar uma diretiva:
app.directive("nomeDaDiretiva", function () {
   //seu método
});

2) para criar uma diretiva modulada:
angular.module('NomeDoModulo', [])
.directive("nomeDaDiretiva", function () {
   //seu método
});

3) O que acontece é que apontamos o modulo para uma variável:
var app = angular.module('NomeDoModulo', []);

4) Então criamos uma diretiva:
app.directive("nomeDaDiretiva", function () {
   //seu método
});

5) No módulo temos que passar os elementos que serão usados na aplicação, conforme coloquei ngResource, ngRoute:
var app = angular.module('NomeDoModulo', ['ngResource','ngRoute']);

6) As diretivas contém algumas restrições que podem ser definidas:

E - Diretiva restrita ao elemento
A - Diretiva restrita ao atributo do elemento
C - Diretiva restrita a classe do elemento
M - Diretiva restrita ao comentário do elemento

Aqui tem um exemplo de diretiva (observe que neste exemplo, contém a restrição EAC (em conjunto) e está modularizado: http://jsfiddle.net/ivanferrer/1cyxoytv/
A diretiva terá um retorno, e nele podem conter os seguintes parâmetros
restrição (restrict), layout (template), método em si (link) e substituição (replace), este receberá um booleano (true ou false).
Também pode conter parametrização do escopo (escope):
angular.module('MeuSistema', [])
.directive('DadosUsuario', function () {
    return {
        restrict: 'E',
        scope:{
           nome:'@',
           email:'@',
           cidade:'@'
        },
        template:'

',
        link: function(scope,element, attributes) {

            element[0].innerHTML =  'Os dados do usuário são:
'
             + 'Nome: ' + scope.nome + '
'
             + 'Email: ' + scope.email + '
'
             + 'Cidade: ' + scope.cidade;

        },
        replace: true
    };
}) //o correto é separar isso em um arquivo só do seu controller em uma pasta "controllers"
.controller('ExibirDados', function() {

  $scope.nome = "Larissa Mourullo";
  $scope.email = "firstname.lastname@example.com";
  $scope.cidade = "São Paulo";

});

E no HTML:

 <title>Exemplo</title>

<dados-usuario nome="{{dados.nome}}"
               email="{{dados.email}}"
               cidade="{{dados.cidade}}">
</dados-usuario>


Inclusion of $L^p$ and weak $L^p$ spaces

Question: Let $0<p_0<p_1<\infty$, $0<\theta<1$, and $1/p_\theta=(1-\theta)/p_0+\theta/p_1$. Show that
$$L^{p_\theta,\infty}(X)\subset L^{p_0}(X)+L^{p_1}(X).$$
Suppose that  $f\in L^{p_\theta,\infty}(X)$, we need to show that $f$ can be written as $f=f_0+f_1$ with $f_0\in L^{p_0}(X)$ and $f_1\in L^{p_1}(X)$. Without loss of generality, we can assume that $\|f\|_{L^{p_\theta,\infty}}=1$, then we have
$$\sup_{t>0}t\lambda_f(t)^{1/p_\theta}\leq 1,$$
where $\lambda_f(t):=\mu(\{x\in X:|f(x)|\geq t\}$ is the distribution function of $f$. I'm stuck here, I don't know how to determine $f_0$ and $f_1$?
Answer: Let $0<p_0<p_1<\infty$, $\theta \in (0,1)$, $\frac{1}{p_\theta}=\frac{1-\theta}{p_0}+\frac{ \theta}{p_1}$ and $f\in L^{p_\theta,\infty}(X)$. For fixed $\delta>0$, set $$f_\delta(x) = f(x) \chi_{\left\{x\in X\ :\ |f(x)|>\delta \right\} }(x),$$ $$f^\delta(x) = f(x) \chi_{\left\{x\in X \ :\ |f(x)|\leq \delta \right\}} (x)$$ (this means that $f=f_\delta+f^\delta$). Since $f$ is measurable, the set $\left\{x\in X\ :\ |f(x)|>\delta \right\}$ is measurable, following the measurability of $\chi_{\left\{x\in X \ :\ |f(x)|> \delta \right\}}$ and consequently of $f_\delta$ (product of two measurable functions is measurable). Furthermore, $f^\delta$ is also measurable, because $f^\delta=f-f_\delta$.
I assert that $f_\delta \in L^{p_0}(X)$ and that $f^\delta \in L^{p_1}(X)$. In fact, due to the construction of these functions
\begin{align}
    &\lambda_{f_\delta}(t)=\begin{cases} \lambda_f(t)\quad if \quad t>\delta, \\ \lambda_f(\delta)\quad if \quad t\leq\delta , \end{cases}
    &\lambda_{f^\delta}(t)=\begin{cases} 0\quad if \quad t\geq \delta, \\ \lambda_f(t)-\lambda_f(\delta) \quad if \quad t <\delta. \end{cases}\nonumber\\
\end{align}
Thus, by Teonelli's Theorem and by the previous equation
\begin{align*}
\|f_\delta\|_{p_0}^{p_0}=\int_{X}|f_\delta(x)|^{p_0}\,d\mu(x)&=\int_{X}\left(p_0\int_{0}^{|f_\delta(x)|} t^{p_0-1} \,dt \right)\,d\mu(x) \\&=p_0\int_{0}^{\infty} \int_{\{x \in X\mid |f_\delta(x)|> t \}}t^{ p_0-1} \,d\mu(x)\,dt
\\&=p_0\int_{0}^{\infty} t^{p_0-1}\mu (\{x \in X\mid |f_\delta(x)|> t \}) \,dt \\&= p_0\int_{0}^{\infty} t^{p_0-1}\lambda_{f_\delta}(t) \,dt\\&
=p_0\int_{0}^{\delta} t^{p_0-1}\lambda_{f}(\delta) \,dt + p_0\int_{\delta}^{\infty} t^{p_0-1 }\lambda_{f}(t) \,dt\\&
=\delta^{p_0}\lambda_{f}(\delta)+ p_0\int_{\delta}^{\infty} t^{p_0-1}\lambda_{f}(t) \,dt
\end{align*}
Furthermore, as $\sup_{t>0}t\lambda_f(t)^{1/p_\theta}=C<\infty$, we have $\lambda_f(t)\leq C^{p_\theta}t^ {-p_\theta}$ for any positive $t$ and so
\begin{align*}
\|f_\delta\|_{p_0}^{p_0}&\leq \delta^{p_0}(C^{p_\theta}\delta^{-p_\theta}) +p_0\int_{\delta} ^{\infty} t^{p_0-1} (C^{p_\theta}t^{-p_\theta}) \,dt\\& \leq C^{p_\theta}\delta^{p_0- p_\theta} + p_0 \cdot C^{p_\theta} \int_{\delta}^{\infty} t^{p_0-p_\theta-1}\,dt<\infty,
\end{align*}
because
\begin{align*}
{p_0-p_\theta-1}=p_0-\left(\frac{p_0p_1}{(1-\theta)p_0+\theta p_1}\right)-1<-1.
\end{align*}
Analogously, we have
\begin{align*}
\|f^\delta\|_{p_1}^{p_1}=\int_{X}|f^\delta(x)|^{p_1}\,d\mu(x)&=\int_{X}\left(p_1\int_{0}^{|f^\delta(x)|} t^{p_1-1} \,dt \right)\,d\mu(x)\\&=p_1\int_{0}^{\infty}\int_{\{x \in X\mid |f^\delta(x)|> t \}}t^{p_1-1} \,d\mu(x)\,dt\\&=p_1\int_{0}^{\infty} t^{p_1-1}\mu (\{x \in X\mid |f^\delta(x)|> t \}) \,dt \\&= p_1\int_{0}^{\infty} t^{p_1-1}\lambda_{f^\delta}(t) \,dt\\&
=p_1\left(\int_{0}^{\delta} t^{p_1-1} (\lambda_f(t)-\lambda_f(\delta)) \,dt + \int_{\delta}^{\infty } t^{p_1-1}\cdot 0 \,dt\right)
\\&\leq -\delta^{p_1}\lambda_{f}(\delta) +p_1\int_{0}^{\delta} t^{p_1-1} (C^{p_\theta}t^ {-p_\theta}) \,dt\\& \leq p_1 \cdot C^{p_\theta} \int_{0}^{\delta} t^{p_1-p_\theta-1}\,dt< \infty,
\end{align*}
because
\begin{align*}
{p_1-p_\theta-1}=p_1-\left(\frac{p_0p_1}{(1-\theta)p_0+\theta p_1}\right)-1>-1.
\end{align*}
Comment: Note: this proof assumes that $(X, \mu)$ is a $\sigma$-finite measure space, since Tonelli's theorem has been invoked.


How to make C# winform application portable

Question: I have developed a winform application with C# 4.5. I want to make it portable. I meant that it should not need to be installed. To deploy this application I would like to just copy and paste the folder of application file. Like Tally or VLC Media player.
The environment and dependencies are as follows
C# Winform
.Net Framework 4.5
SQLite
Microsoft Report Viewer
Please suggest a way how to do it.
Comment: Have you tried to simply copy the executable and necessary files?
Comment: *Did* you try to see if it needs any dependencies, eg just copy the binaries from bin/Debug or bin/Release it to another machine? XCopy deployment was one of the main features of .NET back in 2002.
Answer: For each of your project's references, you should verify Copy Local property is set to True. This way, all the references will be copied in your project's bin folder (at compile time).
This should be suficient for a copy/paste deployment of your bin folder.
Keep in mind,

no program is an island -- Don Box

so deployment machines should need at least target framework installed.
.NET Framework will first search inside bin folder and if reference is not found, it will search the GAC (Global Assembly Cache).
Comment: Thanx for your answer. I did this and it is working for now. Thank you soo much.
Answer: XCopy deployment can be used to deploy your application.
Comment: Just make sure to use "CopyLocal" for all 3rd party assemblies to ensure they're part of the compilation output.


Sql Server 2008, Active Directory Groups, and Failed Logins

Question: I keep getting a Login Failed error in my ASP.net application when connecting to my SQL Server 2008 database. I am trying to login with the user domain\foo.
When I grant a database login (server and database level) for domain\foo, my application can connect.
When I put domain\foo in a group called domain/goo and give domain\goo a database login, the user domain\foo cannot authenticate.
This does not make any sense. Am I doing something wrong? domain\foo and domain\goo are configured identically. The only difference is that on is a user and one is a group containing a user. Adding active directory groups as users to SQL Server 2008 is supposed to work.
Answer: You can't use groups.  I wasn't aware that SQL 2008 had changed this.  I think you have to use individual user accts.  I know... it sucks.
Comment: Did this used to work 2003?
Comment: I've never been able to give groups permission in mssql, it doesn't support that.  However, I'd need to see some specific documentation for sql 2008 showing it supports this to believe it.  If I get some time today I'll look around.
Answer: It  sounds like you encountered a scenario similar to one I did when setting up my first SQL Server 2008. In my particular scenario I was using Windows authentication only, and had granted local administrators sysadmin rights. Yet the only person who could successfully log into SQL Server Management Studio was the Local Administrator of the server. (The errors I saw are at the bottom of this posting.)
After locating the SQL Server debug logs, I discovered that the authentication was succeeding, but access was being denied (State: 11). After further digging in TechNet, I found that UAC masks most group memberships, and the workaround is to run SQL Studio as an administrator.

SQL Server Management Studio

Cannot Connect to {servername}.
Additional information
  ->   Login failed for user '{username}'. (Microsoft SQL Server, Error: 18456)

Windows Event Log

Login failed for user '{username}'.
  Reason: Token-based server access
  validation failed with an
  infrastructure error. Check for
  previous errors. [CLIENT: ]

SQL Server Debug logs
(Located at: {SQL_Server_Root}\MSSQL10.{instance}\MSSQL\Log\ERRORLOG)

{Datestamp} Logon
  Error: 18456, Severity: 14, State: 11.
  {Datestamp} Logon
  Login failed for user
  '{username}'. Reason:
  Token-based server access validation
  failed with an infrastructure error.
  Check for previous errors. [CLIENT:
  ]
Comment: @keith: Group memberships /seem/ to be assigned at log-on. This would explain your symptoms if you added the user to the group in the same session as the one you were running when you tried to log into the DB.
Comment: I had an instance where run as administrator was not fixing this issue.  Once I logged out of the server and back in, I could run as administrator and log in to the Database Engine. BTW, I could connect to Analysis and Reporting services without the run as fix.
Comment: @bitzbyte363: Thanks for this. I had the same problem and this fixed it. +1
Answer: Are these Active Directory Security Groups or Distribution Groups?
I can tell you for a fact that we use AD Security groups to assign permissions in SQL Server version 2000, 2005, and 2008.


Is it possible to disable anti-aliasing on vector images?

Question: On Wear OS in ambient mode, only black or white pixels should be displayed (no grays). Anti-aliasing a black and white image introduces gray pixels. Now, anti-alising can be disabled for a TextView by writing textView.paint.isAntiAlias = false (in Kotlin) but there doesn't seem to be an equivalent for vector images. The one thing I've tried is adding android:antialias="false" to the image XML file, but it seems to have no effect.
Comment: Note that most newer Wear OS devices support up to a limited color palette in ambient mode (as well as greyscale). What made you think you could only use black or white?
Comment: Not that you _can't_, certainly, but black and white are the most energy efficient colors to display, according to Google. Grays are especially discouraged.
Comment: Do you have a reference to where 'grays are especially discouraged'? The docs [actually say](https://designguidelines.withgoogle.com/wearos/patterns/always-on.html#always-on-style): "Use a limited color palette" and "Aim to have 95% of its pixels black".
Comment: [This doc](https://designguidelines.withgoogle.com/wearos/style/color.html) says: "Grays should be avoided, as any tint of color is more battery-efficient than any shade of gray or white."
Comment: that relates to backgrounds, not aliasing in text / icons.
Comment: No, nowhere does it imply that it's only for backgrounds. Furthermore, [this](https://developer.android.com/training/wearables/apps/always-on) doc implies that anti-aliasing should be turned off for text, which correlates to the recommendation to avoid grays..
Comment: try with `setFilterBitmap(false);`
Comment: Calling setFilterBitmap(false) on the image seems to have no effect. https://i.imgur.com/DNqn582.png
Answer: I don't think there is a way to do it in XML.
Personally I've only done this when drawing straight to a canvas. Setting setAntiAlias(false) (don't remember if we ended up using setDither(false) and setFilterBitmap(false) too) on the Paint did the trick.
You can try using a DrawableWrapper and make the necessary changes in the draw() method. Unfortunately this means that you have to set all your drawables in code, but at least you'll still be able to rely on an ImageView.


JavaFX - Listen to Changes in List

Question: Hi I have a probably quite stupid question. I have just started to play around with
Properties and ChangeListeners but have hit a speed bump. I have understood that if I make an ObjectProperty containing an ArrayList any ChangeListener will only fire if the ArrayList itself changes. However I want all ChangeListeners to fire if

The ArrayList itself changes.
The length of the ArrayList changes (that is an element is added or removed).
An element in the ArrayList is changed to a different one.
An element in the ArrayList changes, that is the content of an element changes (If the element is a custom class Person for instance. I want to fire the ChangeListener if the person changes her age for instance.).

Is there some functionality in JavaFX for this already or should I implement this manually? What would be the best way to do this?
/Thanks for any help!
Comment: https://docs.oracle.com/javase/9/docs/api/javafx/collections/FXCollections.html#observableArrayList-javafx.util.Callback-
Answer: You cannot add a listener to a regular ArrayList as it is not observable. However, the FXCollections package does provide an ObservableArrayList<E> that allows you to listen for changed.
Here is a demo program:
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;

public class Main {

    public static void main(String[] args) {
        ObservableList<String> strings = FXCollections.observableArrayList();

        strings.addAll("One", "Two", "Three");

        strings.addListener((ListChangeListener<String>) change -> {
            while (change.next()) {
                if (change.wasAdded()) {
                    System.out.println(change.getAddedSubList().get(0)
                            + " was added to the list!");
                } else if (change.wasRemoved()) {
                    System.out.println(change.getRemoved().get(0)
                            + " was removed from the list!");
                }
            }
        });

        strings.add("Dogs");
        strings.remove("Two");
    }
}

There are more methods within the ListChangeListener that you can use to get more details about what has been changed. Just read up on it!

JavaFX - Listen to Changes in List


Conditional probability questions

Question:
Three dice are rolled. If no two show the same face, what is the probability that one is an ace?
Given that a throw with ten dice produced at least one ace, what is the probability p of two or more aces?

Answers provided by the Author William Feller is

$1-\frac{5*4*3}{6*5*4}=\frac12$

2.$p=1-\frac{10*5^9}{6^{10}-5^{10}}=0.6147724$
I don't understand how did the author calculate these answers?
If any member knows may answer these questions.
Comment: Intuitive hints: (1) asks for the proportion of three-element subsets of $\{1,2,3,4,5,6\}$ that do not include $1$; that is, they are subsets of $\{2,3,4,5,6\}.$ (2)  The value subtracted represents the chance that none of the other $9$ faces is an ace--that is, it's one of the $5$ values $\{2,3,4,5,6\}.$  Its numerator is the sum over all $10$ dice of the value $5^9.$ Its denominator must come from the calculation of conditional probability and can be recognized as the total number of outcomes with at least one ace.
Comment: Hint: 1. P(neither is ace) = (number of combinations where each dice has different face and it isn't ace) / (number of combinations where each dice has different face). P(at least one ace) = 1 - P(neither is ace).
Answer: Explanation of Question 1
The desired probability is: $ P(\text{an ace} | \text{each face is different}) $
So, one of the first things that we should calculate is how many different ways we can roll three die with the faces all being different (the given in the question). This number becomes the size of our sample space (also, the question implicitly assumes that order does not matter. We then want to calculate how many of those possible rolls (in the sample space) do not have an ace. The difference is our desired probability.
Worked out solution:
Ways to roll three die with all different faces: 6*5*4

First dice in the roll can be any of the 6 faces
Second dice in roll can have any face other than that on the first (5)
Third dice in roll can have any face other than first two die (4)

Ways to roll three die with all different faces and no ace: 5*4*3

First dice in the roll can be any of the 5 non-ace faces
Second dice in roll can have any face other than the first or an ace (4)
Third dice in roll can have any face other than first two die or an ace (3)

Putting these together:
$ P(\text{no ace} | \text{each face is different}) = \frac{5*4*3}{6*5*4} $
$ P(\text{an ace} | \text{each face is different}) = 1 - P(\text{no ace} | \text{each face is different}) $
$ P(\text{an ace} | \text{each face is different}) = 1 - \frac{5*4*3}{6*5*4} = \frac{1}{2} $

Conditional probability questions


PHP, Break Up String with Ampersand

Question: I have spent a lot of time searching the web for this, so before someone slams me for not looking ... trust me, I have.
The problem: I am working with a string that includes an ampersand, to display two names. The difficulty: at times I may need to pull the name on the left, or the name on the right for display. The additional difficulty is that some of the names may include HTML entities, which of course also use an ampersand.
Example: I may use something as simple as:
"Fred & Wilma"
To get just "Fred" from the string, I tried using the PHP function STRPOS(), but I get nothing.
$nPos = strpos( " & ", $names );

Note that I am using spaces on either side to avoid issues with HTML entities.
More fun, checking to see if I get no results:
if ( $nPos === 0 )
{
   echo "String ' $' not found in " . $names . "
";
}

Does not return a value. This tells me, from the various documentation and such on the web that I can find, that I should have a value for $nPos that is useful.
If I add:
echo "Position of string ' & ': " . $nPos . "
";

I get a blank value after the text in double quotes.
I am at a loss how to do what I need here. I need to get the position of the " & " characters, but am not getting it. From there obviously use of the substr() function would be necessary to get the values from the left and/or right of the ampersand.
Comment: In addition to the answers correcting your use of `strpos`, please not that `if($nPos === 0)` checks if the needle was found at position `0` in the haystack. You should change it to `if($nPos === FALSE)`.
Comment: You might consider deciding HTML entities so you can deal with the characters they represent.  After all, the correct way to have an ampersand in an HTML is `&`. Re-encode as required afterwards.
Answer: strpos first parameter is haystack - string in which you do the search & second is needle - string you searching for. So just swap parameters:
$nPos = strpos(  $names, " & " );
You can find more info here
Comment: Gotta love PHP and it's consistancy with needle/haystack parameter ordering.
Comment: It is consistent: string functions are haystack, needle and array functions are needle, haystack.
Comment: Thanks -- it was, as noted, the consistency of PHP and parameter ordering that threw me off completely. The suggestion of using explode() is one I had not considered as I am not that familiar with it (I have only recently learned of it). This resolves the issue at the moment. Thanks again!
Answer: If you just needs the names, I would break it into an array:
$nameArray = explode(' & ', $names);

This won't split unexpectedly on HTML because & is not followed by a space in that situation.
Answer: You can use the explode($delimeter, $subject_string) function, which is built-in PHP. For example:
$names = 'firstName & lastName';
// use `&` as delimeter to split on and callback `trim` function on each array item
$names_array = array_map('trim',explode(' & ', $names));

now $names_array will look like this:
array(
  [0] => 'firstName'
  [1] => 'lastName'
)

and can be access as as following:
$firstName = $names_array[0];
$lastName = $names_array[1];

Comment: Strpos is good for seeing whether the substring exists,  but I think this explode is a more elegant way to actually extract them.
Comment: OP said spaceless `'&'` will not do as a delimiter.  See MattS's answer.  I would downvote this answer if I thought it would make a difference.

PHP, Break Up String with Ampersand


How to use a variable in multiple DataGrip queries?

Question: Given I have a bunch of queries
E.g.
delete from permissions where user_id = 9845 and project_id =2;
delete from users_projects where user_id = 9845 and project_id =2;
delete from users where id = 9845 and project_id =2;

How can I avoid having to update the user_id in each query each time I run these?
Ideally, something like
var userId = 9845

delete from permissions where user_id = userId and project_id =2;
delete from users_projects where user_id = userId and project_id =2;
delete from users where id = userId and project_id =2;

I tried using ? and :userId
E.g.
delete from permissions where user_id = :userId and project_id =2;
delete from users_projects where user_id = :userId and project_id =2;
delete from users where id = :userId and project_id =2;

This prompts me to enter a User Id via a dialog, which is fine, except I have to enter ir for each row.
I want to be able to update one place / enter the value once.
Is this possible with DataGrip?
Answer: You can use ${variable_name} syntax to enter a value only once for queries:
delete from permissions where user_id = ${userId} and project_id =2;
delete from users_projects where user_id = ${userId} and project_id =2;
delete from users where id = ${userId} and project_id =2;


Sql like with each word starting charcter

Question: My table:
create table product (
  nama_product varchar(20)
);

insert into product values
('ayam bakar'),
('daging ayam'),
('bayam hijau'),
('daun bayam');

Current Query:
select nama_product
  from product
 where nama_product regexp '(^| )ayam( |$)';

I am got the answer from https://stackoverflow.com/a/37234783/7273263.
I want to search char or word from text value. Current query i am getting the accurate result but problem is thar i have to give entire word.
But i want to get the result if 'aya' instead of 'ayam'
select nama_product
      from product
     where nama_product regexp '(^| )aya( |$)';

I have tried with '%ayam%' but it searched result if middle of the word..
i need to get the same result with input 'aya' Please let me know,
i need specific answer in mysql & sql ;sql lite or any one
Edit: Required Result:
nama_product
ayam bakar
daging ayam

Comment: Then you should read a tutorial. Don't just copy code without understanding how it works.
Comment: If you only want to match the beginning of the word, get rid of `( |$)` after the word.
Comment: Thanks @Barmar it will same for sql lite also rite
Comment: Yes. This is basic regular expression, should work with any engine.
Answer: Solution 1 Like Impression:
SELECT *
FROM product
WHERE nama_product like'aya_%' or nama_product like'% aya_';

Solution 2 Regular Impression:
SELECT nama_product
      FROM product
     WHERE nama_product regexp '(^| )aya';


semisimple Lie algebra and proof of decomposition

Question: A step I don't understand in the proof of the uniqueness of the decomposition of a simple Lie algebra.
We first proof that $$L = L_1\oplus \cdots\oplus L_n$$ with $L_i$ simple ideals.
Now I take $I$ a simple ideal then $$[I,I]\subset[I,L] = I$$
Why is $[I,L] = I$?
What I would say is that $[I,L]$ is an ideal included in $I$ and is this either $I$ or $\{0\}$ but I don't know how to exclude the second possibility.
Comment: I think that in the last line where you write 'What I would says is that $[I, I]$ is an ideal...' you actually meant to write: 'What I would says is that $[I, L]$ is an ideal...'. I cannot edit it for you since edits need to be at least 6 characters long, but perhaps you can change it yourself?
Comment: Yes you're right
Answer: The definition of simple Lie algebra has two parts:
1) It has no non-trivial ideals
2) It is non-abelian
You use 1) to reduce the possibilities to $\{0\}$ and $I$. You can use 2) to rule out zero.
(A simple ideal is an ideal that is simple when considered as a Lie algebra by itself)
REMARK: it is good to realize that every linear subspace of an abelian Lie algebra is an ideal, so you really only need to invoke 2) in the special case that $I$ is 1-dimensional. (Or from the perspective of simple Lie algebras rather than your specific question: the 'additional' axiom 2) in the definition of simple only rules out one (otherwise) simple Lie algebra: the one-dimensional one.)
Answer: $[I,L]\subset I$ is an ideal of $I$. This implies that $[I,L]$ is $I$ or $\{0\}$, now $[I,I]\neq 0$ since $I$ is not Abelian, you deduce that $[I,I]=I$.


Freudenthal suspension theorem- Weak excision lemma

Question: http://www.math.uchicago.edu/~amwright/HomotopyGroupsOfSoheres.pdf
I'm trying to understand this theorem on page 6. Apparantly you can use that to prove the Freudenthal suspension theorem for spheres. However, I think it's wrong particularly $\pi_{i}(A,C) \rightarrow \pi_{i}(X,B)$, shouldn't it be A instead of B in the co-domain. Does anyone know any references to this proof?
Also, is there any texts on this lemma, as I'm trying to find the lemma and it seems to not exists. So I was wondering can someone tell me if the proof is correct and provide sources. As I understand everything upto this point in his project.
This seems to be a simplified theorem to the one in Hatcher.
Answer: In the Book "Elements of homotopy theory" by whitehead there is a Theorem of blakers and massey, also called homotopy excision theorem.
It implies Freudenthals suspension theorem, so you might want to look there.
Comment: Thank you. I looked at the preface online and it mention proving it for spheres and theorem of blackers massey. I will try and see if I can get a copy in the library or if a lecturer has a copy of it. Thanks
Answer: The theorem of Blakers and Massey is also a consequence of a van Kampen theorem for diagrams of spaces: see the references in
R. Brown, ``Triadic Van Kampen theorems and Hurewicz theorems'', Algebraic  Topology, Proc. Int. Conf. March 1988, Edited M.Mahowald and S.Priddy,  Cont. Math. 96 (1989) 39-57.
This method has the advantage of determining the critical triad homotopy group, even in some non-simply connected situations.
The proof of the general theorem van Kampen is quite sophisticated, though!
May 30: I have now made an updated copy of the above paper available at
http://pages.bangor.ac.uk/~mas010/pdffiles/VKTEVAN2.pdf
Part of the point is that one brings in triad homotopy groups, as they are part of exact sequences  which show them as the obstruction to excision. So the problem is that of calculating these groups, and of seeing when they are zero. The paper shows how a structure of crossed square is involved in such calculations.


When doing hierarchical clustering, do we need to exclude variables with high correlation?

Question: I have one question regarding the hierarchical clustering. I personally have used this hierarchical clustering methods a few times, but did not apply it to the protein level data before.
What I am trying to do is to cluster patients (total 100 patients) using their protein level information (about 400 proteins). The data is clean and standardized.
In this case, is it recommended to remove some proteins having high correlations before performing hierarchical clustering? (Usually, when it comes to linear regression, we exclude variables having high correlation with others. I am wondering if the same procedure needs to be applied.)
Or can I keep all 400 proteins and directly apply to the hierarchical clustering method by using a correlation distance metric?
Looking forward to hearing opinions!! Thanks!!
Comment: There is _at least_ one issue with highly correlated features. Using them all (p) is akin to using one feature which is their combination (sum or mean) with weight (importance) =p. Will you like that? That multiplication of information that is common in them?
Comment: Please search the site for "correlated variables clustering", there's a lot to appreciate.
Answer: Ultimately the answer is "it depends". It depends on various things, including potential preprocessing and the distance you use (I guess Euclidean but be aware that this is not the only option). There are also various different methods of hierarchical clustering.
The major issue here in my view is the following, assuming you're using Euclidean distance. Ultimately the variables that you use define the meaning of the clustering (it is a wrong idea to think that there is only one "true" clustering of the data and one "true" selection of variables that should be found - there may be different clusterings in different groups of variables and different clusterings depending on how exactly you aggregate them). If you standardise the variables, they will in a well defined sense all have the same weight in your clustering.
Now the question is: If you have strongly correlated variables, in your situation, does this mean that essentially all these variables encode the same information, which should only be used once (i.e. with the same weight as any other single variable that is not highly correlated with others)? In this case it can be argued that proteins should be removed so that the information shared between them is only taken into account once, as should be. Note though that there are alternative methods such as replacing a group of highly correlated variables by their first principal component (which represents the "shared information" better than if one is used and the others discarded).
However it may also be that regarding your aim of clustering, if several variables are highly correlated, this in fact adds information that should be used by the clustering process. An example is that in social statistics wealth and education level may be highly correlated, but they are still essentially different aspects of what is of interest, so the clustering should use them both anyway assuming that both are relevant to the clustering aim. The correlation basically then means that they together have a strong influence on the clustering, which may well be appropriate as each may be important to the clustering aim in its own right.
It is important to realise that this is an issue that the data cannot decide on their own. It depends on the intended meaning and use of the clustering, and on knowledge about the meaning of the variables.


Numerical error analysis of ODE

Question: Consider the ODE as follows: $$
y' = f(y,t),\;\; y(0) = y_0$$
and the numerical approximation is defined as follows: $$
y_{n+1} = y_{n} + \frac{h}{2}(f(y_n, t_n) + f(y_n + hf(y_n,t_n), t_{n+1}))$$
To proof $$
y(t_{n+1}) - y_{n+1} = C\cdot h^3$$
where of course $y(t_{n+1})$ is the analytic solution at $t_{n+1}$, I assumed $f(y,t) = ay$ with $a<0$ and it is A-stable, i.e. $y_n\xrightarrow{n\to\infty}0$ with some upper bound of $h$.
I think we should use Taylor in two variables at some point but now sure how to proceed it.
I appreciate your reply in advance!
Comment: This is possibly the same question as https://math.stackexchange.com/q/2023015/115115, however the answer there is for the autonomous case, one would need to translate back to the time-dependent case.
Answer: $f(y_n+h f(y_n,t_n),t_n+h)=f(y_n,t_n)+h f_y(y_n,t_n) f(y_n,t_n) + h f_t(y_n,t_n)+O(h^2)$. Plug in and simplify. Then compare with the Taylor series you expect.

Numerical error analysis of ODE


Implement structure like wikipedia on node

Question: I want Implement structure in drupal like wikipedia, register user can change the node content but if admin(a role for this job) approve them the updated  node show to user,else the old version ( not changed ) show. drupal has revision feature but this it applied and not wait for admin approve the changes,any way exist in drupal to achieve this job?
In before project I did something like this but It was about user profile not on content, I used profile module ,but here I want work on content and nodes .
Answer: You can setup a content moderation system for nodes using the Workbench Moderation module


Should a Hausman test be used to decide between fixed vs. random effects?

Question: I was taught that a Hausman test should be used in multilevel modeling in order to check whether random effects can be used.
However, I have now stumbled over several sources stating that the Hausman test is actually being misunderstood when using it in this way and that it rather tests whether the between and within effects are different. e.g.:
Snijders, T. A., & Bosker, R. J. (2011). Multilevel analysis: An introduction to basic and advanced multilevel modeling. Sage.
Bell, A., Fairbrother, M., & Jones, K. (2019). Fixed and random effects models: making an informed choice. Quality & Quantity, 53(2), 1051-1074.
The authors are referring to an article from 2004:
Fielding, A. (2004). The role of the Hausman test and whether higher level effects should be treated as random or fixed. Multilevel Model. Newsl. 16(2), 3–9.
There are, though, relatively recent textbooks treating the Hausman test as a tool to decide between fixed and random effects, e.g.:
Wooldridge, J. M. (2010). Econometric analysis of cross section and panel data. MIT press.
Could somebody please help me out of my confusion?
Answer: What the the Hausman test is doing is testing whether the results (i.e. the estimated coefficients) from a fixed effects and random effects model are significantly different.
(I haven't ever seen people talk about it testing whether whether the fixed and "between" effects are different, although because the random effects model is estimated as a weighted average of the between and fixed effects models, you could look at it that way, I suppose.)
However, the reason it's used to "decide between fixed vs random effects" is that if the results of the two models ARE different then that's a reason to prefer the fixed effects model.
Here's why.
A fixed effects (FE) model accounts for ALL omitted variable bias from variables at the higher "group" level, because a fixed effects model is basically just including a dummy indicator variable for each "group." This means that if you run a FE model you don't have to worry about omitted variable bias at the group level.
A random effects (RE) model does NOT automatically account for all group level  bias (that is, bias due to differences "between groups"), although it allows you to include group level predictors (that is, predictor variables that vary ONLY between groups, but not within groups) that do that. Now, if you were to include ALL significant group level covariates in your random effects model then you would get the same answers (in terms of lower level coefficients) as the FE model (or rather, the two answers will approach each other as sample sizes goes to infinity). But the standard errors of the RE model will be smaller.
What all that means is that if the coefficients of a FE and RE model are basically the same, you should prefer the RE ones, because they have smaller standard errors, but if they are different you should prefer the FE ones because the fact that they are different suggests that there is omitted variable bias at the higher level that the RE model has not accounted for (but the FE model has). So that's why we use a Hausman test to see if the coefficients are different, and if the test says they are, we default to the FE model.
Now, I'll note that in "real life" there are many other criteria by which we might choose between these two models. Sometimes the independent variables we care about are at the higher level in which case we CAN'T use a FE model, since in a FE model you can't include any group-level predictors (because they are colinear with the dummy variables). So a Hausman test is only appropriate when you have other substantive reason to prefer one model over the other.
And I'll also note that in my experience the Hausman test is almost always significant: that is, it almost always tells you that the two models are significantly different even when that difference is so small as to be substantively meaningless. So, as is always the case in statistics: don't just blindly follow the results of the test.
Comment: Great answer. Maybe you could express more clearly that by group level variable you mean a variable which is constant per group (a group being a unit of observation).
Comment: In statistical parlance, if the test is conservative, it tends not to reject the null hypothesis. I suppose the null hypothesis is "no difference". If the test tends to reject that, it must be the opposite of conservative (liberal, I guess). Or did I get it wrong?
Comment: You're right, I shouldn't have used "conservative,"  (in my mind it's "conservative" because a significant tests suggests that there is still bias at the group level). I've edited the answer to avoid using that word.
Answer: Let's say the Hausman test favors the fixed effect model. Why might you still be interested in using the random effects model? The random effects or multilevel model allows a degree of flexibility in modeling that is much messier and in some cases impossible to implement in the fixed effect model. Examples include:

Random slopes for the association between lower level variables and the outcome, which allow you to investigate whether the within-group association varies across groups. A classic example is growth curve modeling whereby the linear (or quadratic) rate of change in the outcome, codified by a continuous time variable) is allowed to vary across individuals or groups. In the fixed effect model, you can get at this in a crude way by interacting the lower-level variable with the cluster dummy variables. If you have a lot of groups, you have a lot of interactions.
Related to the above, random effect models allow for interactions between within- and between-level predictors, which are sometimes called cross-level interactions. To investigate these in a random effects models requires three parameters - a random slope for the lower-level predictor, the covariance between the random slope and random intercept, and the fixed effect term for the interaction. This is not possible to investigate in the fixed effects modeling framework because all cluster-level variables are thrown out.
Investigation of different within- and between- associations for lower-level variables. Here the interest is investigating whether a within-cluster association is different than the between-cluster association. This is sometimes termed contextual effects modeling and also allows you to identify cases of Simpson's paradox. An example is the association between exercise and having a heart attack. While exercising, one is at higher risk for a heart attack, but on average, individuals who exercise a lot tend to have lower risk for a heart attack. Relatedly, adding in the cluster means of lower-level variables takes care of the endogeneity problem at level 1 often used as a reason to prefer fixed effects models.
Prediction - random effects models employ empirical Bayes prediction of the random intercepts and slopes. This is great because the procedure corrects for the reliability of the group's prediction. Smaller groups get pulled toward the sample average prediction.
Comment: I think the point being made (which I very much agree with) is that there are lots of reasons you might want to use a random effects model even when the hausman test is significant. Maybe that could be made more explicit though.
Comment: How does this address the OP? You are not even mentioning the Hausman test.
Comment: @GrahamWright Good point. I edited the answer to address why one might still prefer the random effects model even when the Hausman, a rather blunt test as you point out, suggest fixed effects are warranted.


How to get array of latitude and longitude array from google maps direction api

Question: I am creating Tracking software. Android device is sending its location and now I have to check if that location is within that direction set by the admin.
Basically, admin set a route for an employee (employee is using an android phone) using google maps (could be saved as series of latitude and longitude in database ), if location sent by an employee (latitude , longitude) is not in his route then admin will get a notification on website. I want help with camparison. Simply i want to know if employee is deviated from its route or not . Is it possible to do it? Please do answer I will be very grateful.
<code><script>
  function initMap() {
    var directionsService = new google.maps.DirectionsService;
    var directionsDisplay = new google.maps.DirectionsRenderer;
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 7,
      center: {lat: 41.85, lng: -87.65}
    });
    directionsDisplay.setMap(map);

    var onChangeHandler = function() {
      calculateAndDisplayRoute(directionsService, directionsDisplay);
    };
    document.getElementById('start').addEventListener('change', onChangeHandler);
    document.getElementById('end').addEventListener('change', onChangeHandler);
  }

  function calculateAndDisplayRoute(directionsService, directionsDisplay) {
    directionsService.route({
      origin: document.getElementById('start').value,
      destination: document.getElementById('end').value,
      travelMode: 'DRIVING'
    }, function(response, status) {
      if (status === 'OK') {
          console.log(response);
        directionsDisplay.setDirections(response);
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
  }
</script>
</code>
Can I extract array of latitude and longitude from variable response? If there is better way please share.
Comment: *"check if that location is within that direction"* That is absolutely unclear. What do you want to compare with what? That said, I can't see any attempt at extracting coordinates from the response in the code you posted.
Comment: I am not comparing it yet.. Here is my scenario , Admin set a route for employee from point A to point B on website (Driving direction). I want to check if latitude and longitude that are sent by android device lies in his/her route or not.
Comment: Are you able to get array of Lats and lons? I am looking for the same
Answer: Your question is quite broad and therefore my answer will be broad too but that would be too much to write in a comment...
A route returned by the Directions service is not a collection of points or coordinates. It's a collection of legs and steps, with a start and end point (and an encrypted Polyline). See here for details.
As a side note, encoded Polylines can be decoded too, see here for more info.
Coordinates you might get from the employee devices might not be 100% accurate and thus might not fall exactly on the directions path. So you will need some tolerance calculation.
You might want to check the Roads API and more specifically the Snap to roads and/or Nearest services.
Alternatively, the Geometry library (which you need to load with your API call) also has a method called isLocationOnEdge which you can use to determine whether a point falls on or near a Polyline, based on a custom degree tolerance.
Hope this helps you get started!


Showing that two equations are equal using chain rule.

Question:
Let $u = f(x,y)$, with $x= r \cos\theta$, $y =r\sin\theta$.
  Show that $$\left(\frac{\partial u}{\partial r}\right)^2+\frac{1}{r^2}\left(\frac{\partial u}{\partial \theta}\right)^2=\left(\frac{\partial u}{\partial x}\right)^2+\left(\frac{\partial u}{\partial y}\right)^2$$

How do I solve this question when the equation of $u$ is not given? I know that to get $\left(\dfrac{du}{dr}\right)^{2}$, I would first need to get $\left(\dfrac{du}{dx}\right)$ and $\left(\dfrac{du}{dy}\right)$ because
$$\frac{\partial u}{\partial r}=\frac{\partial u}{\partial x}\cdot\frac{\partial x}{\partial r}+\frac{\partial u}{\partial y}\cdot\frac{\partial y}{\partial r}$$
Also what do the squares on the partial derivatives imply? Do they to just do a simple square of the values or do they mean more? Thanks in advance!
Comment: Hint: Leave the derivatives you don't know explicitly as variables
Comment: @DanZimm What do you mean? $(du/dx)$ is equal to $x$?
Answer: $x= r \cos\theta$ , $y= r \sin\theta$
Using

$$\frac{\partial u}{\partial \theta}=\frac{\partial u}{\partial x}\cdot\frac{\partial x}{\partial \theta}+\frac{\partial u}{\partial y}\cdot\frac{\partial y}{\partial \theta}\quad\text{and} \quad\frac{\partial u}{\partial r}=\frac{\partial u}{\partial x}\cdot\frac{\partial x}{\partial r}+\frac{\partial u}{\partial y}\cdot\frac{\partial y}{\partial r}$$

We have
$$\frac{\partial u}{\partial r}=\frac{\partial u}{\partial x}\cdot\cos\theta+\frac{\partial u}{\partial y}\cdot\sin\theta$$
$$\frac{\partial u}{\partial \theta}=\frac{\partial u}{\partial x}\cdot(-r\sin\theta)+\frac{\partial u}{\partial y}\cdot(r\cos\theta)$$
By squaring these two equations we get
$$\begin{align}\left(\frac{\partial u}{\partial r}\right)^2=&\left(\frac{\partial u}{\partial x}\cdot\cos\theta+\frac{\partial u}{\partial y}\cdot\sin\theta\right)^2\\
=&\left(\frac{\partial u}{\partial x}\right)^2\cdot\cos^2\theta+\left(\frac{\partial u}{\partial y}\right)^2\cdot\sin^2\theta+2\left(\frac{\partial u}{\partial x}\right)\left(\frac{\partial u}{\partial y}\right)\sin\theta\cos\theta\tag{1}\\
\end{align}$$
$$\begin{align}\frac{1}{r^2}\left(\frac{\partial u}{\partial \theta}\right)^2&=\left(\frac{\partial u}{\partial x}\cdot(-\cos\theta)+\frac{\partial u}{\partial y}\cdot\sin\theta\right)^2\\
&=\left(\frac{\partial u}{\partial x}\right)^2\cdot\sin^2\theta+\left(\frac{\partial u}{\partial y}\right)^2\cdot\cos^2\theta-2\left(\frac{\partial u}{\partial x}\right)\left(\frac{\partial u}{\partial y}\right)\sin\theta\cos\theta\tag{2}\\
\end{align}$$
Adding $(1)$ and $(2)$ we get
$$\left(\frac{\partial u}{\partial r}\right)^2+\frac{1}{r^2}\left(\frac{\partial u}{\partial \theta}\right)^2=\left(\frac{\partial u}{\partial x}\right)^2+\left(\frac{\partial u}{\partial y}\right)^2$$
Comment: I don't understand. This is what I wrote above. How do I manipulate these?
Comment: Thank you for your help! Please give me a moment to digest this. I'll let you know if I can't solve it myself. Thanks!
Comment: This is just a minor thing but isn't $(dx/dr) = cos\theta$?
Comment: so for the $(a+b)^{2}$ I got $cos^{2}\theta (dy/dx)^{2} + sin\theta cos\theta (du/dx)(du/dy) + sin^{2}\theta(du/dy)^{2}$ Where do I go from here? Did I do it right?
Comment: Where does the 2 come from? I don't have similar equations to add together. Multiplying $(du/dx)⋅cosθ$ and $(du/dy)⋅sinθ$ only gives $sinθcosθ(du/dx)(du/dy)$ right?
Comment: @i=Integrator But isn't that only true if both a and b have the same variables, which in this case it isn't? Sorry for bothering you but could you please give the solution to the problem? I think I might understand the question better if I see the whole process. Thanks!
Comment: Is the 2 always used in general? How different is this from foiling a general equation. ie. $(x^{2} + y^{2})^{2} = x^{2}y^{2} + x^{2}y^{2} + y^{2}$ and $(x^{2} + y^{2})^{2} = x^{2}y^{2} + 2 x^{2}y^{2} + y^{2}$. The first equation is the right one, right? If it is, where does the 2 come in?


What does 'angular' mean?

Question: I  quote uses of 'angular' and 'angularity' in The Rough Guide to Classical Music (2010 5 ed).
Some uses of 'angular'
p. 286 Bottom, Right Column

Korngold's Symphony (1952) is the most uncompromisingly modern of all his works, more
  angular than his earlier compositions, yet no less
  enjoyable.

p. 379 Bottom, Right Column

Symphony No. 4 –
The Inextinguishable
  The idea of the life force is at the heart of the third
  symphony and the same is true for Symphony
  No. 4 – The Inextinguishable (1914–16). Its title
  was explained by the composer as an attempt "…
  to indicate in one word what only music has the
  power to express in full: the elemental Will of
  Life. Music is Life and, like it, inextinguishable."
  Written when Nielsen's marriage was floundering and shortly after his resignation from the
  Copenhagen Opera, this symphony abounds in
  conflict and contradiction. Its opening is frenetic,
  with percussion, strings and wind seeming to vie
  with each other in clamorous discourse before
  giving way to an ardent, affirmative melody in
  the clarinets. The brief second movement suggests the carefree sounds of a village wind band,
  but the slow movement – with its angular string
  lines – is unremittingly bleak. The finale culminates in a musical battle between two sets of
  spatially separated timpani, a battle that is only

p. 380

resolved by the recall of the lyrical melody from
  the first movement.

p. 492 Middle, Left Column

St Luke's Passion
Scored for huge forces – three solo voices, narrator, three mixed choirs, boys' choir and
  orchestra – the St Luke's Passion was Penderecki's
  most ambitious concert work up to the time of
  its composition (1962–66). Following on from
  the extreme expressionism of the early 1960s,
  the Passion marks a synthesis of avant-garde
  techniques with the great traditions of Western
  choral music – in particular the works of Bach,
  Palestrina and Gregorian chant. Commissioned
  to commemorate the 700th anniversary of
  Münster Cathedral, the work employs angular
  dissonances and some unconventional but
  dramatic effects (such as crowd noises), but communicates a genuinely devotional mood and tells
  its story with undeniable authority and intensity

p. 594 Middle, Left Column.

Amériques & Ionisation
Varèse's search for new sonic possibilities was influenced by Luigi Russolo, the Italian Futurist who
  created noise machines and whose manifesto The
  Art of Noises proposed a new world of organized
  sound which simulated the disparate soundscape
  of modern urban life. In Amériques, premiered
  by members of the Philadelphia Orchestra under
  Stokowski, Varèse calls for nine percussionists
  including two sets of timpani, a siren and the roar
  of a lion (later changed to Ondes Martenot). It's a
  work of raw rhythmic energy – with the occasional
  moment of lyrical repose – which evokes the brash,
  angular and violent sounds of the city. Varèse
  described it as being about "new worlds on earth,
  in the sky or in the minds of men" and it marks
  the beginning of his fascination with the expressive
  possibilities of percussion.

Uses of 'angularity'
p. 146 Middle, Right Column

Piano Music
As well as being a fine pianist, Copland the
  composer used the piano to work out his ideas:
  it's not surprising, therefore, that throughout
  his career he wrote several pieces for the instrument which though not as well-known as his
  orchestral pieces are among his most challenging and original compositions. Both the
  Piano Variations (1931) and the Piano Sonata
  (1941) are uncompromisingly modernist works
  which owe something to both Prokofiev and
  Bartók in their percussiveness and angularity
  but which are also shot through with Copland's
  characteristic "Americanisms" – sparse textures, widely spaced intervals, jazz-inspired
  rhythms. The Sonata is more epic in scope.
  Copland referred to it as grandiose, albeit "… a
  very dry and bare grandiosity, instead of the fat
  grandiosity of a big orchestral work …" There
  is also a definite sense of wartime anxiety in its
  restlessness, ominous hints of tolling bells and
  generally elegaic undertow.

p. 381 Bottom, Left Column.

Wind Concertos
After Nielsen had composed his Wind Quintet
  in 1922, he decided to write a concerto for each
  of the players who had first performed it. In the
  end, he completed only two before he died, but
  both are impressive compositions. The Flute
  Concerto is a predominantly high-spirited and
  lyrical work, and there is some highly beautiful
  writing within its single-movement structure.
  The Clarinet Concerto is in a different vein, with
  Nielsen embracing – or parodying – the unsentimental angularity of modernists like Stravinsky. It
  can be a little hard work in the hands of the wrong
  performers, but it is undoubtedly an exciting and
  unusual work.
Comment: All of this type of "writing about music is" smoke and mirrors. It means whatever they writer thought it meant. Possibly, putting together all your quotes it just means the writer doesn't like "modern music" very much.
Answer: You can describe music as being angular when the line is not smooth and flowing, probably employing intervallic leaps.  It can suggest a texture that is lean rather than full.
Answer: It would seem fairly apparent from the context of some of the other words surrounding 'angular' et al, that it refers to dissonant musical phrases, and musical lines with larger jumps than is normal, rather than the smoother lines more often encountered in the more lyrical styles of music that are often more listenable. Instead of being gently soothed by such music, the author intimates that the listener will be pushed violently around sonically.
Answer: 'Angular' is being used here as an antonym of 'smooth', 'melodic'.

What does 'angular' mean?


using parse to Like a post

Question: in my app there is a function that is analogous to liking a post. In my parse database, I have a "Like" class. In the Like class are 2 columns, one "from_user" that is a pointer column pointing to the user who liked it. The other is "to_post", pointing to the post that was liked. my code is:
    var likeObject = PFObject(className: "Like")
    likeObject["from_user"] = PFUser.currentUser()
    likeObject["to_post"] = objectIDArray[0]

    likeObject.saveInBackground()

For reference, the objectIDArray is an array that contains 1 element, the object ID of the given post that I want to like.
But when I try this, I get an error saying "expected type *Post, got String" which refers to the line of code:
       likeObject["to_post"] = objectIDArray[0]

So how do I make it so that the object ID of the post (that I do have access to) can be used to point to that specific post?
thanks
Answer: What you want to do is use a pointer to the Post class.
The parameter you pass to the to_post key should be of type PFObject*, but instead you're passing a NSString* (the object id).
Considering you already have the ObjectID of the post, what you have to do is fetch the PFObject from that id and set it to your likeObject.
Try this:
var query = PFQuery(className:"Post")
query.getObjectInBackgroundWithId(objectIDArray[0]) {
  (post: PFObject?, error: NSError?) -> Void in
  if error == nil && post != nil {
    likeObject["to_post"] = post
  } else {
    println(error)
  }
}

using parse to Like a post


If the derivative of a function is continuous at all points, can we say that the function is also differentiable at all points??

Question: If the derivative of a function is continuous at all points, can we say that the function is also differentiable at all points?
Comment: Can yo u talk about continuity of  a function that is not even known to exist?
Answer: If the derivative of $f$ is continuous at all points then, in particular, the derivative of $f$ exists at all points. And that is enough to assert that $f$ is differentiable at all points.
Comment: No. A function $f$ may be differentiable at all points and, even so, $f'$ might not be continuous everywhere. Take, for instance,$$\begin{array}{rccc}f\colon&\mathbb R&\longrightarrow&\mathbb R\\&x&\mapsto&\begin{cases}x^2\sin\left(\frac1x\right)&\text{ if }x\neq0\\0&\text{ otherwise.}\end{cases}\end{array}$$
Comment: is-vice versa also true?


Why isn't the half-disk topology separable?

Question:
The half-disk topology is the topology on the upper half plane (with the $X$-axis) where base sets are open balls in the upper half plane and open half discs with the center point (on the $X$-axis). The exact definition is in the picture attached. (it's from the book counterexamples in topology). My problem is, that later in that page, the writer claims that this space is not
separable, and I can't see why. Take the set of all points (p.q) where $p$ and $q$ are rational numbers and where $q \geq 0$. Isn't this a countable dense set if the space described??
Answer: This must be a mistake in the text.  Note that this is Example 78 in Counterexamples in Topology, and if you look at the charts in the Appendix it indicates that Example 78 is separable.  (And your reasoning appears to be impeccable to me!)
Probably what was meant is that the subspace $L$ of $X$ is not separable (it is uncountable and discrete!), and so the entire space cannot be second-countable (since every subspace of a second-countable space is second-countable, hence separable).

Addendum:  This appears to be an error in the first edition.  The above answer took information from the second edition of Counterexamples.  Upon closer inspection, the second edition's information about the Half-Disc Topology differs from the first's on the point in question:

(5.) The subspace $L$ is discrete and uncountable, so $( X , \tau^* )$ is not second countable. Neither is it Lindelöf, for the covering by basis neighbourhoods has no countable subcover.  But clearly $(X , \tau^* )$ is both separable and first countable.

Perhaps find a copy of the second edition?  (Cheap from Dover! Cheaper from Amazon!)
Comment: You are right.. I ordered one.. Thanks!!!


How to match a pattern against an array in JavaScript?

Question: we have $.inArray(searchString, array) function in jQuery, but this will look for the exact match of the string in the values present in the array. But how to check the string in the array like indexOf?
For e.g., Let us take the string "mark_zuck" and if the array looks like this, ["mark", "sheryl", "zuck"]. We can do this by using a loop comparing each value in array with the given string like,
for (i=0; i<array.length; i++) {
    searchString.indexOf(array[i]);
}

I'm looking for a better way to implement this. Please help.
Comment: @Archer What do you mean by "parse the array"?
Comment: I deleted my comments as it turns out I was wrong!  atinder has posted a nearly correct solution.
Answer: array.filter(function(a){
  return searchString.indexOf(a) !== -1;
}

Comment: It should be `return  searchString.indexOf(a) !== -1;`
Comment: Yes, you've highlighted the reason you need `!== -1` at the end.  atinder updated the answer to include it, so try what he has above now.
Comment: @Archer Oops, I didn't notice that. Sorry and thanks :)
Comment: @Archer @ atinder Hey, can you take a look of the fiddle, http://jsfiddle.net/udhayakumar/3v3288s6/. Because it is returning  ["sheryl", "zuck"] instead of  ["mark", "zuck"]. Am I doing something wrong?
Answer: You can use array.some also
var monthNames = ["mark", "sheryl", "zuck"];
var chk = 'mark_zuck';

var test = monthNames.some(function(e) {
   return chk.indexOf(e);
});
console.log(test);

Fiddle: http://jsfiddle.net/haqk2snr/


Does Firestore incur charges for generating document ID?

Question: In a Flutter application, I'm using the following code frequently to generate a document ID before writing the document to Firestore (to include the document ID inside the document):
<code>docID = FirebaseFirestore.instance.collection(path).doc().id
</code>
Will this incur a read charge every time I do it?
Answer: No, it wont incur a read charge. You will only be charged for the write, because you are not actually reading anything off Firestore, the ID is generated client-side.
Comment: Such IDs are statistically guaranteed to be unique, which is a fancy way of saying that it's so random that the chances of two calls generating the same ID are infinitely small.
Comment: you can actually read the source code of how they do that, the question is asked here https://stackoverflow.com/questions/46618719/firestore-are-ids-unique-in-the-collection-or-globally .tl;dr : it's just based on math.random(), so it's not guaranteed to be unique
Comment: Out of curiosity, how does Firestore ensure that the generated ID is unique to that collection if it's generated in the client-side?


passing a variable it to su command in bash script

Question: I need to issue a command from a e.g. root to user zimbra. The problem is that I also need to set an env variable and some other variables.
From a command line I do it like this (that's command used for creating a mailbox in Zimbra):
su - zimbra -c 'export LC_ALL=nb_NO.UTF-8 && p="user.name" && domain="@example.com" && displayname="User Name" && givenname="User" && /opt/zimbra/bin/zmprov ca $p$domain "" cn "$displayname" displayName "$displayname" givenName "$givenname" zimbraPrefFromDisplay "$displayname"'

It works fine. The problem occurs when I try to automate the process in bash script. I can't (or don't know how to) pass a variable generated inside script to su command.
#!/bin/bash
var="something";
su - zimbra -c 'export LC_ALL=nb_NO.UTF-8 && echo $var'

When I use script above it doesn't work because $var is declared for root user, not for zimbra user. Is there a way to to baypass this?
I've tried to bypass this by generating a string first:
#!/bin/bash
var="something";
string="'export LC_ALL=nb_NO.UTF-8 && echo $var'";
su - zimbra -c $string

but when I do this I get
LC_ALL=nb_NO.UTF-8: -c: line 0: unexpected EOF while looking for matching `''
LC_ALL=nb_NO.UTF-8: -c: line 1: syntax error: unexpected end of file
Any help?
Comment: Two things I have noticed. 1. Your `$var` is inside single quotes. So it won't be interpreted. 2. May be you need to enclose the variables inside the double quotes. Like : `su - zimbra -c "$string"`.
Comment: Possible duplicate of https://unix.stackexchange.com/questions/202383/how-to-pass-environment-variable-to-sudo-su
Comment: I've seen this, but that's no this. I need to change only one env, not preserve all from root user. Also that's for env and I need to pass vars
Comment: Basically my problem is that:

    su - zimbra -c 'echo $PATH'

is not the same as:

    string="'echo $PATH'" && echo $string && su - zimbra -c $string
Comment: And here's the answear (depending on what you want to achieve):
    string="echo $HOME" && sudo -H -u zimbra bash -c "$string"
    string="echo \$HOME" && sudo -H -u zimbra bash -c "$string"
Answer: Unfortunately none of the above comments ideas worked for me. I wound up puzzling out that I could do the following. Escaping the double-quotes and wrapping in actual double-quotes seems absolutely necessary, plus pipe to xargs allowed the realized variable to be passed through.
echo "\"/web/jboss-eap-7.1/bin/domain.sh -Djboss.domain.base.dir=$NODE/\ &\"" |  xargs su - jboss -c
Hope this answer helps others!
Comment: nice idea but it doesn't work when su ask a password... any ideas ?