text:
Q: Como usar sleep pra da um efeito de carregamento interface gráfica tkinter Estou querendo usar o sleep do módulo time pra da um efeito de carregamento/espera na verificação de uma condição. Sem usar funções da tkinter, o efeito funciona perfeitamente, porém, quando tento fazer o mesmo com a Label da tkinter, isso já não funciona. Alguém saberia me dizer o por quê?
segue um código exemplo abaixo:
from tkinter import *
from time import sleep

# Janela qualquer
janela = Tk()

# Variáveis com valores hipotéticos
a = 12
b = 15

lb_relacao_vh = Label(janela, font=("Century Gothic", 10, "bold"), bd=5,
                    text="Verificando a relação vão/altura.", anchor="w")
lb_relacao_vh.grid(row=0, column=0, sticky=W)
sleep(1)
lb_relacao_vh['text'] = "Verificando a relação vão/altura.."
sleep(1)
lb_relacao_vh['text'] = "Verificando a relação vão/altura..."

if a > b:
   lb_relacao_vh['fg'] = 'red'
   lb_relacao_vh['text'] = 'Verificando a relação vão/altura...ERRO!'
else:
   lb_relacao_vh['fg'] = 'green'
   lb_relacao_vh['text'] = 'Verificando a relação vão/altura...OK!'

janela.mainloop()

A: Basicamente o interpretador Python está lendo linha por linha do seu código, quando ele chega na linha do sleep() ele fica parado até que o tempo que foi passado acabe (repare que a janela não abre).
Depois que o tempo do sleep() acaba ele:

*

*Configura o widget.

*Faz a verificação do if.

*Entra no mainloop() agora a janela é criada e exibida, contudo o widget já está pronto.

Para evitar isso a interface deve ser criada ao mesmo tempo que fazemos o sleep(), a configuração e a verificação (if), por isso o código deve ser assíncrono (neste caso).
Me baseando no seu código e sem fazer grandes alterações ou mudança do paradigma, cheguei a este código:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Código assíncrono (threading)"""

import threading
import tkinter as tk
from time import sleep

# Janela qualquer (main window)
janela = tk.Tk()

# Variáveis com valores hipotéticos
a = 12
b = 15

# Criando o widget.
lb_relacao_vh = tk.Label(janela, font=("Century Gothic", 10, "bold"), bd=5,
                         text="Verificando a relação vão/altura.", anchor=tk.W)
# Posicionando o widget na janela.
lb_relacao_vh.grid(row=0, column=0, sticky=tk.W)

# Método que será executado de forma assíncrona.
def verificar_altura():
    lb_relacao_vh['text'] = "Verificando a relação vão/altura."
    sleep(1)
    lb_relacao_vh['text'] = "Verificando a relação vão/altura.."
    sleep(1)
    lb_relacao_vh['text'] = "Verificando a relação vão/altura..."
    sleep(1)

    if a > b:
        lb_relacao_vh['fg'] = 'red'
        lb_relacao_vh['text'] = 'Verificando a relação vão/altura...ERRO!'
    else:
        lb_relacao_vh['fg'] = 'green'
        lb_relacao_vh['text'] = 'Verificando a relação vão/altura...OK!'

# Executando o método em um thead do processador diferente daquele onde está o loop da janela.
threading.Thread(target=verificar_altura, daemon=True).start()

# Loop que fica repetindo a janela (FPS).
janela.mainloop()

Se não for essa a ideia vai comentando para podermos refinar o código ou até mesmo localizar outras possibilidades.


text:
Q: Joomla 3.0 Breadcrumbs to show parent page I need my breadcrumb trail to show the parent page but instead it shows all the pages from the category.
I have tried a couple of different modules but all do the same.
Any help is appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Implementing exponential General Linear Model in Stan/RStan I have the following model:

I wish to learn how to implement this model.
Research and Attempt
I've had a look at the following Poisson GLM as an example:

```{stan output.var="PoissonGLMQR"}
  data{
    int<lower=1> n;     // number of observations
    int<lower=1> p;     // number of predictors
    matrix[n, p] x;     // design matrix
    int<lower=0> y[n];  // responses
  }

  transformed data{
    matrix [n, p] Q_ast;
    matrix [p, p] R_ast;
    matrix [p, p] R_ast_inverse;
    Q_ast = qr_Q(x)[,1:p] * sqrt(n - 1.0);
    R_ast = qr_R(x)[1:p,] / sqrt(n - 1.0);
    R_ast_inverse = inverse(R_ast);
  }

  parameters{
    vector[p] theta;  // regression coefficients for predictors
  }

  transformed parameters{
    vector[p] beta;
    vector[n] mu;
    mu = exp(Q_ast*theta);
    beta = R_ast_inverse * theta;
  }

  model{
     y  ~ poisson(mu);
  }
```

I understand that this example has used QR reparameterization (see section 9.2 of the Stan reference manual). However, since I'm new to Stan, I'm finding this quite intimidating, and I'm unsure of how to implement the exponential GLM in the same way. Does one even need to use the QR reparameterization for the exponential case?
Anyway, my naive attempt at the exponential GLM is the following adaptation of the Poisson GLM code:
```{stan output.var="ExponentialGLM"}
  data{
    int<lower=1> n;     // number of observations
    int<lower=1> p;     // number of predictors
    matrix[n, p] x;     // design matrix
    real<lower=0> y[n];  // responses
  }

  transformed data{
    matrix [n, p] Q_ast;
    matrix [p, p] R_ast;
    matrix [p, p] R_ast_inverse;
    Q_ast = qr_Q(x)[,1:p] * sqrt(n - 1.0);
    R_ast = qr_R(x)[1:p,] / sqrt(n - 1.0);
    R_ast_inverse = inverse(R_ast);
  }

  parameters{
    vector[p] theta;  // regression coefficients for predictors
  }

  transformed parameters{
    vector[p] beta;
    vector[n] mu;
    mu = exp(Q_ast*theta);
    beta = (R_ast_inverse * theta);
  }

  model{
     y  ~ exponential(mu);
  }
```

But, I'm totally unsure if this is even the right way to go about coding such a model in Stan. All I did was simply try to adapt the Poisson GLM example to the aforementioned exponential GLM.
I am seeking a demonstration of the exponential GLM and clarifications regarding my misunderstandings above.
Sample Data
    conc  time
 1   6.1   0.8
 2   4.2   3.5
 3   0.5  12.4
 4   8.8   1.1
 5   1.5   8.9
 6   9.2   2.4
 7   8.5   0.1
 8   8.7   0.4
 9   6.7   3.5
10   6.5   8.3
11   6.3   2.6
12   6.7   1.5
13   0.2  16.6
14   8.7   0.1
15   7.5   1.3

A: How about something like this?

*

*We start by reading in the sample data.
df <- read.table(text =
    "    conc  time
 1   6.1   0.8
 2   4.2   3.5
 3   0.5  12.4
 4   8.8   1.1
 5   1.5   8.9
 6   9.2   2.4
 7   8.5   0.1
 8   8.7   0.4
 9   6.7   3.5
10   6.5   8.3
11   6.3   2.6
12   6.7   1.5
13   0.2  16.6
14   8.7   0.1
15   7.5   1.3", header = T);

*We define the Stan model, as a simple Gamma (Exponential) model with a log-link.
model <- "
data {
    int N;                                       // Number of observations
    int K;                                       // Number of parameters
    real y[N];                                   // Response
    matrix[N,K] X;                               // Model matrix
}

parameters {
    vector[K] beta;                              // Model parameters
}

transformed parameters {
    vector[N] lambda;
    lambda = exp(-X * beta);                     // log-link
}

model {
    // Priors
    beta[1] ~ cauchy(0, 10);
    for (i in 2:K)
        beta[i] ~ cauchy(0, 2.5);

    y ~ exponential(lambda);
}
"

Here I assume (standard) weakly informative Cauchy priors on the beta model parameters.

*We now fit the model to the data.
library(rstan);
options(mc.cores = parallel::detectCores());
rstan_options(auto_write = TRUE);

X <- model.matrix(time ~ conc, data = df);
model.stan <- stan(
    model_code = model,
    data = list(
        N = nrow(df),
        K = ncol(X),
        y = df$time,
        X = X),
    iter = 4000);

*To compare point estimates, we also fit a Gamma GLM to the data using glm.
model.glm <- glm(time ~ conc, data = df, family = Gamma(link = "log"));

*The Stan model parameter estimates are
summary(model.stan, "beta")$summary;
#              mean     se_mean         sd       2.5%        25%        50%
#beta[1]  2.9371457 0.016460000 0.62017934  1.8671652  2.5000356  2.8871936
#beta[2] -0.3099799 0.002420744 0.09252423 -0.5045937 -0.3708111 -0.3046333
#               75%      97.5%    n_eff     Rhat
#beta[1]  3.3193334  4.3078478 1419.629 1.002440
#beta[2] -0.2461567 -0.1412095 1460.876 1.002236

The GLM model parameter estimates are
summary(model.glm)$coef;
#              Estimate Std. Error   t value     Pr(>|t|)
#(Intercept)  2.8211487 0.54432115  5.182875 0.0001762685
#conc        -0.3013355 0.08137986 -3.702827 0.0026556952

We see good agreement between the Stan point estimates for the means and Gamma-GLM parameter estimates.

*We plot parameter estimates from both the Stan and glm models.
library(tidyverse);
as.data.frame(summary(model.stan, "beta")$summary) %>%
    rownames_to_column("Parameter") %>%
    ggplot(aes(x = `50%`, y = Parameter)) +
    geom_point(size = 3) +
    geom_segment(aes(x = `2.5%`, xend = `97.5%`, yend = Parameter), size = 1) +
    geom_segment(aes(x = `25%`, xend = `75%`, yend = Parameter), size = 2) +
    labs(x = "Median (plus/minus 95% and 50% CIs)") +
    geom_point(
        data = data.frame(summary(model.glm)$coef, row.names = c("beta[1]", "beta[2]")) %>%
            rownames_to_column("Parameter"),
        aes(x = Estimate, y = Parameter),
        colour = "red", size = 4, shape = 1)

glm estimates are shown in red.

Update (Fit Stan model using QR re-parametrisation)

*

*Stan model with QR re-parametrisation.
model.QR <- "
data {
    int N;                                       // Number of observations
    int K;                                       // Number of parameters
    real y[N];                                   // Response
    matrix[N,K] X;                               // Model matrix
}

transformed data {
    matrix[N, K] Q;
    matrix[K, K] R;
    matrix[K, K] R_inverse;
    Q = qr_Q(X)[, 1:K];
    R = qr_R(X)[1:K, ];
    R_inverse = inverse(R);
}

parameters {
    vector[K] theta;
}

transformed parameters {
    vector[N] lambda;
    lambda = exp(-Q * theta);                     // log-link
}

model {
    y ~ exponential(lambda);
}

generated quantities {
    vector[K] beta;                              // Model parameters
    beta = R_inverse * theta;
}
"

In the QR decomposition, we have lambda = exp(- X * beta) = exp(- Q * R * beta) = exp(- Q * theta), where theta = R * beta and therefore beta = R^-1 * theta.
Note that we do not specify any priors on theta; in Stan this defaults to flat (i.e. uniform) priors.

*Fit Stan model to the data.
library(rstan);
options(mc.cores = parallel::detectCores());
rstan_options(auto_write = TRUE);

X <- model.matrix(time ~ conc, data = df);
model.stan.QR <- stan(
    model_code = model.QR,
    data = list(
        N = nrow(df),
        K = ncol(X),
        y = df$time,
        X = X),
    iter = 4000);

*Parameter estimates
summary(model.stan.QR, "beta")$summary;
#              mean     se_mean         sd       2.5%        25%        50%
#beta[1]  2.9637547 0.009129250 0.64383609  1.8396681  2.5174800  2.9194682
#beta[2] -0.3134252 0.001321584 0.09477156 -0.5126905 -0.3740475 -0.3093937
#               75%      97.5%    n_eff      Rhat
#beta[1]  3.3498585  4.3593912 4973.710 0.9998545
#beta[2] -0.2478029 -0.1395686 5142.408 1.0003236

You can see that parameter estimates between the two Stan models (with and without QR re-parametrisation) agree very well.
If you were to ask me whether QR re-parametrisation makes a (big/any) difference, I'd say "probably not in this case"; Andrew Gelman and others have often emphasised that using even very weakly informative priors will help with convergence and should be preferred over flat (uniform) priors; I would always try to use weakly informative priors on all parameters, and start with a model without QR re-parametrisation; if convergence is poor, I would then try to optimise my model in a next step.


text:
Q: form submit to iframe not working - it only refresh the parent and iFrame I try to submit a form to an iFrame and get search results within iFrame. Whatever text I write and push search its just refreshing parent and child pages.
I have this parent page code :
<form id="SearchForm" <form action="http://itmjobs.ro/" target="my-iframe" method="post">
        What?<input type="text" value="job title, keywords or company name"  onblur="if(this.value=='') this.value='job title, keywords or company name'" onFocus="if(this.value =='job title, keywords or company name' ) this.value=''" />
        Where?<input type="text" value="city, state or zip code"  onblur="if(this.value=='') this.value='city, state or zip code'" onFocus="if(this.value =='city, state or zip code' ) this.value=''" />
        Search

And this are the fields from iframe code where I need to be submit the text  :

Cuvinte cheie
   <input type="text" value="" class="searchText" name="keywords[all_words]"  id="keywords" />

Oras
<input type="text" name="City[like]"  id="City" class="searchStringLike" value=""  />

<input type="submit" id="btn-search" class="button" value="Cauta"/>

A: You need to return false on your submission to prevent a page refresh.
onClick="document.getElementById('SearchForm').submit() return false;"


text:
Q: error TS2540: Cannot assign to 'vfs' because it is a read-only property Im Trying to generate PDF using pdfmaker. In my code it dosent show any errors.but when compiling it show below error. but also pdf is working and generating.
error TS2540: Cannot assign to 'vfs' because it is a read-only property.
>   19 pdfMake.vfs = pdfFonts.pdfMake.vfs;
>                ~~~
>     src/app/component/invoice/invoice.component.ts:235:25 - error TS2345: Argument of type '{ content: ({ text: string; fontSize:
> number; alignment: string; color: string; bold?: undefined;
> decoration?: undefined; style?: undefined; columns?: undefined; } | {
> text: string; fontSize: number; bold: boolean; ... 4 more ...;
> columns?: undefined; } | { ...; } | { ...; })[]; styles: { ...; }; }'
> is not assignable to parameter of type 'TDocumentDefinitions'.
>       Types of property 'content' are incompatible.
>         Type '({ text: string; fontSize: number; alignment: string; color: string; bold?: undefined; decoration?: undefined; style?:
> undefined; columns?: undefined; } | { text: string; fontSize: number;
> bold: boolean; ... 4 more ...; columns?: undefined; } | { ...; } | {
> ...; })[]' is not assignable to type 'Content'.
>           Type '({ text: string; fontSize: number; alignment: string; color: string; bold?: undefined; decoration?: undefined; style?:
> undefined; columns?: undefined; } | { text: string; fontSize: number;
> bold: boolean; ... 4 more ...; columns?: undefined; } | { ...; } | {
> ...; })[]' is not assignable to type 'ArrayOfContent'.
>             The types returned by 'pop()' are incompatible between these types.
>               Type '{ text: string; fontSize: number; alignment: string; color: string; bold?: undefined; decoration?: undefined;
> style?: undefined; columns?: undefined; } | { text: string; fontSize:
> number; bold: boolean; ... 4 more ...; columns?: undefined; } | { ...;
> } | { ...; } | undefined' is not assignable to type 'string |
> ArrayOfContent | ContentText | ContentColumns | ContentStack |
> ContentUnorderedList | ... 11 more ... | undefined'.
>                 Type '{ text: string; fontSize: number; alignment: string; color: string; bold?: undefined; decoration?: undefined;
> style?: undefined; columns?: undefined; }' is not assignable to type
> 'string | ArrayOfContent | ContentText | ContentColumns | ContentStack
> | ContentUnorderedList | ... 11 more ... | undefined'.
>                   Property 'tocItem' is missing in type '{ text: string; fontSize: number; alignment: string; color: string; bold?:
> undefined; decoration?: undefined; style?: undefined; columns?:
> undefined; }' but required in type 'ContentTocItem'.
>
>     235       pdfMake.createPdf(docDefinition).download();
>                                 ~~~~~~~~~~~~~
>
>       node_modules/@types/pdfmake/interfaces.d.ts:253:5
>         253     tocItem: boolean | string | string[];
>                 ~~~~~~~
>         'tocItem' is declared here.
>     src/app/component/invoice/invoice.component.ts:237:25 - error TS2345: Argument of type '{ content: ({ text: string; fontSize:
> number; alignment: string; color: string; bold?: undefined;
> decoration?: undefined; style?: undefined; columns?: undefined; } | {
> text: string; fontSize: number; bold: boolean; ... 4 more ...;
> columns?: undefined; } | { ...; } | { ...; })[]; styles: { ...; }; }'
> is not assignable to parameter of type 'TDocumentDefinitions'.
>
>     237       pdfMake.createPdf(docDefinition).print();
>                                 ~~~~~~~~~~~~~
>     src/app/component/invoice/invoice.component.ts:239:25 - error TS2345: Argument of type '{ content: ({ text: string; fontSize:
> number; alignment: string; color: string; bold?: undefined;
> decoration?: undefined; style?: undefined; columns?: undefined; } | {
> text: string; fontSize: number; bold: boolean; ... 4 more ...;
> columns?: undefined; } | { ...; } | { ...; })[]; styles: { ...; }; }'
> is not assignable to parameter of type 'TDocumentDefinitions'.
>
>     239       pdfMake.createPdf(docDefinition).open();

This is my component.ts code and im using generatePDf function to generate pdf and its working fine and no error showing.
import * as pdfMake from 'pdfmake/build/pdfmake.js';
import * as pdfFonts from 'pdfmake/build/vfs_fonts.js';
pdfMake.vfs = pdfFonts.pdfMake.vfs;

 generatePDF(action = "open") {
    let docDefinition = {
      content: [
        {
          text: "Indika Agro Sales and Service Center",
          fontSize: 16,
          alignment: "center",
          color: "#047886",
        },
        {
          text: "INVOICE",
          fontSize: 20,
          bold: true,
          alignment: "center",
          decoration: "underline",
          color: "skyblue",
        },
        {
          text: "Customer Details",
          style: "sectionHeader",
        },
        {
          columns: [
              [
                  {
                      text: this.invoiceform.value.customerName,
                      bold: true
                  },
                  { text:this.invoiceform.value.cusPhnNumber,  }
              ],
              [
                  {
                      text: `Date: ${new Date().toLocaleString()}`,
                      alignment: 'right'
                  },
                  {
                      text: `Bill No : ${((Math.random() * 1000).toFixed(0))}`,
                      alignment: 'right'
                  }
              ]
          ]
      },
      ],
      styles: {
        sectionHeader: {
          bold: true,
          decoration: "underline",
          fontSize: 14,
          margin: [0, 15, 0, 15],
        },
      },
    };

    if (action === "download") {
      pdfMake.createPdf(docDefinition).download();
    } else if (action === "print") {
      pdfMake.createPdf(docDefinition).print();
    } else {
      pdfMake.createPdf(docDefinition).open();
    }
  }

A: If you use a typing script ...:
import * as pdfMake from "pdfmake / build / pdfmake";
import * as pdfFonts from 'pdfmake / build / vfs_fonts';

(pdfMake as any).vfs = pdfFonts.pdfMake.vfs;


text:
Q: Devolver numero y sucesivos con backtracing - PROLOG El predicado que quiero implementar necesito que haga lo siguiente:
predicado(Máximo,Num1,Num2).

Y debe devolver dos números Num1 y Num2 cumpliendose que:

*

*Num1 < Num2

*Num2 <= Máximo

A continuación dejo algunos ejemplos para que se comprenda mejor:
predicado(1,Num1,Num2).
false

predicado(2,Num1,Num2).
Num1=1,Num2=2;
false

predicado(3,Num1,Num2).
Num1=1,Num2=2;
Num1=1,Num2=3;
Num1=2,Num2=3;
false

predicado(4,Num1,Num2).
Num1=1,Num2=2;
Num1=1,Num2=3;
Num1=1,Num2=4;
Num1=2,Num2=3;
Num1=2,Num2=4;
Num1=3,Num2=4;
false

Y así sucesivamente.
He desarrollado un código para intentar solucionarlo, es el siguiente:
obtener_numerosSwap(NRegs,NRegs2,NRegs):-
    NRegs>1,
    NRegs2 is NRegs-1.

obtener_numerosSwap(N2,N1,N2) :-
    N2 > 1,
    Nnew is N2-1,
    obtener_numerosSwap(Nnew,N1,Nnew).

obtener_numerosSwap(NRegs,N1,N2) :-
    var(N2),
    NRegs > 1,
    N2 is NRegs-1,
    obtener_numerosSwap(N2,N1,N2).

Dejo algunos ejemplos de su ejecución. Quiero aclarar que funciona para N<=3, pero eso no está bien.
1 ?- obtener_numerosSwap(1,A,B).
false.

2 ?- obtener_numerosSwap(2,A,B).
A = 1,
B = 2 ;
false.

3 ?- obtener_numerosSwap(3,A,B).
A = 2,
B = 3 ;
A = 1,
B = 3 ;
A = 1,
B = 2 ;
false.

También recalcar que da igual que no salgan ordenados y, que como ya he dicho antes, es necesario que funcione por backtracking, es decir, que cada vez que de ; me devuelva una solución.
A continuación os enseño como para N>3 no funciona:
4 ?- obtener_numerosSwap(4,A,B).
A = 3,
B = 4 ;
A = 2,
B = 4 ;
A = 1,
B = 4 ;
A = 2,
B = 3 ;
A = 1,
B = 3 ;
false.

Sé donde está el fallo, y es que en el tercer predicado de obtener_numerosSwap hace el decremento de NRegs, pero solo funciona cuando el N2 no está instanciado y la resta es true. El problema es que no se como solucionarlo.
Gracias de ante mano a cualquier ayuda!

A: Simplemente necesitas una función que genere un rango de números por reevaluación:
ran(X,Y,X) :- X < Y.
ran(X,Y,Z) :- X < Y, X2 is X+1, ran(X2,Y,Z).

Ahora puedes implementar tu predicado en base a dos rangos:

*

*De 1 al máximo (X+1), que será el segundo número (Z)

*De 1 a Z, que será el primer número (Y)

Es decir:
p(X,Y,Z) :- X2 is X+1, ran(1,X2,Z), ran(1,Z,Y).


text:
Q: Python: Applying volatility formula to data from multiple dataframes I have 3 dataframes which I have watered as shown below. df  = stock weightage of 3 stocks (A,B,C), df2  = standard deviation fo 2 stocks, corr = correlation matrix of the 3 stocks
df = pd.DataFrame([[0.4, 0.2, 0.4], [0.1, 0.3, 0.6], [0.3, 0.2, 0.5], [0.3,0.3,0.4]], columns=['WA', 'WB','WC'])

    WA  WB  WC
0   0.4 0.2 0.4
1   0.1 0.3 0.6
2   0.3 0.2 0.5
3   0.3 0.3 0.4

df2 = pd.DataFrame([[0.5, 0.2, 0.4]], columns = ['stv_A', 'stv_B', 'stv_c'])

 stv_A  stv_B   stv_c
    0   0.5 0.2 0.4

cor = np.corrcoef([[0.1, .32, .2, 0.4, 0.8], [.23, .18, .56, .61, .12], [.9, .3, .6, .5, .3]])
corr = pd.DataFrame(cor, index=['A', 'B', 'C'], columns=['A', 'B', 'C'])
       A             B         C
A   1.000000    -0.351531   -0.747365
B   -0.351531   1.000000    0.238102
C   -0.747365   0.238102    1.000000

I would need to apply a portfolio volatility formula to the above data as shown below
https://i.stack.imgur.com/slJyQ.png
I have all the necessary data in the dataframe but do know how to apply the formula to it


text:
Q: Passing an int pointer into a function to print that array in C This is my first post so bear with me. I am getting back into writing in C after being out of school for a while. I am trying to pass an array of integers into a function that will print the entire array out on the same line (as a part of a larger effort). My dumbed down code follows:
// main.c
#include <stdio.h>

int main(void) {

    int arr[] = {3,4,5,6,7};
    int *ptr = arr;
    int l = 5;

    printarr(arr,l);
    return 0;
}

And
// function printarr
#include <stdio.h>

void printarr(char *ptr, int l) {

    int k = 0;
    for (k = 0; k < l; ++k) {
        printf("%d", ptr[k]);
    }
}

After compiling and running main.c, the output I get is:
30004

I feel like I have been beating my head against a wall trying to figure out a simple problem. When I iterate and print the array in main I get the output I would expect ('34567') but when I try to do it through the function it comes out sad. I suspect I am misusing the pointer but yeah I'm not sure.
Help is appreciated.
Thanks.
edit: Upon glancing at the first two comments, I am entirely ashamed of myself. Thank you folks. Wow, just wow.

A: You should change your function to
void printarr(int *ptr, int l)

as you're passing an int * to it. As pointed by @Malife, you should enable the compiler warnings with -Wall, so you get a proper message. Optionally make all warnings into errors with -Werror.
char and int have different sizes, int being much bigger. 4 times bigger as you can see from your output. You're iterating the memory where your int numbers are allocated in a partial manner when looking at the values as char.

A: printarr should be expecting an int array, not char array, so should be
 void printarr(int *ptr, int l)

In main, int *ptr = arr; is not used or needed.
You probally also want to put a space or new line between each value of the array you are printing out:
void printarr(char *ptr, int l) {

    int k = 0;
    for (k = 0; k < l; ++k) {
        printf("%d\n", ptr[k]);
    }
 }

A: I think the problem is that you pass a char pointer in "printarr". In fact when you pass "ptr" you have this situation: 00000011 00000000 00000000 00000000 00000100 .... A char has 8 bit, an int 32 bit, and the Ram is often Little Endian for the bytes order. Then you call a printf passing an int, and the byte is extended to 32 bits so you print: 3 0 0 0 4. In the main "ptr" is an int, so you print the int, in this case 3 4 5 6 7. You must change char *ptr -> int *ptr in "printarr"


text:
Q: php : variable value not saved in db I have a php code where i am taking the logged in user name. Then the form comes and then i need to save the logged in user name in db.
<?PHP
 function renderForm($id, $task, $comments, $assignee, $priority, $status, $dataum1, $dataum2, $error )
 {
require_once("./include/membersite_config.php");

if(!$fgmembersite->CheckLogin())
{
    $fgmembersite->RedirectToURL("login.php");
    exit;
}
$user = $fgmembersite->UserFullName();
?>

Html Form comes here...........
<?php
 }

 // connect to the database
 include('configdb1.php');

 // check if the form has been submitted. If it has, process the form and save it to the database
 if (isset($_POST['submit']))
 {

 mysql_query("INSERT INTO comments (comment_id, comments, user) VALUES ('$id', '$text', '$user')")
 or die(mysql_error());

?>

But the $user which i declared as the login name is not getting inserted into db. Please help.
This is my entire code :
<?PHP
 function renderForm($id, $task, $comments, $assignee, $priority, $status, $dataum1, $dataum2, $error )
 {
require_once("./include/membersite_config.php");

if(!$fgmembersite->CheckLogin())
{
    $fgmembersite->RedirectToURL("login.php");
    exit;
}

?>

<title></title>
<link href="style.css" rel="stylesheet" type="text/css" />

                                                      <color = 'white'>
                                                      Welcome back   <?= $fgmembersite->UserFullName(); ?>! , Logout

                 <img src="images/m1.gif" alt="" color = "white" width="112" height="33" id="Image9"

 &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp  &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp  &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp  &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp

 <form action="" method="post">
  <input type="hidden" name="id" value="<?php echo $id; ?>"/>

ID: <?php echo $id; ?>

Enter the Task

<input name="task" readonly value= <?php echo $task; ?> type="text" size = "127" input style="height:30px;font-size:13;" ...../>

Enter Task Description

<textarea readonlyname="comments" ROWS="10" Cols = "91"> <?php echo $comments; ?></textarea>

   <?php
include('configdb.php');
    $query = "SELECT username FROM users";

    $result = mysqli_query($mysqli,$query) or die(mysqli_error($mysqli));
    $assignee = "<select name='user'> width = '200'";
    while($row = mysqli_fetch_assoc($result)) {
    $assignee .= "\r\n<option width = '200'  value='{$row['username']}'>{$row['username']}</option>";
    }
    $assignee .= "\r\n</select> ";

    ?>
Assignee: &nbsp &nbsp &nbsp &nbsp <select name = "assignee" value = <?php echo $assignee ?></select> &nbsp &nbsp  &nbsp &nbsp  &nbsp &nbsp

Priority: &nbsp &nbsp &nbsp &nbsp <select name = "type" id="type">
    <option <?php if ($type == 'MAC OS') { echo 'selected="selected"'; } ?>>MAC OS</option>
    <option <?php if ($type == 'WINDOWS OS') { echo 'selected="selected"'; } ?>>WINDOWS OS</option>
    <option <?php if ($type == 'GENERAL TASK') { echo 'selected="selected"'; } ?>>GENERAL TASK</option>
</select> &nbsp &nbsp  &nbsp &nbsp  &nbsp &nbsp

Priority: &nbsp &nbsp &nbsp &nbsp <select name = "priority" id="priority">
    <option <?php if ($priority == 'Low') { echo 'selected="selected"'; } ?>>Low</option>
    <option <?php if ($priority == 'Medium') { echo 'selected="selected"'; } ?>>Medium </option>
    <option <?php if ($priority == 'High') { echo 'selected="selected"'; } ?>>High</option>
</select> &nbsp &nbsp  &nbsp &nbsp  &nbsp &nbsp

Status: &nbsp &nbsp &nbsp &nbsp     <select name = "status" id="status">
    <option <?php if ($status == 'Assigned') { echo 'selected="selected"'; } ?>>Assigned</option>
    <option <?php if ($status == 'Yet to Start') { echo 'selected="selected"'; } ?>>Yet to Start </option>
    <option <?php if ($status == 'In Progress') { echo 'selected="selected"'; } ?>>In Progress</option>
    <option <?php if ($status == 'Completed') { echo 'selected="selected"'; } ?>>Completed</option>
     <option <?php if ($status == 'Blocked') { echo 'selected="selected"'; } ?>>Blocked</option>
</select>

Start Date :&nbsp &nbsp <input type="text" size = "25" input style="height:25px;font-size:13;" name="datum1" id="datum1" value="<?php echo $dataum1; ?>">&nbsp &nbsp &nbsp &nbsp  &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp  &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp  &nbsp &nbsp &nbsp
End Date :&nbsp &nbsp <input type="text"  size = "25" input style="height:25px;font-size:13;" name="datum2" id="datum2" value="<?php echo $dataum2; ?>">

                            <input name="submit" type="submit" value="submit"/>
                            </form>

 <?php
 }

 // connect to the database
 include('configdb1.php');

 // check if the form has been submitted. If it has, process the form and save it to the database
 if (isset($_POST['submit']))
 {
 // confirm that the 'id' value is a valid integer before getting the form data
 if (is_numeric($_POST['id']))
 {
 // get form data, making sure it is valid
 $id = $_POST['id'];
 $task = $_POST['task'];
 $comments = $_POST['comments'];
$assignee = $_POST['assignee'];
 $priority = $_POST['priority'];
 $status = $_POST['status'];
 $dataum1 = $_POST['datum1'];
 $dataum2 = $_POST['datum2'];
    // check that firstname/lastname fields are both filled in
if ($task == '' || $comments == '')
 {
 // generate error message
 $error = 'ERROR: Please fill in all required fields!';

 //error, display form
 renderForm($id, $task, $comments, $assignee, $priority, $status, $dataum1, $dataum2, $error );
 }
 else
 {
 // save the data to the database
 mysql_query("UPDATE work SET task='$task', comments='$comments', assignee='$assignee', priority='$priority', status='$status', dataum1='$dataum1', dataum2='$dataum2' WHERE id='$id' ")
 or die(mysql_error());

 // once saved, redirect back to the view page
 header("Location: view.php");
 }
 }
 else
 {
 // if the 'id' isn't valid, display an error
 echo 'Error!';
 }
 }
 else
 // if the form hasn't been submitted, get the data from the db and display the form
 {

 // get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
 if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
 {
 // query db
 $id = $_GET['id'];
 $result = mysql_query("SELECT * FROM work WHERE id=$id")
 or die(mysql_error());
 $row = mysql_fetch_array($result);

 // check that the 'id' matches up with a row in the databse
 if($row)
 {

 // get data from db
 // get data from db
 $task = $row['task'];
 $comments = $row['comments'];
  $assignee = $row['assignee'];
   $priority = $row['priority'];
    $status = $row['status'];
     $dataum1 = $row['dataum1'];
      $dataum2 = $row['dataum2'];

 // show form
 renderForm($id, $task, $comments, $assignee, $priority, $status, $dataum1, $dataum2,'');
 }
 else
 // if no match, display result
 {
 echo "No results!";
 }
 }
 else
 // if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
 {
 echo 'Error!';
 }
 }
?>

A: try this (add ") because comment may have special chars :
mysql_query("INSERT INTO comments (comment_id, comments, user) VALUES ('".$id."', '".$text."', '".$user."')") or die(mysql_error());

A: Do you have a field named "submit"?
My guess is that the check if the form was posted is incorrect.
That's why you query is never executed.
Try something like:
if (count($_POST) > 0)
// QUERY


text:
Q: Jars Issues in Maven Spring Hibernate Project I had made Web Application on Spring and Hibernate by taking reference from Vaannila
When I specify lib name on pom.xml using eclipse, the maven repository could not include all the jars.
How can I include the jars on my application?

A: you could use the maven install:install command which includes the jars into your maven repo
mvn install:install-file -DgroupId=group_id -DartifactId=artifact_id -Dversion=version -Dpackaging=jar -Dfile=path_to_jar
For this , you could try mvn package - maven will given an error asking use to use the above command - copy paste it , change the path and use it in your command prompt .
or
add the jar as an external jar - Right click your project in Eclipse - go to properties -->Build path -->Libraries -->Add external jars
To download from the central repo ,add the following to your pom
<repositories>
 <repository>
  <id>central</id>
  <name>Maven Repository Switchboard</name>
  <layout>default</layout>
  <url>http://repo1.maven.org/maven2</url>
  <snapshots>
    <enabled>false</enabled>
  </snapshots>
 </repository>
</repositories>

Hibernate and Hibernate annotations are separate jars . These are the dependencies I use . Try them .
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-annotations</artifactId>
        <version>3.4.0.GA</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>3.5.6-Final</version>
    </dependency>

To do this manually ,
Download hibernate-annotations  from here and save it in C:/temp or wherever you want. Then perform
mvn install:install-file -DgroupId=org.hibernate -DartifactId=hibernate-annotations -Dversion=3.4.0.GA -Dpackaging=jar -Dfile=C:/temp/hibernate-annotations-3.4.0.GA.jar

A: See this Maven Spring Hibernate example project.
Hopefully you will easily understand from there.


text:
Q: How tinder gets friend list from facebook? I have seen many apps like Tinder and many other apps gets friends lists from facebook. When i login to these app they import all my friends list and sotre to their database. According to facebook doc it says only taggable friends are available through api which should be used to tag on user posts. But Tinder and other apps do not tag friends in the post. So I m curious to know how they get facebook friends.

A: /me/friends gets all friends who authorized the App with user_friends too, so they most likely used Tinder already.
The answer in this thread explains everything you need to know: Facebook Graph Api v2.0+ - /me/friends returns empty, or only friends who also use my app


text:
Q: Snowplow: Warning: No tracker configured I am facing problem during interrelation of snowplow to my angular app I am following official documentation from here enter link description here
My code is
    <script type="text/javascript">

    ;(function(p,l,o,w,i,n,g){if(!p[i]){p.GlobalSnowplowNamespace=p.GlobalSnowplowNamespace||[];
p.GlobalSnowplowNamespace.push(i);p[i]=function(){(p[i].q=p[i].q||[]).push(arguments)
};p[i].q=p[i].q||[];n=l.createElement(o);g=l.getElementsByTagName(o)[0];n.async=1;
n.src=w;g.parentNode.insertBefore(n,g)}}(window,document,"script","http://d1fc8wv8zag5ca.cloudfront.net/2.6.1/sp.js","snowplow_tracker"));

      console.debug(snowplow_tracker);

    snowplow_tracker('gotoTrackerMethode', '{{MY-COLLECTOR-URI (cloudFront URl)}}');
    function gotoTrackerMethode(a, b)
    {
        console.debug(a);
    }
    function gotoTrackerName(s){
      console.debug("asdf");
    }
    // window.snowplow_tracker('enableActivityTracking', 30, 10);
    // window.snowplow_tracker('enableLinkClickTracking');
    // window.snowplow_tracker('trackPageView');
    </script>

any help would be highly appreciated.

A: After a lot of R&D i find the solution myself which is you need to invoke callback method not simple but callback like
 ;(function(p,l,o,w,i,n,g){if(!p[i]){p.GlobalSnowplowNamespace=p.GlobalSnowplowNamespace||[];
p.GlobalSnowplowNamespace.push(i);p[i]=function(){(p[i].q=p[i].q||[]).push(arguments)
};p[i].q=p[i].q||[];n=l.createElement(o);g=l.getElementsByTagName(o)[0];n.async=1;
n.src=w;g.parentNode.insertBefore(n,g)}}(window,document,"script","http://d1fc8wv8zag5ca.cloudfront.net/2.6.1/sp.js","snowplow_tracker"));

    // callbacks
  snowplow_tracker(function () {
    console.log("sp.js has loaded");
  });

  snowplow_tracker(function (x) {
    console.log(x);
  }, "sp.js has loaded");

  //Find the utma cookie and extract the unique user ID
  function getGoogleId() {
      var id, a, c = document.cookie.split('; ');
      for (var i in c) {
          a = c[i].split('=');
          if (a[0]==='__utma') {
              id = a[1].split('.')[1];
          }
      }
      return id || 'unknown';
  }

        // Configure a tracker instance named "cf"
  snowplow_tracker('newTracker', 'cf', 'd3rkrsqld9gmqf.cloudfront.net', {
      appId: 'snowplowExampleApp',
      platform: 'web'
  });

  // Access the tracker instance inside a callback
  snowplow_tracker(function () {
      var cf = this.cf;
      var userFingerprint = cf.getUserFingerprint();
       var domainUserId = cf.getDomainUserId();
       var domainUserInfo = cf.getDomainUserInfo();
       var userId = cf.getUserId();
      console.debug(userId);
      console.debug(domainUserInfo);
      console.debug(userFingerprint);
      console.debug(domainUserId);
  })

   snowplow_tracker('enableActivityTracking', 30, 10);
  snowplow_tracker('enableLinkClickTracking');
  snowplow_tracker('trackPageView');

This is working fine now.


text:
Q: Why am I getting different results on a prediction using the same Keras model and input? posting here is my last resort cause I can't find anything like it online. I trained a model to classify embeddings into categories (a simple three layer Dense neural network).
Now I want to use the trained model to make predictions in real time, but I discovered that if I input the whole test dataframe to the model, get the prediction for say the element number i, and compare it to the prediction that I get by inputting just the element number i of the test data frame into the model, I get different results. This is the code in case I didn't explain it good enough:
i = 522
y_pred = model.predict(X_test)
y_pred_2 = model.predict(X_test.iloc[[i]])

print (f'{np.argmax(y_pred[i])} {np.argmax(y_pred_2)}')

output: 8 5

It's like my model is behaving differently if it processes the whole test set in a single run than if it processes a single row at a time. I'm using pandas for the input data.
EDIT: More info, the output shapes of y_pred and y_pred_2 are (603, 10) and (1, 10) respectively, where 10 is the number of classes I have.
Some example values for both predictions, with an arbitrary i:
y_pred[i]: array([1.3353945e-02, 2.8374636e-09, 1.4435661e-08, 3.4135045e-18,
   7.7986561e-02, 3.7737598e-03, 2.0284578e-10, 2.7154891e-03,
   9.0203673e-01, 1.3346069e-04], dtype=float32)

y_pred_2 = array([[1.1702824e-16, 1.6781385e-37, 2.5281618e-33, 0.0000000e+00,
        2.3075200e-09, 1.0000000e+00, 9.9125501e-35, 6.2606384e-22,
        5.8689110e-14, 2.3486194e-24]], dtype=float32)

A: np.argmax defaults to the row axis. You're getting the maximum prediction across rows, and you want it across columns. Try:
print(f'{np.argmax(y_pred[i], axis=1)} {np.argmax(y_pred_2, axis=1)}')


text:
Q: Which code does a servlet context use to match the requestedURI and servlet urlPatterns? I created a java annotation and use it on servlet methods, so methods will be invoked from servlet service() method.
Like this:
@Run(Address="/abc/*",Priority=1)
public void doSomething(){}

So, i need exactly the code snippet which servlet contexts use to match the requestedURI and servlet urlPatterns.
I don't want to use regular expressions, want to follow the approach java servlet uses.
Thanks.

A: If only it were that simple. The process of mapping a URI to the correct servlet is non-trivial. Tomcat has a separate Mapper class to do this.


text:
Q: Wikitude SDK project derived from samples doesn't work I've been modifying the sample projects Wikitude SDK provides, and I'm facing a problem: it seems like this code never works:
this.tracker = new AR.Tracker("/assets/magazine.wtc", {
    onLoaded: this.worldLoaded
});

That is, the world never loads, so the function "worldLoaded" is never called.
I have no idea why the world doesn't load as the file is the original provided in the samples and it used to work.
The difference seems to be trivial, I only added a new member to the World variable that would define some additional parameteres.
The error I get is
Uncaught TypeError: Cannot read property 'apply' of undefined
ade.js:1AR.i.__executeFunctionByName ade.js:1AR.i.callAsync ade.js:1l

Any idea how to tackle this?

A: It seems as if you have the ADE activated, which is not necessary on a mobile device. In your HTML, please delete the line  (your path to ade.js might differ slightly). This will make the error go away.
In addition, my suggestion is to also add an onError event to the tracker. In this case, you'll be notified when the tracker cannot be loaded (wrong location specified, invalid file etc), and you can react accordingly.


text:
Q: PHPMyadmin redirection issues on Apache2 A couple of days back I updated Apache on the webserver. Which seems to have broken accessing Phpmyadmin through server IP:
server.ip/phpmyadmin

Instead now when typing above the ip/phpmyadmin it redirects to the domain which is hosted on the server.
domain.com/phpmyadmin

It gives a 404 error obviously, since /var/html/www where the domain is pointed has no Phpmyadmin directory/resource.
I have tried the following, upto no avail:
sudo dpkg-reconfigure phpmyadmin

Checked the following directories for any reference to phpmyadmin redirection:
/etc/apache2
/etc/phpmyadmin

Any ideas?

A: PHPMyadmin was set to use SSL.
Using 'https' instead of 'http' resolved the issue.


text:
Q: loading object thats inside of an object into a html table so i am trying to make a file manger in node.js and socket.io so every time the walker module detects a file or folder it emits an event to the client that puts it in the table using this large function
    socket.on('loadItem', function(type, name, dateCreated, size, itemPath, parentPath, fileExtension){
        if (type == 'dir'){
            var itemPathID = itemPath.split(' ').join('-');
            var parentPathID = parentPath.split(' ').join('-');
            console.log('parent-path ' + parentPathID)
            document.getElementById('main-table').innerHTML += '
	' + name+ '	' + dateCreated + '	' + size + ' bytes
'
            document.getElementById('main-content-div').innerHTML += '

'
            document.getElementById(itemPathID).innerHTML += table
        }
        if(type == "file"){
            if(fileExtension == 'js'){
            var parentPathID = parentPath.split(' ').join('-');
            console.log(parentPathID)
            document.getElementById('main-table').innerHTML += '
	' + name + '	' + dateCreated + '	' + size + ' bytes
'

        }else if(fileExtension == "txt"){
            var parentPathID = parentPath.split(' ').join('-');
            console.log(parentPathID)
            document.getElementById('main-table').innerHTML += '
	' + name + '	' + dateCreated + '	' + size + ' bytes
'
        }else if(fileExtension == "css"){
            var parentPathID = parentPath.split(' ').join('-');
            console.log(parentPathID)
            document.getElementById('main-table').innerHTML += '
	' + name + '	' + dateCreated + '	' + size + ' bytes
'
            }
            else{
                var parentPathID = parentPath.split(' ').join('-');
            console.log(parentPathID)
            document.getElementById('main-table').innerHTML += '
	' + name + '	' + dateCreated + '	' + size + ' bytes
'
            }
        }

    })

but if i have alot of file it will crash the browser sending all of that data individualy through websockets is bad i guess :( so now i construct a object like this on server side
         dirItems[itemPath] = {
            item:{
                name:itemName,
                type:'dir',
                birtDate:stat.birthtime,
                itemSize:stat.size,
                itemPath:itemPath,
                parentPath:parentPath,
                itemExtension:'null'

            }
          }

and i then send it over to the client page but what my problem is is that i don't know how to put this in my table there isnt like a foreach thing for this i dont think i have tried using this with no su
var cols = ['type', 'name', 'date', 'size'];

    for (var i = 0; i < dirItems.item.length; i++) {
    console.log("moo")
$('#main-table').append('

');

for (var j = 0; j < cols.length; j++) {
    $('#main-table tr:last-child').append('' + dirItems[i][cols[j]] + '	');
}
}

any pointers?

A: This is how you do the for loops in ES6. The idea is to have your table as the HTML template and then append the results of the for loop as

 within the
.

var A = [
          {type:'dinosaur',name:'Rex',date:'1 Jan -00',size:'massive'},
          {type:'dog',name:'Woof',date:'12 Jan 2015',size:'impressive'},
          {type:'parrot',name:'Parry',date:'13 Mar 2018',size:'fistsize'}
          ];
for(animal of A) {
  $('#sometable tbody').append('
'+animal.type+'	'+animal.name+'	'+animal.date+'	'+animal.size+'
');
}
#sometable {
  border:1px solid black;
}
#sometable td {
  padding:0.2em 1em;
}

      Type
      Name
      Date
      Size

If you fancy the old-school way of doing things, then your for statement will look like:
for(var i=0;i<A.length;i++) {
  var animal = A[i];
  $('#sometable tbody').append('
'+animal.type+'	'+animal.name+'	'+animal.date+'	'+animal.size+'
');
}


text:
Q: use VBA in excel to get data from closed workbooks with multiple file names I have a workbook that has a list of excel file names in one column and I need to use those file names to have a macro get data from one cell from each one of those files in the list. Where do I begin? Sorry for such a dumb question.
workbook with data sheet
I would like to get data from a workbook whose name comes from column K, with the worksheet name coming from column L, and always cell A13. And put that value in the correct row in column M.

A: This is what you have to do :

*

*Iterate through each of the names (lets say  the list range is A1:A5)

*Open that workbook.

*Get the value from the cell

*Paste that value on main workbook

*Close workbook and go to the next one

This is how you do this:
Sub CopyFromWorkbooks()
Dim path As String
    path = "THE PATH WERE THOSE WORKBOOKS ARE SAVED (Eg: "C:\Users\YOU\Documents")"
            For Each cell In ThisWorkbook.Sheets("YOUR_SHEET_NAME").Range("A1:A5")
            'Open the workbook
            Workbooks.Open Filename:=path & "\" & cell.Value  'adding workbook name and path to get full workbook path

            'Copy cell value to this workbook
            Workbooks(cell.Value).Sheets("YOUR_SHEET_NAME").Range("THE RANGE TO COPY").Copy

            'Paste copied value in this workbook
            ThisWorkbook.Sheets("YOUR_SHEET_NAME").Range("THE RANGE TO PASTE").PasteSpecial Paste:=xlPasteValues

            'Close Workbook
             Workbooks(cell.Value).Close True

             Next cell
End Sub

This code as is will paste the copied data always on the same cell if you need help with that just write back ;)


text:
Q: Extending the Sudden Approximation to 2nd quantised systems? Background
So basically there is a dictionary/correspondence between first and second quantised quantum mechanical theories. When I suddenly turn on a potential in potential in first quantised theories I can use the sudden approximation and find the probability of the final state. I can use the dictionary to find a result in the second quantised theory as well. My question is what happens when the potential turned on is such that the particle number is not conserved? Is there a way to extend the approximation?
Calculations
Let us restrict our discussion to bosons and adopt the convention First Quantised $\leftrightarrow $ Second Quantised Theory (we are following these Ashok Sen's Quantum Field Theory I of HRI institute also on my google drive). Consider a single particle system's hamiltonian $\hat h$ and energy operator $\hat E$:
$$ \hat h \psi = \hat E \psi $$
with energy eigenstates $u_i$ and eigenvalues $e_n$
$$ \hat h u_n = e_n u_n$$
Now moving to an assembly of quantum mechanical Hamiltonians (many body system)  $\sum_i h_i$ with an interacting potential $\hat v_{ik}$ corresponds to a second quantised version (Page 16):
$$ \hat H_N = \sum_{i=1}^N \hat h_i + \frac{1}{2}\sum_{\substack i\neq j
 \\ i,j=1 }^N \hat v_{i,j} \leftrightarrow \sum_{n=1}^\infty e_n a_n^\dagger a_n  + \frac{1}{2} \sum_{m,n,p,q=1}^\infty \Big(\int \int  d^3 r_1 d^3 r_2 u_{m}(\vec r_1)^* u_{n}(\vec r_2)^* \hat v_{12} u_{m}(\vec r_1) u_{p}(\vec r_2) \Big) a^\dagger_m a^\dagger_n  a_p a_q$$
where $e_n$ i the $n$th energy eigevalue,  $u_i$ are the one-particle eigenstates and $a_i^\dagger$ is the creation operator of the $i$'th particle and they obey the energy eigenvalue system $h_i u_n = e_n u_n$. The symmetric wave function for $H_N$ corresponds as a second quantised version (Page 6):
$$ u_{n_1,n_2,\dots n_N} \equiv \frac{1}{\sqrt{N!}} \sum_{\text{Permutations of $r_1,\dots,r_N$}}u_{n_1} (\vec r_1) \dots u_{n_N} (\vec r_N) \leftrightarrow (a_1^\dagger)^{n_1} (a_2^\dagger)^{n_2} \dots (a_N^\dagger)^{n_N} |0 \rangle$$
The potential corresponds for one body operator (Page 14):
$$ \sum_{i=1}^N \hat B_{i} \leftrightarrow  \sum_{n,p = 1}^\infty \Big( \int d^3 r_1 u_n^* (\vec r_1) B_{1} u_p (\vec r_1) \Big) a^\dagger_n a_p$$
Now, let's say I suddenly turn on the one body operator (potential) in the assembly of quantum mechanical systems. Then:
$$  H'_N = \sum_{i=1}^N \hat h_i + \frac{1}{2}\sum_{\substack i\neq j
 \\ i,j=1 }^N \hat v_{i,j} + \sum_i^N \hat B_{i} $$
Let the new energy eigenstates be $\tilde u_n$ with the original state be $u_{n_1,n_2,\dots,n_N}$. Then the final state being in $\tilde u_{n'_1,n'_2,\dots,n'_N}$ has probability $| \int \tilde u_{n'_1,n'_2,\dots,n'_N}u^*_{n_1,n_2,\dots,n_N} d^3 r|^2 $. Now using the dictionary we can find the corresponding $2$nd quantised state. This is nothing but the sudden approximation.
Question
Is there a way to extend the sudden approximation to potentials which do not conserve particle number? An example of where this might be relevant would be Emergence of a molecular Bose-Einstein condensate from a Fermi gas. In this system the particle number would be double and the Hamiltonian undergoes rapid transition (for fermionic to bosonic).


text:
Q: Ineffable Cardinals and Critical Point of Elementary Embeddings A cardinal $\kappa$ is a ineffable if and only if for all sequences $\langle A_\alpha : \alpha < \kappa\rangle$ such that $A_\alpha \subseteq \alpha$ for all $\alpha < \kappa$, then there exists $A \subseteq \kappa$ such that $\{\alpha < \kappa : A \cap \alpha = A_\alpha\}$ is stationary in $\kappa$.
Now suppose $M$ and $N$ are transitive models of $\text{ZFC}$, $\mathcal{P}^M(\kappa) = \mathcal{P}^N(\kappa)$, and $j : M \rightarrow N$ is a nontrivial elementary embedding and $\kappa = \text{crit}(j)$. Lemma 17.32 of Jech claims that $\kappa$ is an ineffable cardinal in $M$.
Jech takes $\langle A_\alpha : \alpha < \kappa\rangle$ be any sequence as above. $j(\langle A_\alpha : \alpha < \kappa\rangle) = \langle A_\alpha : \alpha < j(\kappa)\rangle$ for some $A_\alpha \subseteq \alpha$ when $\kappa \leq \alpha < j(\kappa)$. $A_\kappa \in M$ by the assumption. He claims that $A_\kappa$ is such that $\{\alpha < \kappa : A_\kappa \cap \alpha = A_\alpha\}$ is stationary in $\kappa$. I can not see why this set should be stationary.

A: Let's let $B = \{ \alpha < \kappa : A_\kappa \cap \alpha = A_\alpha \}$.
Suppose $C \in M$ is a club subset of $\kappa$.  We want to show that $C \cap B \neq \varnothing$.  It follows that $j(C)$ is a club subset of $j(\kappa)$, and also that $j(B) = \{ \alpha < j(\kappa) : j(A_\kappa) \cap \alpha = A_\alpha \}$.
Now note two things:

*

*$\kappa \in j(C)$;

*$j(A_\kappa) \cap \kappa = A_\kappa$.

Thus $\kappa \in j(C) \cap j(B)$, meaning $j(C) \cap j(B) \neq \varnothing$, and so by elementarity $C \cap B \neq \varnothing$.


text:
Q: InputFormTextBox setting an focus and a onblur event, in a SharePoint web part I'm making use of a bunch of InputFormTextBoxes and I'd like to have an onblur event get fired when the box is no longer in focus. This is when RichText == true.
This is because I have a Sharepoint Webpart that has a lot of editable areas and richtext is required. However, the screen gets cluttered if they are all available. So I'm making it autosave and hide the text box when the user clicks away. This saves screen real estate, and improves the page performance greatly.
I can get this to work with RichText == false, so it's just a normal TextArea HTML control. However, I can't set focus with JavaScript on the textarea, and I can't get an event to fire for the onblur event.

A: You can do this fairly easily with javascript.  If I understand your requirements, you have large text areas that you want to expand and collapse dynamically as the user moves in and out of them.  That way you don't take up so much real estate.  I tested this code on a normal edit page with two multi-line textboxes.  You'll probably need to adjust for your web part.
$(function(){
    var collapsedHeight = 18;
    var expandedHeight = 50;
    var editors = $("iframe[title='Rich Text Editor']");
    editors.attr("height", collapsedHeight);
    editors.blur(function(){
        $(this).attr("height", collapsedHeight);
    });
    editors.focus(function(){
        $(this).attr("height", expandedHeight);
    });
});


text:
Q: Can't block site in /etc/hosts In my /etc/hosts I have added this line to block the www.bbc.com/persian:
127.0.0.1 www.bbc.com/persian

I am using Firefox on Antix Linux (Debian), and had no success, the site can still be reached just as before. How can I block that page by using /etc/hosts?


text:
Q: how to make an error message when input is a string instead of an int beginner here. As mentioned before my question is: how do you output an error when the input is a string instead of an int? I'm trying to created a program that outputs a workers raise in salary, and I wanted to implement a function that displays an error when the user entered something other than a number for their salary. here's my code:
package calculating.salary;
import java.util.Scanner;

public class CalculatingSalary {

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    System.out.println("Please input yearly salary:");

    int salary = in.nextInt();
    //this is where I would implement the error message

    System.out.println("Please input how many years worked:");

    boolean running = true;
    while (running){

    String years = in.nextLine();

    if (years.equals ("1")|| years.equals("one")){
        System.out.println("Your salary is now $"+(salary + salary*0.02));
        break;
    }

    if (years.equals("2")||years.equals("two")){
         System.out.println("Your salary is now $"+(salary + salary*0.03));
        break;
    }
    if (years.equals("3")||years.equals("three")){
         System.out.println("Your salary is now $"+(salary + salary*0.04));
        break;
    }
    if (years.equals("4")||years.equals("four")){
         System.out.println("Your salary is now $"+(salary + salary*0.05));
        break;
    }
    if (years.equals("5")||years.equals("five")){
         System.out.println("Your salary is now $"+(salary + salary*0.06));
        break;
    }
        else {
        System.out.println("Please type in a number from 1 through 5");
    }
}
    }
 }

A: String salary = in.nextLine();
int salaryValue;
try {
    salaryValue = Integer.parseInt(salary);
} catch (NumberFormatException e) {
    System.out.println("You didn't enter a valid integer.");
}

This will store the user's input in a String instead of an int, then manage the conversion separately.  If the conversion fails, an exception is thrown, which causes the message to be printed.


text:
Q: Javascript to load multi SWF file I have a situation like this. I need to repeatedly overload the single div with different SWF files. A folder has many swf files, like sample_0.swf sample_1.swf sample_2.swf sample_3.swf ... sample_n.swf.
Now, I want to have a single HTML file that which loads all SWF files one by one. In which one replacing the previously loaded object.
No need to wait until sample_0.swf 's completion loops to load the next file sample_1.swf and so on. I need to do some testing. Please help to provide a JS along with HTML.
Edit:
Please someone give me a working example
Thanks

A: You could use swfobject, a js object that provides the functionality you' re asking.


text:
Q: Creating database using already prepared migrations ASP.NET MVC I have a ASP.NET MVC 5 project from GitHub, but there is nothing in App_Data. I have all models, migrations etc... I'm sure that everything works. I'd like to create database to use this project. How can I create it?

A: There is a PowerShell command that comes with Entity Framework Code First which updates the database based on the migrations in the project:

Update-Database will apply any pending migrations to the database

You can run this easily from within Visual Studio using the Package Manager Console (Tools –> Library Package Manager –> Package Manager Console). Make sure to select the project that contains the DbContext class as Startup Project in Solution Explorer as well as Default Project in Package Manager Console, before running the Update-Database command. Also ensure you have defined a connection string for a local database that the command will update.
For more details follow the instructions in documentation.


text:
Q: NMAKE fatal error U1077 in Qt build with webkit I am trying to build Qt 4.8.6 as a x64 static library by Visual Studio 2013 SP5 with webkit included, but I get this error after a few minutes of running nmake:
Generating Code...
        lib /NOLOGO  /OUT:..\..\lib\QtDeclarative.lib @C:\Users\Siavash\AppData\Local\Temp\nm3EA3.tmp qdeclarativeevents.obj : warning LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library qlistmodelinterface.obj : warning LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library
        cd src\3rdparty\webkit\Source\ && C:\MSVS2013\VC\BIN\nmake.exe -f Makefile.WebKit

Microsoft (R) Program Maintenance Utility Version 12.00.21005.1 Copyright (C) Microsoft Corporation.  All rights reserved.

        cd JavaScriptCore\ && C:\MSVS2013\VC\BIN\nmake.exe -f Makefile.WebKit

Microsoft (R) Program Maintenance Utility Version 12.00.21005.1 Copyright (C) Microsoft Corporation.  All rights reserved.

        c:\Qt\4.8.6\bin\qmake.EXE -o Makefile.WebKit JavaScriptCore.pro
        C:\MSVS2013\VC\BIN\nmake.exe -f Makefile.WebKit.Release

Microsoft (R) Program Maintenance Utility Version 12.00.21005.1 Copyright (C) Microsoft Corporation.  All rights reserved.

        cl -c -nologo -Zm200 -Zc:wchar_t- -FS -wd4291 -wd4344 -wd4396 -wd4503 -wd4800 -wd4819 -wd4996 -O2 -MD -GR -EHsc -DUNICODE -DWIN32 -DNDEBUG -DBUILDING_QT__=1 -DNDEBUG -DQT_ASCII_CAST_WARNINGS -D_HAS_TR1=0 -DBUILDING_JavaScriptCore -DBUILDING_WTF -DQT_NO_DEBUG -DQT_CORE_LIB -DQT_HAVE_MMX -DQT_HAVE_3DNOW -DQT_HAVE_SSE -DQT_HAVE_MMXEXT -DQT_HAVE_SSE2 -DQT_THREAD_SUPPORT -I"..\..\..\..\..\include\QtCore" -I"..\..\..\..\..\include" -I"." -I"..\..\Source" -I"..\ThirdParty" -I"assembler" -I"bytecode" -I"bytecompiler" -I"heap" -I"dfg" -I"debugger" -I"interpreter" -I"jit" -I"parser" -I"profiler" -I"runtime" -I"wtf" -I"wtf\gobject" -I"c:\Qt\4.8.6\src\3rdparty\webkit\Source\JavaScriptCore\wtf\symbian" -I"wtf\unicode" -I"yarr" -I"API" -I"ForwardingHeaders" -I"generated" -I"os-win32" -I"..\..\Source" -I"..\..\include" -I"\include\QtWebKit" -I"\include" -I"..\..\..\..\..\include\ActiveQt" -I"tmp\moc\release_static" -I"..\..\..\..\..\mkspecs\win32-msvc2013" -Fotmp\obj\release_static\ @C:\Users\Siavash\AppData\Local\Temp\nm4880.tmp DateMath.cpp
.\wtf/MathExtras.h(117) : error C2491: 'round' : definition of dllimport function not allowed
.\wtf/MathExtras.h(124) : error C2491: 'roundf' : definition of dllimport function not allowed
.\wtf/MathExtras.h(146) : error C2084: function 'bool signbit(double)' already has a body
        C:\MSVS2013\VC\INCLUDE\math.h(324) : see previous definition of 'signbit'
        c:\qt\4.8.6\src\3rdparty\webkit\source\javascriptcore\runtime\JSValueInlineMethods.h(168) : error C2264: 'signbit' : error in function definition or declaration; function not called dtoa.cpp
.\wtf/MathExtras.h(117) : error C2491: 'round' : definition of dllimport function not allowed
.\wtf/MathExtras.h(124) : error C2491: 'roundf' : definition of dllimport function not allowed
.\wtf/MathExtras.h(146) : error C2084: function 'bool signbit(double)' already has a body
        C:\MSVS2013\VC\INCLUDE\math.h(324) : see previous definition of 'signbit' DecimalNumber.cpp
.\wtf/MathExtras.h(117) : error C2491: 'round' : definition of dllimport function not allowed
.\wtf/MathExtras.h(124) : error C2491: 'roundf' : definition of dllimport function not allowed
.\wtf/MathExtras.h(146) : error C2084: function 'bool signbit(double)' already has a body
        C:\MSVS2013\VC\INCLUDE\math.h(324) : see previous definition of 'signbit' Generating Code...
    NMAKE : fatal error U1077: 'C:\MSVS2013\VC\BIN\x86_amd64\cl.EXE' : return code '0x2' Stop.
    NMAKE : fatal error U1077: 'C:\MSVS2013\VC\BIN\nmake.exe' : return code '0x2' Stop.
    NMAKE : fatal error U1077: 'cd' : return code '0x2' Stop. NMAKE : fatal error U1077: 'cd' : return code '0x2' Stop.

This problem does not exist when I do not explicitly configure qt to build webkit, which will not be built otherwise, even if it is a default option.
Also this is the configuration that I use:
configure -opensource -release -static -webkit -platform win32-msvc2013

I understand my problem might be similar to this one, but because Visual Studio 2013 is supported by Qt 4.8.6 I think this problem has a different reason. Furthermore, I have tried moving all of the necessary packages and even reinstalling VS to ensure that the PATHs that I use do not include any spaces or are not "too long". I have searched through so many guides and posts but nothing seems to help me with this.
Is there something that I might be missing?


text:
Q: jsf2 f:selectItem itemLabel complex i18n render I've a f:selectitem with its itemLabel and i want to render the label so "pretty"!
The problem:

<f:selectItem itemLabel="#{msg['message.1']}" itemValue="1" />
<f:selectItem itemLabel="#{msg['message.2']}" itemValue="2" />

My properties i18n file:
message.1=some message by {0}
message.2=another message by {0}

I want to do a inline replacement of {0} by #{somebean.theUser}
The result should be something like this (bold included):
some message by HUSTON

In tag file i should do something like this (or in similar way)
<f:selectItem itemLabel="#{msg['message.1']{''+somebean.theUser+''}}" itemValue="1" />

In other words, i want to add the i18n string param replacement directly into itemLabel tag.
I've try with  <f:facet name="itemLabel"> but nothing.
Someone can help me?
Thanks in advice,
Agharta

A: JSF won't let you do that from the markup side. There is no way to use for example <h:outputFormat /> for it.
Instead you need to simply create a bean, that will read the contents from properties file and format accordingly:

<f:selectItem itemLabel="#{helperbean.someMessage}" itemValue="1" />
<f:selectItem itemLabel="#{helperbean.anotherMessage}" itemValue="2" />

That was JSF part, in your bean:
public String getSomeMessage() {
  // Actually you need some common access helper, it is just simplified example
  String messagePattern = null;
  try {
    ResourceBundle rb = ResourceBundle.getBundle("path/to/properties/file");
    String messagePattern = rb.getString("message.1");
    return MessageFormat.format(messagePattern, somebean.getTheUser());
  } catch (MissingResourceException mre) {
     logger.warn("Missing resource file or resource key", mre);
     return "!message.1!"; // That will show you where the problem is
  }
}

Few additional points regarding Localizability:

*

*Please use meaningful key names. Something like "message.1" gives no context to translators. I don't know what you are up to, but maybe "some-module.select.message.radio.message.sent.by.pattern" will be something better - the translator needs to know a) where it will be displayed, b) what is the purpose of this text (whether it is some description, message pattern, general text, window/dialog title, button caption, etc.). Be sure to provide them such context.

*Be sure to include formatting tags into the message itself. That means, the message should look like message.1=some message by {0} in your properties file. You'd be surprised how often these kind of tags need to be removed (or replaced with other emphasis means). You should be especially careful, since you seem to be doing something with RTL languages and bolded fonts does not work with them very well.


text:
Q: SELinux: Letting Apache talk to MySQL on CentOS So I have chrooted MySQL into /opt/chroot/mysql, and everything runs fine. Apache is configured normally, and also runs fine.
I created a small PHP script which connects to the MySQL Daemon, and configured PHP so that the default socket used is the chrooted one. When SELinux is disabled, the script is able to connect fine. However, when SELinux is enabled, the script fails to connect (with error number 13), and the audit log tells me that SELinux denied the request.
Every tutorial I've found that deals with this problem tells me to disable SELinux. This is not what I want to do, so please don't suggest it! I want a solution that works whilst SELinux is enabled...I assume one must exist...
I'd guess that I probably have to change the SELinux contexts for the mysql files, but I'm not sure what to change them into to make it work.

A: UPDATE 2

type=AVC msg=audit(1318863312.959:435): avc: denied { connectto } for
  pid=12472 comm="httpd"
  path="/opt/chroot/mysql/var/lib/mysql/mysql.sock"
  scontext=unconfined_u:system_r:httpd_t:s0
  tcontext=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
  tclass=unix_stream_socket

You can build the custom SELinux policy module by following steps:
# grep httpd_t audit.log | audit2allow -m httpd > httpd.te
# checkmodule -M -m -o httpd.mod httpd.te
# semodule_package -m httpd.mod -o httpd.pp
# semodule -i httpd.pp

Refer to this topic for more details.

UPDATE

*

*Run semanage command to add a context mapping for /opt/chroot/mysql/var/lib/mysql/:
# semanage fcontext -a -t mysqld_db_t "/opt/chroot/mysql/var/lib/mysql(/.*)?"

*And use restorecon command to apply this context mapping:
# restorecon -Rv /opt/chroot/mysql/var/lib/mysql

If you are connecting via TCP/IP, try this:
# setsebool -P httpd_can_network_connect 1


text:
Q: DSL-JSON: java.io.IOException: Unable to serialize provided object. Failed to find serializer for: class I'm trying to use DSL-JSON running one of the examples.
I'm getting the following error:
Exception in thread "main" java.io.IOException: Unable to serialize provided object. Failed to find serializer for: class dsl.test.Example$Model
    at com.dslplatform.json.DslJson.serialize(DslJson.java:2718)
    at dsl.test.Example.main(Example.java:231)

I've only added the dependency on my pom.xml:
    <dependency>
      <groupId>com.dslplatform</groupId>
      <artifactId>dsl-json</artifactId>
      <version>1.7.3</version>
    </dependency>

What's missing?

A: I once had the same problem as you,and I add this setting to solve it.You may try this:
DslJson<Object> json = new DslJson<>(Settings.withRuntime().allowArrayFormat(true).includeServiceLoader());

A: Please make sure you have added dsl-json-processor dependency in your pom file
for example
<!-- https://mvnrepository.com/artifact/com.dslplatform/dsl-json-processor -->
<dependency>
    <groupId>com.dslplatform</groupId>
    <artifactId>dsl-json-processor</artifactId>
    <version>1.9.9</version>
</dependency>


text:
Q: Connect-AzAccount - how to avoid azure device authentication? I have installed the PowerShell 6.1.3 version and
I want to get a connection to the Azure account using the following Azure PowerShell command:
Connect-AzAccount -Tenant <tenantId> -Subscription <subId>

After entering this command I get the warning with the url and some code.
Then I have to go to the URL and enter the code there. After that, I get a connection to the Azure account.
Are there any ways to avoid this confirmation?
I've also tried to do it using the following command:
az login -u <username> -p <password>

This command only returns some account information(subscriptionId, tenantId etc) but it doesn't install a connection to this account.

A: 1.To login with the user account, try the command as below, make sure your account doesn't enable the MFA(Multi-Factor Authentication).
$User = "xxx@xxxx.onmicrosoft.com"
$PWord = ConvertTo-SecureString -String "<Password>" -AsPlainText -Force
$tenant = "<tenant id>"
$subscription = "<subscription id>"
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User,$PWord
Connect-AzAccount -Credential $Credential -Tenant $tenant -Subscription $subscription

2.You can also use a service principal to login, use the command as below.
$azureAplicationId ="Azure AD Application Id"
$azureTenantId= "Your Tenant Id"
$azurePassword = ConvertTo-SecureString "strong password" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Connect-AzAccount -Credential $psCred -TenantId $azureTenantId  -ServicePrincipal

See a similar issue I answered here, it use the old AzureRM module, for Az, just change the last line.
If you are not familiar with service principal, Also see : How to: Use the portal to create an Azure AD application and service principal that can access resources, the application id and authentication key are the Azure AD Application Id and strong password you need.

A: You have 2 options.
Sign in with credentials (Requires Az.Accounts v 1.2.0 or higher)
You can also sign in with a PSCredential object authorized to connect to Azure. The easiest way to get a credential object is with the Get-Credential cmdlet. When run, this cmdlet will prompt you for a username/password credential pair.
$creds = Get-Credential
Connect-AzAccount -Credential $creds

Sign in with a service principal
Service principals are non-interactive Azure accounts. Like other user accounts, their permissions are managed with Azure Active Directory. By granting a service principal only the permissions it needs, your automation scripts stay secure.
To learn how to create a service principal for use with Azure PowerShell, see Create an Azure service principal with Azure PowerShell.
Source: https://learn.microsoft.com/en-us/powershell/azure/authenticate-azureps?view=azps-1.3.0

A: If Multi Factor Enabled then also below logic should work
    $clientId = "***********************"
    $clientSecret = "********************"
    $tenantId = "***********************"
    $tempPassword = ConvertTo-SecureString "$clientSecret" -AsPlainText -Force
    $psCred = New-Object System.Management.Automation.PSCredential($clientId ,
    $tempPassword)
    Connect-AzAccount -Credential $psCred -TenantId $azureTenantId  -ServicePrincipal


text:
Q: ImportError while performing pip install While in my virtual environment, i'm trying to perform 'pip install .' with a setup.py such as :
from setuptools import setup
import pbr

... some functions ...

setup(
    name='example',
    setup_requires=['pbr'],
    py_modules=['example'],

    entry_points='''
        [console_scripts]
        example=example:main
    ''',
)

The thing is that i get the following error ImportError: No module named pbr
This seems quite legit as i didn't install pbr in my virtual environment BUT i thought that specifying 'setup_requires' would do the trick ... :/
Does someone understand why this does not work and knows how to fix it ? :)

A: The script does import pbr before running setup() so setup() was not given a chance to install pbr.
The fix is to not import pbr before running setup(). See https://docs.openstack.org/pbr/latest/user/using.html:
#!/usr/bin/env python

from setuptools import setup

setup(
    setup_requires=['pbr'],
    pbr=True,
)


text:
Q: Trigger system volume bar Is it possible by pressing a button in my Activity to make the volume bar appear? The volume bar is the view that appears when you press one of the hardware volume buttons.
Is there a API function to do this or do I have to recreate that view by hand?

A: if you call setStreamVolume, pass the flag FLAG_SHOW_UI
See http://developer.android.com/reference/android/media/AudioManager.html#FLAG_SHOW_UI

A: Working code
AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                    AudioManager.ADJUST_SAME, AudioManager.FLAG_SHOW_UI);

A: I use this code to turn sound on/off:
    val audio = getSystemService(getApplication(), Context.AUDIO_SERVICE) as AudioManager
    audio.adjustStreamVolume(
        AudioManager.STREAM_MUSIC,
        AudioManager.ADJUST_SAME, AudioManager.FLAG_SHOW_UI
    )
}

It's worked.


text:
Q: Indentation went crazy in Emacs Haskell Mode After a recent full-system update I've noticed that indentation in Haskell mode has become really strange:
import Data.Ratio
    _

Underscore signifies position of caret after pressing Enter, i.e. in my case at 4 column. It's really unbearable because it goes to column 4 every time I hit Enter.
I'm sure it has nothing to do with Haskell Mode itself, since it has no fresh updates and it worked perfectly until now. However, there seems to be new version of Emacs: 24.4, so I'm wondering if they changed something that would cause this bug.
Does anyone else encounter the problem? Do you have any ideas how to fix it?

A: Seems there was a new indentation mode electric-indent-mode introduced with 24.4
(see "Editing Changes ... Indentation" section here)
You can disable by (for the session)
M-x electric-indent-mode

or adding something like
(electric-indent-mode 0)

to your .emacs file.
You can disable it just on haskell-mode too with this:
(add-hook 'haskell-mode-hook
          (lambda () (electric-indent-local-mode 0)))


text:
Q: Exception as e. The e is not visible in the debugger Python 3.6
def get_results(drv):
    try:
        table_element = WebDriverWait(drv,60).until(EC.presence_of_element_located((By.TAG_NAME, "tbody")))
    except TimeoutException as e:
        raise TimeoutException(e.message)

Screen shot: https://b.radikal.ru/b05/1810/52/65f03791c2e2.png
    Traceback (most recent call last):
      File "/home/michael/PycharmProjects/PoiskOptim/keyword_stuffing.py", line 56, in get_results
        table_element = WebDriverWait(drv, 60).until(EC.presence_of_element_located((By.TAG_NAME, "tbody")))
      File "/home/michael/PycharmProjects/PoiskOptim/venv/lib/python3.6/site-packages/selenium/webdriver/support/wait.py", line 80, in until
        raise TimeoutException(message, screen, stacktrace)
    selenium.common.exceptions.TimeoutException: Message:

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "/home/michael/Documents/pycharm-community-2018.2.3/helpers/pydev/pydevd.py", line 1664, in <module>
        main()
      File "/home/michael/Documents/pycharm-community-2018.2.3/helpers/pydev/pydevd.py", line 1658, in main
        globals = debugger.run(setup['file'], None, None, is_module)
      File "/home/michael/Documents/pycharm-community-2018.2.3/helpers/pydev/pydevd.py", line 1068, in run
        pydev_imports.execfile(file, globals, locals)  # execute the script
      File "/home/michael/Documents/pycharm-community-2018.2.3/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
        exec(compile(contents+"\n", file, 'exec'), glob, loc)
      File "/home/michael/PycharmProjects/PoiskOptim/main.py", line 14, in <module>
        funcs[choice]()
      File "/home/michael/PycharmProjects/PoiskOptim/keyword_stuffing.py", line 141, in keyword_stuffing
        parse_all(phrases)
      File "/home/michael/PycharmProjects/PoiskOptim/keyword_stuffing.py", line 134, in parse_all
        handle_chunks(drv, phrases)
      File "/home/michael/PycharmProjects/PoiskOptim/keyword_stuffing.py", line 81, in handle_chunks
        get_results(drv)
      File "/home/michael/PycharmProjects/PoiskOptim/keyword_stuffing.py", line 58, in get_results
        raise TimeoutException(e.message)
    AttributeError: 'TimeoutException' object has no attribute 'message'

Could you help me understand what is going on here. I set TimeoutException as e. Well, I hoped that e would be at least visible in the debugger. But  no. There is no e in the context.
Added later
The question is: Why there is no e in the context?

A: This is pretty obvious. You try to access the message attribute of your e variable which happens to be an object of type TimeoutException. In Python3 an Exception object does not have a message attribute anymore. If you want to print the exception message just use str(e).


text:
Q: Write values to text boxes on web page with CefSharp I integrated CefSharp into my project. I was able to work out some points. However, I couldn't figure out how to check Inputboxes for example on a given site. So how can I write data into that InputBox. I request your help in this matter.
Thanks in advance.

A: You won't be able to modify the content of your web page running inside CefSharp from the C# code directly. What you can do however is to pass javascript code that will run on the page and will change content.
For example, something similar to this:
var browser = new ChromiumWebBrowser("https://www.example.com");
await browser.ExecuteScriptAsync("document.getElementById('myTextBoxId').value='the value'");


text:
Q: ktlint and KotlinProjectExtension I tried to implement Kotlin check style in project using ktlint.
I added
plugins {
    id("org.jlleitschuh.gradle.ktlint") version "10.1.0" apply false
}

in root build.gradle.kts and
plugins {
id("org.jlleitschuh.gradle.ktlint")
}

in build.gradle.kts in subprojects
When I called

gradlew ktlintCheck

I got
FAILURE: Build failed with an exception.

* What went wrong:
org/jetbrains/kotlin/gradle/dsl/KotlinProjectExtension

How can I fix it?

A: This is how I went about it for Klint with Kotlin DSL on gradle.kts files for Android Gradle. Have also added Spotless with Kotlin DSL ( code formatter ) at the same time.
It is also worth noting mine is NOT a Multi Module project.
Step 1 - gradle.kts (app) - Add Klint and Spotless plugins and import Reporters
import org.jlleitschuh.gradle.ktlint.reporter.ReporterType

plugins {
            id("com.android.application") ...
            //Klint
            id("org.jlleitschuh.gradle.ktlint") version "11.0.0"

            //Spotless
            id("com.diffplug.spotless")
        }

Step 2 - gradle.kts (app) - Configure Klint only
// ktlintFormat task will need to run before preBuild
tasks.getByPath("preBuild")
    .dependsOn("ktlintFormat")

configure<org.jlleitschuh.gradle.ktlint.KtlintExtension> {

    android.set(true)
    ignoreFailures.set(false)
    disabledRules.set(setOf("final-newline", "no-wildcard-imports"))
    reporters {
        reporter(ReporterType.PLAIN)
        reporter(ReporterType.CHECKSTYLE)
        reporter(ReporterType.SARIF)
    }
}

Step 3 - gradle.kts(app) - Configure Spotless only
configure<com.diffplug.gradle.spotless.SpotlessExtension> {
    kotlin {
        // version, setUseExperimental, userData and editorConfigOverride are all optional
        ktlint("0.45.2")
            .setUseExperimental(true)
            .userData(mapOf("android" to "true"))
            .editorConfigOverride(mapOf("indent_size" to 2))
    }
    kotlinGradle {
        target("*.gradle.kts") // default target for kotlinGradle
        ktlint() // or ktfmt() or prettier()
    }
}

Step 4 - gradle.kts(project) - Add Spotless in the Classpath
buildscript {

    repositories{
        google()
        mavenCentral()
    }
    dependencies {

        ...
        //class path for Spotless
        classpath("com.diffplug.spotless:spotless-plugin-gradle:6.9.1")
    }

}

The 2 plugins works fine with this set-up.


text:
Q: Получить список файлов? Имеется сайт, на котором есть личный кабинет. Каждый пользователь может загружать файл (../upload) – txt файл (ранее список был виден для всех).
При переходе по адресу: site.ru/upload
Forbidden
You don't have permission to access /upload/ on this server.

Но если указать прямой путь до файла (site.ru/upload/file.txt), то соответственно можно получить доступ. Таких файлов много, и они имеют разные названия (перебор по имени подошёл бы, но имена файлов могут быть и такими eq3wr23c23c.txt). В кэше гугла естественно нету этой страницы.
Может есть какой-нибудь способ получить список этих файлов?

A: В папке upload нужно создать файл .htaccess и указать в нём Options +Indexes.


text:
Q: Rasa nlu server failure I started the rasa server by typing this command in cmd:
  rasa run --enable-api -m models/(my_model).tar.gz --cors "*" --debug

I put this command in another cmd:
  curl -X POST localhost:5005/model/parse -d '{"text":"hello"}'

After that I got this error:
  {"version":"1.2.2","status":"failure","message":"An unexpected error occurred. Error: Failed when parsing body as json","reason":"ParsingError","details":{},"help":null,"code":500}

Any help? How can I integrate Rasa with Node.js?

A: Please try
 curl -H "Content-Type: application/json"  -X POST -d '{"sender":"y1mLd","message":"hi"}' http://localhost:5005/webhooks/rest/webhook

Output would be
[{"recipient_id":"y1mLd","text":"Welcome, Please let me know how I could be a help today!"}]

Hope this helps!

A: Simple curl without method type worked for me:
curl localhost:5005/model/parse -d '{"text":"hello"}'

A: I also faced this error on Windows 10 . Following commands worked for me finally.
curl localhost:5005/model/parse -d "{\"text\":\"hello\"}"

and
curl -H "Content-Type: application/json" -X POST localhost:5005/model/parse -d "{\"text\":\"hello\"}"


text:
Q: TortoiseHG doesn't show up in 13.04 TortoiseHG previously worked on 12.10, but after today's reinstall, it simply doesn't show up, not even with the thg command.

A: I managed to install it rather easily by using the tortoisehg ppa:
sudo add-apt-repository -y ppa:tortoisehg-ppa/releases
sudo apt-get update
sudo apt-get install mercurial tortoisehg

Note: @piwi's method works too.

A: This is not a solution but rather a workaround. The version of TortoiseHG from the repository works fine.
I first installed the latest version of mercurial (otherwise thg will complain about a version mismatch for hg); I installed it in ~/opt:
hg clone --branch stable http://selenic.com/hg ~/thg/mercurial
cd ~/thg/mercurial
python setup.py install --prefix=$HOME/opt

export PATH="$HOME/opt/bin:$PATH"
export PYTHONPATH="$HOME/opt/lib/python2.7/site-packages:$PYTHONPATH"

I use bash, so I needed to remove the hash entry for mercurial:
hash -d hg

Then I made a copy of the thg repository and ran it from the repository I wanted to work from:
hg clone --branch stable http://bitbucket.org/tortoisehg/thg ~/thg/tortoisehg
cd ~/devel/myrepo
~/thg/tortoisehg/thg


text:
Q: Sync Framework - consistency unit I was reading sync framework glossary when I found the following statement:

consistency unit : The minimal unit of consistency. Because all changes that have the same consistency unit are sent together, synchronization can never be interrupted when only part of a consistency unit is applied.

My question is: If connection falls when one consistency unit is being applied, what does happen?
I am suspecting that I am facing a problem related to this. I am simulating the following scenario: I am doing sync through a WCF service when internet falls. So, sync is interrupted and in other opportunity I repeat synchronization. When I do it, I get violation of primary key conflict. More specifically:

Violation of PRIMARY KEY constraint 'PK_AREAPERIODOAGRONEGOCIO'. Cannot insert duplicate key in object 'dbo.AreaPeriodoAgronegocio'. The duplicate key value is (7). The statement has been terminated.


text:
Q: How to disable android hiding an activity on keycode_button_... events? I'm using a rooted tabled with an USB port in host mode to read the value of an xbox-controller-joystick (with onJoystickMotion).
Now, I also want to track the buttons keycode_button_a, keycode_button_b, keycode_button_x, keycode_button_y and keycode_button_select. The tracking is working, but pressing these buttons will hide the activity.
Is there any way to disable android hiding an activity on this keycode_button_... events?

A: @Override
public boolean dispatchKeyEvent(KeyEvent event) {
    InputDeviceState state = getInputDeviceState(event);
    if (state != null) {
        switch (event.getAction()) {
            case KeyEvent.ACTION_DOWN:
                if (state.onKeyDown(event)) {
                    //Do my thing
                }
                break;
            case KeyEvent.ACTION_UP:
                if (state.onKeyUp(event)) {
                    //Do my thing
                }
                break;
        }
        return true;
    }
    return super.dispatchKeyEvent(event);
}

Yeah :D


text:
Q: Convert large text from Gibberish to Hebrew in C# I want to convert Gibberish text (for example "îö"á äùàìåï" to hebrew).
So I used that code:
            string oldText = "îö"á äùàìåï";
            var enc = Encoding.GetEncoding("windows-1255");
            string newText;
            newText = enc.GetString(oldText.ToCharArray().Select(c => checked((byte)c)).ToArray());

The problem is that GetString receives only byte, and my knowledge of overriding it with a different function that will receive Int or Int64 is very low.
This result with long text to convert brings an overflow error.
How can I convert the Gibberish text so it will allow long text to be converted to Hebrew (Windows-1255)?
My goal is to paste a Gibberish text into a textbox and the converted text will be in a different textbox...
EDIT
OK I changed my code:
string oldText = txtOriginal.Text;
        var enc = Encoding.GetEncoding("windows-1252");
        string convertedText = "";
        byte[] buffer;
        try
        {

            buffer = enc.GetBytes(oldText);
            convertedText = Encoding.GetEncoding("windows-1255").GetString(buffer);
            txtConverted.Text += convertedText;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

Now I have a new problem - what if the input text contains Hebrew characters?
is there a way to check the encoding of a textbox?
Something like check if its Hebrew then skip the conversion, else, convert to Hebrew.
Thanks in advance


text:
Q: How to exclude unwanted comparisons in two-way ANOVA in R I would like to know the way to exclude all the unwanted pairs of POST-HOC tests from the output generated from two-way ANOVA. Details as follows:
I have datTable contain proportion data under two factor site (four levels: A, B, C, D) and treatment(two levels: control and treated). Specifically, I want to do a pair-wise test among all the site under each same treatment (e.g. control-A VS. control-B, control-A VS.control-C, treated-A VS.treated-C, etc.), while excludes comparisons between different sites and different treatments(e.g., pairs such as control-A VS. treated-B, control-B VS. treated-C).
The data looks like this:
> datTable
   site treatment proportion
     A   control  0.5000000
     A   control  0.4444444
     A   treated  0.1000000
     A   treated  0.4000000
     B   control  0.4444444
     B   control  0.4782609
     B   treated  0.0500000
     B   treated  0.3000000
     C   control  0.3214286
     C   control  0.4705882
     C   treated  0.1200000
     C   treated  0.4000000
     D   control  0.3928571
     D   control  0.4782609
     D   treated  0.4000000
     D   treated  0.4100000

I did a two-way ANOVA (also not sure whether to use within subject site/treatment or between subject site*treatment...), and summarised the results.
  m1 <- aov(proportion~site*treatment,data=datTable) # Or should I use 'site/treatment'?

Then my summary(m1) gave me the following:
> summary(m1)
               Df  Sum Sq Mean Sq F value Pr(>F)
site            3 0.02548 0.00849   0.513 0.6845
treatment       1 0.11395 0.11395   6.886 0.0305 *
site:treatment  3 0.03686 0.01229   0.742 0.5561
Residuals       8 0.13239 0.01655

Next step is to use TukeyHSD post-hoc test to see actually which pair caused the * significance in site factor.
> TukeyHSD(m1)
  Tukey multiple comparisons of means
    95% family-wise confidence level

Fit: aov(formula = proportion ~ site * treatment, data = datTable)

$site
            diff        lwr       upr     p adj
B-A -0.042934783 -0.3342280 0.2483585 0.9631797
C-A -0.033106909 -0.3244002 0.2581863 0.9823452
D-A  0.059168392 -0.2321249 0.3504616 0.9124774
C-B  0.009827873 -0.2814654 0.3011211 0.9995090
D-B  0.102103175 -0.1891901 0.3933964 0.6869754
D-C  0.092275301 -0.1990179 0.3835685 0.7461309

$treatment
                      diff        lwr         upr     p adj
treated-control -0.1687856 -0.3171079 -0.02046328 0.0304535

$`site:treatment`
                            diff        lwr       upr     p adj
B:control-A:control -0.010869565 -0.5199109 0.4981718 1.0000000
C:control-A:control -0.076213819 -0.5852551 0.4328275 0.9979611
D:control-A:control -0.036663216 -0.5457045 0.4723781 0.9999828
A:treated-A:control -0.222222222 -0.7312635 0.2868191 0.6749021
B:treated-A:control -0.297222222 -0.8062635 0.2118191 0.3863364  # Not wanted
C:treated-A:control -0.212222222 -0.7212635 0.2968191 0.7154690  # Not wanted
D:treated-A:control -0.067222222 -0.5762635 0.4418191 0.9990671  # Not wanted
C:control-B:control -0.065344254 -0.5743856 0.4436971 0.9992203
D:control-B:control -0.025793651 -0.5348350 0.4832477 0.9999985
A:treated-B:control -0.211352657 -0.7203940 0.2976887 0.7189552  # Not wanted
B:treated-B:control -0.286352657 -0.7953940 0.2226887 0.4233804  # Not wanted
C:treated-B:control -0.201352657 -0.7103940 0.3076887 0.7583437  # Not wanted
D:treated-B:control -0.056352657 -0.5653940 0.4526887 0.9996991
D:control-C:control  0.039550603 -0.4694907 0.5485919 0.9999713
A:treated-C:control -0.146008403 -0.6550497 0.3630329 0.9304819  # Not wanted
B:treated-C:control -0.221008403 -0.7300497 0.2880329 0.6798628  # Not wanted
C:treated-C:control -0.136008403 -0.6450497 0.3730329 0.9499131
D:treated-C:control  0.008991597 -0.5000497 0.5180329 1.0000000  # Not wanted
A:treated-D:control -0.185559006 -0.6946003 0.3234823 0.8168230  # Not wanted
B:treated-D:control -0.260559006 -0.7696003 0.2484823 0.5194129  # Not wanted
C:treated-D:control -0.175559006 -0.6846003 0.3334823 0.8505865  # Not wanted
D:treated-D:control -0.030559006 -0.5396003 0.4784823 0.9999950
B:treated-A:treated -0.075000000 -0.5840413 0.4340413 0.9981528
C:treated-A:treated  0.010000000 -0.4990413 0.5190413 1.0000000
D:treated-A:treated  0.155000000 -0.3540413 0.6640413 0.9096378
C:treated-B:treated  0.085000000 -0.4240413 0.5940413 0.9960560
D:treated-B:treated  0.230000000 -0.2790413 0.7390413 0.6429921
D:treated-C:treated  0.145000000 -0.3640413 0.6540413 0.9326207

However, there are some pairs I don't want to be included in the two-way ANOVA which I preformed, specified as # not wanted.
Is there any way that I can tweak the aov or TukeyHSD function to exclude those possibilities ('not wanted' ones) I listed above? I could easily select the significant entires that I am interested (with *) from the long list produced from TukeyHSD. But I don't want my result from anova to be biased by those! (It happens in the real data that the significance actually caused by those unwanted pairs!)
NB: You might have noticed that the site:treatment post-hoc tests doesn't show any significance, this is because I only selected a small sample from the original data.


text:
Q: Implement IEntityWithKey with POCO template I (for me, quite surprisingly) have never seen any questions or blog posts about this.
Is it possible to modify the POCO T4 template in a way that POCO classes implement the IEntityWithKey interface? I would like to do this in order to be able to attach entities directly to the ObjectContext.
Is this possible? What are the drawbacks?

A: You didn't see any question about this because implementing the interface will mean that your entity is not persistent ignorant any more (which is main reason to use POCO) because it would expose persistent related property dependent on Entity framework. That is the reason why nobody use it with POCO template.
But yes it is possible to implement this interface.


text:
Q: Injecting custom network url not working relayjs I am following this sample app : https://github.com/relayjs/relay-starter-kit
Relay.injectNetworkLayer(
  new Relay.DefaultNetworkLayer('http://localhost:8080/graphql')
);

with custom url i am getting following errors

OPTIONS http://localhost:8080/graphql
  net::ERR_EMPTY_RESPONSEself.fetch @ relay.js:21558Promise @
  app.js:3335self.fetch @ relay.js:21508sendTimedRequest @
  relay.js:20131module.exports @ relay.js:20186tryCallTwo @
  relay.js:3762doResolve @ relay.js:3879Promise @
  relay.js:3782fetchWithRetries @ relay.js:20122_sendQuery @
  relay.js:13042(anonymous function) @ relay.js:12976sendQueries @
  relay.js:12975sendQueries @ relay.js:3502processQueue @
  relay.js:17591(anonymous function) @ relay.js:17582tryCallOne @
  relay.js:3754(anonymous function) @ relay.js:3820flush @ relay.js:9457
  relay.js:21558 OPTIONS http://localhost:8080/graphql
  net::ERR_EMPTY_RESPONSEself.fetch @ relay.js:21558Promise @
  app.js:3335self.fetch @ relay.js:21508sendTimedRequest @
  relay.js:20131 relay.js:21558 OPTIONS http://localhost:8080/graphql
  net::ERR_EMPTY_RESPONSEself.fetch @ relay.js:21558Promise @
  app.js:3335self.fetch @ relay.js:21508sendTimedRequest @
  relay.js:20131 relay.js:7449 Network request failed_markAsRejected @
  relay.js:7449_handleSubtractedQueryFailure @ relay.js:7430tryCallOne @
  relay.js:3754(anonymous function) @ relay.js:3820flush @ relay.js:9457

A: I'm guessing that your application is running on port 3000. If you try to make client=>server requests to a different domain/port combination, without enabling such cross-origin requests on the server side, your browser will use its default CORS policies to block the request.
You can enable requests from all origins, on the server side, like this:
import cors from 'cors';

var graphQLServer = express();
graphQLServer.use(cors());
/* ... */

Check out the cors docs for more fine grained control.
Be sure to npm install --save cors, wherever your server code lives.


text:
Q: How would you code a Click-Pixel next to an Impression-Pixel (Tracking)? Context:
you are running a web site with ads coming from different providers. For an ad you usually get a whole javascript snippet (that inserts everything needed by the client to track the ad). Sometimes you have smaller clients that can only provide the creative (JPG) and an URL to track the impressions (impression pixel).
Question:
Now you got a client who wants a Click-Pixel in addition to the Impression-Pixel. Means: Whenever the ad is displayed (JPG), also the Impression-Pixel URL is called (easy) but if a user clicks on the ad, the browser should not only open the target URL but should also call the Click-Pixel URL (also an invisible 1x1 px image). How would you implement the click-pixel?
My solution so far:
Is there any better approach how to implement a click-pixel?
Alternatives to a click pixel:
I would count clicks on the client side (via Google Analytics) but some clients do not want to use GA or other tracking mechanisms like that.
HTML:

jQuery:
$(document).ready(function() {
  $('a#ad').click(function() {
    var url = $(this).attr("clickpixelurl");
    $.get(url); // this will call a GET async but won't wait for the answer
  });
});

How would you implement a click pixel?


text:
Q: SQLAlchemy setting server_default to values of other columns I have a pre-populated database with two columns. Column 'A' is a unique id which is just an integer, and column 'B' is just some string.
I want to create a new column that is simply the string concatenation of the two columns.
How would I do this using server_default?
Thanks!

A: You could use a Computed column to hold the value:
import sqlalchmy as sa

tbl = sa.Table(
    't73280376',
    sa.MetaData(),
    sa.Column('a', sa.Integer, primary_key=True),
    sa.Column('b', sa.String),
    sa.Column('c', sa.String, sa.Computed('a::text || b')),
)

Note that the column cannot be updated independently of a and b.
Passing the same expression to server_default
sa.Column('c', sa.String, server_default=sa.text('a::text || b'))

does not generate valid DDL:
test# CREATE TABLE t73280376 (
test(#         a SERIAL NOT NULL,
test(#         b VARCHAR,
test(#         c VARCHAR DEFAULT a::text || b,
test(#         PRIMARY KEY (a)
test(# )
test-# ;
ERROR:  cannot use column reference in DEFAULT expression
LINE 4:         c VARCHAR DEFAULT a::text || b,