Como pintar determinadas linhas em um totalcross.ui.Grid

Question: Ao preencher um Grid do Totalcross, eu possuo registros condicionados que devem ficar destacados em relação aos demais. Eu pensei em trocar a cor da linha, ou mostrar a fonte em negrito.
O Grid por padrão mostra as linhas "zebradas" com as cores branco e cinza intercaladas e que podem ser facilmente modificadas com os atributos firstStripeColor e secondStripeColor, além da linha quando selecionada, com highlightColor. Essas alternativas não me atendem, pois eu posso ter registros em sequencia para serem destacados. Procurei um pouco na documentação e encontrei a classe totalcross.ui.Grid.CellController, essa talvez atendesse mas não encontrei nenhum exemplo de como utiliza-la.
Será que é possível utilizar a CellController para isso, ou existe alguma outra alternativa somente com a Grid?

Implementação:

Criei uma classe e estendi a CellController, e no construtor recebo um array de inteiros primitivo que indica qual a posição deve ser destacada, e no método getBackColor() verifico se a posição da linha com valor igual a 1 e atribuindo a cor vermelha:

public class GridController extends CellController {
      int[] highlight;
      public GridController(int[] highlight) {
          this.highlight = highlight;
      }
      @Override
      public int getBackColor(int row, int col) {
          return (highlight[row] == 1) ? Color.RED : -1;
      }
      @Override
      public String[] getChoices(int arg0, int arg1) {
          return null;
      }
      @Override
      public int getForeColor(int arg0, int arg1) {
          return 0;
      }
      @Override
      public boolean isEnabled(int arg0, int arg1) {
          return true;
      }
  }

E para usar, crio um array de inteiros com o tamanho da lista, e dentro do laço na condição desejada atribuo o valor 1 que será a condição para a linha ser destacada, instancio a classe GridController criada antes e seto na grid :

private void buildGrid() {
      int highlight[] = new int[lista.size()];
      for (int i = 0; i < lista.size(); i++) {
          X x = lista[i];
          if (x.getOverdue().isAfter(x.getDueDate()))
              highlight[i] = 1;
          grid.add(new String[] { x.getId(), x.getDescricao() });
      }
      GridController gridController = new GridController(highlight);
      grid.setCellController(gridController);
      repaint();
  }
Answer: Sim, o Grid.CellController permite o controle do jeito que você desejar.
Se você baixou o TotalCross do site, então deve ter percebido uma pasta src no lugar em que você instala ele. Dentro de lá, procure por src/main/java/tc/samples/api/ui/GridSample.java.
De todo caso, vamos examinar com calma o Grid.CellController.
public static abstract class CellController {

  public abstract int getForeColor(int row, int col);
  public abstract int getBackColor(int row, int col);
  public abstract String[] getChoices(int row, int col);
  public abstract boolean isEnabled(int row, int col);

  public Font getFont(int row, int col) {return null;}
}

Para cada método, é passado um número de linha/row e coluna/col. Isso significa que é possível pulverizar do jeito adequado os seus dados. Conhecendo a linha e a coluna, você pode definir individualmente qual a cor de fundo getBackColor e qual a cor de frente/a cor que se imprime o texto getForeColor.
Os outros métodos, por enquanto, parecem supérfluos pro seu uso.
Exemplos
Vou por aqui 4 exemplos de CellController e seus respectivos screenshots para você se basear.
CellController colunas = new CellController() {
    @Override
    public int getForeColor(int row, int col) {
        return 0;
    }

    @Override
    public int getBackColor(int row, int col) {
        return (col % 2 == 0) ? 0xffffff : 0xe0e0e0;
    }

    @Override
    public boolean isEnabled(int row, int col) {
        return true;
    }

    @Override
    public String[] getChoices(int row, int col) {
        return null;
    }
});

CellController tresDois_doisTres = new CellController() {
    @Override
    public int getForeColor(int row, int col) {
        return 0;
    }

    @Override
    public int getBackColor(int row, int col) {
        int threshold;
        if ((row / 5) % 2 == 0) {
            threshold = 3;
        } else {
            threshold = 2;
        }

        return (row % 5) < threshold ? 0xffffff : 0xe0e0e0;
    }

    @Override
    public boolean isEnabled(int row, int col) {
        return true;
    }

    @Override
    public String[] getChoices(int row, int col) {
        return null;
    }
});

CellController xadrez = new CellController() {
    @Override
    public int getForeColor(int row, int col) {
        return 0;
    }

    @Override
    public int getBackColor(int row, int col) {
        return ((row + col) % 2 == 0) ? 0xffffff : 0xe0e0e0;
    }

    @Override
    public boolean isEnabled(int row, int col) {
        return true;
    }

    @Override
    public String[] getChoices(int row, int col) {
        return null;
    }
});

CellController padrao = new CellController() {
    @Override
    public int getForeColor(int row, int col) {
        return 0;
    }

    @Override
    public int getBackColor(int row, int col) {
        return (row % 2 == 0) ? 0xffffff : 0xe0e0e0;
    }

    @Override
    public boolean isEnabled(int row, int col) {
        return true;
    }

    @Override
    public String[] getChoices(int row, int col) {
        return null;
    }
});

O código que usei para tirar os screenshots segue neste snippet.
Comment: Resolvido @Jefferson Quesado, obrigado pela ajuda. Vou postar a minha implementação (editando a minha pergunta) para que sirva de ajuda para quem precisar.


R tmap sf Error: arguments imply differing number of rows when viewing map

Question: I am trying to create a map of all school districts in each state.  The code below works for all states, except in Florida I get this error:
Error in data.frame(..., check.names = FALSE) :
  arguments imply differing number of rows: 67, 121
require(dplyr)
require(sf)
library(tmap)
require(lwgeom)

  temp <- tempfile()  ### create a temporary file to download zip file to
  temp2 <- tempfile() ### create a temporary file to put unzipped files in
  download.file("https://s3.amazonaws.com/data.edbuild.org/public/Processed+Data/SD+shapes/2018/shapefile_1718.zip", temp) # downloading the data into the tempfile

  unzip(zipfile = temp, exdir = temp2) # unzipping the temp file and putting unzipped data in temp2

  filename <- list.files(temp2, full.names = TRUE) # getting the filename of the downloaded data

  shp_file <- filename %>%
    subset(grepl("*.shp$", filename)) ## selecting only the .shp file to read in

  state_shape <- sf::st_read(shp_file) %>% ## reading in the downloaded data
    dplyr::mutate(GEOID = as.character(GEOID),
                  GEOID = stringr::str_pad(GEOID, width = 7, pad = "0")) %>%
    filter(State == "Florida")

  url = "https://s3.amazonaws.com/data.edbuild.org/public/Processed+Data/Master/2017/full_data_17_geo_exc.csv"
  master <- read.csv(file = url, stringsAsFactors = FALSE) %>%
    dplyr::mutate(NCESID = as.character(NCESID),
                  NCESID = stringr::str_pad(NCESID, width = 7, pad = "0"),
                  year = "2017") %>%
    dplyr::select(-NAME, -State, -STATE_FIPS) ## removing variables that duplicate with shapes

  state_shape <- state_shape %>%
    dplyr::left_join(master, by = c("GEOID" = "NCESID")) %>%
    select(GEOID, NAME, State, StPovRate)

  shape.clean <- lwgeom::st_make_valid(state_shape) # making all geometries valid

  povertyBlues <-  c('#dff3fe', '#92DCF0', '#49B4D6', '#2586a5', '#19596d')

  map <- tm_shape(shape.clean) +
    tm_fill("StPovRate", breaks=c(0, .1, .2, .3, .4, 1), title = "Student Poverty",
            palette = povertyBlues,
            legend.format=list(fun=function(x) paste0(formatC(x*100, digits=0, format="f"), " %"))) +
    tm_shape(shape.clean) +
    tm_borders(lwd=.25, col = "#e9e9e9", alpha = 1) +
    tm_layout(inner.margins = c(.05,.25,.1,.05))

  map  ### view the map

The length of the tm_shape$shp and state_shape are both 67.  Does anyone know what could be causing the "arguments imply differing number of rows: 67, 121"?
Thanks!!
Comment: Welcome to Stack Overflow. When you ask any questions, you want to provide all data along with your code. Right now, you are missing `shape.clean`, which I believe your data containing `StPovRate`. Please provide this data. Otherwise, nobody can replicate your situation and think how to help you.
Comment: the state_shape is has invalid geometry; this can be fixed by `lwgeom::st_make_valid()`. However: the downloaded file (which is 28 mb for anyone trying on a weak connection) does not contain "StPovRate" field.
Comment: I edited my question to add StPovRatem apologies for the oversight.  Jindra, you are correct that state_shape has invalid geometry but unfortunately st_make_valid does not fix it.  I added it to the example for clarity.
Answer: I was not able to get these shapes to print using tmap, but I was able to manually remove the problems points and lines so that they don't trigger errors in tmap.  Both Florida and Nebraska had geometry collections in them, so I used the following script to remove any line or points and change the geometry collections to multipolygons.  I am sure there is a better way, and would be happy to hear them if others have a more elegant solution.  This, at least, allows me to move on!
### Create an st_is function that works for many types
st_is = function(x, type) UseMethod("st_is")

st_is.sf = function(x, type)
  st_is(st_geometry(x), type)

st_is.sfc = function(x, type)
  vapply(x, sf:::st_is.sfg, type, FUN.VALUE = logical(1))

st_is.sfg = function(x, type)
  class(x)[2L] %in% type

####### Correct Florida #########

#### import my florida file
  temp <- tempfile()  ### create a temporary file to download zip file to
  temp2 <- tempfile() ### create a temporary file to put unzipped files in
  download.file("https://s3.amazonaws.com/data.edbuild.org/public/Processed+Data/SD+shapes/2018/shapefile_1718.zip", temp) # downloading the data into the tempfile

  unzip(zipfile = temp, exdir = temp2) # unzipping the temp file and putting unzipped data in temp2

  filename <- list.files(temp2, full.names = TRUE) # getting the filename of the downloaded data

  shp_file <- filename %>%
    subset(grepl("*.shp$", filename)) ## selecting only the .shp file to read in

  florida <- sf::st_read(shp_file) %>% ## reading in the downloaded data
    filter(State == "Florida")

#### extract polygon shapes from any geometry collection
solution <- for (i in florida) {
  for(j in seq_along(i)) {
    if (class(i[[j]]) != "character" & class(i[[j]]) != "double" & class(i[[j]]) != "numeric") {
      if (st_is.sf(i[[j]], c("GEOMETRYCOLLECTION"))) {
        i[[j]] <- st_collection_extract(i[[j]], type = c("POLYGON"))
      }
      else {
        next
      }
    }
    else {
      next
    }
  }
}

florida_clean <- florida
st_geometry(florida_clean) <- NULL #### remove geometry from original florida
sfc_geo <- sf::st_sfc(i)  #### define i as an sfc
florida_clean$geometry <- sfc_geo  #### attach i to florida
florida_clean <- sf::st_set_geometry( florida_clean, sfc_geo )  ### set florida's geometry as i, with the points and lines removed

Answer: I just had a similar issue and managed to address it with the trick explained here
https://www.r-spatial.org/r/2017/03/19/invalid.html
namely applying a buffer of 0.0 to the shapes that are invalid
p[which(st_is_valid(p)== FALSE),]= st_buffer(p[which(st_is_valid(p)== FALSE),], 0.0)

where p is the layer in question. I hope this helps.
Answer: I had a similar issue relating to GEOMETRYCOLLECTIONs mixed in with other geometry types (in my case, MULTIPOLYGONs), producing the same error re: differing numbers of rows. By unpacking the GEOMETRYCOLLECTIONs to POLYGONs, and then casting to MULTIPOLYGON, I got a uniform spatial file comprising only MULTIPOLYGONs without dropping the features contained in the GEOMETRYCOLLECTIONs, and without the tmap error. Something akin to:
florida <- sf::st_read(shp_file) %>% ## reading in the downloaded data
    filter(State == "Florida") %>%
    st_collection_extract(type = "POLYGON") %>% ##unpacking into POLYGON-type geometries
    st_cast ##type-casting (in this case, st_cast automatically casts to MULTIPOLYGONs)


Install Maven Error - Can you help me?

Question: When I install maven to create project or kaptcha are like and find some way not yet fix.

Can you help me fix this it?
Comment: 1) Don't include a screenshot.  Copy/paste the text direct from the command prompt or redirect it to a file! 2) For better help sooner, post an [SSCCE](http://sscce.org/).
Answer: To use maven you need access to the internet, and repo.maven.apache.org in particular.  Maven uses this repository to download the latest version of plugins that version supports and the libraries they use.
It appears you have setup a proxy server http://proxy.hapv.com:8888 and this server is refusing your attempts to access Maven Central. It doesn't appear to be running on that port.  I suggest you check your proxy settings.
You can use maven in an off-line mode once you have working build, but until then you need to let maven install itself from the internet.
Comment: Thank you
I also better understand the problem, thank you enthusiastic help

Install Maven Error - Can you help me?


Como inserir a conexão dentro das funções sem repetir as instuções?

Question: Visto que eu tenho várias funções que vão usar esta conexão, como inserir o $pdo dentro da função sem copiar o require e $pdo dentro de cada uma das funções que vou elaborar?
require("classes/Database.php");
$pdo  = Database::connect();

function inserir (){

}
function listar (){

}
function atualizar (){

}

function excluir(){

  if ($_GET['tipo'] == 'blog' && $_GET['funcao'] == 'excluir'){

    $pdo->query("DELETE FROM tb_blog WHERE ID = " . $_GET['id'] . "");
    echo "
      <META HTTP-EQUIV=REFRESH CONTENT = '0;URL='>

      ";
    return;
  }

}
excluirDados();

Comment: Pode passar `$pdo` como argumento para função ...  `$_GET` também deveria ser variáveis globais ou externas não devem ser injetadas diretamente assim. Outra opção é criar uma classe para compartilha `$pdo` entre os métodos.
Comment: ... **passar como argumento para a função** ... pode me demonstrar isso?
Answer: Pode passar $pdo como argumento para as funções ou criar uma classe para compartilha a conexão entre o métodos. Não injecte variáveis globais ou externas dentro de um função pois elas podem quebra o comportamento da função que é um pedaço de código reaproveitavel.
function novo ($pdo, $registro){

}
function listar ($pdo){

}
function atualizar ($pdo, $registro){

}

function excluir($pdo, $id){

    $stmt = $pdo->prepare("DELETE FROM tb_blog WHERE ID = ?");
    if(!$stmt->execute(array($id))){
       print_r($stmt->errorInfo());
    }
    echo "
      <META HTTP-EQUIV=REFRESH CONTENT = '0;URL='>

      ";
    return;
  }

}

 if (!empty($_GET['tipo']) && $_GET['tipo'] == 'blog' && !empty($_GET['funcao']) && $_GET['funcao'] == 'excluir'){
    $id = !empty($_GET['id']) && ctype_digit($_GET['id'] ? $_GET['id'] : 0;
    excluir($pdo, $id);
}

Abordagem com classe, não repeti a validação com $_GET mas ela ainda necessária, use a função header() para redirecionar o usuário não faz sentido usar javascript para isso
class blogDAO{
    private $connection;

    function __construct(PDO $pdo){
        $this->connection = $pdo;
    }

    function novo($registro){

    }
    function listar(){

    }
    function atualizar ($pdo, $registro){

    }

    function excluir($id){

        $stmt = $this->connection->prepare("DELETE FROM tb_blog WHERE ID = ?");
        if(!$stmt->execute(array($id))){
            print_r($stmt->errorInfo());
            return false;
        }else{
            return true;
        }
    }

}

$daoBlog = new blogDAO(Database::connect());

if($_GET ...){
    if($daoBlog->excluir($id)){
        header('Location: index.php');
    }else{
        echo 'erro ...';
    }
}

Comment: Não estou conseguindo fazer o listar ... **listar();** Tá dando erro no meu código quando eu chamo a função dessa forma. Pode demonstrar na própria resposta pf.
Comment: rray muitooooo obrigado pela sua resposta mas ainda estou trilhando os caminhos do POO, já entendo muita coisa que está ai mas ainda tenho dificuldade em usar TUDO ISSO. Por enquanto uma solução com as **functions** vai resolver, mas com certeza futuramente vou usar sua classe.
Comment: **function listar()** o tempo todo **Fatal error: Call to a member function query() on a non-object on line 12 >>> foreach ($pdo->query($sql) as $linha) { ?>**
Comment: @MarcosVinicius parece que a conexão `$pdo` não é válida.
Comment: @MarcosVinicius coloca ai o código do listar e a chamada dele. Não deve ser extenso.
Answer: A ideia do @rray de passar PDO como argumento realmente é excelente.
Apenas como complemento, é possível induzir o tipo do parâmetro para que seja passado sempre o PDO.
Exemplo:
function excluir(\PDO $pdo, $id) {
    $pdo->query(/*...*/);
}

Nesse caso, se passar outra coisa que não seja a instância de um PDO, um erro fatal será gerado.
Isso pode fazer com que seu código fique mais legível para outros programadores ;)
Exemplo:
$pdo = new PDO(/* Dados para conexão **/);

excluir($pdo, 5);

Ou ainda:
$ob = new MinhaClasse

$ob->excluir($pdo, 5);


while loop php timeout

Question: Olá, preciso fazer uma verificação periódica em uma lista com mais de 4000 ids para fazer uma verificação e enviar para o banco de dados, recebo os dados via API e faço um while para fazer as verificações.
qual seria a melhor maneira de tratar esse tipo de laço para nao retornar um timeout, pois dentro desse while preciso chamar a api novamente para cada id e verificar os dados, nos teste que fiz, todas as vezes nao consegui concluir por retornou timeout.
Obrigado
Answer: Você pode executar o PHP pelo terminal. Caso você queira executar pelo navegador e aguardar o resultado para exibir na tela, você pode executar o script pelo terminal e fica verificando se ele já terminou de executar para dar um retorno.
Answer: Olá, verifica o tempo de resposta da API que você está consumindo. Depois vai no php e configura o timeout maior(conforme a necessidade)!
Configurar o timeout:
set_time_limit(120); direto no código, no início do arquivo

Configurar o timeout no php.ini:
max_execution_time = 120

E também tem a possibilidade de remover timeout (Possa ser que não funcione por questão de segurança):
set_time_limit(0);

Você está usando CURL para consumir à API?
Se tiver usando o CURL:
$segundos = 10;//conforme a necessidade
...
curl_setopt($curl, CURLOPT_TIMEOUT, $segundos);
...

Comment: Obrigado pela resposta, isso verifiquei mesmo assim continuo com o erro, um colega de outro grupo me sugeriu usar por paginação o consumo desta API, estou procurando algo sobre mas ate o momento encontrei algo relevante, nunca usei api com paginação.
Comment: Certo, verificar na documentação da api se ela tem suporte a paginação. Ela é uma api privada, com autenticação?
Comment: Sim é privada! Consegui, fiz isto mesmo, usei com a paginação e processo em background, rodou sem problemas, obrigado!

while loop php timeout


Configurar SessionFactory Hibernate 5.2

Question: Alguém sabe de algum tutorial ou consegue me dar um exemplo de configuração para classe HibernateUtil.java para versão 5.2 do hibernate?
Já vi algumas configurações, inclusive na documentação. Porém ainda estou com dúvidas por ser novo em java e hibernate.
Answer: Sua pergunta não contém muitos detalhes, mas acho que sei o que te aflige:
Esta classe utilitária deve ser a Fábrica de persistência com o banco de dados, onde ela receberá uma unidade de persistência do persistence.xml:
Ex01:
a questão do nome da classe é opcional, como uso a especificação JPA, o nome da minha classe é JPAUtil a sua se chama HibernateUtil.
package br.com.financas.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

    public class JPAUtil {

        private static EntityManagerFactory entityManagerFactory = Persistence
                .createEntityManagerFactory("financas");

        public EntityManager getEntityManager() {
            return entityManagerFactory.createEntityManager();
        }

    }

Note que "financas" é o nome da persistence-unit do arquivo persistence.xml;
a seguir temos uma classe de execução, onde instancio objetos e faço transações com o banco:
Ex02:
note que busco a instância do EntityManager através da classe JPAUtil, nesse trecho do código: (EntityManager manager = new JPAUtil().getEntityManager(););
package br.com.financas.util;

import java.math.BigDecimal;
import java.util.Calendar;

import javax.persistence.EntityManager;

import br.com.financas.modelo.Conta;
import br.com.financas.modelo.Movimentacao;
import br.com.financas.modelo.TipoMovimentacao;

public class PopulaBanco {

    public static void main(String[] args) {

        EntityManager manager = new JPAUtil().getEntityManager();

        manager.getTransaction().begin();

        Conta conta1 = new Conta();
        Conta conta2 = new Conta();
        Conta conta3 = new Conta();
        Conta conta4 = new Conta();
        Conta conta5 = new Conta();

        conta1.setBanco("001 - BANCO DO BRASIL");
        conta1.setNumero("16987-8");
        conta1.setAgencia("6543-0");
        conta1.setTitular("Maria dos Santos");

        conta2.setBanco("237 - BANCO BRADESCO");
        conta2.setNumero("86759-1");
        conta2.setAgencia("1745");
        conta2.setTitular("Paulo Roberto Souza");

        conta3.setBanco("341 - BANCO ITAU UNIBANCO");
        conta3.setNumero("46346-3");
        conta3.setAgencia("4606");
        conta3.setTitular("Antonio Duraes");

        conta4.setBanco("033 - BANCO SANTANDER");
        conta4.setNumero("12345-6");
        conta4.setAgencia("9876-0");
        conta4.setTitular("Leandra Marques");

        conta5.setBanco("104 - CAIXA ECONOMICA FEDERAL");
        conta5.setNumero("987654-3");
        conta5.setAgencia("1234");
        conta5.setTitular("Alexandre Duarte");

        // persistindo as contas
        manager.persist(conta1);
        manager.persist(conta2);
        manager.persist(conta3);
        manager.persist(conta4);
        manager.persist(conta5);

        // Movimentacoes da conta1
        Movimentacao movimentacao1 = new Movimentacao();
        Movimentacao movimentacao2 = new Movimentacao();
        Movimentacao movimentacao3 = new Movimentacao();
        Movimentacao movimentacao4 = new Movimentacao();

        movimentacao1.setData(Calendar.getInstance());
        movimentacao1.setDescricao("Conta de luz - ABRIL/2012");
        movimentacao1.setValor(new BigDecimal("135"));
        movimentacao1.setTipoMovimentacao(TipoMovimentacao.SAIDA);
        movimentacao1.setConta(conta1);

        manager.persist(movimentacao1);

        movimentacao2.setData(Calendar.getInstance());
        movimentacao2.setDescricao("Almoco no Restaurante - AGOSTO/2012");
        movimentacao2.setValor(new BigDecimal("175.80"));
        movimentacao2.setTipoMovimentacao(TipoMovimentacao.SAIDA);
        movimentacao2.setConta(conta1);

        manager.persist(movimentacao2);

        movimentacao3.setData(Calendar.getInstance());
        movimentacao3.setDescricao("Aluguel - MAIO/2012");
        movimentacao3.setValor(new BigDecimal("680.00"));
        movimentacao3.setTipoMovimentacao(TipoMovimentacao.ENTRADA);
        movimentacao3.setConta(conta1);

        manager.persist(movimentacao3);

        movimentacao4.setData(Calendar.getInstance());
        movimentacao4.setDescricao("Salario - FEVEREIRO/2012");
        movimentacao4.setValor(new BigDecimal("3830.68"));
        movimentacao4.setTipoMovimentacao(TipoMovimentacao.ENTRADA);
        movimentacao4.setConta(conta1);

        manager.persist(movimentacao4);

        // Movimentacoes da conta2
        Movimentacao movimentacao5 = new Movimentacao();
        Movimentacao movimentacao6 = new Movimentacao();

        movimentacao5.setData(Calendar.getInstance());
        movimentacao5.setDescricao("Conta de telefone - SETEMBRO/2011");
        movimentacao5.setValor(new BigDecimal("168.27"));
        movimentacao5.setTipoMovimentacao(TipoMovimentacao.SAIDA);
        movimentacao5.setConta(conta2);

        manager.persist(movimentacao5);

        movimentacao6.setData(Calendar.getInstance());
        movimentacao6.setDescricao("Aniversario - MAIO/2011");
        movimentacao6.setValor(new BigDecimal("200"));
        movimentacao6.setTipoMovimentacao(TipoMovimentacao.ENTRADA);
        movimentacao6.setConta(conta2);

        manager.persist(movimentacao6);

        // Movimentacoes da conta3
        Movimentacao movimentacao7 = new Movimentacao();
        Movimentacao movimentacao8 = new Movimentacao();
        Movimentacao movimentacao9 = new Movimentacao();

        movimentacao7.setData(Calendar.getInstance());
        movimentacao7.setDescricao("Lanche - JULHO/2011");
        movimentacao7.setValor(new BigDecimal("28.50"));
        movimentacao7.setTipoMovimentacao(TipoMovimentacao.SAIDA);
        movimentacao7.setConta(conta3);

        manager.persist(movimentacao7);

        movimentacao8.setData(Calendar.getInstance());
        movimentacao8.setDescricao("Presente - DEZEMBRO/2011");
        movimentacao8.setValor(new BigDecimal("49.99"));
        movimentacao8.setTipoMovimentacao(TipoMovimentacao.SAIDA);
        movimentacao8.setConta(conta3);

        manager.persist(movimentacao8);

        movimentacao9.setData(Calendar.getInstance());
        movimentacao9.setDescricao("Bonus - JANEIRO/2012");
        movimentacao9.setValor(new BigDecimal("2000"));
        movimentacao9.setTipoMovimentacao(TipoMovimentacao.ENTRADA);
        movimentacao9.setConta(conta3);

        manager.persist(movimentacao9);

        // Movimentacoes da conta4
        Movimentacao movimentacao10 = new Movimentacao();

        movimentacao10.setData(Calendar.getInstance());
        movimentacao10.setDescricao("Carnaval - MARCO/2012");
        movimentacao10.setValor(new BigDecimal("765.20"));
        movimentacao10.setTipoMovimentacao(TipoMovimentacao.SAIDA);
        movimentacao10.setConta(conta4);

        manager.persist(movimentacao10);

        // Movimentacoes da conta5
        Movimentacao movimentacao11 = new Movimentacao();
        Movimentacao movimentacao12 = new Movimentacao();

        movimentacao11.setData(Calendar.getInstance());
        movimentacao11.setDescricao("Salario - ABRIL/2012");
        movimentacao11.setValor(new BigDecimal("2651.90"));
        movimentacao11.setTipoMovimentacao(TipoMovimentacao.ENTRADA);
        movimentacao11.setConta(conta5);

        manager.persist(movimentacao11);

        movimentacao12.setData(Calendar.getInstance());
        movimentacao12.setDescricao("Bonus - JANEIRO/2012");
        movimentacao12.setValor(new BigDecimal("1000"));
        movimentacao12.setTipoMovimentacao(TipoMovimentacao.ENTRADA);
        movimentacao12.setConta(conta5);

        manager.persist(movimentacao12);

        manager.getTransaction().commit();

        manager.close();
    }

}

o arquivo persistence.xml:
Ex03:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
        http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">

    <persistence-unit name="financas">

        <provider>org.hibernate.ejb.HibernatePersistence</provider>

        <class>br.com.financas.modelo.Conta</class>
        <class>br.com.financas.modelo.Movimentacao</class>

        <properties>

            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/financas" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="javax321" />

            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
        </properties>
    </persistence-unit>
</persistence>

Comment: Ok, acredito que entendi em parte.
No caso dos teus exemplos, vi que usa o JPA, como estou utilizando Maven, iria mudar muita coisa?
Algumas outras dúvidas que tinha, você conseguiu me responder. Entretanto a minha principal questão aqui seria como configurar a fabrica de persistencia do Hibernate 5.2, pois vi que nesta versão ficou diferente o código da classe.
Comment: Na configuração do Maven não muda nada, pois lá só diz quais dependências vc está usando, por exemplo, eu uso a especificação do JPA, mas a implementação do Hibernate 5.3.9 (biblioteca) na pasta lib do projeto, no caso do Maven vc só escreve no pom.xml a versão da biblioteca que vc gostaria de usar, por exemplo Hibernate 5.2 q ele vai buscar no repositório de dependências.
Comment: A questão da fábrica de persistência... vc está usando as classes do próprio hibernate, incluindo o hibernate.cfg.xml? Neste caso, realmente precisa de uma configuração específica pra esta classe, e posso publicá-la, porém usar essa configuração é desaconselhada, para evitar o alto acoplamento. seu código ficaria muito dependente da implementação do hibernate, caso algum dia vc queira mudar de provedor, para o EclipseLink por exemplo, seria uma dor de cabeça imensa.
Comment: ah, poste suas classes e arquivos de configuração.

Configurar SessionFactory Hibernate 5.2


Hermetian conjugates exercise

Question:
Find the hermetian conjugates of the following matrices. Which of these is hermetian?
$A = \begin{bmatrix} 1 + i & 4-7i \\ 3 + 2i & 7 \\ 4-18i & 6-3i \end{bmatrix}$
$B = \begin{bmatrix} 1-5i & 1+2i \\ 1-2i & 1+5i \end{bmatrix}$
$C = \begin{bmatrix} 1-7i & 4+3i & 2-8i \\ 4+6i & 1-6i & 8 + 4i \end{bmatrix}$

Here are my answers. Can someone please verify them?
$A^* = \begin{bmatrix} 1-i & 3-2i & 4+18i \\ 4+7i & 7 & 6+3i\end{bmatrix}$
$B^* = \begin{bmatrix} 1+5i & 1+2i \\ 1-2i & 1-5i \end{bmatrix}$
$C^* = \begin{bmatrix} 1+7i & 4-6i \\ 4-3i & 1+6i \\ 2+8i & 8-4i \end{bmatrix}$
None of these matrices is hermetian.
Comment: Right off the bat, you know that A,C are not Hermitian cause they aren't even square (A hermitian matrix is one whose hermitian conjugate is itself). To find the hermitian conjugate, you just transpose the matrix and then conjugate all of the entries.
Answer: I agree with your answers and that none of the matrices is hermetian.
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.
Comment: @MTurgeon Did you read the question??  This is [tag:solution-verification].

Hermetian conjugates exercise


Head First C# - Chapter 1 propertytoanimate not working

Question: I am currently running throught this course Head First C# and I got stuck at the end of a first lesson where last error remains and I have no idea how to fix it please could some of you help?
thank you, really appreciate it

This is the problematic code... property to animate is at the end of it
     Storyboard.SetTargetProperty(animation, propertyToAnimate);
    using System;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;

    using System.Windows.Media.Animation;

    namespace Save_The_Human
    {
    ///
    /// Interaction logic for Window1.xaml
    ///
    public partial class MainWindow : Window
    {
        Random random = new Random();
        private double To;

        private void startButton_Click(object sender, RoutedEventArgs e)
        {
            AddEnemy();
        }
        private void AddEnemy()
        {
            ContentControl enemy = new ContentControl();
            enemy.Template = Resources["EnemyTemplate"] as ControlTemplate;
            AnimateEnemy(enemy, 0, playArea.ActualWidth - 100, "(Canvas.Left)");
            AnimateEnemy(enemy, random.Next((int)playArea.ActualHeight - 100),
                random.Next((int)playArea.ActualHeight - 100), "(Canvas.Top)");
            playArea.Children.Add(enemy);
        }

        private void AnimateEnemy(ContentControl enemy, double from, double to, string propertyToAnimate)
        {
            Storyboard storyboard = new Storyboard() { AutoReverse = true, RepeatBehavior = RepeatBehavior.Forever };
            DoubleAnimation animation = new DoubleAnimation();
            {
                var From = from;
                To = to;
                var Duration = new Duration(TimeSpan.FromSeconds(random.Next(4, 6)));
            };
            Storyboard.SetTarget(animation, enemy);
            Storyboard.SetTargetProperty(animation, propertyToAnimate);
            storyboard.Children.Add(animation);
            storyboard.Begin();
        }
    }

}

Comment: I believe the problem cannot be explained by just looking into the code you have shared. There might be an issue in the `SetTarget` or `SetTargetProperty` methods.
Comment: you get the error at compiletime or ? the code is allmost the same as the example here, https://msdn.microsoft.com/library/windows/apps/br210503 - the only difference I can see is that in the example the line with SetTarget goes after the line with SetTargetProperty
Answer: Looks like a breaking change in some version of .NET or something like that.
You can fix it by replacing the declaration of AnimateEnemy method and calls to it:
...
AnimateEnemy(enemy, 0, playArea.ActualWidth - 25, new PropertyPath("(Canvas.Left)"));
AnimateEnemy(enemy, random.Next((int)playArea.ActualHeight - 25), random.Next((int)playArea.ActualHeight - 25), new PropertyPath("(Canvas.Top)"));
...
private void AnimateEnemy(ContentControl enemy, double from, double to, PropertyPath propertyToAnimate)
...


Krasnoselskii contraction mapping

Question: Definition: Give metric space $(X,d)$. Mapping $f: X \to X$ is called Krasnoselskii contraction mapping if
$$\forall a,b>0, a<b, \exists k \in (0,1): a \le d(x,y) \le b \Rightarrow d(f(x),f(y)) \le kd(x,y).$$
Problem: Prove mappings below is Krasnoselskii contraction mapping

Mapping $f: X \to X$ satisfy $$d(f(x),f(y)) \le \varphi(d(x,y)),$$
where $\varphi: [0,+\infty) \to [0,+\infty)$ is continuous,
$\varphi(0)=0$ and $0 < \varphi(t) < t$ for all $t>0$.
$X$ is compact space and $f:X \to X$ satisfy $$d(f(x),f(y)) <
d(x,y), \forall x \neq y$$

My attempt:

By setting $\psi(t)=\dfrac{\varphi(t)}{t}, t\in[a,b]$, I have proved
that $f$ is Krasnoselskii contraction mapping.

I don't know how to use $X$ is compact to solve the problem.
Comment: In 2) the inequality can only hold for $x \neq y$.
Comment: @KaviRamaMurthy Sorry, this my bad. I missed $x \neq y$ in 2). Thank you.
Answer: Suppose this is false. There exist $x_k,y_k$ such that $a \leq d(x_k,y_k) \leq b$  and $d(f(x_k),f(y_k)) >(1-\frac  1 k) d(x_k,y_k)$. By compactness $(x_k)$ and $(y_k)$ converge to some $x$ and $y$ along a subsequence. Let the limits be $x$ and $y$ . Then  $ d(f(x),f(y) \geq d(x,y)$.  This contradicts the hypothesis since $d(x,y) \geq a >0$ so $x \neq y$.
Comment: @TungNguyen Right, there was a mistake. I have revised my answer.
Comment: Your contradiction have something wrong because $n \in (0,1)$.

Krasnoselskii contraction mapping


Why are chord inversions rarely/never mentioned in beginning jazz (solo) piano?

Question: I've learned about chord inversions in my basic piano instruction, usually emphasizing voice leading as being important for a more accomplished sound.
But this seems to be absent in beginning jazz piano, particularly for the lowest note. It is implied, for the mid-range tones, when discussing open voicing. But not the lowest note. Why? Isn't voice leading a good thing in jazz solo piano?
To clarify my question, I referring to reading from lead sheets, and how there seems to be an emphasis on using 1 -7 or 1-3-7 or say 1-5-7 chord tones in the left-hand.
Comment: Can you clarify what you mean by "particularly for the *lowest note*"? Inversions are all about the lowest note, so I'm having a little trouble following your question.
Comment: Note that if you're seeing "slash chords" like G/B, then that notation indicates inversion. That example is a first inversion. The note name after the slash indicates the lowest sounding note that should be played from the chord. Also slash notation can indicate that a non-chord tone should be played as the lowest note, like G/F. If you're not seeing slash notation anywhere in your music, or you're playing from scores that are written out with no inversions, then maybe you're playing from a strange book or a book for (as you note) beginners. They might want to introduce inversions later.
Answer: The practice is largely based on history and theory. More specifically, jazz piano education tends to place a very large value on:

understanding many different historical traditions in jazz, and
progressing in jazz theory.

History
At a very general level, the most important jazz piano voicing techniques would include stride piano (which frequently alternates between the 1 and the 5 in the base), Bud Powell shell voicings (which use 1-7 or 1-3), rootless Bill Evans voicings (which don't have the 1 at all), and Tyner/Corea/Hancock quartal voicings. This isn't a comprehensive list, but it's a decent sketch of the evolution of a jazz pianist's left hand. To be a rounded jazz pianist, one must master all of these things, along with using the left hand to walk bass lines during solo performance. Compared to that expansive list, inversions of shell voicings aren't as historically significant.
Theory
Moreover, many teachers/programs focus on theory. From a theoretical perspective, students start with the basics, and perhaps the most important things to master first are guide tones. Along with the root, guide tones define the chord quality. Extensions and alterations all rely on the chord quality established by the guide tones. Shell voicings are the perfect way to learn guide tones, because they contain the root & guide tones. But from the perspective of theory, the next logical question is to ask what additional notes beyond the 1, 3, and 7 can be added to the chord. And thus, after one learns shell voicings, they next learn rootless voicings, which incorporate other scale tones like the 5th, 6th, 9th, etc. Learning how to invert the shell voicings might be useful, but it doesn't progress the student's theoretical knowledge in the same way that rootless voicings do.
Answer: A lot of jazz piano instruction covers LH chord VOICINGS, but assumes a bass player will be taking care of the lowest note and hence the inversion.
Comment: I'm finding there is a --lack-- of inversions.  For example, I don't see 3-7-1, or 3-5-1 left-hand chord voicing being taught.


FTP - 500 I won't open a connection to xx.xx.xx.xx

Question: I'm running a server on AWS and I'm connecting out to a partner's FTP site (not much idea what they are running).  My server has an elastic IP.  In the results below xx.xx.xx.xx is the internal IP (same as I get from IPConfig).  yy.yy.yy.yy is the external IP (same as I am RDPed into).
Connected to ftp.site.com.
220---------- Welcome to Pure-FTPd [privsep] ----------
220-You are user number 1 of 50 allowed.
220-Local time is now 22:47. Server port: 21.
220-IPv6 connections are also welcome on this server.
220 You will be disconnected after 15 minutes of inactivity.
User (ftp.site.com:(none)): someuser
331 User someuser OK. Password required
Password:
230 OK. Current restricted directory is /
ftp> literal pasv
227 Entering Passive Mode (69,28,68,87,255,170)
ftp> ls
500 I won't open a connection to xx.xx.xx.xx (only to yy.yy.yy.yy)

I tried PASV mode, but it's not working.
I have nothing open on my security group except the RDP.
Windows Firewall is running on the server as well with what looks like Amazon's default configuration.
Once I get this connection working I will probably be FTPing data from an SSIS package to their server, FWIW.
I know FTP is quirky through NAT like this with the connections being opened coming back.  What do I need to do?
Comment: You forgot to mention the operating system of your machine, and the FTP client you are using.
Comment: Windows Server 2008, command-line ftp to test the connection and see the folder names, then I'll be using the SSIS FTP or something to automate the process.
Answer: The command line FTP client built into Windows doesn't support passive mode at all. Those hacks you found on the Internet about literal pasv or quote pasv don't actually do anything as far as the FTP client is concerned; they tell the server to enter passive mode, but the client remains blissfully unaware. You'll need to obtain a third party FTP client.
Answer: The trouble is that your pasv command is telling the server to connect to the internal ip.  Not your external ip. That won't work for two reasons.

The server cannot see your internal ip.
While the ftp protocol does support you setting up the data connection to talk to a different ip from the control connection. Most servers now refuse to honour it (for security reasons) some will simply ignore the ip and only use the port. Others like this one will just refuse to accept the command.


Get Field Collection values not IDs

Question: I am searching for a solution for past few days but can't find it :(
I have exposed a node with rest api views and there's a couple of field collections inside my node which i want to access over API but the api is retuning field collection IDs not the actual data. How can i get the values of field collection without sending aother request to api for values?
<code>"field_custom_data": {

"und": [

 {
   "value": "3",
   "revision_id": "3"
 },
 {
   "value": "4",
   "revision_id": "4"
 },
 {
   "value": "5",
   "revision_id": "5"
 },
 {
   "value": "6",
   "revision_id": "6"
 },
 {
   "value": "7",
   "revision_id": "7"
 },
 {
   "value": "8",
   "revision_id": "8"
 }
] },
</code>
Answer: Before returning response to api you should load field collection using field collection ID, then you can get fields value of field collection.
<code>entity_load('field_collection_item', array($item_id))
</code>
Source: How to load field collection
Comment: Thanks @Yogesh Kushwaha, but how do i intercept the API response to add add those values? thanks.

Get Field Collection values not IDs


Customizing the way the form is displayed to admin user

Question: I am developing a module which requires an administrator form.The admin will enter some settings data which will be saved in database.Then i will use these settings to display information to the website users depending on the settings chosen by admin.
So for administrator screen i need the form to be displayed like this
HEADING_ONE    HEADING_TWO     HEADING_THREE     HEADING_FOUR
TEXTFIELD_ONE  TEXTFIELD_TWO   TEXTFIELD_THREE     TEXTFIELD_FOUR
I need to have a table like structure. How can this be done?
Answer: You can make use of system_settings_form to make admin form and theme_table to make a table output.


In hook_node_insert drupal_goto with alias name not working

Question: In hook_node_insert() i have used drupal_goto(), to go to the newly created node with alias name of it, but id doesn't work.
I have already created url alias with patterns for that content type.
$alias = drupal_get_path_alias('node/'.$node->nid);
drupal_goto($alias);

If i give drupal_goto() with nid it works.
drupal_goto('node/'.$node->nid);

What is the issue with respect to alias name not working or how to get alias of newly created node and get it redirected to view page of it with alias name as url.
Any ideas or suggestions? Thanks in advance.
[Updated code]
This is the code which i am trying
function hook_node_insert($node)
{
    if($node->type == 'product')
    {

        $_SESSION['product_node_nid'] = $node->nid;
        $banner = $_SESSION['banner'];
        $theme = $_SESSION['theme'];
        $params = array();
        $params['node'] = $node;
        $site_email = variable_get('site_mail', '');
        if(($banner || $theme) || ($banner && $theme)) {
            drupal_goto('payment-approval');
        }
        else {
            //$alias = drupal_get_path_alias('node/'.$node->nid);
            module_load_include('inc', 'pathauto'); // include the inc file for Pathauto module
            pathauto_create_alias('node', 'insert', 'node/'.$node->nid, array('node' => $node), $node->type, $language->language); // Language is optional
            $alias = drupal_get_path_alias('node/'.$node->nid);
            //$alias = drupal_get_path_alias('node/'.$node->nid); print_r($alias); exit();
            drupal_goto($alias);
        }
    }
}

Comment: What are the circumstances that would require this, exactly? The default action after submitting the node add form is already to redirect to the new node. Use drupal_goto() with care in hooks; it can interfere with cron runs if it ever gets executed by cron.
Comment: As LesLim said, there is default functionality of `node` module to redirect to `node/[nid]` when new node be save. What you want to achieve with your code, its not clear. Please update the complete scenario, so you will find the correct solution.
Comment: [Updated code] is the one which i am trying.
Answer: I checked the drupal_goto and found out that you must provide the path for parameter. You can't use alias for drupal_goto. So i think you can solve your problem like that:

While you create node. You will also create the alias for that node. The reference for create the alias for node here. In your code just normally redirect like that
drupal_goto('node/'.$node->nid);

After that you will install Global redirect module. This module will have responsibility to redirect your node/nid to your node's alias

[Updated]
Can you try to generate the alias by using the Pathauto. So can you put these code in hook_insert()
function yourmodule_node_insert($node){
  module_load_include('inc', 'pathauto');
  pathauto_cleanstring($node->title);
  $node->path = array('pathauto' => TRUE );
  drupal_goto('node/'.$node->nid);
}

Comment: Tried installing Global redirect module, gave like this drupal_goto('node/'.$node->nid);still redirects to node/nid only
Comment: in hook_node_insert will node alias will get created or is it after tat only is the question.Because its only redirecting with node/nid.
Comment: module_load_include('inc', 'pathauto');
pathauto_create_alias('node', 'insert', 'node/'.$node->nid, array('node' => $node), $node->type, $language->language);
$alias = drupal_get_path_alias('node/'.$node->nid);
drupal_goto($alias);

Still it goes to node/nid only.
Comment: Can you check the alias is created or not $alias = drupal_get_path_alias('node/'.$node->nid); print_r($alias); exit();
Comment: Its printing node/207 this only. Not alias name
Comment: Hi! Please check my update and give a try
Comment: still its going to node/nid only.
Comment: In hook_node_insert in if condition i am sending the node after hook_node_insert to payment form and completing the form, then i redirect to drupal_goto('node/'.$nid), but it goes with alias name properly as expected and in  else condition i am trying to redirect to drupal_goto() with alias name , but its redirecting to node/nid. wat i am doing wrong ?
Answer: Third variable for module_load_include() function is missing in your code.
You should use code module_load_include('inc', 'pathauto', 'pathauto');
instead of module_load_include('inc', 'pathauto');
There is another method for your problem that you can use hook_form_alter instead of hook_node_insert hook in your module.
hook_node_insert will execute if you will insert node using any other method like importing node using feeds module.
Update Code:
function custom_feature_node_insert($node) {

  $options = array('language' => pathauto_entity_language('node', $node));

  //$alias = drupal_get_path_alias('node/'.$node->nid);
  module_load_include('inc', 'pathauto', 'pathauto'); // include the inc file for Pathauto module

  pathauto_create_alias('node', 'insert', 'node/'.$node->nid, array('node' => $node), $node->type, $options['language']); // Language is optional
  $alias = drupal_get_path_alias('node/'.$node->nid);

  drupal_goto($alias);

}

Comment: tried this one module_load_include('inc', 'pathauto', 'pathauto'); instead of module_load_include('inc', 'pathauto'); still it is redirecting to node/nid not alias name
Comment: @Ram, Have you checked `$alias` in your function before `drupal_goto()` function.
Comment: this is wat print_r($alias) is printing node/212
Comment: @Ram, it mean `pathauto_create_alias()` function is not working in your condition.
Comment: pathauto_create_alias() first parameter module i can give module only know ??? i gave node is tat correct rite ? then wats the issue?
Comment: @Ram, I have updated answer with working code.
Answer: drupal_get_path_alias() expects a full internal Drupal path, like this:
drupal_get_path_alias('node/23');

However, you're only giving it an NID, which is being evaluated like this:
drupal_get_path_alias(23);

Comment: See my updated question. i tried like that, it still goes like this only node/nid
Comment: Hmm, okay. I'm guessing you're using Pathauto, which also uses hook_node_insert() to generate the URL path for the node. Your hook is probably running before Pathauto does its work.
Comment: You can adjust your module's weight to ensure that it runs its hooks after Pathauto, or you can implement hook_module_implements_alter() to change the execution order for a particular hook: http://drupal.stackexchange.com/a/9720/23553


Is there a Drupal module to add a Creative Commons license to entities?

Question: I am looking for a module (beyond the Media Gallery module) that allows content creators to licence the content they create by means of the Drupal WCMS under one of the Creative Commons licenses. Is there a module for this?
Answer: Yes, in addition the the Creative Commons licensing support that is integrated in the Media Gallery module, there exists a module for that does exactly that: the Creative Commons licenses module. From the project page:

The Creative Commons module allows users to select and assign a Creative Commons license to a node and any attached content, or to the entire site. It also provides integration between CC and Drupal technology.

It was originally written for D6 and is still under development for D7 (up to alpha2 at the time of writing), but the core functionality is in place.
Somebody may ask:

"Why would you need a module for that? Why can't you just add an Entity Reference field to link to whatever license the user chooses? What tasks should this module accomplish that a simple dropdown (or dropdown with link) cannot?"

The answer is that there is a lot more to Creative Commons licensing than just linking content to the CC license.
I think that reading the road map for the D7 port will shed some light on what is desirable, and why you need a module to accomplish it. To summarize: When licensing content under Creative Commons it is highly desireable that RDFa and ccREL metadata is properly presented, and you need more than a link for that. A CC search option should also be is available.
Looking at the issue queue for the Creative Commons module, it looks like development may have stalled when it comes to porting the more advanced features of the D6 version to D7, but I think it still is worth checking out.
There is also an experimental module named Attributions. It is not only for Creative Commons. It lets module and themes authors who use third party materials (e.g. fonts, photos and icons) that requires attribution register an attribution string in the project's <code>.info</code>-file. All the registered attribution strings from various projects can then be shown together on an attribution page or block.  Disclosure: I am one of the co-maintaners of Attributions.
Comment: Thanks for answering my comment, too :) Too bad you wasn't able to edit original question, I'm afraid OP might consider our community harsh and uncaring, and that wasn't what I wanted when I commented. I genuinely wanted to get clarifications as the topic seemed to have potential.


How do (National League) managers decide when to "pinch hit" for their pitchers?

Question: You're in the top of the seventh inning with a 1-1 tied score. Your starter has thrown about 80 pitches, meaning that he's good for at least one, maybe two, more innings. Your bullpen is tired, but is still rated better than the other team's bullpen. Your seventh, eighth and ninth players are up. For now, we'll assume that whether or not we "pinch hit" for our starter depends on what the seventh and eighth players do. Here are my preferences.

If the seventh and eight batters both get on base, and one or both of them score (e.g. the second batter gets an extra base hit that scores the first batter, and possibly himself if it's a home run), I'll keep the pitcher in to protect my new (2-1 or 3-1) lead.
If the seventh and eighth batters both make an out, I'll let my pitcher close the top of the inning, so he can pitch at least the bottom of the seventh, on the theory that he'll "save" more runs than we'll score by having a pinch hitter bat for him. I might even tell him to strike out intentionally so he won't run the risk of getting injured.
If the seventh and eighth batters both get on base, say first and second, I'll "pinch hit" for my pitcher to try to score a go-ahead run.
If the seventh and eighth batters make one single (or walk) and one out, that's a close one, because I'm undecided between trying to score, or save, an extra run.

Two more considerations. 1) There's only one bench player left, meaning that if you use him now, all remaining pitchers will have bat for themselves. 2) Your starter bats only .053, but all your relievers bat .000.
The actual (Pirates') manager decided to pinch hit for the pitcher in scenario 2, after two outs.
What would cause him to do this? Put another way, what considerations would govern his choice?
Comment: this is a tough one because every manager has a different approach.  Some go with their gut while some go with the numbers.  The situation you describe there is no way I pinch hit, unless for some reason the pitcher is getting tired at 80 pitches.
Answer: There are 3 viable options.

Let the pitcher hit swinging away
Have the pitch bunt runners over
Pinch hit for the pitcher

Which of the three you choose largely depends on who you have available on the bench, how close the same is and who the pitcher is. If we assume it's late game, the score is tied, and the pitcher is only going to pitch one more inning (with a slightly better than average bullpen), then we can go from there.
Now, with the pitcher up 3rd in the order, there are three possibile situations:

None on, 2 out
One on 1 out (runner on 1/2/3)
Two on, 2 out.

I'm going to assume three things:

The pinch hitter has about a 50% chance of improving the run frequency of the inning (walk, hit, sac fly)
The pitcher will succeed on a sac bunt 90% of the time (it's not this high)
The pitcher swinging away will advance the run frequency of the inning about 20% of the time.

Let's examine the possible run frequencies and run expectancies of our starting state:

none on 2 out: 0.117 (number of runs you're likely to score)

In this case it doesn't matter who hits. The pitcher should probably do so if he will be better than a reliever. The run expectancy is already so low, that the unlikely case of a homerun from either party is the only thing that will truly improve it (obviously that's an automatic run). The most likely outcome from a pinch hitter, a single or a walk, only really raises the run expectancy to .251 runs. Still quite unlikely

1 on, 1 out: .573/.725/.983 (runs you're expected to score). Let's look at our three scenarios here.

Let the pitcher hit: pitchers generally get on base at less than .200, and their most likely result is a K, so let's look at where that leaves our run expectancies: .251/.344/.387. If the pitcher manages to advance the runner we have .344/.378/1.117(since a run scores). It the pitcher manages to get a single, that will provides us a lot more possibilities, more than I can list here (view the matrix to see for your self). However, for the sake of argument, let's assume that a pitcher getting a hit always leads to exactly 1 run. So let's see on average, the pitcher striking (or otherwise failing to advance the runner) out drops .4, advancing the runners drops .1 and getting a hit raises it by .3. If we assume that the pitcher has a 50% chance of not advancing the runner, a 20% chance of a hit, and a 30% chance of advancing the runner. Than the average change is .2 * .3 - .5 * .4 - .3 * .1 = -.17
A sac bunt is a bit easier to figure. Going from 1 out to 2 is always bad for run expectancy and should be avoided. Sac bunting is not an option.
For the pinch hitter, we can use the same formula we used for the pitcher, and tweak the odds. He is much more likely to get a hit or draw a walk, being that he's a bench player, we'll call it .35. Add in another 30% chance to advance the runner   .35 * .3 - .3 * .4 - .35 * .1 = -.05.

two on, no out: 1.904/2.052/2.417. This is a huge situation, and an automatic out does not automatically kill your rally here. However, it does lessen the chance of scoring multiple runs pretty significantly. A sac bunt is still a terrible play (the only time it's even close to even is, with 0 outs, getting a runner from second to third). This is a definite spot for a pinch hitter, as the higher contact rate and much higher OBP will lead to better results.

So suffice to say, if there is a runner on, it's almost always better to pinch hit in this circumstance. No matter who pitches the 7/8/9 the odds are good you are going to need another run to keep pace and two to win. So it's a good idea to pinch hit for your pitcher if you even have a chance to score.
Comment: (all of this math is pretty back of the envelope, if you're an actual NL manager, consult your sabermetrics staff not some idiot on the internet )
Answer: You are on the road if you get a player in scoring position its time to pinch hit.  If you are at home I would be comfortable with going into next inning with a tie.
If you have a starter with good slugging percentage on the bench getting a rest that day and a fast runner at first I might pinch hit.
Are you in the race?  You might have to bring in tomorrow's starter? (a tie is possible no matter what happens)
Who is rested in AAA?
When can they get to the park?
(You might need a new pitcher tomorrow)
Do you have any options left on your bullpen pitchers?


Limit datatables fields

Question: I am using AJAX to source my datatables data. However, I am getting the error:
unknown parameter '0' for row 0, column 0
because my ajax response object has more fields than what I defined in my table's initialization. Is there a way I can limit or specify what parts of the ajax response go into my datatable? Here's my javascript:
$.ajax({
    type: "GET",
    url: "/api/admin/employees",
    success: function(data) {
        $('#eployees').DataTable({
                responsive: true,
                data: data,
                columns: [
                    { title: "Name" },
                    { title: "Position" },
                    { title: "Office" },
                    { title: "Extn." },
                    { title: "Start date" },
                    { title: "Salary" }
                ]
        });
    },
    error: function(data, status, res) {
        console.log('error...');
        console.log(res);
    }
});

Note - my data object contains 20 fields, but I only need the 6 that are defined below.
Can someone help? Thanks in advance!
Comment: Please shoe an example of how the ajax response looks like.
Comment: What is the structure of `data`?
Answer: Your records (data) should be JSON, not array (see example https://datatables.net/reference/option/columns.data#Examples)
The examples show how to create mapping column to data field
Comment: correct, not necessarily, but if your `array` doesn't match the table columns, then it should be `json`
Comment: No, not necessarily - you can easily use an array of strings instead of an array of JSON items.

Limit datatables fields


Why isn't hook_node_access() invoked when a node is created?

Question: The following code doesn't work.
function mymodule_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {
    $type = $node->getType();

  if ($type == 'application' && $op == 'create' && arg(3) != "" ) {
    print_r(arg(3));
    return AccessResult::neutral();
  }
  else {
    // ...
    return AccessResult::forbidden();
  }
}

Could you tell me what is wrong in the code?
Answer: As documented in hook_ENTITY_TYPE_access(), hook_node_access() is only invoked when the users try to view, update, or delete a node. The documentation doesn't make it explicit, but when an entity is created, the invoked hooks are hook_ENTITY_TYPE_create_access() and hook_entity_create_access().
With both hook_ENTITY_TYPE_access() and hook_ENTITY_TYPE_create_access(), a single hook implementation returning AccessResult::forbidden() is sufficient to block users from acting on the entity. If you are noticing users aren't allowed to take an action on an entity when you expect them to be able to take that action, that is one of the probably causes.
I assume the code shown in the question is part of the code inside the mymodule.module file, or that a module with that machine name is installed on the site. Differently, Drupal would not consider that function a hook, and it would not invoke it (which could be a reason to say it doesn't work).
As side note, arg() is implemented in Drupal 4.6.x, 4.7.x, 5.x, 6.x, and 7.x, but not 8.x.y, nor 9.x.y. (Click on Same name and namespace in other branches in the documentation page to see the list of Drupal versions for which that function is implemented.)

The code shown in the question should thrown an error about a call to a not existing function.
Answer: Seems hook_node_access is not longer called for the create operation. Use hook_ENTITY_TYPE_create_access instead.
See hook_node_access() no longer fires for the 'create' operation for background info and code samples on how to change your code.

Also arg() is deprecated.


How to get the current field value in Ajax callback?

Question: I 've a problem with Drupal 8 ajax callbacking. I created a multivalue field for country - region listing as new field type using a custom module. In first selectlist I loaded all country codes and I set this field as multivalued.
I wrote the below code in FieldWidgetType Class.
     public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $element['value'] =  array(
      '#type' => 'select',
      '#title' => 'Select Country',
      '#name' => 'value',
      '#options' => array(
        0 => t('- Select Country -')) + $termNameArr,
      '#default_value' => isset($items[$delta]->value) ? $items[$delta]->value : NULL,
      '#ajax' => [
              'callback' => array($this, '_regions_ajax_callback'),
              'event' => 'change',
              'progress' => array(
                 'type' => 'throbber',
                 'message' => t('Please wait.Fetching data...'),
                ),
             ],
      '#suffix' => ''
    );
    return $element;
    }

I have to load regions of the selected country in an another select box using ajax. The selectbox should populate with the regions of selected country in change event of country select box item (here I'm calling ajax). Or else, can ajax simply return the selected country value to append in span (.email-valid-message) specified in #suffix.
My current callback to return at least the selected country name is:
    public function _regions_ajax_callback(&$form, &$form_state) {
      $response = new AjaxResponse();
      $element = $form['value'];
      $default_value = isset($element['#default_value']) ? element['#default_value'] : NULL;
      $value = $form_state->getValue($element['#name']);
      $changed = $default_value == $value;
        if ($changed) {
       $response->addCommand(new HtmlCommand('.email-valid-message', $value));
       }
    return $response;
    }

I used namespaces
    use Drupal\Core\Ajax\AjaxResponse;
    use Drupal\Core\Ajax\HtmlCommand;

What am I doing wrong? How can I change my callback function to get current field value? Did I miss to add any namespace?
Comment: I guess issue in your callback's parameters?
Answer: in your _regions_ajax_callback()
$element = $form_state->getTriggeringElement();
element['#value'] <-- value is in here

Comment: This is not the case for me, my element's `#value` is empty.
Answer: I did by using getUserInput()
i.e.
  public function myAjaxCallback(array &$form, FormStateInterface $form_state) {

    $input = $form_state->getUserInput();
    $input = $input['field-name-goes-here'];

    // Sanitize input.
    $input = Xss::filter($input);

    //...


React native - Align image vertically and horizontally

Question: In my react native application, I created a screen to show a certain list and in the flat list I configured a "renderEmpty" method to show an image in place of the list when the list is not empty. I was able to align the image horizontally, but not be able to align it vertically. What am I doing wrong? I would like your help to achieve this vertical alignment
Follow the code below:
import {
    StyleSheet,
    SafeAreaView,
    FlatList,
    TouchableOpacity,
    View,
    Text,
    Image
} from 'react-native';

export default function App() {

    const list = [];

    const renderEmpty = () => (
        <View style={styles.emptyListContainer}>
            <Image
                source={require('./assets/empty-list.png')}
                style={styles.emptyListImage}
            />
            <Text style={styles.emptyListText}>No content</Text>
        </View>
    );

    const renderItem = ({ item, index }) => {
        return (
            <View style={styles.listItem}>
                <View style={styles.itemContainer}>
                    <TouchableOpacity>
                        <Text style={styles.item}>{item.nome}</Text>
                    </TouchableOpacity>
                </View>
            </View>
        );
    }

  return (
    <SafeAreaView style={styles.container}>
      <View style={{flex: 1}}>
        <FlatList
          style={{flex:1}}
          keyExtractor={item => item.id}
          data={list}
          renderItem={({ item }) => renderItem({item})}
          ListEmptyComponent={renderEmpty}
          onEndReachedThreshold={0.2}
        />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginTop:15,
    },
    listItem:{
        elevation: 5,
        width:"95%",
        margin: 3,
        marginBottom: 7,
        flex: 1,
        alignSelf:"center",
        flexDirection:"row",
        borderRadius:5
    },
    itemContainer: {
        flex: 1,
        padding: 20,
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center"
    },
    item: {
        color: 'black',
        fontWeight: "800",
        fontSize: 24,
        fontFamily: 'helvetica'
    },
    emptyListContainer: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center'
    },
    emptyListImage: {
        width: 200,
        height: 200,
    },
    emptyListText: {
        fontSize: 18,
        fontWeight: 'bold',
        marginTop: 20,
    }
});

The code is available at https://snack.expo.dev/d7HXkFB3c
Thanks!!
Answer: Your FlatList needs the following prop
<FlatList
  style={{flex:1}}
  contentContainerStyle={{ flexGrow: 1 }} // new! can also be flex: 1 in your case
  // but flexGrow also takes care of the "list snaps back on scroll" issue
  ...

FlatLists are built on top of ScrollViews.  ScrollViews contain two Views: an outer View and and inner one that holds the content (contentContainer).  The style prop styles the outer View; contentContainerStyle styles the inner View.  Your inner view didn't know to fill the space of the outer view.
You can read more about contentContainerStyle here: https://reactnative.dev/docs/scrollview#contentcontainerstyle


Read localStorage data in AppModule

Question: I want to bootstrap different component manually in AppModule based on data stored in localStorage.
I googled a lot and got way to manually bootstrap the component.
https://medium.com/learnwithrahul/ways-of-bootstrapping-angular-applications-d379f594f604
// create DOM element for the component being bootstrapped
// and add it to the DOM
const componentElement = document.createElement('d-comp');
document.body.appendChild(componentElement);

// bootstrap the application with the component
app.bootstrap(ComponentDynamic);

But now I'm unable to localStorage methods like (setItem and getItem) as it does not idetifies localStorage.
Can anyone please help me this?
Answer: LocalStorage can be found on window.
If you don't have access to window in some reason, create some service for obtainining window like:
import { Injectable } from '@angular/core';

@Injectable()
export class WindowRef {

   getWindow(): Window {
      return window;
   }
}

Read localStorage data in AppModule


Stopping the contents of a div section moving

Question: I have a div section, which is full of  tags, on a event on the page I shrink the div section BUT if the user tabs into the div section, it moves so that the highlighted  has focus, is there any way to lock a div section that it's contents don't move ?
So for example the code (psuedo not real) I have the following

Heading</hv>
  Link 1
  Link 2
  Link 3

I shrink the div section so that only the h4 is displayed {overflow:hidden}, however the user can then tab to the  elements and this scroll so that they are displayed in the the div "window" which is not what I want, so in effect I get
Link 1
 where what I want to remain is

heading

 in effect I want to stop the contents of the div sectio scrolling so that the selected element is displayed. I know that if they press return the selected link will be follow, but I'm not worried about this, just what is displayed
I hope thats cleared, you can see my problem if you go to link text click on the training section on the left and then back tab (shift tab) , the article section above changes.
Thanks
Comment: How do you shrink the div? using javascript? do you use a framework?
Comment: Yes using javascript to shrink the div section
Comment: I don't really think I understand your problem, please eleborate. What do you mean by that the contents move? actual moving of the content or the scrollposition in the div moving?
Comment: Hi edited the question and given a link to an example
Answer:
is there any way to lock a div section that it's contents don't move?

Not really*, but you don't really want that anyway. Even if you locked it in place, the invisible links would still accept focus, resulting in a confusing tab behaviour.
(*: short of something horrendous like changing the scrollTop of the overflowing element from JavaScript onfocus. Ugh.)
What you should probably do is put a div around the links, and set its display style to 'none' when the links are elided. That way they won't participate in the tabbing order.
Answer: From what I can make of your question, you want your div to stay fixed relative to the browser window. If this is the case, it can simply be done by declaring position:absolute for the div.
If you want something else, please clarify your question.


Nested data correction with mixed models

Question: We have collected data from n patients, with each patient having one eye treated and the other untreated.
We would like to see if the treated eye progresses differently to the untreated eye using biomarkers measured from each eye.
Currently, I am using the model:
lmer(biomarker_change ~ days + treated_yn + (1 | patient_id), data = study)

using the lme4 package. Is the random effect (1 | patient_id) enough here? I feel like since the eyes are from the same patient, something is a bit strange/ missing here.
Also, I'm using biomarker change as opposed to raw marker values to allow for differing starting points.
Comment: looks quite OK to me at first glance
Comment: @PatrickCoulombe ok, thanks. It seems ok to me too, just that there will be a biological effect being the same patient involved which is hard to control for.
Answer: A couple of points:

You do not need to work with differences from baseline because the random intercepts term accounts for these differences.
Using only random intercepts means that the correlations between the biomarker measurements over time are constant. Most often, this is not realistic. You could try also including random slopes, i.e., lmer(... + (days | patient_id)) and compare the two models using a likelihood ratio test implemented by the anova() function.
Measurements from the same eye will probably be more strongly correlated than measurements from different eyes on the same patient. You could test that by including the nested random effect, i.e., lmer(... + (1 | eye_id)).
Answer: I think you need to nest the eyes within each subject ID, so
lmer(biomarker_change ~ days + treated_yn + (1 | patient_id/eye), data = study)
As you have already questioned, your original model was incomplete by not accounting for the random variation from the two eyes from the same patient. The (1 | patient_id/eye) term is equivalent to (1 | patient_id) + (1 | patient_id:eye) where the : denotes the interaction between each patient's right and left eyes.
See
Nested Data - Mixed Linear Effects in R Assumptions
And
Have I correctly specified my model in lmer?


two numbers chosen from 0 to 1, expected val of larger number

Question: If I pick two numbers in the interval (0,1), what is the expected value of the larger number?
Please help. I know that the expected value of one number is 0.5 but I'm not sure how to find the expected vlaue of the larger number here.
Comment: I am going to take a wild guess, which could easily be **wrong**, based on Bayes Theorem: $$\lim_{n\to\infty} \frac{\sum_{i=1}^n (i/n)^2}{\sum_{i=1}^n (i/n)}.$$  The idea is that the denominator represents the sum of the probabilities of all the intervals, and the numerator weights each interval with the actual value associated with that interval.
Answer: Assume that the value of the larger number is $x$. The probability of this is equal to the probability that the other number is less than $x$. This probability is obviously $x $. Therefore the expected value of the larger number is:
$$2\int_0^1 x\cdot x\, dx=\frac23,
$$
where the factor 2 counts the ways to choose the larger number.
Answer: Imagine the scenario with two die:

6 6 6 6 6 6
5 5 5 5 5 6
4 4 4 4 5 6
3 3 3 4 5 6
2 2 3 4 5 6
1 2 3 4 5 6

The expected value here is:
$$\frac{1+6+15+28+45+66}{36}=\frac{161}{36}=4.47\dot2$$
$161$ is the sixth term in the sequence of hexagonal pyramid numbers ($A002412$).
These are given by:
$$\frac{n(n+1)(4n-1)}{6}$$
On the unit grid, we can do a similar trick. However if say we use a resolution of $k$, then to calculate the expectation we use $kP(X=k)$, and over $k^2$ squares, to give the result as:
$$\lim_{k\to\infty}\frac{k(k+1)(4k-1)}{6k^3}=\frac23$$


Send binary response from UInt8Array in Express.js

Question: I am using Express.js with Typescript and I would like to send a UInt8Array as binary data.
This is what I use so far and it works, but I would like not to save the file before, because I think it wastes performance:
const filePath = path.resolve(__dirname, 'template.docx');
const template = fs.readFileSync(filePath);
const buffer: Uint8Array = await createReport({
  template,
  data: {
    productCode: data.productCode,
  },
});
fs.writeFileSync(path.resolve(__dirname, 'output.docx'), buffer);
res.sendFile(path.resolve(__dirname, 'output.docx'));

I am using docx-templates to generate the file by the way.
Answer: You can use a PassThrough stream for this purpose, it'll keep the file in memory with no need to write to disk.
Something like this should do it:
    const stream = require("stream");
    const readStream = new stream.PassThrough();

    // Pass your output.docx buffer to this
    readStream.end(buffer);
    res.set("Content-disposition", 'attachment; filename=' + "output.docx");
    res.set("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    readStream.pipe(res);

The complete node.js code:
const fs = require("fs");
const express = require("express");
const port = 8000;
const app = express();
const stream = require("stream");

app.get('/download-file', (req, res) => {
    const buffer = fs.readFileSync("./test.docx");
    console.log("/download-file: Buffer length:", buffer.length);

    const readStream = new stream.PassThrough();
    readStream.end(buffer);
    res.set("Content-disposition", 'attachment; filename=' + "test.docx");
    res.set("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    readStream.pipe(res);
});

app.listen(port);
console.log(`Serving at http://localhost:${port}`);

To test, add a 'test.docx' file to the same directory, then point your browser to http://localhost:8000/download-file
Comment: Hey, Terry,

How am I supposed to download this on the Client side? Currently, when I make a call to this API endpoint, and have this code, it returns successful response, but nothing downloads.

I am using vuejs with vuetify, if that helps.
Comment: Hi Vitomir, I've added the complete Node.js code, hope this helps.
Answer: Terry,
Thanks for the update of your answer and providing the full code. However, it still does not help much. I am trying to understand how I can handle this on the front-end side, in my case in Vue. Here is the following code:
router.post('/chart/word', async (req, res, next) => {
    try {
        if (!req.body.chartImage) throw new BadRequest('Missing the chart image from the request body')

        const wordTemplate = await s3GetFile('folder', 'chart-templates-export/charts-template.docx')
        const template = wordTemplate.Body

        const buffer = await createReport({
            cmdDelimiter: ["{", "}"],
            template,
            additionalJsContext: {
                chart: () => {
                    const dataUrl = req.body.chartImage.src
                    const data = dataUrl.slice("data:image/jpeg;base64,".length);
                    return { width: 18 , height: 12, data, extension: '.jpeg' }
                }
            }
        })

        const stream = require('stream')
        const readStream = new stream.PassThrough()

        readStream.end(buffer)
        res.set("Content-disposition", 'attachment; filename=' + "output.docx")
        res.set("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
        readStream.pipe(res)
    } catch (err) {
        console.log(err)
        next(err)
    }
})

And here is my Vue code, tested various stuff, but nothing...:
async exportCharts() {
    console.log('this.$refs.test: ', this.$refs.test)
    let img = {
        src: this.$refs.test.getDataURL({
            type: 'jpeg',
            pixelRatio: window.devicePixelRatio || 1,
            backgroundColor: '#fff'
        }),
        width: this.$refs.test.getWidth(),
        height: this.$refs.test.getHeight()
    }
    const answersReq = await this.axios({
        method: 'post',
        url: '/pollAnswers/chart/word',
        data: {
            chartImage: img
        }
        responseType: 'arraybuffer' // 'blob' // 'document'
    })

    console.log('answersReq: ', answersReq)

    if (answersReq.data) {
        downloadURL(answersReq.data, 'report.docx')
    }
}

What I am basically doing is: sending an image to the API (taken from html vue-echart element), then inserting it in a docx template, by using docx-templates library, which returns me Uint8Array that I want to export as the new Word Document with the populated charts. Then, the user (on the UI) should be able to choose the destination.
Here is the code for the download URL:
export function downloadURL(data, fileName) {
    const mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    const blob = new Blob([data], { type: mimeType })
    const url = URL.createObjectURL(blob)

    const element = document.createElement('a')

    element.href = url
    element.download = fileName

    element.style.display = 'none'

    document.body.appendChild(element)
    element.click()
    URL.revokeObjectURL(element.href)
    document.body.removeChild(element)
}

P.S. Just to mention, if I directly save the buffer (the Uint8Array returned from the createReport) in the API, it works, the file is downloaded successfully and I can read it without any problems - it populates the correct chart in the file.
UPDATE:
I figured that out, but I am not sure why this is necessary and why it works that way and not the other. So, in the /chart/word endpoint, I am converting the Uint8Array buffer into a stream, then passing it as a response (the same way you used). Afterwards, in the Vue, I fetched this as responseType: 'arraybuffer', which converted the stream response into Uint8Array buffer again, then, I used the same method for the download and it works. Initially, I tried to send directly the buffer (without converting it as stream as you mentioned), but then on the front-end, the response was received as object that contained the Uint8Array buffer values, which was not what is expected and I could not create legit docx file. So, for some reason, it is required to convert the buffer as stream in the API, before sending it as response. Afterwards, on the front-end, I have to convert it back to arraybuffer and, finally, to make the docx download.
If you can explain to me why it works like that, I will be very happy.


Dúvida de como utilizar o hover

Question: Queria quando eu colocasse o mouse em cima da div.caixa alterasse minha div.caixa-titulo, porém não consegui.
Meu código:

 <!DOCTYPE html>

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

Calendário

              Aqui está um calendário simples que você pode adicionar atividade nele, clique Aqui

Answer: Você deve colocar o :hover na classe da caixa .caixa para alterar a classe filha .caixa-titulo:
       evento
         ↓
.caixa:hover .caixa-titulo{
   ↑               ↑
  pai            filha

Veja:

<!DOCTYPE html>

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

Calendário

              Aqui está um calendário simples que você pode adicionar atividade nele, clique Aqui

Dúvida de como utilizar o hover


Unregister to an event using WithEvents declaration

Question: When using the WithEvents declaration instead of AddHanlder, what is the corresponding code to unregister (removeHandler) to an Event? Is this simply to set that WithEvents variable to Nothing?  Is this enough (Framework wise)?
Comment: You can't unregistered the statically bind events.
Comment: Why are you trying to do this?
Comment: @AVD : Why do you tell it as a comment? Is this an answer? Do you mean that the 2 objects are linked forever?
Answer: Let's say I have a form that I only show for a short while and then it goes away, but it subscribes to my main domain model to get updates about changes. I might have code like this:
Private WithEvents _model As WeatherModel

Public Sub New(model As WeatherModel)
   _model = model
End Sub

Private Sub WeatherModel_Update(sender As Object, e As WeatherUpdateEventArgs) _
  Handles _model.WeatherUpdate

  'Handle updated weather conditions
End Sub

Since the model I have a reference to will out-live me, if I don't unsubscribe my event handler, it'll cause this form to not be garbage collected. In that case, I'd want to make sure I do _model = Nothing in my FormClosing event-handler.
In the case that both the form and the WithEvents object have the same lifetime (i.e. go out of scope at the same time) or exist for the entire lifetime of the application, you don't need to worry about it.


Coding categorical variables for linear regression and random forest, factors/characters

Question: I am a newbie in Data Science so that do not judge me for this questions.
Making a regression model (linear model, lm_model) with numeric and categorical variables, I realized that Estimate coefficients in summary (lm_model) are the same for categorical variables whether categorical variables are factors or characters.

So, what is the preferred method to use for modeling (regression or classification)? As I read before, factors are preferred, but in my case, I actually do not see any difference.
In some cases, people say, if categorical variables have many levels (more than 32 levels), it is not possible to use a linear model or random forest model. What are the solutions for this problem, except splitting categorical variables into small groups? Is it ok to convert factors into characters?
Also, I am a bit of stuck in this question. What algorithms are required to transform categorical variables into numeric (or dummy variables)? Or is it not necessary? As I know, algorithms such as linear regression, logistic regression are required; on the other hand, trees algorithms like random forest are not required. But using caret package in R, I noticed that a linear model with categorical variables as factors or even characters runs pretty well and I can see Estimate coefficients. What is a preferred method for this case?
What are real constraints to use dummy variables? Of course, it depends on data, but is there a rule when it is not recommended to use it?

Thank you very much in advance!!
Answer: First, characters are turned into factors in what the algorithm is doing behind the scenes. To be more specific, characters or factors are both just turned into dummy-coded variables. If you are using the R language, you can run:
dat <- data.frame(
  y = rnorm(99),
  x = c("a", "b", "c"),
  stringsAsFactors = FALSE
)

If you look at str(dat$x), you'll see that it says it is a character. But the lm function that does linear models will turn this character vector into a design matrix underneath the hood. It does this using the model.matrix() command. You can run this manually by giving it the terms of your lm (that is, just the right side of the ~ and the data): model.matrix(~ x, dat). This will return the dummy-coded variable x and an intercept. The same thing happens if you make stringsAsFactors = TRUE. If you run the following code, you'll see that it returns TRUE, noting that both of the model matrices are identical:
set.seed(1839)
dat1 <- data.frame(
  y = rnorm(99),
  x = c("a", "b", "c"),
  stringsAsFactors = FALSE
)
set.seed(1839)
dat2 <- data.frame(
  y = rnorm(99),
  x = c("a", "b", "c"),
  stringsAsFactors = TRUE
)
identical(
  model.matrix(~ x, dat1),
  model.matrix(~ x, dat2)
)

This means that characters and factors are the same things. Any other statistical software will do the same thing.
Second, when you talk about "regression or classification," this refers to the dependent variable; what you are talking about, it seems, is the independent variable. Broadly speaking, regression is used when the dependent variable is numeric, while classification is used when it is categorical.
Third, you need to figure out perhaps a better way to model a factor with 32 categories. Is there a big enough sample size in each of the categories that you can actually run the model? Do you care about interpretability of coefficients? If the answer to those questions are yes and no, respectively, then you can use a factor with 32 categories. If not, you could find ways to collapse these 32 categories into fewer. Or you could do a multilevel/hierarchical model and treat these 32 categories as groups. This is dependent on the situation.
Fourth, you do not need an algorithm to transform a character/factor variable into dummy-coded variables. Often the question in doing the analyses in applied settings is: "Is the function smart enough to do it for me, or do I need to make them myself first?" It will depend on the package you use. If you need to make them beforehand, there are a lot of packages that will help you (I tend to just use the model.matrix function).
Comment: Thank you a lot for such a detailed answer! Everything is clear now


DNS Pointer to old server name

Question: We have a SBS2003 server that was migrated to a new hardware platform, the computer name has changed but the domain is the same.  The desktop's are trying to do offline files to the old server name.  There is a nslookup entry for the old server name and a DNS entry for the old server.
How do we safely remove the old DNS entry without breaking the computer offline folder storage locally.
Can we change the pointing location on the offline file storage to point to the new server name.
Answer: You can not. Offline storage runs by computer name. What you can do is have clients retire the offline storage (i.e. remove the shares) then reopen them with the new server name.
Altenratively you could CNAME the old name to the new server's name, so sync should / would work.

DNS Pointer to old server name


Expected value of dice sum

Question: We roll a dice. If we get 6, then we roll again. What's the expected value of sum of rolls?
Let $X$ be the sum. In this game we can only obtain sum in form $6k + x$ where $k \in \mathbb{Z}$ and $x \in \{1,2,3,4,5\}$. If $n$ is in this form then probability of obtaining it is equal $(\frac{1}{6})^{[\frac{n}{6}]}\cdot\frac{1}{6}$. To get the expected value I would to sum only these $n$ which are in this form but I don't know how to properly do it. Or maybe my idea is wrong?
Comment: The expected number of $6$'s rolled in this game is $\frac{1}{5}$.  The expected number of the final non-6 roll is $3$.  This gives an overall expected value of $6\times \frac{1}{5}+3=4.2$
Comment: @JMoravitz I think that should be an answer rather than a comment.
Comment: @JMoravitz could you give more detailed answer? I don't understand where some of the values came from. I'd appreciate it.
Answer: Here's a trick: let $E$ be the expected value. When you roll a $6$, you win $6+E$ points. Therefore
$$E = \frac16\left(1+2+3+4+5+(6+E)\right)$$
Now solve for $E$.

Expected value of dice sum


Change default theme of "project.net"

Question: I want to change complete theme of an open source project "project.net". Can anyone help me that how to change overall theme into custom theme.
NOTE: i already done with coloring and images change by CSS etc... my question is about change theme structure. e.g. and beautiful header in new theme. Accordion on left navigation etc.
Your quick prompt will be great!
Answer: Use master pages.

Change default theme of "project.net"


Need to find Max, Min, Avg number in Array - no size declared

Question: So I have this array, I need to find the Min, Max, and Average. I have figured out how to get the Max, my code looks right for the minimum but it does not work so I must be missing something. I also need to find the average of the numbers entered. Everything I can find on this only works when you have the size of the array set. I have a max size set for the array but it does not get filled by user input. I have been staring and testing on this for days and still cant figure it out.
I know for the average I need something like (with added declartions at the top), but I cannot figure out how to get it to work:
for (i = 0; i < numOfGrades; i++) {
    sum += grades[i];
    }
avg = (double) sum / numOfGrades;

Here is the rest of my code:
#include <stdio.h>

int main(){

int grades [100];
int i = 0;
int small, big, input;

printf("Enter a series of grades. When done, enter any number above 100.\n\n");

while (i <= 100) { //while loop to set maximum for array
    printf("Enter grade:");

    if (scanf("%d", &input) == 1) {
        if (input >= 0 && input <=100) {
            grades[i] = input; //if good, add to array
            i++;
            }
        else {
            printf("\n\nExiting entry.\n");
            printf("\n\nGrades entered:\n\n");
            i = i - 1;
            break; //exiting loop
            }
        }
    }
int x, y;
    for (x = 0; x <= i; x++) {
        printf("Grade: %d\n", grades[x]);  //print array
        }
    big = small = grades[0];
    for (y = 0; y  big) {
            big = grades[y];
            }
        else if (grades[y] < small) {
            small = grades[y];
            }
        }
    printf("Highest number : %d\n", big);
    printf("Smallest number: %d\n", small);

    return 0;
}

Comment: If you *initialize* the array with some value (that let's say, can't be a valid grade), you'd be able to easily recognize when you reached the "end"...
Comment: Perhaps 1) `i <= 100` --> `i < 100`  2) Delete `i = i - 1;`.  3) `x <= i;` --> `x < i;`  4) Other things?
Comment: For your average code, `numOfGrades` is just the `i` from your `while` loop. Look at what `i` ends up set to: the number of grades input by the user. You just need to loop from 0 to that point to get the sum of the entered grades.
Answer: Here you do the right thing:
 for (x = 0; x <= i; x++) {

Because x <= i will take you from 0 to the value of i. Then in your min/max loop you do this:
 for (y = 0; y < i; y++) {

So you are going from 0 to to i-1. You have 2 options:

Make the above loop correct with y <= i.
Dont decrement i in the while loop (Dont do this i = i - 1;) That way, i represents the number of numbers entered, instead of number of numbers entered -1 (you will need to fix the x <= i to x < i).

Here is a live example. http://ideone.com/ZEaDue
To calculate the average, you are doing the right thing, you can re-use i though:
int sum = 0, avg = 0;
for (y = 0; y < i; y++) {
    sum += grades[y];
}
avg = (double) sum / i;
printf("Avg: %d\n", avg);

Comment: This was amazingly helpful and work fantastic, except one minor detail, I needed to leave the `x  <= i` rather than `x < i`
Comment: @PhilipHudson, then use option 1.
Comment: I still had to get rid of the `i = i - 1`
Answer: Actually you do have the number of grades
   if (scanf("%d", &input) == 1) {
        if (input >= 0 && input <=100) {
            grades[i] = input; //if good, add to array
            i++;
            }
        else {
            numOfGrades=i;
            printf("\n\nExiting entry.\n");
            printf("\n\nGrades entered:\n\n");
            i = i - 1;
            break; //exiting loop
            }

As for the minimum, your logic should be like this:
for (y = 0; y < numOfEdges; y++) {
    if (grades[y] > big) {
        big = grades[y];
        }
    if (grades[y] < small) {
        small = grades[y];
        }
    }

The else statement I removed should do the trick. Also I would always use
for(int var = 0; var < numOfEdges; var++) in any of the loop constructs. It's easyer to follow the logic this way: You have counted the number of edges (numOfEdges), but your loop goes only to numOfEdges-1 since you start with index 0.


Sort an object literal on its attribute value

Question: Below is my input, I would be looping through each of this element and sending each element to another function.
 distinctParameterList  =  [{
        careerGroupLevel: 'Analyst',
        careerGroupCode: 130,
        m06: 83,
        m05: 82,
        m08: 85,
        fymcl: 'FY18|PromotionsOut|AN-10000100:CL 2',
        m07: 84,
        m09: 86,
        intersectionId: '54697113|India|520|N'
    },
     {
        careerGroupLevel: 'Analyst',
        careerGroupCode: 130,
        m06: 95,
        m05: 94,
        m08: 97,
        fymcl: 'FY18|PromotionsOut|AN-10000110:CL 2',
        m07: 96,
        m09: 98,
        intersectionId: '54697113|India|520|N'
    },
     {
        careerGroupLevel: 'Analyst',
        careerGroupCode: 130,
        m06: 22,
        m05: 21,
        m08: 24,
        fymcl: 'FY17|PromotionsOut|AN-10000100:CL 2',
        m07: 23,
        m09: 25,
        intersectionId: '54697113|India|520|N'
    },
     {
        careerGroupLevel: 'Analyst',
        careerGroupCode: 130,
        m06: 42,
        m05: 41,
        m08: 44,
        fymcl: 'FY17|PromotionsOut|AN-10000110:CL 4',
        m07: 43,
        m09: 45,
        intersectionId: '54697113|India|520|N'
    }]

I am also calculating a value "calcCareerId " below :
let calcCareerId = fymclData.split("-")[1].split(":")[0];

Now i want to sort this structure on the basis of the "calcCareerId " value in fymcl attribute, so that i can get all the "10000100" values first and then "10000110".
Comment: That is a JavaScript object literal.  JSON is a `string`.
Comment: sorry, let me make the edit
Answer: Define the function:

let calcCareerId = fymclData => fymclData.split("-")[1].split(":")[0];

You can use lodash's sortBy function to sort in lexicographically ascending order. If you want descending order, just call .reverse on the result.

const result = _.sortBy(distinctParameterList, ({fymcl}) => calcCareerId(fymcl));

or use the native sort:

const result = distinctParameterList.sort((a, b) => {
  const valueA = calcCareerId(a.fymcl);
  const valueB = calcCareerId(b.fymcl);
  return (valueA === valueB) ? 0 : (valueA < valueB ? 1 : -1)
})

Note that the native sort mutates the array and is not stable.
Comment: Why resort to a library instead of using native `Array.prototype.sort()`?
Comment: But "calcCareerId" is only available when iam looping through the array. But the requirement is that before triggerring that loop, i need the array sorted by "10000100" etc i.e. the "fymcl" attribute value
Comment: @Rishabh Then define `calcCareerId` at the same level as `distinctParameterList`.
Comment: but calcCareerId can only be calculated when i loop in through each element of this array and then locate the fymcl attribute and then split it.
Comment: lets not confuse with calcCareerId. What i need is the array should be sorted on the basis of the value in fymcl attribute
Comment: const result = distList.sort((a, b) => {
  const valueA = (a.fymcl.split("-")[1].split(":")[0]);
  const valueB = (b.fymcl.split("-")[1].split(":")[0]);
  return (valueA === valueB) ? 0 : (valueA < valueB ? 1 : -1)
})      // this is now sorting
Comment: is there a way to use sort in a callback ?