text:
Q: Having problems applying xsl:choose I am having problems applying xsl:choose in my xslt document, trying to transform xml to html.
The xml document looks like this (it's german)
and so on...
now, in my html document I created a table that shows the moviename (Filmtitel) and then the title of the review (Reviewtitel) - with that I want, that in the background color of the table, where the review title is, you can see how good or how bad a person rated this movie. Therefore - if it's rated "good" - points 7-10 out of ten, the backgroundcolor will be green, if it's rated average 4-7 points out of ten the backgroundcolor will be yellow and if someone didn't enjoy this movie and rated it with 1-3 out of 10 points the backgroundcolor of the review title will be red.
I am afraid that i cannot make this work because I want to relate the element "Reviewtitel" with the element "Bewertung" to both show in the same table space - Reviewtitel shows the words that belong to that element but with the backgroundcolor I relate to it with xsl:choose out of the element Bewertung.
This is my xslt document so far
Any suggestions?
I am really a bloody beginner to xslt and stuff but whenever i tried to make it work, the table input with the name of the review disappeared completely.


text:
Q: Windows service not stoping in ASIO blocking socket I have a Windows service , adapted from
https://learn.microsoft.com/en-us/windows/win32/services/the-complete-service-sample?redirectedfrom=MSDN
that starts/stops normally when doing a simple task, like
writing in a while loop to a text file, like in this sample

#include <windows.h>
#include <string>
#include "service.hh"
#include "log.hh"

LPSTR service_name = "_service_test";
std::string log_program_name("M:\\" + std::string(service_name));

VOID WINAPI service_main(DWORD, LPTSTR*);
void write_txt_file(const std::string& file_name, const std::string& input);

SERVICE_STATUS_HANDLE service_handle = NULL;
HANDLE service_stop_event = INVALID_HANDLE_VALUE;
DWORD current_state = 0;

/////////////////////////////////////////////////////////////////////////////////////////////////////
//main
//create service in administrator shell with
//sc create _service_test binPath= "L:\net\build\Debug\test_service.exe"
/////////////////////////////////////////////////////////////////////////////////////////////////////

int main(int argc, char* argv[])
{
  events::start_log();

  //A service process has a SERVICE_TABLE_ENTRY structure for each service that it can start.
  //The structure specifies the service name and a pointer to the service main function for that service.
  //The main function of a service program calls the StartServiceCtrlDispatcher
  //function to connect to the service control manager (SCM)

  SERVICE_TABLE_ENTRY service_table[] =
  {
      { service_name, (LPSERVICE_MAIN_FUNCTION)service_main },
      { NULL, NULL }
  };

  if (StartServiceCtrlDispatcher(service_table))
  {
    return 0;
  }
  else
  {
    return 1;
  }
}

void WINAPI service_main(DWORD argc, LPTSTR* argv)
{
  service_handle = RegisterServiceCtrlHandler(service_name, service_handler);
  if (service_handle == NULL)
  {
    return;
  }

  report_status(SERVICE_START_PENDING);

  events::log("service start pending..." + std::to_string(current_state));

  service_stop_event = CreateEvent(NULL, TRUE, FALSE, NULL);
  if (service_stop_event == NULL)
  {
    return;
  }

  report_status(SERVICE_RUNNING);

  events::log("service running..." + std::to_string(current_state));

  int i = 0;

  while (WaitForSingleObject(service_stop_event, 1000) != WAIT_OBJECT_0)
  {
    write_txt_file("M:\\log.txt", "writing...#" + std::to_string(i));
    Sleep(1000);
    i++;
  }

  report_status(SERVICE_STOP_PENDING);
  events::log("service stop pending..." + std::to_string(current_state));
  CloseHandle(service_stop_event);
  report_status(SERVICE_STOPPED);
  events::log("service stopped..." + std::to_string(current_state));
}

void write_txt_file(const std::string& file_name, const std::string& input)
{
  FILE* f = fopen(file_name.c_str(), "a+");
  fprintf(f, "%s\n", input.c_str());
  fclose(f);
}

this produces the log output
2020-09-05,14:18:03 service start pending...2
2020-09-05,14:18:03 service running...4
2020-09-05,14:18:20 service stop pending state...4
2020-09-05,14:18:21 service stop pending...3
2020-09-05,14:18:21 service stopped...1

However , when using the service as a ASIO server on a blocking socket, when a service stop is requested , it never reaches the stop state, only the pending stop state
abbreviated server code

asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), port_num));

while (WaitForSingleObject(service_stop_event, 1000) != WAIT_OBJECT_0)
{

   tcp::socket sock(io_service);
   acceptor.accept(sock); /// blocking call

}

service code functions
/////////////////////////////////////////////////////////////////////////////////////////////////////
//handles
/////////////////////////////////////////////////////////////////////////////////////////////////////

extern SERVICE_STATUS_HANDLE service_handle;
extern  HANDLE service_stop_event;
extern  DWORD current_state;

/////////////////////////////////////////////////////////////////////////////////////////////////////
//service_handler
//handles stop service
/////////////////////////////////////////////////////////////////////////////////////////////////////

VOID WINAPI service_handler(DWORD code)
{
  switch (code)
  {
  case SERVICE_CONTROL_SHUTDOWN:
  case SERVICE_CONTROL_STOP:
    events::log("service stop pending state..." + std::to_string(current_state));
    report_status(SERVICE_STOP_PENDING);
    SetEvent(service_stop_event);
    break;
  default:
    events::log("service running state..." + std::to_string(current_state));
    report_status(current_state);
    break;
  }
  return;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////
//report_status
/////////////////////////////////////////////////////////////////////////////////////////////////////

void report_status(DWORD state)
{
  current_state = state;
  SERVICE_STATUS service_status = {
      SERVICE_WIN32_OWN_PROCESS,
      current_state,
      state == SERVICE_START_PENDING ? 0 : SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN,
      NO_ERROR,
      0,
      0,
      0,
  };

  if (SetServiceStatus(service_handle, &service_status) == FALSE)
  {
    return;
  }
}

A: Solved by sending a "dummy" self request on the server, that unblocks acceptor.accept(sock);
SetEvent(service_stop_event);
send_close(port);

where the close call is

/////////////////////////////////////////////////////////////////////////////////////////////////////
//temporary client connection to self on localhost to unblock acceptor.accept()
/////////////////////////////////////////////////////////////////////////////////////////////////////

void http::send_close(const std::string& port_num)
{
  asio::io_service io_service;
  asio::ip::tcp::resolver resolver(io_service);
  asio::ip::tcp::socket socket(io_service);
  asio::connect(socket, resolver.resolve("127.0.0.1", port_num));
  std::string request("GET /stop_service HTTP/1.1\r\n\r\n");
  asio::write(socket, asio::buffer(request, request.size()));
  socket.shutdown(asio::ip::tcp::socket::shutdown_both);
  socket.close();
  events::log("sent GET /stop_service");
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como buscar uma String dentro de um ArrayList Estou com dificuldades na utilização da classe ArrayList, mais especificamente na busca de uma String. A questão é a seguinte, o meu código até funciona, mas quando cadastro mais de dois livros dentro do ArrayList, na hora de fazer a consulta ele só "encontra" o último livro cadastrado, não acha os anteriores.
Essa é a minha classe livro:
public final ArrayList<Livro> livros = new ArrayList<>();
// Atributos
private String titulo;
private String autor;
private String editora;
private String consultaLivros;
private int numPags;
private int pagAtual;

public void informacoes() {
    System.out.println("_____________________________________");
    System.out.println("Título: " + this.getTitulo());
    System.out.println("Autor: " + this.getAutor());
    System.out.println("Editora: " + this.getEditora());
    System.out.println("Número de páginas: " + this.getNumPags());
    System.out.println("Página atual: " + this.getPagAtual());
}

public void apresentacao() {
    System.out.println("_____________________________________");
    System.out.println("Título: " + this.getTitulo());
    System.out.println("Número de páginas: " + this.getNumPags());
}

// Getter e Setters
public String getTitulo() {
    return titulo;
}

public void setTitulo(String titulo) {
    this.titulo = titulo;
}

public String getAutor() {
    return autor;
}

public void setAutor(String autor) {
    this.autor = autor;
}

public String getEditora() {
    return editora;
}

public void setEditora(String editora) {
    this.editora = editora;
}

public String getConsultaLivros() {
    return consultaLivros;
}

public void setConsultaLivros(String consultaLivros) {
    this.consultaLivros = consultaLivros;
}

public int getNumPags() {
    return numPags;
}

public void setNumPags(int numPags) {
    this.numPags = numPags;
}

public int getPagAtual() {
    return pagAtual;
}

public void setPagAtual(int pagAtual) {
    this.pagAtual = pagAtual;
}

// Métodos
public void virarPagina(int pagAtual) {
    this.setPagAtual(this.getPagAtual() + 1);
}

public void consultaLivro() {
    System.out.print("Digite o nome do título a ser pesquisado: ");
    Scanner input = new Scanner(System.in);
    this.setConsultaLivros(input.nextLine());

    for (int i = 0; i < livros.size(); i++) {
        if (livros.get(i).getTitulo().contains(this.getConsultaLivros())) {
            livros.get(i).informacoes();
            System.out.println("");
            break;
        } else {
            System.out.println("Título não encontrado!");
            System.out.println("");
            break;
        }
    }
}

Esse é a classe principal:
    entrada = new Scanner(System.in);
    Livro book = new Livro();
    int verificarCadastro = 1;
    while (verificarCadastro == 1 || verificarCadastro == 2) {
        System.out.println("Bem vindo a sua biblioteca. ");
        System.out.println("Digite 1 para NOVO livro.");
        System.out.println("Digite 2 para CONSULTAR livro.");
        System.out.println("Digite 0 para SAIR.");
        verificarCadastro = entrada.nextInt();
        System.out.println("");
        switch (verificarCadastro) {
            case 0:
                System.out.println("Você saiu do programa.");
                System.out.println("");
                break;
            case 1:
                System.out.print("Digite o nome do livro: ");
                entrada.nextLine();
                book.setTitulo(entrada.nextLine());

                System.out.print("Digite o nome do Autor: ");

                book.setAutor(entrada.nextLine());

                System.out.print("Digite o nome da editora: ");
                book.setEditora(entrada.nextLine());

                System.out.print("Digite o número de páginas: ");
                book.setNumPags(Integer.parseInt(entrada.nextLine()));

                System.out.print("Digite a página atual: ");
                book.setPagAtual(Integer.parseInt(entrada.nextLine()));
                System.out.println("");
                book.livros.add(book);
                break;
            case 2:
                book.consultaLivro();
                break;
            default:
                System.out.println("Você digitou uma opção inválida.");
                System.out.println("");
                break;
        }
    }
}

A: A resposta do Math já demonstrou o problema no seu método consultaLivro(). Mas há ainda outros problemas.
Basicamente, na sua classe Livro, você tem esses dois campos:
public final ArrayList<Livro> livros = new ArrayList<>();
private String consultaLivros;

Isso significa que cada livro tem vários livros e que cada livro tem uma String de consulta de livros. Isso não é uma modelagem orientada a objetos adequada, pois a lista de livro não pertence a nenhum livro. A String de busca também não pertence a um livro. Além disso, o campo livros é público, e você deve saber que não é boa prática manter campos de instância públicos.
Além disso, você não precisa do campo consultaLivros para nada, e nem o getter e setter correspondente. Veja no seu método consultaLivro:
this.setConsultaLivros(input.nextLine());

for (int i = 0; i < livros.size(); i++) {
    if (livros.get(i).getTitulo().contains(this.getConsultaLivros())) {

Observe que você lê um dado (consultaLivros), o coloca dentro do objeto e tira esse mesmo dado deste mesmo objeto. Isso daí é um dado que uma vez lido, só tem sentido dentro desse método, e uma vez finalizado o método, ele perde o sentido de existir. Além disso, só faria sentido armazenar isso na instância (this) se esse dado fosse transportado para algum outro lugar, o que não é o caso aqui pois o consultaLivros perde o propósito de existir dentro do mesmo método no qual ele nasce. Logo, isso deveria ser uma variável local, e não um campo do objeto. Assim sendo, já contando com as alterações do Math, o seu método ficaria assim:
public void consultaLivro() {
    System.out.print("Digite o nome do título a ser pesquisado: ");
    Scanner input = new Scanner(System.in);
    String consultaLivros = input.nextLine();

    boolean achou = false;
    for (int i = 0; i < livros.size(); i++) {
        if (livros.get(i).getTitulo().contains(consultaLivros)) {
        System.out.println("O livro cadastrado está na posição: " + livros.indexOf(i));
        livros.get(i).informacoes();
        System.out.println("");
        achou = true;
    }
    if (!achou) {
        System.out.println("Título não encontrado!");
        System.out.println("");
    }
}

E o campo consultaLivros e o getter e setter correspondentes podem ser apagados.
Como já mencionei antes, não faz sentido um livro ter vários livros ou um livro pertencer a outro livro. Aliás, é pior que isso. Na sua classe principal, você tem isso:
Livro book = new Livro();
// ... várias linhas de código aqui.
book.livros.add(book);

Esses são os únicos dois lugares onde você cria um livro ou o adiciona à lista de livros. Isso significa que:

*

*O seu sistema só tem um único livro (afinal de contas, você só instanciou ele uma única vez).

*Que a lista de livros vai conter várias vezes o mesmo livro.

*Que um livro contém a si mesmo várias vezes.

*Que um livro pertence a si mesmo múltiplas vezes.

Ou seja, isso daí não vai fazer nada que seja parecido com o que você quer.
Isso pode ser resolvido ao criar uma classe Biblioteca que contém uma lista de livros:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Biblioteca {
    private final List<Livro> livros;

    public Biblioteca() {
        this.livros = new ArrayList<>(10);
    }

    public void adicionarLivro(Livro livro) {
        this.livros.add(livro);
    }

    public void consultarLivro() {
        System.out.print("Digite o nome do título a ser pesquisado: ");
        Scanner input = new Scanner(System.in);
        String consultaLivros = input.nextLine();

        boolean achou = false;
        for (int i = 0; i < livros.size(); i++) {
            if (livros.get(i).getTitulo().contains(consultaLivros)) {
            System.out.println("O livro cadastrado está na posição: " + livros.indexOf(i));
            livros.get(i).informacoes();
            System.out.println("");
            achou = true;
        }
        if (!achou) {
            System.out.println("Título não encontrado!");
            System.out.println("");
        }
    }
}

Além disso, vamos ver o seu método virarPagina:
    public void virarPagina(int pagAtual) {
        this.setPagAtual(this.getPagAtual() + 1);
    }

Observe que o parâmetro pagAtual não é utilizado.
Veja bem, no seu código, o book.setAutor(entrada.nextLine()); está alterando o autor do livro, ao invés de estar definindo o autor do livro que está sendo cadastrado. Esse é um outro problema que tende a levar você a cometer enganos que fazem estar sempre alterando o mesmo livro ao invés de criar livros novos. Conceitualmente, quando um livro é cadastrado, ele já contém todas as informações necessárias para ser um livro e considerando que tenham sido cadastradas corretamente, não faz sentido que sejam alteradas. Ou seja, o construtor já deve devolver um objeto Livro pronto para uso, e não um esqueleto incompleto a ser consertado depois por meio da invocação de um monte de setters.
Outro detalhe, é que os métodos setPagAtual e virarPagina não respeitam o número de páginas do livro. Você não pode virar a página se já estiver na última.
Abreviar nomes (ex: pagAtual) também não é boa prática de programação. Use paginaAtual.
Considerando tudo isso, eis a sua nova classe Livro:
public class Livro {

    private String titulo;
    private String autor;
    private String editora;
    private int numeroPaginas;
    private int paginaAtual;

    public Livro(String titulo, String autor, String editora, int numeroPaginas, int paginaAtual) {
        if (numeroPaginas <= 0) throw new IllegalArgumentException();
        if (paginaAtual <= 0 || paginaAtual > numeroPaginas) throw new IllegalArgumentException();
        this.titulo = titulo;
        this.autor = autor;
        this.editora = editora;
        this.numeroPaginas = numeroPaginas;
        this.paginaAtual = paginaAtual;
    }

    public String getTitulo() {
        return titulo;
    }

    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }

    public String getAutor() {
        return autor;
    }

    public void setAutor(String autor) {
        this.autor = autor;
    }

    public String getEditora() {
        return editora;
    }

    public void setEditora(String editora) {
        this.editora = editora;
    }

    public int getNumeroPaginas() {
        return numeroPaginas;
    }

    public void setNumeroPaginas(int numeroPaginas) {
        this.numeroPaginas = numeroPaginas;
    }

    public int getPaginaAtual() {
        return paginaAtual;
    }

    private boolean paginaExiste(int numeroPagina) {
        return numeroPagina >= 1 && numeroPagina <= numeroPaginas;
    }

    public void setPaginaAtual(int novaPaginaAtual) {
        if (!paginaExiste(novaPaginaAtual)) throw new IllegalArgumentException();
        this.paginaAtual = novaPaginaAtual;
    }

    public void virarPagina() {
        if (paginaExiste(paginaAtual + 1)) this.paginaAtual++;
    }

    public void voltarPagina() {
        if (paginaExiste(paginaAtual - 1)) this.paginaAtual--;
    }
}

Não é boa prática de programação misturar lógica de visualização (seja ela System.out.println, telas e layout desktop, HTML, android, etc) com lógica de negócio (que é aquela que define o que o seu sistema faz e como se comporta). A ideia é que uma mesma lógica de negócio deveria ser capaz de ser expressa e manuseada independente daquilo que é utilizado para exibi-la e interagir com o usuário, o que a torna portável para vários ambientes. Entretanto, sempre que você usa um System.out, um JOptionPane ou um pedaço de HTML dentro da sua lógica de negócio, você joga essa premissa por terra. Há ainda outros vários motivos para não se misturar essas coisas (mais sobre isso abaixo).
Assim sendo, retirei os métodos informacoes() e apresentacao() da sua classe Livro acima. Vamos refazer a sua classe Biblioteca pensando nisso:
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class Biblioteca {
    private final List<Livro> livros;

    public Biblioteca() {
        this.livros = new ArrayList<>(10);
    }

    public void adicionarLivro(Livro livro) {
        this.livros.add(livro);
    }

    public Optional<Livro> consultarLivro(String consultaLivros) {
        for (Livro book : livros) {
            if (book.getTitulo().contains(consultaLivros)) return Optional.of(book);
        }
        return Optional.empty();
    }
}

O Optional é um objeto que pode ou não conter um outro dentro. Se conter, significa que aquilo que era produrado foi encontrado. Se não, é porque não foi encontrado. E note que o método consultaLivro se preocupa apenas em consultar o livro e devolvê-lo se for encontrado. Não é responsabilidade dele pedir ao usuário qual é o livro a ser consultado e nem exibir esses dados em qualquer lugar. Uma vez que esse método está desacoplado da lógica de visualização, você não vai se ferrar se quiser colocar as informações do livro em um arquivo ao invés de colocar no System.out. Algo parecido pode ser argumentado acerca do System.in.
Por fim, as suas classes principais:
import java.util.Scanner;
import java.util.Optional;

public class CadastroBiblioteca {
    private final Scanner entrada;
    private final Biblioteca biblioteca;

    public CadastroBiblioteca() {
        this.biblioteca = new Biblioteca();
        this.entrada = new Scanner(System.in);
    }

    public void lerLivro() {
        System.out.print("Digite o nome do livro: ");
        String titulo = entrada.nextLine();

        System.out.print("Digite o nome do autor: ");
        String autor = entrada.nextLine();

        System.out.print("Digite o nome da editora: ");
        String editora = entrada.nextLine();

        System.out.print("Digite o número de páginas: ");
        int numeroPaginas = Integer.parseInt(entrada.nextLine());

        System.out.print("Digite a página atual: ");
        int paginaAtual = Integer.parseInt(entrada.nextLine());

        biblioteca.adicionarLivro(new Livro(titulo, autor, editora, numeroPaginas, paginaAtual));
    }

    public void consultarLivro() {
        System.out.print("Digite o nome do título a ser pesquisado: ");
        String consulta = entrada.nextLine();

        Optional<Livro> opt = biblioteca.consultarLivro();

        if (!opt.isPresent()) {
            System.out.println("Título não encontrado!");
            return;
        }

        Livro livro = opt.orElseThrow(AssertionError::new);
        System.out.println("_____________________________________");
        System.out.println("Título: " + livro.getTitulo());
        System.out.println("Autor: " + livro.getAutor());
        System.out.println("Editora: " + livro.getEditora());
        System.out.println("Número de páginas: " + livro.getNumeroPaginas());
        System.out.println("Página atual: " + livro.getPaginaAtual());
    }
}

public class SistemaBiblioteca {

    public static void main(String[] args) {
        CadastroBiblioteca cadastro = new CadastroBiblioteca();
        while (true) {
            System.out.println("Bem vindo a sua biblioteca. ");
            System.out.println("Digite 1 para NOVO livro.");
            System.out.println("Digite 2 para CONSULTAR livro.");
            System.out.println("Digite 0 para SAIR.");
            String verificarCadastro = entrada.nextLine();
            System.out.println("");
            switch (verificarCadastro) {
                case "0":
                    System.out.println("Você saiu do programa.");
                    return;
                case "1":
                    cadastro.lerLivro();
                    break;
                case "2":
                    cadastro.consultarLivro();
                    break;
                default:
                    System.out.println("Você digitou uma opção inválida.");
                    System.out.println("");
                    break;
            }
        }
    }
}

Dividi em duas para separar o menu da implementação das funcionalidades.

A: Na sua consulta você varre a lista mas interrompe o loop logo no primeiro elemento sendo o titulo do livro encontrado ou não ao utilizar os breaks dentro do if e do else
for (int i = 0; i < livros.size(); i++) {
    if (livros.get(i).getTitulo().contains(this.getConsultaLivros())) {
        System.out.println("O livro cadastrado está na posição: " + livros.indexOf(i));
        livros.get(i).informacoes();
        System.out.println("");
        break; //AQUI
    } else {
        System.out.println("Título não encontrado!");
        System.out.println("");
        break; //E AQUI
    }
}

Você pode tirar os breaks e deixar a lista ser varrida completamente, e a mensage de "Título não encontrado" ser emitida fora do loop, assim:
boolean achou = false;
for (int i = 0; i < livros.size(); i++) {
    if (livros.get(i).getTitulo().contains(this.getConsultaLivros())) {
        System.out.println("O livro cadastrado está na posição: " + i);
        livros.get(i).informacoes();
        System.out.println("");
        achou = true;
    }
}
if (!achou) {
    System.out.println("Título não encontrado!");
    System.out.println("");
}

Veja funcionando em no Ideone


text:
Q: MATLAB GUI - Displaying messaging while loading data I am creating a MATLAB GUI where if a user presses start button,
the program will load .mat file, then display analyzed data.
The .mat file that I am loading is large, and it take few minutes to load data and then start showing plots from the loaded data.
I want to display a message "Loading data..." (StatusMessage) while the data is being loaded so that the user doesn't think that the program froze.
The code that I have below will display the message but after the data is loaded... I want the message to be displayed while the data is being loaded, not after.  Any help will be greatly appreciated!
Below is the part of my code for 'Start' button:
% --- Executes on button press in Start.
function Start_Callback(hObject, eventdata, handles)
% hObject    handle to Start (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Load data
set(handles.StatusMessage, 'String', num2str('Loading data...'));
load('data.mat');

A: add a drawnow command just before your load command:
% Load data
set(handles.StatusMessage, 'String', num2str('Loading data...'));
drawnow();
load('data.mat');


text:
Q: How to hide horizontal scroll in table (ngGrid)? I'm using ngGrid for table but I don't know how I can remove horizontal scroll? Just "overflow-x: hidden"  unsuccessful
My table:
.row(ng-controller="MyCtrl")
.form.form-group
   .col-sm-8
       div.gridStyle(
        id="myTable"
        ng-grid="myTableGrid"
        )
   .col-sm-2
   .col-sm-2

Angular code:
    $scope.myTableGrid = {
      data: 'data',
      multiSelect: true,
      showSelectionCheckbox: true,
      columnDefs:[

        {field: 'program_name', displayName: 'Program name'},
        {field: 'date', displayName: 'Date'}

      ],

  }

And test data for table:
 $scope.data=  [
                {id:10, program_name:'program1', date: '13.02.2015 8:52:45'} ,
                {id:102, program_name:'program2', date: '13.02.2015 9:16:23'} ,
                {id:130, program_name:'program3', date: '13.02.2015 9:20:40'} ,
                {id:102, program_name:'program4', date: '13.02.2015 9:16:23'} ]


text:
Q: Trirand jqgrid for asp.net - load drop down values when editing rows I have a jqgrid from trirand (asp.net version) and cannot work out how to simply load values for a drop down list from a web method when editing a cell.
Every example I have found on the internet is creating the grid completely from javascript which is NOT what I want to do.
markup for the grid is as follows:
   <tri:JQGrid runat="server" ID="jqgStockItems" Height="400px">
                    <Columns>
                        <tri:JQGridColumn HeaderText="Code" DataField="StockItemCode" DataType="System.String">
                        </tri:JQGridColumn>
                        <tri:JQGridColumn DataField="Description" DataType="System.String" HeaderText="Name">
                        </tri:JQGridColumn>
                        <tri:JQGridColumn DataField="SupplierPartNo" DataType="System.String" HeaderText="Supplier Part No">
                        </tri:JQGridColumn>
                        <tri:JQGridColumn DataField="ProductGroupDescription" DataType="System.String" HeaderText="Product Group">
                        </tri:JQGridColumn>
                        <tri:JQGridColumn DataField="BuyingUnitDescription" DataType="System.String" HeaderText="Buying Unit"
                            EditType="DropDown" Editable="True" >
                        </tri:JQGridColumn>
                        <tri:JQGridColumn DataField="UnitPrice" DataFormatString="{0:n2}" DataType="System.String"
                            HeaderText="Unit Price" TextAlign="Right" Editable="True">
                        </tri:JQGridColumn>
                        <tri:JQGridColumn DataField="Quantity" DataFormatString="{0:n2}" DataType="System.Decimal"
                            Editable="True" HeaderText="Quantity" TextAlign="Right" Width="100">
                        </tri:JQGridColumn>
                    </Columns>
                    <PagerSettings PageSize="100000" />
                    <ToolBarSettings ShowSearchToolBar="True">
                    </ToolBarSettings>
                    <EditInlineCellSettings Enabled="True" />
                </tri:JQGrid>

as you can see my buying unit description is the column which has a drop down edit control. I need to populate this per row as the options are differnet per row.
How can I do this with the asp.net version of the grid without setting the grid up in javascript. Surely this must be possible!?

A: ok worked it out.
if anyone wants the solution I wrote it here:
Load dropdowns dynamically


text:
Q: what is keyAlias="aaaa" in tomcat server.xml file I have SSL certificate purchased and installed into tomcat. I created tomcat.keystore file which I include in server.xml file also put password but not able to understand keyAlias="aaa". If I put keyAlias="localhost" then I get exception given below. And if I remove keyAlias itself from the Connector tag then I get another exception which is given below next localhost exception.
java.io.IOException: Alias name localhost does not identify a key entry
    at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeyManagers(JSSESocketFactory.java:588)
    at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeyManagers(JSSESocketFactory.java:526)
    at org.apache.tomcat.util.net.jsse.JSSESocketFactory.init(JSSESocketFactory.java:471)
    at org.apache.tomcat.util.net.jsse.JSSESocketFactory.createSocket(JSSESocketFactory.java:218)
    at org.apache.tomcat.util.net.JIoEndpoint.bind(JIoEndpoint.java:400)
    at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:649)

Here is exception after removing keyAlias itself from the Connector tag.
Aug 08, 2015 2:39:18 PM org.apache.catalina.core.StandardService initInternal
SEVERE: Failed to initialize connector [Connector[HTTP/1.1-443]]
org.apache.catalina.LifecycleException: Failed to initialize component [Connector[HTTP/1.1-443]]
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:106)
    at org.apache.catalina.core.StandardService.initInternal(StandardService.java:559)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
    at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:821)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
    at org.apache.catalina.startup.Catalina.load(Catalina.java:638)
    at org.apache.catalina.startup.Catalina.load(Catalina.java:663)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:280)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:454)
Caused by: org.apache.catalina.LifecycleException: Protocol handler initialization failed
    at org.apache.catalina.connector.Connector.initInternal(Connector.java:980)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
    ... 12 more
Caused by: java.net.BindException: Address already in use <null>:443
    at org.apache.tomcat.util.net.JIoEndpoint.bind(JIoEndpoint.java:413)
    at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:649)
    at org.apache.coyote.AbstractProtocol.init(AbstractProtocol.java:434)
    at org.apache.coyote.http11.AbstractHttp11JsseProtocol.init(AbstractHttp11JsseProtocol.java:119)
    at org.apache.catalina.connector.Connector.initInternal(Connector.java:978)
    ... 13 more
Caused by: java.net.BindException: Address already in use
    at java.net.PlainSocketImpl.socketBind(Native Method)
    at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:376)
    at java.net.ServerSocket.bind(ServerSocket.java:376)
    at java.net.ServerSocket.<init>(ServerSocket.java:237)
    at java.net.ServerSocket.<init>(ServerSocket.java:181)
    at javax.net.ssl.SSLServerSocket.<init>(SSLServerSocket.java:136)
    at sun.security.ssl.SSLServerSocketImpl.<init>(SSLServerSocketImpl.java:107)
    at sun.security.ssl.SSLServerSocketFactoryImpl.createServerSocket(SSLServerSocketFactoryImpl.java:84)
    at org.apache.tomcat.util.net.jsse.JSSESocketFactory.createSocket(JSSESocketFactory.java:219)
    at org.apache.tomcat.util.net.JIoEndpoint.bind(JIoEndpoint.java:400)
    ... 17 more

Following is the content of server.xml file.
<Connector port="443" SSLEnabled="true" protocol="org.apache.coyote.http11.Http11Protocol"
           maxThreads="150" scheme="https" secure="true"
           clientAuth="false" sslProtocol="TLS"
           keystoreFile="tomcat.keystore"
           keystorePass="test" keyAlias="aaa"/>

What is that keyAlias ? Why am I getting exception after removing it which is Binding exception ?

A: KEYALIAS:
https://www.digicert.com/ssl-certificate-installation-tomcat.htm`

*

*When you import your certificate into the keystore, you would typically give an "alias":
keytool -import -trustcacerts -alias server -file your_site_name.p7b -keystore your_site_name.jks

*In your server.xml, you must then declare the same "alias":
<Connector port="443" maxHttpHeaderSize="8192" maxThreads="150"
  minSpareThreads="25" maxSpareThreads="75" enableLookups="false"
  disableUploadTimeout="true" acceptCount="100" scheme="https"
  secure="true" SSLEnabled="true" clientAuth="false" sslProtocol="TLS"
  keyAlias="server" keystoreFile="/home/user_name/your_site_name.jks"
  keystorePass="your_keystore_password" />

*Here are some other links that might help:
https://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html
https://www.mulesoft.com/tcat/tomcat-ssl
https://wolfpaulus.com/jounal/mac/tomcat-ssl/
SECOND ISSUE, "CAN'T BIND":
As far as "address in use", I would simply try rebooting the server and see if Tomcat starts correctly.
If you encounter the error again,

*

*Look in your Tomcat settings to see which port you're trying to use (e.g. 443)

*Check your system to see who else is using the port (lsof, nmap, etc):
http://www.howtogeek.com/howto/28609/how-can-i-tell-what-is-listening-on-a-tcpip-port-in-windows/
https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/3/html/Security_Guide/s1-server-ports.html

A: These errors are not related.

*

*keyAlias is documented in the Tomcat documentation, and that is where you should look for its meaning.

*The error you have made is to not import the signed certificate with the same alias you used when generating the keypair. They must be the same so that they keytool will associate the keypair with the certificate and create a key entry instead of a certificate entry.

*The BindException means that some other process, probably a prior invocation of Tomcat that hasn't exited yet, is using the port. Or possibly you have configured two Connectors to use the same port. It only shows up as an error when you configure the SSL connector correctly.


text:
Q: JNI & Multi Threads I have a multi threaded JAVA app that uses a shared c lib. What will happen to this library if I'l access it from different threads?
Thanks,
Nahum

A: This absolutely depends on the C library. If the function does not store any state (e.g. just computes some result and only uses local variables on stack ) it will be safe to use it from multiple Threads. Otherwise you have to take care that the state ist stored separately for each thread, e.g. by using malloc and returning a handle for further calls, so that following calls will reuse the state in the malloced memory block.
If I dont know the internals of the code, I prefer building a small C application and calling it using Runtime.exec, but this is useful only if the C function is doing enough work to justify the exec overhead.


text:
Q: Draw on Google Map within Visualforce I'm wanting to be able to free-form draw on top of a map within a Salesforce page if possible. I believe this can be done but am having a hard time getting the code to work. Any help is appreciated.
    <apex:page standardStylesheets="false" >

</apex:page>


text:
Q: perl cannot compile with error of lazy symbol binding not found for _mysql_init I'm running mac OS X Snow Leopard and I recognize that this is a common problem.
I have installed and reinstalled both the 32- and 64-bit binary installations of MySQL.
That didn't work, so I went ahead and (against my common sense) installed perl5 through macports to have an entirely different perl than the version that ships with Snow Leopard.
I re-installed DBI and DBD::mysql modules into the new perl, both with success.
And yet still:
me$ perl5 processmail
dyld: lazy symbol binding failed: Symbol not found: _mysql_init
  Referenced from: /opt/local/lib/perl5/site_perl/5.8.9/darwin-      2level/auto/DBD/mysql/mysql.bundle
  Expected in: dynamic lookup

dyld: Symbol not found: _mysql_init
  Referenced from: /opt/local/lib/perl5/site_perl/5.8.9/darwin-2level/auto/DBD/mysql/mysql.bundle
  Expected in: dynamic lookup

I have also tried perl5 processmail --mysql_config=/usr/local/mysql/bin/mysql_config.
Thanks in advance

A: Do you get the same error running your perl script as root?
Does your shell environment possibly have VERSIONER_PERL_PREFER_32_BIT=no set?
there's more info about both of these at http://www.perlmonks.org/?node_id=793727

A: I just finally solved this on our box by getting rid of the default setting
defaults delete com.apple.versioner.perl
Suddenly it just works!  Whatever


text:
Q: Problema al intentar vaciar y cargar un DataGridView en C# estoy intentando cargar un DataGridView con un listado de socios que me llegan filtrados, pero al momento de cargar me cargar todos los socios mas los que filtro. No veo donde puede estar el error. El filtro lo aplica mientras se va escribiendo, para explicarme mejor: si ingreso fra me tiene que mostrar todos los socios, cuyo nombre inician con esas 3 letras, como Franco, Francisco, Franca, etc.
El codigo del textBox es el siguiente:
private void txt_filtro_nombre_TextChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrWhiteSpace(txt_filtro_nombre.Text))
            {
                cargarGrilla(svSocio.getSocioPorNombre(txt_filtro_nombre.Text));
            }
        }

El codigo de getSocioPorNombre(textbox) que me trae los datos es el siguiente:
public IList<DTO_Socio> getSocioPorNombre(string nombre)
        {
            IList<DTO_Socio> lista = new List<DTO_Socio>();
            IList<Socio> listaSocios = dao.getSociosPorNombre(nombre);
            foreach (Socio socio in listaSocios)
            {
                lista.Add(mapSocio.getDtoSocio(socio));
            }

            return lista;
        }

el cual se comunica con el DAO que me trae los datos desde la base de datos y tiene este codigo:
public IList<Socio> getSociosPorNombre(string nombre)
        {
            string sp = "listar_socios_por_nombre";
            var parametro = new SqlParameter("@nombre", nombre);
            parametro.SqlDbType = SqlDbType.VarChar;

            IList<Socio> listaSocios = getSocios();
            DataTable tabla = helper.consultarStoredProcedureConUnParametro(sp, parametro);
            foreach (DataRow fila in tabla.Rows)
            {
                listaSocios.Add(mapper(fila));
            }
            return listaSocios;
        }

El codigo del helper que se comunica con la base de datos:
public DataTable consultarStoredProcedureConUnParametro(string sp, SqlParameter parametro)
        {
            SqlConnection cnn = new SqlConnection();
            SqlCommand cmd = new SqlCommand();
            DataTable tabla = new DataTable();

            try
            {
                cnn.ConnectionString = string_conexion;
                cnn.Open();
                cmd.Connection = cnn;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = sp;
                cmd.Parameters.Add(parametro);
                tabla.Load(cmd.ExecuteReader());
                return tabla;
            }
            catch (SqlException ex)
            {
                MessageBox.Show("EXPLOTO EL HELPER", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw (ex);
            }
            finally
            {
                this.CloseConnection(cnn);
            }
        }

El codigo de cargarGrilla():
dgv_socios.Rows.Clear();
            if (lista != null)
            {
                foreach (DTO_Socio dto in lista)
                {
                    dgv_socios.Rows.Add(new Object[]
                            {
                                dto.NumeroSocio,
                                dto.Nombre,
                                dto.Apellido,
                                dto.Dni
                            }
                        );
                }
            }
            else
            {
                MessageBox.Show("No hay datos para mostrar", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

No logro ver donde esta el error, por el cual me trae todos los socios + los filtrados.
Les dejo una imagen de lo que digo

Ejecute el SP en la base de datos para ver si eso fallaba, pero funciona excelente

A: Franco, revisando el código que publicaste, hay una instrucción que llamó mi atención en el método getSociosPorNombre.
Se trata de la instrucción donde inicializas la variable listaSocios y aunque no publicaste el código del método getSocios(), por el nombre que tiene supongo que es el responsable de buscar todos los socios.
Esa variable debería ser inicializada con una lista vacía.
public IList<Socio> getSociosPorNombre(string nombre)
    {
        string sp = "listar_socios_por_nombre";
        var parametro = new SqlParameter("@nombre", nombre);
        parametro.SqlDbType = SqlDbType.VarChar;

    //    Sospecho que esta es la línea del problema
    //                              |
    //                              V
        IList<Socio> listaSocios = getSocios();

        DataTable tabla = helper.consultarStoredProcedureConUnParametro(sp, parametro);
        foreach (DataRow fila in tabla.Rows)
        {
            listaSocios.Add(mapper(fila));
        }
        return listaSocios;
    }


text:
Q: SQL query execution on WP7.1 SQL Server CE database I need to develop a function that takes a SQL query as input and execute this in phone database (SQL Server CE) and return result.
As far I know we can query SQL Server CE in wp7.1 only through LINQ. So is it possible to develop that kind of function?
Please help....

A: you can query SQL Server CE in wp7.1 only through LINQ.


text:
Q: print form on the full page instead of a part of it i want to print my form on the whole page but instead the picture looks like this :
http://i.stack.imgur.com/JSXh2.jpg
it looks very small that's why i need the form to be printed on the whole full page
here is my code :
private void button5_Click(object sender, EventArgs e)
    {
        CaptureScreen();
        printDocument1.Print();

    }

    private Bitmap _memoryImage;

    private void CaptureScreen()
    {
        // put into using construct because Graphics objects do not
        //  get automatically disposed when leaving method scope
        using (var myGraphics = CreateGraphics())
        {
            var s = Size;
            _memoryImage = new Bitmap(s.Width, s.Height, myGraphics);
            using (var memoryGraphics = Graphics.FromImage(_memoryImage))
            {
                memoryGraphics.CopyFromScreen(Location.X, Location.Y, 0, 0, s);
            }
        }
    }

    private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {

        var wScale = e.MarginBounds.Width / (float)_memoryImage.Width;
        var hScale = e.MarginBounds.Height / (float)_memoryImage.Height;

        // choose the smaller of the two scales
        var scale = wScale < hScale ? wScale : hScale;

        // apply scaling to the image
        e.Graphics.ScaleTransform(scale, scale);

        // print to default printer's page
        e.Graphics.DrawImage(_memoryImage, 0, 0);

    }

your help would be appreciated

A: try this to make a bitmap of your form:
Bitmap bm = new Bitmap(f1.Width, f1.Height);
this.DrawToBitmap(bm, new Rectangle(f1.Location, f1.Size));

maybe that's the problem! Report back if it works!
If you want to print it in landscape format than you have to rotate your bitmap using:
public Bitmap rotateInternalFunction(Bitmap bitmap)
{
    bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
    return bitmap;
}


text:
Q: How to track initial page views in next.js projects? I went through next.js example projects, especially how to integrate google analytics and facebook pixel.
Both integrations use routeChangeComplete event here and here. It triggers when user changes route and then page view event is sent to analytics tools.
routeChangeComplete event doesn't trigger on initial render (first user visit). It triggers only when user changes route (enters another route). I think Google Analytics and Facebook Pixel page view events should be sent on the first user's visit as well. How to do that correctly in next.js projects?

A: You can do it by creating a custom _app.jsx file. There you can track the initial visit by adding a useEffect hook with an empty dependency array so that the function will only fire on the initial render:
export default function MyApp({ Component, pageProps }) {
  React.useEffect(() => {
    // Track the initial view
  }, []);

  return <Component {...pageProps} />;
}


text:
Q: Spring - Call a Service method in JSTL I'm using Spring Security to handle user authentication for my Spring MVC web app. I'm able to get the username from the Authentication object, but my username is the email address, and I want to be able to show the user's actual name in my header.
So I have my custom User class:
class Users{

    String name;
    String email;
    String password;

    // getters and setters
}

I thought about using an aop scoped proxy to set the User in the session, as explained in this blog: http://richardchesterwood.blogspot.co.uk/2011/03/using-sessions-in-spring-mvc-including.html . The problem I faced using this approach is that the AuthenticationSuccessHandler is actually a Service and should be stateless. So Spring doesn't autowire a Users object for me in the Service.
So I created a Service method that would get the username (or email) from the Authentication object and return my Users object. This I can use in my Controllers.
@Service
@Transactional
public class UserServiceImpl implements UserService {

@Override
public Users getCurrentUser() {
     Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    User userD = (User)auth.getPrincipal();

    Users currentUser = getUserByEmail(userD.getUsername());

    return currentUser;
}

}

So is there a way that I can call this Service method from JSTL to get the user's full name, which I can display in my header?
Am also open to suggestions for a better way to implement this.
EDIT:
In my earlier approach using the AuthenticationSuccessHandler, my code goes like this:
@Service("userDetailsService")
@Transactional
public class UserAuthenticationServiceImpl implements AuthenticationSuccessHandler {

@Autowired
Users currentUser;

@Override
public void onAuthenticationSuccess(HttpServletRequest hsr, HttpServletResponse hsr1, Authentication a) throws IOException, ServletException {
    User user = (User) a.getPrincipal();

    Users user1 = userDao.getUserByEmail(user.getUsername());

    currentUser.setName(user1.getName());
    currentUser.setUserRoles(user1.getUserRoles());

    //currentUser = user1;

}

}

And in my spring-servlet.xml file, I have this:
<bean id="currentUser" class="com.foo.bean.Users" scope="session">
    <!-- this next element effects the proxying of the surrounding bean -->
    <aop:scoped-proxy/>
</bean>

The problem I'm facing here is that Spring isn't autowiring my currentUser object because the Service isn't in the session scope.

A: If the only thing you need is the full name just use an AuthenticationSuccessHandler to retrieve the user and add the name to the session (or the full user if you need more then that).
@Override
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication auth) throws IOException, ServletException {

    User user = (User) auth.getPrincipal();
    Users user1 = userDao.getUserByEmail(user.getUsername());
    WebUtils.setSessionAttribute(req, "currentUser" user1);
}

Then in your JSP the only thing you need is ${currentUser.username}.
Although I wouldn't suggest stuffing the full user in the session I would suggest just adding the information needed.
WebUtils.setSessionAttribute(req, "currentUsername" user1.getUsername());

Then in your JSP ${currentUsername} saves you a lot of serialization overhead of the session.


text:
Q: SpriteKit - Determine Side A Square Collided With So for the App I'm working on, I have two cubes colliding. I check for this in the standard way. The app tells me when they collide in my "didBeginContact" method.
-(void)didBeginContact:(SKPhysicsContact *)contact {
    if (contact.bodyA.categoryBitMask == WALL_CATEGORY && contact.bodyB.categoryBitMask == CHARACTER_CATEGORY) {
        CGPoint point = contact.contactPoint;
    }
}

So i know where the collision takes place, but because it is two squares it can be at any point along the side including the corners. So how would I check if the collision on the left/right/top/bottom exclusively?
Edit: Correct Answer: Might not be the cleanest way to do it but it works. Hopefully it'll help someone in the future.
m_lNode = [SKNode node];
m_lNode.position = CGPointMake(-(CHARACTER_SIZE / 2), 0);
m_lNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(1, m_character.size.height)];
m_lNode.physicsBody.allowsRotation = NO;
m_lNode.physicsBody.usesPreciseCollisionDetection = YES;
m_lNode.physicsBody.categoryBitMask = CHARACTER_L_CATEGORY;

m_rNode = [SKNode node];
m_rNode.position = CGPointMake((CHARACTER_SIZE / 2), 0);
m_rNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(1, m_character.size.height)];
m_rNode.physicsBody.allowsRotation = NO;
m_rNode.physicsBody.usesPreciseCollisionDetection = YES;
m_rNode.physicsBody.categoryBitMask = CHARACTER_R_CATEGORY;

m_tNode = [SKNode node];
m_tNode.position = CGPointMake(0, (CHARACTER_SIZE / 2));
m_tNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(m_character.size.width , 1)];
m_tNode.physicsBody.allowsRotation = NO;
m_tNode.physicsBody.usesPreciseCollisionDetection = YES;
m_tNode.physicsBody.categoryBitMask = CHARACTER_T_CATEGORY;

m_bNode = [SKNode node];
m_bNode.position = CGPointMake(0, -(CHARACTER_SIZE / 2));
m_bNode.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(m_character.size.width, 1)];
m_bNode.physicsBody.allowsRotation = NO;
m_bNode.physicsBody.usesPreciseCollisionDetection = YES;
m_bNode.physicsBody.categoryBitMask = CHARACTER_B_CATEGORY;

[m_character addChild:m_tNode];
[m_character addChild:m_bNode];
[m_character addChild:m_lNode];
[m_character addChild:m_rNode];

-(void)didBeginContact:(SKPhysicsContact *)contact {
    if (contact.bodyA.categoryBitMask == WALL_CATEGORY) {
        switch (contact.bodyB.categoryBitMask) {
            case CHARACTER_T_CATEGORY:
                NSLog(@"Top");
                m_isHitTop = true;
                break;
            case CHARACTER_B_CATEGORY:
                NSLog(@"Bottom");
                m_isHitBottom = true;
                break;
            case CHARACTER_L_CATEGORY:
                NSLog(@"Left");
                m_isHitLeft = true;
                break;
            case CHARACTER_R_CATEGORY:
                NSLog(@"Right");
                m_isHitRight = true;
                break;
        }
    }
}

Added some relevant code. It's my code so there is variables amongst other things but you should be able to figure it out.

A: I think the best way to determine what side is involved in your contact (top,left,bottom,right side) is to:

*

*calculate the points leaved by a centering cross for up, down, left and right sides (for example if you have a squared sprite..)

let halfWidth = self.frame.width/2
let halfHeight = self.frame.height/2
let down = CGPointMake(self.frame.origin.x+halfWidth,self.frame.origin.y)
let up = CGPointMake(self.frame.origin.x+halfWidth,self.frame.origin.y+self.frame.size.height)
let left = CGPointMake(self.frame.origin.x,self.frame.origin.y+halfHeight)
let right = CGPointMake(self.frame.origin.x+self.frame.size.width,self.frame.origin.y+halfHeight)

*

*Calculate the distance between the contactPoint and each point sides (up, left , right and down)

This step can be possible with this little function:
func getDistance(p1:CGPoint,p2:CGPoint)->CGFloat {
    let xDist = (p2.x - p1.x)
    let yDist = (p2.y - p1.y)
    return CGFloat(sqrt((xDist * xDist) + (yDist * yDist)))
}

After, the point involved with the lowest distance calculated is the side point nearest the contactPoint.
What are the advantages of this method:

*

*You don't paint zombies or ghost nodes and relative physic bodies

*This method work also inside a dynamic mutable CGPath, not only with a
knowed rectangular boundaries

*Is fast, few lines of code and if you add other few lines you can be
able to determine also diagonals and make more precise your
algorithm.

A: the easiest way is to add child sprites the top, left, right, bottom of your squares.  Add physics bodies to those, and then you can tell where things are colliding.  I'd recommend trying this method first unless you have many many squares on the screen.
If you have a ton of squares on the screen and youre worried about performance.  then maybe use contact.contactPoint and convert that point to square coordinates.  given the center point of the square, the angle of the squares rotation and that point, you should be able to tell where the square collided.  That would require some math.. and I was afraid writing up that kind of solution when the first one may be all that you really need.


text:
Q: Meta Query Filtering not working on Custom Meta Box using Radio Buttons I have a custom post type called "bids".
I'm trying to get the loop to filter posts according to a meta_query.
The query should allow for only posts that have the radio button with the value "open" checked.
The meta boxes show up properly in the admin and save, but the filtering is not working.
Anyone know where I went wrong? I suspect it's somewhere in the 2nd section...
/****** CUSTOME POST-TYPE ******/

<?php

// CREATE CUSTOME META BOX
function r_create_mb_bids(){
    add_meta_box(
        'r_bid_visibility_mb',
        __( ' Bid Visibility', 'bids' ),
        'r_bid_visibility_mb',
        'bids',
        'normal',
        'high'
    );
}
add_action( 'add_meta_boxes', 'r_create_mb_bids' );

// DISPLAY IN ADMIN
function r_bid_visibility_mb( $post ){
    $bid_data            =   get_post_meta( $post->ID, 'bid_data', true );

    if( empty($bid_data) ){
        $bid_data =   array(
        'bid_vis'   =>  '',
        );
    }

    ?>

    Bid Visibility
    <input type='radio' name='r_inputVis' value='open' <?php checked( $bid_data["bid_vis"], 'open' ); ?> /> Open
    <input type='radio' name='r_inputVis' value='secure' <?php checked( $bid_data["bid_vis"], 'secure' ); ?> /> Secure

    <?php
}

add_action( 'save_post_bids', 'r_save_post_admin_bids', 10, 3 );

// SAVE META DATA
function r_save_post_admin_bids( $post_id, $post, $update ){
    if( !$update ){
    return;
    }

    $bid_data    =   array();
    $bid_data['bid_vis']    =   sanitize_text_field( $_POST[ 'r_inputVis' ]);

    update_post_meta( $post_id, 'bid_data', $bid_data );
}

?>

/****** PAGE TEMPLATE ******/

<?php

// THE LOOP
$args = array(
    'post_type'  => 'bids',
    'posts_per_page' => -1,
    'meta_query' => array(
    array(
        'key'   =>  'r_inputVis',
        'value'   => 'open'
    ),
    ),
);

$query = new WP_Query( $args ); while ( $query->have_posts() ) : $query->the_post();

?>

[ ... ]

<?php endwhile; ?>

A: I think I found another way. Seems to be working great.
/****** CUSTOME POST-TYPE ******/

<?php

// CREATE CUSTOME META BOX
function r_create_mb_bids(){
    add_meta_box(
        'r_bid_visibility_mb',
        __( ' Bid Visibility', 'bids' ),
        'r_bid_visibility_mb',
        'bids',
        'normal',
        'high'
    );
}
add_action( 'add_meta_boxes', 'r_create_mb_bids' );

// DISPLAY IN ADMIN
function r_bid_visibility_mb( $post ){
  global $post;
  $bid_data = get_post_custom($post->ID);
  $visibility = $bid_data['visibility'][0];
 ?>

  <?php $visibility_value = get_post_meta($post->ID, 'visibility', true);
      $visibility_checked = 'checked="checked"';
  ?>
    <input type='radio' name='visibility' value='yes' <?php if($visibility_value =='yes'){ echo $visibility_checked; }  ?>/> Open
    <input type='radio' name='visibility' value='no' <?php if($visibility_value =='no'){ echo $visibility_checked; }  ?>/> Secure
    <?php
}

// SAVE META DATA
add_action('save_post', 'save_details_visibility');

function save_details_visibility(){
  global $post;

if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
    return $post->ID;
}

  update_post_meta($post->ID, 'visibility', $_POST['visibility']);
}

?>

/****** PAGE TEMPLATE ******/

<?php

// THE LOOP
    $args = array(
        'post_type'  => 'bids',
        'posts_per_page' => -1,
        'meta_query' => array(
            array ( 'key' => 'visibility', 'value' => 'yes', )
        )
    );

    $query = new WP_Query( $args ); while ( $query->have_posts() ) : $query->the_post();

?>

[ ... ]

<?php endwhile; ?>

?>


text:
Q: PHP Adjacency Data to Nested Array I am having array as follows:
Array
(
    [0] => Array
        (
            [question_id] => 1
            [question_title] => Q1
            [child_question_id] => NULL
        )

    [1] => Array
        (
            [question_id] => 2
            [question_title] => Q2
            [child_question_id] => NULL
        )

    [2] => Array
        (
            [question_id] => 3
            [question_title] => Q3
            [child_question_id] => 4
        )

    [3] => Array
        (
            [question_id] => 3
            [question_title] => Q3
            [child_question_id] => 5
        )

    [4] => Array
        (
            [question_id] => 4
            [question_title] => Q4
            [child_question_id] => NULL
        )

    [5] => Array
        (
            [question_id] => 5
            [question_title] => Q5
            [child_question_id] => NULL
        )

    [6] => Array
        (
            [question_id] => 6
            [question_title] => Q6
            [child_question_id] => NULL
        )

    [7] => Array
        (
            [question_id] => 7
            [question_title] => Q7
            [child_question_id] => 6
        )

)

And using PHP I am expecting result as:
Array
(
    [0] => Array
        (
            [question_id] => 1
            [question_title] => Q1
            [child_question_id] => NULL
        )

    [1] => Array
        (
            [question_id] => 2
            [question_title] => Q2
            [child_question_id] => NULL
        )

    [2] => Array
        (
            [question_id] => 3
            [question_title] => Q3
            [children] => array(
               [0] => Array
               (
                  [question_id] => 4
                  [question_title] => Q4
               )

              [1] => Array
              (
                  [question_id] => 5
                  [question_title] => Q5
               )

              )
        )

    [3] => Array
        (
            [question_id] => 7
            [question_title] => Q7
            [children] => array(
              [0] => Array
               (
                    [question_id] => 6
                    [question_title] => Q6
               )
              )
        )

)

I tried to build final array using following logic:

*

*Traversing array to collect child ids and child data

*Traversing array again and match items child id with child array
formed earlier, if found then create children array

Could you please help me out to create better solution?

A: Did you mean something like that?
$i = 0;
$new = array();
$unsetter = array();
foreach($array as $val)
{
    $new[$i] = array();
    foreach($val as $key => $data)
    {
        if(($key == 'child_question_id') && (!is_null($data)))
        {
            $new[$i]['children'] = array();
            $new[$i]['children']['question_id'] = $data;
            $new[$i]['children']['question_title'] = $array[$data]['question_title'];
            $unsetter[] = $data;

        } else {
            $new[$i][$key] = $data;
        }
    }
    $i++;
}
foreach($unsetter as $uns)
{
        unset($new[$uns]);
}
$new = array_values($new);
var_dump($new);

This will output
array (size=5)
  0 =>
    array (size=3)
      'question_id' => int 1
      'question_title' => string 'Q1' (length=2)
      'child_question_id' => null
  1 =>
    array (size=3)
      'question_id' => int 2
      'question_title' => string 'Q2' (length=2)
      'child_question_id' => null
  2 =>
    array (size=3)
      'question_id' => int 3
      'question_title' => string 'Q3' (length=2)
      'children' =>
        array (size=2)
          'question_id' => int 4
          'question_title' => string 'Q4' (length=2)
  3 =>
    array (size=3)
      'question_id' => int 3
      'question_title' => string 'Q3' (length=2)
      'children' =>
        array (size=2)
          'question_id' => int 5
          'question_title' => string 'Q5' (length=2)
  4 =>
    array (size=3)
      'question_id' => int 7
      'question_title' => string 'Q7' (length=2)
      'children' =>
        array (size=2)
          'question_id' => int 6
          'question_title' => string 'Q6' (length=2)

Live Demo


text:
Q: C - Proper reuse of code / methods between files I'm a C beginner with average Java Skills and I'm not sure how to reuse C code between files properly.
Let's say I have two files / modules: server.c and client.c
They are not linked (with GCC) and should run in separate processes.
There are two methods in server.c that I want to use in client.c. Those methods use global, static (const) variables in the same module. Basically I want the same functionally as when I would copy them into the other file.
Small example:
server.c
static const char *progname = "server";

static int sockfd = -1;
static int connfd = -1;

static void free_resources(void)
{
    if (sockfd >= 0) {
        (void) close(sockfd);
    }

    if (connfd >= 0) {
        (void) close(connfd);
    }
}

client.c
static const char *progname = "client";

static int sockfd = -1;
static int connfd = -1;

// I want to use free_resources here

If I want to use the same method in client.c, what would be the right way to do it?
If I create a separate util.c / util.h module with the method, how do I access the global variables? Should I pass them as arguments every time? Remove static?
In Java I would probably create a class and pass the (reference to the) global variables once. Is there a similar approach in C?

A:
In Java I would probably create a class...

The equivalent in C is to create a structure, and pass a pointer to the structure to any functions that need access to the variables. The structure declaration should be in utils.h, e.g.
typedef struct
{
    char *progname;
    int sockfd;
    int connfd;
}
Info;

void free_resources( Info *info );

Create and initialize the structure in server.c and client.c, and then pass the address to the common functions, e.g.
Info server_info = { "server", -1, -1 };

int main( void )
{
    // ...

    free_resources( &server_info );
}

Then the code in utils.c looks like this.  (Note that you can't use the static keyword, since the function must be callable from outside utils.c)
void free_resources( Info *info )
{
    if (info->sockfd >= 0) {
        (void) close(info->sockfd);
    }

    if (info->connfd >= 0) {
        (void) close(info->connfd);
    }
}


text:
Q: numpy.load from io.BytesIO stream I have numpy arrays saved in Azure Blob Storage, and I'm loading them to a stream like this:
stream = io.BytesIO()
store.get_blob_to_stream(container, 'cat.npy', stream)

I know from stream.getvalue() that the stream contains the metadata to reconstruct the array. This is the first 150 bytes:
b"\x93NUMPY\x01\x00v\x00{'descr': '|u1', 'fortran_order': False, 'shape': (720, 1280, 3), }                                                  \n\xc1\xb0\x94\xc2\xb1\x95\xc3\xb2\x96\xc4\xb3\x97\xc5\xb4\x98\xc6\xb5\x99\xc7\xb6\x9a\xc7"

Is it possible to load the bytes stream with numpy.load or by some other simple method?
I could instead save the array to disk and load it from disk, but I'd like to avoid that for several reasons...
EDIT: just to emphasize, the output would need to be a numpy array with the shape and dtype specified in the 128 first bytes of the stream.

A: I tried to use several ways to realize your needs.
Here is my sample codes.
from azure.storage.blob.baseblobservice import BaseBlobService
import numpy as np

account_name = '<your account name>'
account_key = '<your account key>'
container_name = '<your container name>'
blob_name = '<your blob name>'

blob_service = BaseBlobService(
    account_name=account_name,
    account_key=account_key
)

Sample 1. To generate a blob url with sas token to get the content via requests
from azure.storage.blob import BlobPermissions
from datetime import datetime, timedelta
import requests

sas_token = blob_service.generate_blob_shared_access_signature(container_name, blob_name, permission=BlobPermissions.READ, expiry=datetime.utcnow() + timedelta(hours=1))
print(sas_token)
url_with_sas = blob_service.make_blob_url(container_name, blob_name, sas_token=sas_token)
print(url_with_sas)

r = requests.get(url_with_sas)
dat = np.frombuffer(r.content)
print('from requests', dat)

Sample 2. To download the content of blob into memory via BytesIO
import io
stream = io.BytesIO()
blob_service.get_blob_to_stream(container_name, blob_name, stream)
dat = np.frombuffer(stream.getbuffer())
print('from BytesIO', dat)

Sample 3. Use numpy.fromfile with DataSource to open a blob url with sas token, it will actually download blob file into local filesystem.
ds = np.DataSource()
# ds = np.DataSource(None)  # use with temporary file
# ds = np.DataSource(path) # use with path like `data/`
f = ds.open(url_with_sas)
dat = np.fromfile(f)
print('from DataSource', dat)

I think Samples 1 & 2 are better for you.

A: When it comes to np.savez the above solution normally want work.
Upload to storage:
import io
import numpy as np

stream = io.BytesIO()
arr1 = np.random.rand(20,4)
arr2 = np.random.rand(20,4)
np.savez(stream, A=arr1, B=arr2)
block_blob_service.create_blob_from_bytes(container,
                                          "my/path.npz",
                                          stream.getvalue())

Download from storage:
from numpy.lib.npyio import NpzFile

stream = io.BytesIO()
block_blob_service.get_blob_to_stream(container, "my/path.npz", stream)

ret = NpzFile(stream, own_fid=True, allow_pickle=True)
print(ret.files)
""" ['A', 'B'] """
print(ret['A'].shape)
""" (20, 4) """

A: This is a bit of a hacky way I came up with, which basically just gets the metadata from the first 128 bytes:
def load_npy_from_stream(stream_):
    """Experimental, may not work!

    :param stream_: io.BytesIO() object obtained by e.g. calling BlockBlobService().get_blob_to_stream() containing
        the binary stream of a standard format .npy file.
    :return: numpy.ndarray
    """
    stream_.seek(0)
    prefix_ = stream_.read(128)  # first 128 bytes seem to be the metadata
    dict_string = re.search('\{(.*?)\}', prefix_[1:].decode())[0]
    metadata_dict = eval(dict_string)

    array = np.frombuffer(stream_.read(), dtype=metadata_dict['descr']).reshape(metadata_dict['shape'])

    return array

Could fail in numerous ways, but I'm posting it here if anyone wants to give it a shot. I'll be running tests with this and will get back as I know more.

A: A little late but in case anyone wants to do this using numpy.load, here's the code (Azure SDK v12.8.1):
from azure.storage.blob import BlobServiceClient
import io
import numpy as np

# define your connection parameters
connect_str = ''
container_name = ''
blob_name = ''

blob_service_client = BlobServiceClient.from_connection_string(connect_str)

blob_client = blob_service_client.get_blob_client(container=container_name,
                                                  blob=blob_name)

# Get StorageStreamDownloader
blob_stream = blob_client.download_blob()
stream = io.BytesIO()
blob_stream.download_to_stream(stream)
stream.seek(0)

# Load form io.BytesIO object
data = np.load(stream, allow_pickle=False)

print(data.shape)


text:
Q: Efficient generation of infrasound It seems that the most common sources of infrasound are earthquake, tsunami, volcano eruption, etc, which are all large scale behaviors.
Why is it difficult for a human to generate infrasound?
Is it because that the infrasound has long wavelength, which is much bigger than the size of a human? Presumably, any action can generate some infrasound. The problem is just that the low frequency component is negligibly small, right?

A: To efficiently radiate sound waves from a vibrating source in air, the physical dimensions of the radiator should be approximately the same length as the wavelength of the sound wave. So, for example, a 1000Hz source (having a wavelength of about one foot) is well-coupled to air if the source is about a foot across, as it would be for a loudspeaker of 12" diameter.
A 100Hz sound source should ideally be ten feet across, and a 10Hz source would need to be 100 feet across to radiate well. You can see that ultralow sound frequencies require gigantic radiators, which is why it's hard to build radiators that function with reasonable efficiency in that range.


text:
Q: How to get objectId on Parse.com android It is said that we can retrieve our data if we are having objectId for that particular row, but it is auto generated and we cant insert it while setting data , so how to get data if i am not having object id , or any other means so that i can set objectId on my means.
Code is here as in comment:
ParseObject gameScore = new ParseObject("My Parse File");
String objectId = gameScore.getObjectId();

A: ObjectId doesnt't exist until a save operation is completed.
ParseObject gameScore = new ParseObject("My Parse File");

To retrieve the object id you need to save the object and register for the save callback.
gameScore.saveInBackground(new SaveCallback <ParseObject>() {
  public void done(ParseException e) {
    if (e == null) {
      // Success!
       String objectId = gameScore.getObjectId();

    } else {
      // Failure!
    }
  }
});

ObjectId can be retrieved from the original ParseObject(gameScore) once the done save callback is fired.

A: You can use this for getting current user object id
ParseUser pUser= ParseUser.getCurrentUser();
String objId= pUser.getObjectId();

A: not sure if this will apply to android , but I was trying to retreive the objectid, but for an entry that is already created. I did something like this and it worked.
ParseObject gameScore = new ParseObject("My Parse File");
var obId = gameScore.id;

Got it from the Javascript docs on Parse.com

The three special values are provided as properties:

var objectId = gameScore.id;

var updatedAt = gameScore.updatedAt;

var createdAt = gameScore.createdAt;

A: You can't unfortunately use the ObjectId until the object's been saved. I'm having this same problem now. The only solution I can think of, and posted a similar question relating to it here
My solution would be to make a tempId on the object and refer to that locally until it has an actual ObjectId, perhaps using a saveInBackground or saveEventually() callback to set other objects relating to it, to it's newly created ObjectId instead of it's old temp one.. when it's made available

A: It takes times for your values to be stored in table. Use this to get ObjectId
gameScore.saveInBackground(new SaveCallback() {
    public void done(ParseException e) {
        if (e == null) {
            // Saved successfully.
            Log.d("main", "User update saved!");
            Log.d("main", "ObjectId "+gameScore.getObjectId());

        } else {
            // The save failed.
            Log.d("main", "User update error: " + e);
        }
    }
});

A: In case you're handling the thread yourself:
First save:
gameScore.save();

Then you'll be able to access the id:
String parseId = gameScore.getObjectId();


text:
Q: How to properly present a popup view in SwiftUI (not as a sheet)? I would want to present a popup Slider in my iOS app. I'm currently using overlay like so:
.overlay(
    HStack {
        if isEditingValue {
            Slider(value: $valueToEdit)
                .offset(y: 90)
        }
    }
)

The problem is that any content after the view with the .overlay, will be drawn on top of the slider, that has been moved down with .offset so as not to obscure the value to be edited.
How can I get the popup Slider to be presented above all other content in correct relation to the view it will edit? I'm currently hiding all content below the value to be edited when the popup Slider is visible, which is not optimal.

A: Within one view hierarchy this can be solved by zIndex, like
TargetView()
.overlay(
    HStack {
        if isEditingValue {
            Slider(value: $valueToEdit)
                .offset(y: 90)
        }
    }
)
.zIndex(1) // default is 0, so others will be below
//.zIndex(isEditingValue ? 1 : 0)    // as variant

// ... other sibling views

if view hierarchy is complex, then view with slider might be overlapped with view from different view hierarchy, and such case cannot be solved just by layout modifiers and needs to be solved at global level of your app UI design.


text:
Q: Steam api. Принять предложение обмена Здравствуйте. Подскажите, пожалуйста, как принять предложение обмена программно ?
Все чего я смог достичь, так это найти активные предложение и вытащить их id. Но как можно реализовать принятие этих предложений ? Знаю что это возможно, очень много сайтов с такой системой, но, к сожалению, информации об этом нигде абсолютно нету. Может кто-то помочь ?
P.S. Делаю приложение для  Google Chrome, так что про авторизацию думать не нужно.

A: Собсна принять их можно простым Post-запросом на https://steamcommunity.com/tradeoffer/"tradeId"/accept где tradeId - собственно, ID оффера.
В шапке отправки нужно указать:
{"sessionid", ...},
{"serverid", ...},
{"tradeofferid", ...},
{"partner", ...},
{"captcha", ...}

Первые два параметра должны храниться в контейнере, который собирается при авторизации. Третий и четвертый параметры, будут получены через IEconService, а Капча, по умолчанию, string.empty


text:
Q: Object garbage collection after reference's scope expires Firstly let me say I am aware that System.gc() is more of a suggestion to collect garbage than a command, and that collection is not guaranteed to finish, start, or collect a specific object. And yet...
With the following code , the a1 instance only gets collected if I explicitly put null in the reference. If a1 simply goes out of scope, it does not get collected.
class A {
    @Override
    protected void finalize() throws Throwable {
        System.out.println("Collecting A");
    }
}
public class Example {
    public static void main(String[] args) throws InterruptedException {
        try {
            A a1 = new A();
            //a1 = null; // a1 gets collected only if I uncomment this line
        }
        finally {
            System.out.println("Finally executed");
        }
        System.gc();
        Thread.sleep(1000);
    }
}

Why does a1 not get collected if it simply goes out of scope, when there are no strong references to it ? Is it because this scope does not constitute a separate stack frame?

A: It's totally up to the JVM to decide when a1 gets collected or whether the finalizer runs.
For instance, a JVM might decide to run this in an interpreter which simply has a local variable table that holds every local variable in the method - similarly to how this works in the byte code - and variables don't really go 'out of scope' from the GC's perspective until the method exits.
But, for instance, a JIT compiler could be more aggressive with limiting the GC scope of locals (or rather, it simply doesn't keep track of what it doesn't need to). So, if you for instance run the program with -Xcomp (on the HotSpot JVM) which forces this code to be JIT compiled, you might (or might not) see the output:
Finally executed
Collecting A

Without setting a1 to null explicitly.
On the other hand, if you were to run this with Epsilon GC (which is a no-op GC) using the VM options: -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC (again on HotSpot), you might not see Collecting A in the output at all, even if you explicitly set a1 to null.
So, yeah, it's really up to the VM.


text:
Q: How to programmatically set WCF client maxBufferSize parameters? I am setting wcf client parameters programmatically like below:
try
{
ServiceReference1.MyDbServiceClient webService =
    new ServiceReference1.MyDbServiceClient(new System.ServiceModel.BasicHttpBinding(),
    new System.ServiceModel.EndpointAddress((string)((App)Application.Current).Resources["wcfMyDBServiceEndPoint"]));

    webService.GetSeriesImagesCompleted += new EventHandler<ServiceReference1.GetSeriesImagesCompletedEventArgs>(webService_GetSeriesImagesCompleted);
    webService.GetSeriesImagesAsync(index);
}

It works just fine for the default maxBufferSize.  However when a client exceeds the default size, an exception is throughn: "the maximum message size quota for incoming messages (65536) has been exceeded."
How to set this parameter in code?
Thanks.

A: BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.CloseTimeout = new TimeSpan(00, 05, 00);
binding.OpenTimeout = new TimeSpan(00, 05, 00);
binding.ReceiveTimeout = new TimeSpan(00, 05, 00);
binding.SendTimeout = new TimeSpan(00, 05, 00);
binding.TextEncoding = System.Text.Encoding.UTF8;
binding.MaxReceivedMessageSize = int.MaxValue;
binding.MaxBufferSize = int.MaxValue;

binding.GetType().GetProperty("ReaderQuotas").SetValue(binding, XmlDictionaryReaderQuotas.Max, null);

Create binding based on your requirement.


text:
Q: How to calculate RSI in Javascript with two series inputs I am looking to manually calculate RSI in JS using an upwards and downwards movement arrays
let upArr = [*upwards movement data series]

let downArr = [*downwards movement data series]

In order to achieve something like this
let rsi = 100 - 100 / (1 + upArr / downArr)

EDIT
Solution I ended up using,
var rsi1 = upArr.map((a, i) => a / downArr[i]);

var rsi2 = rsi1.map((a, i) => a + 1);

var rsi3 = rsi2.map((a, i) => 100 / a);

var rsi = rsi3.map((a, i) => 100 - a);


text:
Q: load of an outlet I have an incubator with an internal outlet that, according to the manual, "can provide a maximum of 1A". I'm trying to understand if this actually means that the maximum load is 120Vx1A=120W? In other words, is the limit set by the power or by the current? I ask because I would like to connect a shaker to the incubator's internal outlet, and the label on the back of the shaker says "19V, 4.74A", i.e. its load is 19Vx4.74A=90W. Will the internal outlet support the shaker?

A: Read more of the label on the power supply
The power brick for my laptop says how much input current it needs, yours should too. That is the number that will determine if that outlet is suitable.
The power supply brick for my laptop says "input 120-240V 1.3A" so this power brick would not be suitable (this is a 45W power supply: 20V, 2.25A), so based on that it's not looking good for your 90W power supply being compatible with that outlet.
You my need to ask the vendor to read the details on the power supply.
this page seems to have their contact info
https://www.boekelsci.com/contact/general-info.html/

A:
I have an incubator with an internal outlet that, according to the manual, "can provide a maximum of 1A". I'm trying to understand if this actually means that the maximum load is 120Vx1A=120W? In other words, is the limit set by the power or by the current?

You should check how it is wired inside the device, but... usually this means the outlet is controlled by a switch (in the case of an incubator, probably a thermostat) and the switch is rated for a 1 Amp current. Either that, or they used very thin wires for cost.

I would like to connect a shaker to the incubator's internal outlet, and the label on the back of the shaker says "19V, 4.74A",

So your shaker is powered by a 19V power supply which probably looks like a laptop brick. You have to use the power supply of course, you can't connect a 19V device to a 120V outlet, but you know that already.
Check the INPUT current rating on the power brick label. Something like "xxx mA 120V". This will probably be less than 1A, so it'll be OK. The output current rating like "19V 5A" does not concern the mains side of the adapter.
Since these supplies tend to draw a very large inrush current when plugged in, due to capacitor charging, I'd recommend checking if the incubator internal outlet goes through a switch or a thermostat. If it does go through a thermostat rated for a low current, like a few amps, I'd rather avoid having it switch the 19V power brick, as the thermostat contacts could be harmed by repeatedly switching a load with high inrush current.
If the internal outlet is only switched on/off by a manual switch on the incubator, then this won't be a problem as the manual switch won't be operated very often. Contacts only wear when they switch on/off.

A: The real key here is that IF the outlet provides 120 V power (you didn't say one way or the other), and the shaker requires 19 V.  You will damage or destroy the shaker if you plug it into a 120 V outlet.
What kind of plug does the shaker have on it's power cord?  I would be surprised if it's a standard 3-prong plug that's intended for 120 V use.

A: The circuit capacity is 1 amp x your line voltage, in VA
So if your line voltage is 120V, the socket supports 120 VA.
Watts is (roughly) the part of the sinewave the appliance uses, but it doesn't tell the whole picture about the thermal heating that occurs in the supply wires.
Look at the thing that has an AC power plug
Your shaker doesn't plug into a 120V outlet, so its nameplate is irrelevant. It plugs into a wall-wart or power brick; its nameplate is relevant.
If you don't agree with or believe the nameplate, you can get a tester like a Kill-a-Watt and actually measure the VA of the appliance at its most extreme operating mode, and go with that figure instead.  That accounts for thngs like PCs with 850 watt power supplies that actually only have Intel on-board video instead of the dual 980s and six hard drives the power supply is sized for.


text:
Q: Getting the cheapest prices in Google's qpx-express API I'm sending the following request to https://www.googleapis.com/qpxExpress/v1/trips/search?key=[mykey]
{
    "request": {
        "passengers": {
            "adultCount": 1
        },
        "slice": [{
            "origin": "JFK",
            "destination": "PDX",
            "date": "2017-04-21",
            "maxStops": 20
        }],
        "solutions": 500
    }
}

I get a valid response.  However, the cheapest price I see in the response is consistently a great deal higher than that which Google's GUI delivers:
Cheapest price in JSON response:

*

*response.trips.tripOption[0].saleTotal

*Cheapest price: "USD421.80"

Cheapest price in Google's app:

*

*https://www.google.com/flights/#search;f=JFK;t=PDX;d=2017-04-21;r=2017-04-25;tt=o

*https://screencast.com/t/r9A4cZTjE64

*Cheapest price: $230

Can anyone spot a way I could improve my request body, in order to acquire the cheaper options?  It may just be that Google doesn't surface all options in their API, but this seems a bit strange to me.
Thanks in advance for your input!

A: You need to access the saleTotal in this location:
dat['trips']['tripOption'][0]['pricing'][0]['saleTotal']

Hope it helps


text:
Q: QGIS virtual layers and slow performance I am using QGIS to create a layer comprised of counties in 7 northeast US states.
I start with the US census 5M cartographic state borders file, and then set a filter on that layer:
"NAME" in (
  'New York',
  'Massachusetts',
  'Rhode Island',
  'Connecticut',
  'New Hampshire',
  'Vermont',
  'Maine'
)

That gives me a layer with seven features. I wanted to take the US census 5M cartographic county borders file and restrict that to the same geographic area. I thought I could do it by setting up a virtual layer and setting up a spatial join, like this:
select a.*
  from cb_2018_us_county_5m as a
  join cb_2018_us_state_5m as b
  on (st_contains(b.geometry, a.geometry))

That works, but it takes 5 or 6 seconds to render the county outlines; I can watch as they show up one by one. Given the relatively small number of features involved in this operation, I was surprised by the performance. Am I doing something suboptimal? The same query in, say, PostGIS is a sub-second operation.

A: For attributes join, I found that you can improve speed by first ordering the layers on the join attribute. Not sure if it would work on spatial joins too.
As an example, joining two delimited-text datasources (using the ogr driver) of 500 and 1000 entities respectively was taking roughly 10 seconds :
 SELECT
     *
 FROM
     a
 JOIN
     b
 ON
     a.foo = b.foo

Using ordered subqueries, the same join takes a few milleseconds :
 SELECT
     *
 FROM
     (SELECT * FROM a ORDER BY foo) a
 JOIN
     (SELECT * FROM b ORDER BY foo) b
 ON
     a.foo = b.foo

Since virtual layers are backed by Sqlite, I think that using the order by clause in the subqueries somehow gives hints to the Sqlite engine which can optimize the query plan and avoid scanning as many times as the number of lines in the datasources to perform the join (I'm not a Sqlite expert though).


text:
Q: What's the best way to perform an UPDATE/FROM but using Pandas DataFrames? I have a Stored Procedure in my database that collects a bunch of data from several tables into a single temporary table and then updates my main fact table given the data in the temporary table. It's something similar to this:
CREATE temporary TABLE temp_flat_bom AS
SELECT   source_id,
         cpn,
         cm_odm,
         period_start,
         Sum(To_num(product_actual)  * To_num(component_usage)) AS actual,
         Sum(To_num(product_forecast) * To_num(component_usage)) AS forecast
FROM     flat_bom
WHERE    source_id = v_source_id
AND      deactivated_date IS NULL
GROUP BY source_id,
         cpn,
         cm_odm,
         period_start;

UPDATE materials spd
SET    forecast_dependent_demand = fb.forecast,
       actual_dependent_demand = fb.actual,
       updated_by='airflow',
from   temp_flat_bom fb
WHERE  fb.period_start = spd.period_start
AND    spd.deactivated_date IS NULL;

Of course, this is a straightforward example to illustrate this scenario. And what I'm trying to achieve is to perform this same operation but using Pandas Dataframes.
My first approach is to create a dataframe for the temporary table, another for the main fact table and merge them. Then, deactivate old records from the main fact table and insert this newly merged dataframe into the table.
Can anyone provide me with guidance?


text:
Q: File uploaded with Google Apps corrupted I implemented the tutorial from Google Apps Script documentation. However, the uploaded file is corrupted. I suspect it might be encoded, but I didn't figure out how. Any ideas?
Here it is for reference:
Code.js:
function doGet() {
  return HtmlService.createHtmlOutputFromFile('Index');
}

function processForm(formObject) {
  var formBlob = formObject.myFile;
  var driveFile = DriveApp.createFile(formBlob);
  return driveFile.getUrl();
}

index.html
<!DOCTYPE html>

    <base target="_top">

    <form id="myForm" onsubmit="handleFormSubmit(this)">
      <input name="myFile" type="file" />
      <input type="submit" value="Submit" />
    </form>


text:
Q: In Powershell, how do you build an array of table objects instead of an array of table names? Building an array of table that match a list of table names, and then generate a script to build those tables:
$tablelist = @( 'TableBlah', 'TableWidget')

#populate Tableset with tables that match the names in the array

ForEach ($item in $tablelist)
  { $tableset = $database.Tables  | where-object {$_.name -eq $item} }

#generate the script to build each table in the tableset
$tableset.ForEach(
 {$table.script() | out-file c:\temp\createtables.sql -append})

But it errors:

[System.String] does not contain a method named 'script'

I presume because the tableset array is being treated as an array of strings so the .script() method isn't applicable
How do you create an array of table objects instead of strings of the table names?
I have also tried
{$tableset =get-childitems $database.Tables  | where-object {$_.name -like $item} }
but that errors with get-childitem:

The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters.

Or is there a better way to achieve this outcome?
Thanks

A: If $database.Tables is an array of tables then that is also what $tableset will be.  Doing either ($database.Tables).GetType() or $database.Tables | Get-Member or both might help clear things up.  If it is an array of tables Get-Member will show you if indeed a script() method does exist or not as well as any other methods and properties available on the object or objects contained in the array.

A: I ended up using scripter rather than just script() and that helped solve the problems, here is my working prototype (I still need to check what other scripter options also should be set, but this does generate output)
param
(

  $username = $(read-host "Username: "),
  $password = $(read-host "Password: ")
)

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null

$srv = new-object ('Microsoft.SqlServer.Management.Smo.Server') "servername"
$srv.ConnectionContext.LoginSecure = $false
$srv.ConnectionContext.Login =  $username
$srv.ConnectionContext.Password = $password

$dbs=$srv.Databases['DBname']

$tablelist = @(
 'TableBlah',
 'TableWidget'

 )

$scripter = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') $srv
$scripter.Options.ScriptSchema = $true
$scripter.Options.ScriptData = $false
$scripter.Options.ScriptDrops = $false

$listcnt=$tablelist.Count

$tablesout = @()

ForEach ($item in $tablelist)
{
    $tablesout += $dbs.Tables |  where-object {$_.name -like $item}
}

$outcnt=$tablesout.Count

$scripter.Script($tablesout) + "`r GO `r " | Out-File c:\temp\createtablesSQL.sql

"$listcnt tables were requested, $outcnt were scripted"

Blockquote


text:
Q: What would be the best table structure for user post sharing system? I am creating an app where users can create content, other users can like, comment those posts, now I want to implement sharing feature. I want to know what would the best way to implement this.
Following is the table structure for posts
| post_id | post_content | post_user | post_date |

Users can see post only from people they are following.
First of all I thought I would add another row to the above posts table but that would create unnecessary duplication of data, then I thought of adding rows to my user_action table in which I am storing post likes and comments, but thats making the system complicated..
I searched over SO, but couldn't find anything, or may be my search terms were not reachable to those questions.
Is there any better way for achieving this?

A: I agree that adding another row with duplicated data is not good. Let's take a closer look at what you're trying to do.
You have users, and you have posts. These should definitely be separate entities with their own table.
'Like' is a N-M relationship since a user can like any number of posts, and a post can be liked by any number of users. So this will be its own table with two foreign keys, user and post.
Comments are similar to posts, but contains some contents. The same user and post combination can also contain multiple comments. Comments will also be its own table with two foreign keys, user and post. The combination of these two will be unique in like, but non-unique in comment.
Now the sharing part. You want users to be able to follow other users. This is also an N-M relationship since any user can follow any number of users, and any user can be followed by any number of users. Thus, you'll want one more table for this relationship with two foreign keys, user and user. The combination of these two user keys will be unique.
For a given user John, to find all posts of users that he's following, we can use the following pseudo query:
select posts.*
from posts
join user intermediateUser on posts.author = intermediateUser.id
join follow on follow.followee = intermediateUser.id
where follow.follower = John


text:
Q: I would like to write the most efficient code to import Microsoft SQL data to a data frame I would like to load a SQL query into a data frame as efficiently as possible. I read different sources and everyone seems to use a different approach. I am not sure why... Some are using cursors some aren't.
Currently I have:
import pandas as pd
import pyodbc

con = pyodbc.connect('Driver={something};'
    'Server=something;'
    'Database=something;'
    'Trusted_Connection=yes;'
)

sql="""
SQL CODE
"""

df = pd.read_sql_query(con,sql)

And for some reason, this doesn't work in my machine.

A: Try this solution
import pyodbc
import pandas as pd

cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=something;"
                      "Database=something;"
                      "Trusted_Connection=yes;")

cursor = cnxn.cursor()
cursor.execute('SELECT * FROM something')

for row in cursor:
    print(row)

A: import pandas as pd
import pyodbc

con = pyodbc.connect('Driver={something};'
    'Server=something;'
    'Database=something;'
    'Trusted_Connection=yes;'
)

cursor = con.cursor()

cursor.execute("SQL Syntax")

Not quite sure what your last line is doing, but the cursor method works well and runs with efficiently with minimal code.
This should run. You can test it by adding in sqllist = list(cursor.fetchall()) and then print(sqllist)

A: Just pack it in a function. Also I add username and password (just in case)
import pandas as pd
import pyodbc

def GetSQLData(dbName, query):

    sPass = 'MyPassword'
    sServer = 'MyServer\\SQL1'
    uname = 'MyUser'

    cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                    "Server=" + sServer + ";"
                    "Database=" + dbName + ";"
                    "uid=" + uname + ";pwd=" + sPass)

    df = pd.read_sql(query, cnxn)

    return df


text:
Q: Why don't we ever see astronauts on space walks adjusting their orientation by rotating their arms? Why don't we ever see astronauts on space walks, or floating 'weightless' in the ISS, adjusting their orientation by rotating their arms like we do instinctively when about to lose our balance and fall backwards head over heels. Would it work? How about adjusting one's orientation by rotating a hand in a circle over one's head and/or moving a hand in a horizontal circle in front of one's chest and consequently one's body rotating the opposite way around a vertical axis? Or by twiddling one's thumbs for a very long time?
I'm thinking that conservation of angular momentum should make this work. It would be a great physics lesson to see it, if it worked.
Could a space ship be turned around by the crew running or walking in a circle inside it? How about by a crew member sitting on the outside of the ship and whirling a mass on a long string?

A: We do not see astronauts in the ISS adjusting their orientation by rotating their arms , because it is much simpler to rotate themselves by pushing off the walls of the compartment, they are in. Rotating themselves, using just their body and arms is much more strenuous and hence not very efficient.
But it can be done, somewhat like how a cat rotates itself while falling using just the contortions of its body.
You can see an astronaut demonstrating how he can rotate himself in space in this video
https://youtu.be/VJcno_XL4RU?t=43
Even better example is this video as suggested by OP in comments
https://youtu.be/7ZPVg3qD07g?t=127
Regarding if the spaceship can be turned around by its crew walking and running around, of course  theoretically it can be done. But obviously, the scale and mass of the spaceship compared to that of a few humans makes it  nearly impossible to do in practice.


text:
Q: Unable to run nginx inside docker I am trying to run an nginx image inside a Docker container. I have tried these steps

*

*ssh inside ubuntu docker image docker run -v /var/run/docker.sock:/var/run/docker.sock -it ubuntu:latest bash

*Installed  Docker

*Run Nginx image docker run  -d -p 80:80 nginx
curl localhost:80 gives Connection refused

A: Mapping docker.sock to containers means you will be using the docker daemon of the host machine, not the container's.
So when you run docker run  -d -p 80:80 nginx command, the nginx container is created and run in host machine (sibling of the ubuntu container). Hence, 80:80 maps in the host machine.
Validate this by running docker ps in ubuntu container and in the host machine. The result should match. And I guess, you can do curl localhost in the host machine and hit the nginx server as well.