Como fazer com que uma DIV preencha toda a largura disponível

Question: Tenho duas divs, uma com largura fixa, 250px; que fica à esquerda, será um menu fixo, sempre à esquerda.
E outra div à direita que quero fazer com que ela fique 100%, sempre que o usuário manusear os cantos da tela, ela fiquei 100%.
Algo assim:
.menu{width: 250px; float: left; position;fixed}
.resto{width:100%; float:right;}

Answer: Faça assim:
.menu{ width: 250px; float: left; background-color: blue; }
.resto{ background-color: red; overflow: hidden;}

Para que fique assim:

Note que se o conteúdo tiver múltiplas linhas, ele não vai aparecer debaixo do menu. Isso é feito pelo uso do estilo overflow: hidden. Além disso, o conteúdo não precisa do estilo float que você usou.
Exemplo no jsfiddle
Se não fosse pelo uso do overflow: hidden ficaria assim:
Comment: Muito obrigado Miguel, sua dica foi muito útil! :)
Comment: psss... Onde foste buscar o `position:blocked` ? _(ver: [W3C - CSS Properties - Position](http://www.w3.org/wiki/CSS/Properties/position))_ Quer uses `position:blocked` quer não, como o valor para essa propriedade é inválido, essa declaração não é interpretada pelo navegador. O resultado se removeres isso do teu código é rigorosamente o mesmo, mantendo a tua solução como válida.
Comment: @Zuul: Tomei por base a resposta do @JeffersonAlison, mas ao invés de usar `height: 100%` nas classes CSS, eu usei `overflow: hidden` na classe `resto`... não sei de onde veio o `position:blocked`. =D
Comment: Não tinha reparado que ele também tinha esse `position:blocked`, obrigado pelo feedback, já deixei comentário na resposta dele em relação a este assunto.
Answer: Acho que assim da certo: EXEMPLO
CSS:
//Opcional para pegar 100% de altura
body, html, .menu, .resto{
    height: 100%;
    color: #fff;
}

.menu{
    width: 250px;
    float: left;
    background-color: #f09;
    position:blocked;
}

HTML:

    Menu Fixed com 250px

    Resto do conteudo (liquido)

Comment: psss... Onde foste buscar o `position:blocked` ? (ver: [W3C - CSS Properties - Position](http://www.w3.org/wiki/CSS/Properties/position)) Quer uses `position:blocked` quer não, como o valor para essa propriedade é inválido, essa declaração não é interpretada pelo navegador. O resultado se removeres isso do teu código é rigorosamente o mesmo, mantendo a tua solução como válida.
Answer: Se queres que as div's alterem o tamanho consoante o manusear da tela, tens de por todas as medidas em %. Ou seja, esse 250px tens de passar para %. Caso contrário ele vai sempre assumir esse tamanho e nunca o tamanho do ecrã.
EDIT:
Penso que seja isto que procuras. Tens de usar a position a blocked.
Segue JSFiddle que fiz, penso que seja a tua solução:
JSFIDDLE com div's
Comment: Na verdade, eu quero que apenas a div resto fica 100%, no caso à direita. A div com o menu não pode alterar de tamanho nem largura, ela é uma div fixa à esquerda. Será que tenho que fazer isso em javascript?
Comment: Editei o meu comentário. Dá uma olhadela
Comment: Se a largura é 100% não precisa de `float`
Comment: Pois não, apenas copiei o código do @FelipeStoker e já la vinha o `float`
Comment: Fiz a alteração. A div está aumentando 100%, teria como fazer isso também com os elementos dentro dessa div? inclusive com imagens?
Comment: Queres que as imagens também mudem de tamanho?
Comment: Isso mesmo, se possível isso também.
Talvez:

.resto img {width:100%}
?
Comment: Para ser sincero nunca experimentei :P Mas também deves ter de usar percentagens
Answer: Você quer fazer um layout responsivo? Caso sim dê uma olhada em bootstrap grid template, dessa forma você irá poder layouts responsivos facilmente.
Comment: Mas você quer que ela mude a característica quando as o usuário modificar o tamanho da tela do browser?
Comment: Responsivo, acho que não seria o termo certo. Eu quero que apenas uma div seja manuseada, no caso a div resto.
Answer: Acho que o que vc deseja é um menu lateral e o conteúdo no centro ?
Dê uma olhada no exemplo que eu fiz: http://jsfiddle.net/kLFk9/2/
Answer: Segue uma possível solução para seu problema.
PS: position:blocked, como citado não é um valor permitido para o position.
HTML

...

...

CSS
.box {
  border:1px solid #ccc;
  width: 900px;
  overflow:hidden;
}

/* coluna da esquerda */
.col1 {
  background-color: red;
  float: left;
  width: 300px;
}

/* coluna da direita */
.col2 {
  background-color: blue;
  width: 100%;
}

Veja no JSFiddle
Answer: Obrigado a todos, consegui resolver.
Na div do Menu. usei como de praxe:
.menu{position:fixed; width:192px; z-index:10;}
.resto{float:right; margin: 0 auto;}

Ai, foi necessário um JS
function resizeHome(){
    var largura = $(window).width();
        if(largura>=*tamanho mínimo da tela (VALOR)*){
            $('.resto').css('width',($(window).width()-*largura da div menu*)+'px');
        }
}

Comment: poste a solução para que mais pessoas vejam...
Comment: Editei meu comentário. =D
Comment: Cara, não tem necessidade de usar javascript pra isso, da uma olhada na minha resposta.
Comment: não seria melhor colocar os tamanhos todos em % pra não precisar usar javascript?
Comment: O que acontece é que existem elementos dentro dessas divs 100%, e esses elementos precisam ficar alinhados ao centro, ou seja, esses elementos precisam de um width definido e uma margin: auto, portanto, só com % não irá funcionar.
Answer: Caso você queira utilizar o menu com com position:fixed, uma boa maneira seria:
.menu{
    width:250px;
    position:fixed;
    top:0;left:0;
}
.resto{
    margin-left:250px;
}

Exemplo: FIDDLE


Finding an unknown joint PDF?

Question:
Knowing that $X$ and $Y$ are random variables, $f_{X,Y}(x,y)$ is their joint PDF, and
  \begin{align}
f_{X,Y}(x,y)=k, \qquad(0<x<2; 0<y<x)
\end{align}
  How can I compute $k$?
Comment: You can find $k$ by knowing and using that the total probability equals $1$.
Comment: \begin{align} \int_0^2\int_{0}^xf_{X,Y}(x,y)dydx \end{align} ?
Comment: Yes, that integral should equal $1$.
Answer: \begin{align}
& \int_{x = 0}^{2}\int_{y = 0}^{x}f_{X, Y}(x, y)\, dy\, dx = 1 \\
\implies & \int_{x = 0}^{2}\int_{y = 0}^{x} k \, dy\, dx = 1 \\
\implies & k \int_{x = 0}^{2} x \, dx = 1 \\
\implies & k \dfrac{x^{2}}{2}\Bigg\vert_{0}^{2} = 1 \\
\implies & 2k = 1 \\
\implies & k = 0.5
\end{align}
Answer: We know that
$$\int_0^2\int_{0}^{x} f_{X,Y}(x,y) \ dy \ dx =1$$
since this is a density.
So
$$\int_0^2\int_{0}^{x} k \ dy \ dx =1$$
$$\int_0^2\big[ky\big]_0^x \ dx =1$$
$$\int_0^2kx \ dx =1$$
$$\left[\frac12kx^2\right]_0^2=1$$
$$2k=1$$
$$k=\frac12$$
Answer: Geometrically, $0\lt x \lt 2, 0\lt y \lt x$ is a triangle with vertices in $O(0,0), A(2,0), B(2,2)$ and its area is $2$. Thus, the integral of the (constant) PDF over that triangle is $k\cdot \operatorname{Area}(\triangle OAB)$, i.e. $1=2k$, which gives $k=\frac{1}{2}$.

Finding an unknown joint PDF?


displaying several treeviews one below the other

Question: I have a project that consists in displaying a datamodel using qtreeview from a folder that contains several files. I displayed a treeview of a single file but i couldn't display several treeviews one under the other of several files.
here is my main.py :
import sys
from PyQt5.QtWidgets import *
from start_window import StartWindow

def main():
    app = QApplication(sys.argv)
    start_window = StartWindow()
    start_window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

my start_window.py where I need to implement the choose folder function to reach the goal :
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from table_view import Table
from odl_parser import ODLParser

class StartWindow(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('Open ODL File or Folder')
        self.resize(600, 400)

        main_layout = QHBoxLayout(self)

        self.image_label = QLabel(self)
        self.image_label.setPixmap(QPixmap('ACLViewer.jpg').scaled(300, 300, Qt.KeepAspectRatio))
        main_layout.addWidget(self.image_label)

        buttons_layout = QVBoxLayout()

        self.choose_file_button = QPushButton('Choose File', self)
        self.choose_file_button.clicked.connect(self.choose_file)
        buttons_layout.addWidget(self.choose_file_button)

        self.choose_folder_button = QPushButton('Choose Folder', self)
        self.choose_folder_button.clicked.connect(self.choose_folder)
        buttons_layout.addWidget(self.choose_folder_button)

        main_layout.addLayout(buttons_layout)

    def choose_file(self):
        file_path, _ = QFileDialog.getOpenFileName(self, "Open ODL File", "", "ODL Files (*.odl)")
        if file_path:
            self.open_table_view(file_path)

    def choose_folder(self):
        folder_path = QFileDialog.getExistingDirectory(self, "Open Folder Containing ODL Files")
        if folder_path:
            # code for the folder

    def open_table_view(self, file_path):
        parser = ODLParser(file_path)
        window = Table(parser)
        window.setWindowTitle('DM Parsing - ' + file_path)
        window.show()

I displayed one tree view of a single parsed file , but when I click on choose folder i want to display all the treeviews of all the files in this folder
Comment: Please don't [delete questions](https://stackoverflow.com/q/78230541/2001654) just to recreate them right after. Instead, use the [edit] button under them and *take your time* to properly update the post with the necessary information asked in comments. Right now it's **still unclear** what problem you have: what do you mean by "all the treeviews"? Are you referring to the *branches* of *one* tree? If you have difficulties in English language and technical terms, find somebody that can help you.
Comment: Can you tell us what is expected in the output ? what exactly is the output needed ?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: make suitable changes as needed.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTreeView, QFileSystemModel

class FileTreeView(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("File Treeview")
        self.setGeometry(100, 100, 800, 600)

        # Create a QTreeView widget
        self.tree_view = QTreeView(self)
        self.tree_view.setGeometry(50, 50, 700, 500)

        # Create a QFileSystemModel instance
        self.model = QFileSystemModel()
        self.model.setRootPath('')
        self.tree_view.setModel(self.model)

        # Set the root path for the model
        folder_path = "/path/to/your/folder"  # Change this to your folder path
        self.tree_view.setRootIndex(self.model.index(folder_path))

        # Expand the treeview to show all contents
        self.tree_view.expandAll()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    file_treeview = FileTreeView()
    file_treeview.show()
    sys.exit(app.exec_())


If a periodic function is written as linear combination of 2 functions then must they also be periodic?

Question: Given a non constant periodic function with period $T$, say $f(x)$. Also given that $f(x)$ can be written as a linear combination of 2 independent functions as
$$f(x) = a \, g(x) + b \, h(x),$$
where $a$ and $b$ are real constants.
Then my question is that does this imply that $g$ and $h$ are also periodic functions with period $T$ (not necessarily fundamental)??
Intuitively it seems true. But not sure how.
Answer: As long as $ a $ and $ b $ are both non-zero, you can let $ g $ be any non-periodic function, and let $ h $ be $ \frac 1 b ( f - a g ) $.  Then $ f = a g + b h $, $ g $ and $ h $ are linearly independent, and neither $ g $ nor $ h $ is periodic.
So for example, if $ f $ is the sine function (with period $ 2 \pi $), $ a $ and $ b $ are both $ 1 $, and $ g $ is the identity function, then $ h ( x ) = \sin x - x $ for all $ x $.  Now $ f = 1 g + 1 h $, $ g $ and $ h $ are linearly independent, and neither $ g $ nor $ h $ is periodic.  But this example is nothing special.
However, as long as $ b $ is non-zero, if $ f $ and $ g $ are periodic (with a same period), then $ h $ must also be periodic (with that period).  That's because $$ h ( x + T ) = \frac 1 b \bigl ( f ( x + T ) - a g ( x + T ) \bigr ) = \frac 1 b \bigl ( f ( x ) - a g ( x ) \bigr ) = h ( x ) \text . $$  Perhaps this is what your intuition was going for.
Answer: Consider something like
$$g(x)=
\begin{cases}
\sin x\text{,}&\text{if $x\notin\Bbb Q$,}\\
0\text{,}&\text{if otherwise.}
\end{cases}
\quad\text{and}\quad
h(x)=
\begin{cases}
\sin x\text{,}&\text{if $x\in\Bbb Q$,}\\
0\text{,}&\text{if otherwise.}
\end{cases}
$$


Obter dados como Array e não como objeto - Codeigniter

Question: Olá!
Eu pretendo obter os dados da tabela tbl_devedor_parcela, utilizando o campo negociacao_id, sendo assim, eu preciso recuperar os dados da tabela tbl_devedor_parcela como array de objetos. O primeiro ID da tabela tbl_devedor_parcela, está sendo recuperado como array de objetos, porem os demais, estão sendo recuperado somente como objeto.

Como faço para recuperar tudo como array de objetos ?
Seguem tabelas;
tbl_devedor_negociacao
DROP TABLE IF EXISTS `tbl_devedor_negociacao`;
CREATE TABLE IF NOT EXISTS `tbl_devedor_negociacao` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `dt_negociacao` DATE NULL DEFAULT NULL,
  `atualizar` VARCHAR(5) NULL DEFAULT NULL,
  `id_finalizacao` INT(11) NULL DEFAULT NULL,
  `contrato_id` INT(11) NULL DEFAULT NULL,
  `crud` VARCHAR(2) NULL DEFAULT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 1;

tbl_devedor_parcela
DROP TABLE IF EXISTS `tbl_devedor_parcela`;
CREATE TABLE IF NOT EXISTS `tbl_devedor_parcela` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `dt_vencimento` DATE NULL DEFAULT NULL,
  `num_parcela` VARCHAR(20) NULL DEFAULT NULL,
  `valor` VARCHAR(20) NULL DEFAULT NULL,
  `negociacao_id` INT(11) NULL DEFAULT NULL,
  `atraso` VARCHAR(20) NULL DEFAULT NULL,
  `crud` VARCHAR(2) NULL DEFAULT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 1;

Código Model
//Fonte - Início
//Negociações
$id_contratos = array_map(function($item) {
    return $item['id'];
}, $result['contratos']);
$negociacoes = $this->obter_negociacao($id_contratos);

//Parcelas
$id_parcelas = array_map(function($item) {
    return $item['id'];
}, $negociacoes);
$parcelas = $this->obter_parcela($id_parcelas);

//view
$id_contratos = array_map(function($item) {
    return $item['id'];
}, $result['contratos']);
$empresa = "Banco Semear";
$view["empresa"] = $empresa;

for ($i = 0; $i < count($result['contratos']); $i++) {
    $id = $result['contratos'][$i]['id'];
    $result['contratos'][$i]['view'] =
        array_filter($view, function($a) {
            return $a;
        });
}

for ($i = 0; $i < count($negociacoes); $i++) {
    $id = $negociacoes[$i]['id'];
    $negociacoes[$i]['parcelas'] =
        array_filter($parcelas, function($a) use($id) {
            return $a['negociacao_id'] == $id;
        });
}

for ($i = 0; $i < count($result['contratos']); $i++) {
    $id = $result['contratos'][$i]['id'];
    $result['contratos'][$i]['negociacoes'] =
        array_filter($negociacoes, function($a) use($id) {
            return $a['contrato_id'] == $id;
        });
}

return $result;
//Fonte - Fim

//Obter negociações
public function obter_negociacao($id) {
    $this->db->from($this->tbl_devedor_negociacao);
    $this->db->select("tbl_devedor_negociacao.*, IF(tbl_devedor_negociacao.crud = 'C', 'R', 'C') as crud", FALSE);
    if (is_array($id)) {
        $this->db->where_in('contrato_id', $id);
    }
    else
    {
        $this->db->where('contrato_id', $id);
    }
    $this->db-> order_by('contrato_id');
    $query = $this->db->get();
    return $query->result_array();
}
//Obter parcela
public function obter_parcela($id) {
    $this->db->from($this->tbl_devedor_parcela);
    $this->db->select("tbl_devedor_parcela.*, IF(tbl_devedor_parcela.crud = 'C', 'R', 'C') as crud", FALSE);
    if (is_array($id)) {
        $this->db->where_in('negociacao_id', $id);
    }
    else
    {
        $this->db->where('negociacao_id', $id);
    }

    $query = $this->db->get('');
    return $query->result_array();
}

Answer: Precisa adicionar junto com array_filter o array_values, para que seja criado também o array, exemplo:
for ($i = 0; $i < count($negociacoes); $i++) {
    $id = $negociacoes[$i]['id'];
    $negociacoes[$i]['parcelas'] = array_values(array_filter($parcelas,
     function($a) use($id) {
      return $a['negociacao_id'] == $id;
    }));
}

Referencias

SOEn- array_filter and multidimensional array
array_filter
array_values
Comment: perfeito, funcionou..
Obrigado


Prove superpolynomial growth rate

Question: Let $p(n)$ be the number of partitions of $n$.
Prove that growth rate of $p(n)$ is superpolynomial, meaning that for every given $k$ there is $p(n)= \omega (n^k)$.
Comment: What do you mean by "the number of divisions" of $n$? If you mean the number of *divisors*, that can't be, since that's way less than $n$ itself. But maybe you mean the number of *partitions*. Look that up, and see if you can find the information you need. See also http://math.stackexchange.com/questions/564907/help-understanding-solution-to-growth-of-partition-function
Comment: It was my mistake - I mean partitions.
Answer: Given $k$, the number of compositions of $n$ into $k+1$ parts is $\binom{n+k}k$, which is a polynomial of degree $k$ in $n$. The number of partitions of $n$ into $k+1$ parts is at least $\frac1{(k+1)!}$ times the number of compositions. This gives the required order of growth only considering partitions into $k+1$ parts, which of course is a lower bound for the total number of partitions.

Prove superpolynomial growth rate


Where Is My Mistake? (Integration, Fourier Series)

Question: I am trying to calculate $c_m = \displaystyle{\int_0^1e^{-2\pi ixm} \sum_{n= -\infty}^\infty  c_n e^{2\pi ixn} \, dx}$ for $m = 0$.
Here is my work:
$\displaystyle{\int_0^1e^{-2\pi ixm} \sum_{n= -\infty}^\infty  c_n e^{2\pi ixn} \, dx = \int_0^1 \sum_{n = -\infty}^\infty c_n e^{-2\pi ixm} e^{2\pi ixn} \, dx = \sum_{n=-\infty}^\infty c_n \int_0^1 e^{-2\pi ixm} e^{2\pi ixn} \, dx}$
(I know that interchanging a sum and an integral is not always possible, but I am almost certain that through the Fubini-Tonelli Theorem it is justified here)
$\displaystyle{m = 0 \Rightarrow \sum_{n = -\infty}^\infty c_n \int_0^1 e^{0} e^{2\pi ixn} \, dx = \sum_{n = -\infty}^\infty c_n \int_0^1 e^{2\pi ixn} \, dx = \sum_{n = -\infty}^\infty c_n \frac{e^{2\pi ixn}}{2 \pi in} \biggr\rvert_0^1 = \sum_{n = -\infty}^\infty \frac{c_n}{2 \pi in} \left( e^{2 \pi in} - e^{0} \right) = \sum_{n = -\infty}^\infty \frac{c_n}{2 \pi in} \left( \left( \left( e^{\pi i} \right)^2 \right)^n - 1 \right) = \sum_{n = -\infty}^\infty \frac{c_n}{2 \pi in} \left( \left( \left( -1 \right)^2 \right)^n - 1 \right) = \sum_{n = -\infty}^\infty \frac{c_n}{2 \pi in} \left( \left( 1 \right)^n - 1 \right) = \sum_{n = -\infty}^\infty \frac{c_n}{2 \pi in} \left(1 - 1 \right) = 0}$
My source says that the answer is $\frac{1}{6}$. Where did I go wrong?
Edit: I feel like it's confusing that $m$ and $n$ look so alike, so I would like to reiterate: It is given that $m = 0$, not $n = 0$
Comment: I apologize in advance for any typos; I'm not in the best mood as the result of being frustrated with this question.
Comment: What is your justification for the penultimate equality? $(-1)^n = \pm 1$ depending on the parity of $n$, so why have you said that $(-1)^n =1$?
Comment: @SeraPhim It's $\left( \left( -1 \right)^2 \right)^n$. Thus, $1^n = 1$
Comment: Your integration formula $\int_0^1\exp(0\times2\pi ix)dx=(1-1)/(2\pi i 0)=0$ is wrong.
Comment: Oh yes my apologies, I misread it
Comment: @kimchilover If you are referring to $e^0e^{2\pi ixn}$, then I never simplified it as $e^{0 \times 2\pi ixn}$, as that would be wrong. The $e^0$ goes away, since $e^0$ is 1. Additionally, if I were to write it an a single exponential, it would be $e^{0 \textbf{+} 2 \pi ixn }$, not $e^{0 \times 2 \pi ixn}$
Comment: @SeraPhim All good :)
Comment: Are you computing the Fourier coefficient of the product of a constant function times a Fourier series?
Answer: You haven't actually told us what the function is other than it has a Fourier expansion $\sum c_ne^{2\pi inx}$, so there is no way for us to tell you how to get $c_0=\frac16$.  But let's assume you can calculate the integrals $\int_0^1 e^{2\pi imx}f(x)\,\mathrm{d}x$ in some way.
You made a mistake with the integration of the $n=0$ term.  Specifically, when $n=0$, you can't have "divide by $n$".  Instead,
$$
e^{2\pi ix0}=1\quad\forall x
$$
so
$$
\int_0^1 e^{2\pi ix0}\,\mathrm{d}x=1,\text{ not }\left.\dfrac{e^{2\pi i0x}-1}{2\pi i0}\right\rvert_0^1.$$
Comment: I'm not assuming $n = 0$, but rather $m = 0$. So $e^{2 \pi ixn}$ never simplifies to $e^{2 \pi ix0}$, as $n$ is just an arbitrary constant in the integral, which is with respect to $x$.
Comment: Huh? $n$ is your dummy in $\sum_n c_n e^{2\pi ix n}$ which you swapped out the summation of.  Now you imposed $m=0$ in the integral so when $n=0$, which is a perfectly valid term in your sum, you get to integrate $e^{2\pi ix0}=1$ rather than $e^{2\pi ixn}$, $n\neq 0$.
Comment: Doesn't the integral take priority first? That's why I calculated the integral first and dealt with $n$ as just some constant.
Comment: No!  If it is a term in the sum, then it is there in the integral of the sum or the sum of integrals, so you need to deal with it.  You only dealt with all $n\neq 0$ but you can't use them to conclude the same must be true for $n=0$.
Comment: I understand now, thank you very much for your solution. I just have one final question. Does the whole thing then evaluate to $c_0$? Since the only $n$-term that doesn't end up as $0$ is $n = 0$, which ends up as 1 in the integral and the sum collapses to a single term: $c_0$.
Comment: Yes, and we have $\int_0^1 e^{-2\pi i m x} \sum_n c_ne^{2\pi i n x}\,\mathrm{d}x=c_m$ for all $m$.


Adiciono itens ao ArrayList mas quando vou utilizá-lo ele está vazio

Question: Não consigo adicionar itens ao meu ArrayList
Classe principal, onde o array é instanciado
public class act_principal extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener{

    private List<Medico> medicos = new ArrayList<Medico>();

Método onde os itens deveriam ser adicionados ao Array
public void setArrayMedico()
    {
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, json_url_getMedicos, (String)null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                int codigo = 0;
                String nome="";

                for(int i=0; i<response.length(); i++)
                {
                    try {
                        JSONObject jsonObject = response.getJSONObject(i);

                        codigo = jsonObject.getInt("Codigo");
                        nome = jsonObject.getString("Nome");

                        medicos.add(new Medico(codigo, nome));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        MySingleton.getInstance(this).addToRequest(jsonArrayRequest);
    }

Quando debugo, ele insere normalmente no Array os itens, porém, quando acesso o Array após essa função, o mesmo está com size() == 0, ou seja, vazio. Onde está o meu erro?
Desde já, agradeço
Answer: Note que não é o método setArrayMedico() que preenche a lista mas sim o método onResponse(), da classe JsonArrayRequest.
Dito de outro modo: quando o método setArrayMedico() é chamado ele retorna de imediato, antes de a lista ser preenchida.
Se o código que está a utilizar é algo assim:
setArrayMedico();
boolean isEmpty = medicos.isEmpty();

isEmpty será true.
Uma solução possível será:

Não declare o ArrayList como atributo da Activity, isso garantirá que não é usado sem estar preenchido.
Declare um método que será chamado quando a lista estiver preenchida:
private void onMedicosIsReady(List<Medico> medicos){

    //Utilize aqui a lista
}

No método onResponse() chame esse método depois da lista estar preenchida:
@Override
public void onResponse(JSONArray response) {
    int codigo = 0;
    String nome="";

    //Declaração do ArrayList
    List<Medico> medicos = new ArrayList<Medico>();

    for(int i=0; i<response.length(); i++)
    {
        try {
            JSONObject jsonObject = response.getJSONObject(i);

            codigo = jsonObject.getInt("Codigo");
            nome = jsonObject.getString("Nome");

            medicos.add(new Medico(codigo, nome));

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    //Chama o método quando estiver preenchido
    onMedicosIsReady(medicos);
}

Comment: Certo, entendi. E como eu faria pra preencher meu ArrayList, se os dados que eu preciso estão no onResponse?
Comment: O problema é como(onde) está a utilizar o arraylist, pois ele é preenchido. Onde quer utilizar essa lista?
Comment: Sim, ele é preenchido, mas quando vou usar ele está vazio. O ideal seria chamar a setArrayMedico() para popular meu array, e na linha de baixo, jogar os dados para um ListView


Error attempting to uninstall Kibana with Brew

Question: I installed Kibana on myb mac using brew.  The kibana version is too recent for my ES cluster so I was going to uninstall and reinstall an older version.
When I issue this command:
brew uninstall kibana

I get the following error:
Error: No such keg: /usr/local/Cellar/kibana

I'm absolutely positive I installed using "brew install kibana" Is there anything I can do to uninstall kibana so I can reinstall an older version?
Answer: If you list directories inside Cellar folder, you will find a folder named kibana-full. You need to run
brew uninstall kibana-full

Comment: Alternatively, run `brew uninstall elastic/tap/kibana-full`


specifying the right perl version for git

Question: We want to install git on our system which runs HP UX 11.31 and the standard version of Perl (5.8.8e) which comes with the system. It is of utmost importance that the perl command keeps referring to Perl 5.8.8e so that our scripts run fine.
Git has a dependency on Perl 5.28. Mind, it was working fine with Perl 5.8.8e but we'd rather not risk running into issues later, so we installed it in a separate folder.
Now how can we make sure that git uses the correct version of Perl?
Comment: @bluppfisk, No, that doesn't say git depends on 5.28. It says that package requires the perl 5.28 package. It says that because the git package was created on a system with perl 5.28, not because git requires 5.28 (which came out earlier this year and which I've never installed, even though I've been using git for many many years)
Comment: Re "*Git has a dependency on Perl 5.28*", That's not true. The docs doesn't even mention it requires Perl (though it does mention it requires some Perl modules), so I suspect it only requires Perl 5.8.
Comment: http://hpux.connect.org.uk/hppd/hpux/Development/Tools/git-2.20.1/ on this website it states perl as a dependency. But yes it doesn't necessarily mean it has to be 5.28. Just wanted to be sure.
Comment: Have you considered moving away from a version of Perl that is over twelve years old? What is preventing you from doing that?
Comment: rrreaaaaallly strict system administrators and lots of legacy code. And expensive devs. And a general culture of "if it ain't broken don't fix it." which is fair enough. It should be possible to run them side-by-side.
Comment: okay good! I noticed the only reason there's a perl "dependency" seems to be that there's a perl API included in the source code.
Answer: The Perl scripts that Git runs begin with #! lines.  In the Git source, these lines read #!/usr/bin/perl, but as you build Git to install it, the source-builder replaces these with the correct path.  So if the correct path for a correct version of Perl is /usr/local/bin/perl, tell the build to use that; if it's /compat/perl5.28, tell the build to use that, and so on.
Answer: As illustrated with Git 2.44 (Q1 2024), the minimum version requirement for Perl to 5.8.1 (from September 2002).
That is because newer versions of Getopt::Long started giving warnings against our (ab)use of it in git send-email.
Bump the Perl version to simplify our implementation.
See commit 6ff658c, commit d13a73e (16 Nov 2023) by Todd Zullinger (tmzullinger).
(Merged by Junio C Hamano -- gitster -- in commit 1ef1cce, 09 Dec 2023)

perl: bump the required Perl version to 5.8.1 from 5.8.0
Signed-off-by: Todd Zullinger

The following commit will make use of a Getopt::Long feature which is only present in Perl >= 5.8.1.
Document that as the minimum version we support.
Many of our Perl scripts will continue to run with 5.8.0 but this change allows us to adjust them as needed without breaking any promises to our users.
The Perl requirement was last changed in d48b284 ("perl: bump the required Perl version to 5.8 from 5.6.[21]", 2010-09-24, Git v1.7.4-rc0 -- merge).
At that time, 5.8.0 was 8 years old.
It is now over 21 years old.

CodingGuidelines now includes in its man page:

We try to support Perl 5.8.1 and later ("use Perl 5.008001").


Use Arrays in Twig Template from Custom Block

Question: I'm attempting to use arrays in a twig template from variables in a custom block.
In my custom block I have
public function build() {
    $query = \Drupal::entityQuery('node')
        ->condition('type','product')
        ->sort('created', 'DESC');

    $nids = $query->execute();
    $i = 0;

    foreach ($nids as $nid) {
        $node = NODE::load($nid);
            $imageurl[$i] = $node->get('field_product_page_display')->entity->getFileuri();
            $title[$i] = $node->get('field_title')->value;
            $imageurl[$i] = str_replace("public://", "", $imageurl[$i]);
            $i += 1;

        }
    return array(
        '#theme' => 'product_display',
        '#imageurl' => $imageurl,
        '#product_title' => $title,
        );
}

In my mymodule.module file I have
function mymodule_theme($existing, $type, $theme, $path){
    return array('header' =>
        array(
            'variables' => array(
                'header_title' => 'Default Title',
                'header_size' => 'h1',
                'text_align' => 'center',
                'uppercase' => FALSE,
                'grid_size' => 12,
                ),
            ),
        'product_display' =>
            array(
                'variables' => array(
                    '#imageurl' => [],
                    '#product_title' => [],
                    ),
                ),
        );
}

in my product_display.html.twig file I have
{% for product in product_title %}
    {% for image in imageurl %}

                            {{ product }}

    {% endfor %}
{% endfor %}

I know for sure that my custom block.php file is able to retrieve the data properly because using Debug() on $imageurl or $title displays all the information. However using Dump() in product-display.html.twig shows the #imageurl and #product_title arrays as empty.
Answer: There is a syntax error in your hook_theme. Use this instead:
function mymodule_theme($existing, $type, $theme, $path){
return array('header' =>
    array(
        'variables' => array(
            'header_title' => 'Default Title',
            'header_size' => 'h1',
            'text_align' => 'center',
            'uppercase' => FALSE,
            'grid_size' => 12,
            ),
        ),
    'product_display' =>
        array(
            'variables' => array(
                'imageurl' => [],
                'product_title' => [],
                ),
            ),
    );

}
The # sign in a render array is used to differenciate a key that has a meaning in the rendering versus an element. It shouldn't be included in the theme definition.
Comment: That is not a syntax error.
Comment: Well, in terms of php it is not. In terms of drupal, I think it is though because the number sign has a special meaning in the render arrays. It might work (not tested it) if the render array has a double number sign like '##imageurl' for variables since it has a number sign in the theme declaration, but I sure wouldn't recommend it as it might have an unexpected behavior.


Overriding permissions of existing page blocks all users

Question: Problem
I'm trying to block access to Drupal's taxonomy pages for anonymous users.
I'm using the solution set out in this answer, but for Drupal 7 rather than 6.
I'm using hook_menu_alter and hook_permission to create a new access argument for taxonomy pages. The permission is successfully created, but no matter what roles I tick the pages remain blocked. Any ideas what I'm doing wrong?
Example Code
function custom_module_menu_alter(&$items) {
  $items['taxonomy/term/%']['access arguments'] = array('access taxonomy permission');
}

function custom_module_permission() {
  return array(
    'access taxonomy permission' => array(
        'title' => t('Access taxonomy pages'),
    )
  );
}

Answer: Is there any special reason that you're using 'taxonomy/term/%' instead of 'taxonomy/term/%taxonomy_term' in your implementation of hook_menu_alter()? If not, I would change that and clear the cache, see if it helps.
Edit...Here's a code example from the Term Per Role module:
function term_per_role_menu_alter(&$items) {
  $path = 'taxonomy/term/%taxonomy_term';
  if (isset($items[$path])) {
    $items[$path]['page arguments'] = array_merge($items[$path]['page arguments'], array($items[$path]['page callback']));
    $items[$path]['page callback'] = 'term_per_role_taxonomy_term_page';
  }
}

(A module which I would have recommended but the last commit on the project was over 3 years ago.)


Selenium "session not found" from FirefoxDriver

Question: I am new to Selenium and am trying to use the example on http://docs.seleniumhq.org/docs/03_webdriver.jsp. However, it doesn't work. Every time I run it, either from a JUnit test via Maven or from Eclipse Juno as a Java Application, I get something like this:
Exception in thread "main" org.openqa.selenium.WebDriverException: Session not found: 1d1a9aa2-f089-4f36-bb05-e1505c7b4e85
Command duration or timeout: 28 milliseconds
Build info: version: '2.33.0', revision: '4ecaf82108b2a6cc6f006aae81961236eba93358', time: '2013-05-22 12:00:17'
System info: os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.6.0'
Session ID: 1d1a9aa2-f089-4f36-bb05-e1505c7b4e85
Capabilities [{handlesAlerts=true, rotatable=false, databaseEnabled=true, locationContextEnabled=true, acceptSslCerts=true, applicationCacheEnabled=true, cssSelectorsEnabled=true, nativeEvents=true, takesScreenshot=true, platform=XP, browserName=firefox, javascriptEnabled=true, version=17.0.6, webStorageEnabled=true, browserConnectionEnabled=true}]
Driver info: org.openqa.selenium.firefox.FirefoxDriver
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
...

Here is the code that is failing:
public static void main(String[] args) {
    // Create a new instance of the Firefox driver
    // Notice that the remainder of the code relies on the interface,
    // not the implementation.
    WebDriver driver = new FirefoxDriver();

    // And now use this to visit Google
    driver.get("http://www.google.com"); // FAILURE

I debugged through it and saw that, when the FirefoxDriver constructor is called, a Firefox window actually opens on my system, then disappears, and then opens up again. It then fails on the driver.get() call.
I searched this site and found references to issues were the problem was with Chrome or IE, but Firefox worked. Everything else seemed to be a different error. I tried to get my Firefox version from the window it left open, but all I get when choosing "About Firefox" is this:
<window xmlns:html="http://www.w3.org/1999/xhtml"
^

If I launch Firefox directly, I see that my Firefox version is 17.0.6, and it says, "You are currently on the esr update channel". By the way, leaving that window open has no effect, either - it still opens a new Firefox window, closes it, reopens it, then leaves it there.
Comment: Do you have any entries in your [`etc/hosts`](http://en.wikipedia.org/wiki/Hosts_%28file%29) file? If there's any other binding to 127.0.0.1 other than `localhost`, WebDriver will fail.
Comment: It is possible that the version of Selenium you are using is not ompatible with Firefox17. Have you considered downgrading to FF12/13 or upgrading to FF19? Which version of Selenium are you using?
Comment: Slanec - I actually did have a second entry for 127.0.0.1 in my hosts file. However, removing it made no difference. Do I need to reboot Win 7 after making that change?
Comment: Sri, I am using Selenium 2.33.  This version of FF is the one mandated by my company, so changing the version is not something I can do lightly.
Comment: Rebooting after removing the extra etc hosts line made no difference. Also, I have a co-worker who has the same level of FF installed, but it's on Linux, and the exact same example code works with no problem for him.
Answer: I have exactly the same setup as you (Windows / Selenium 2.33 / FF 17.0.6 ) and I WAS seeing exactly the same behavior. I had tried everything I could find on the net.
Then I read somewhere that a user seeing this same issue is using their companies distribution of FF 17.0.6 ESR and when they downloaded and installed (along side their companies FF install) a fresh copy of FF 17.0.6 ESR  (and pointed the FF driver to use the new Firefox.exe binary) it worked.
So that is what I tried, as I WAS using a company deployed version of FF, and it worked!!  Here is my code using the second installation of FF 17.0.6 ESR
File pathToBinary = new File("C:\\Program Files (x86)\\Mozilla Firefox\\Firefox.exe");
FirefoxBinary ffBinary = new FirefoxBinary(pathToBinary);
FirefoxProfile ffProfile = new FirefoxProfile();
WebDriver ffDriver = new FirefoxDriver(ffBinary, ffProfile);
System.out.println("***Execute testGetTitle()");
ffDriver.get(pdURL);

(new WebDriverWait(ffDriver, 10)).until(new ExpectedCondition<Boolean>() {
     public Boolean apply(WebDriver d) {
     return d.getTitle().equals("Your Title Here")
     }
});

ffDriver.quit();

Give that a try and see if it is an issue with your FF install.
Comment: Yes, it was my company's version of FF. I actually uninstalled it, unzipped a copy of FF 19, put it in my path, and no Selenium works perfectly. Thanks!


Javascript/populate form fields

Question: I have a basic HTML form which is a table with four fields on either side. Each field has three values: comment, date, sameas
What I am trying to figure out is getting those "same as" menus to populate data into the corresponding field. ie: A user enters a date and comment at Right3 and chooses "Same as Left2," the date, comment and sameas values are automatically populated at Left2.
I am a novice at javascript, but if someone could push me in the right direction, I'd appreciate it.
Edit: I have figured out how to populate the text areas thanks to your code snippets.
Here is the result so far
Can I integrate the other two fields into the same function?
Answer: I would use jQuery to get the value of the select when it changes (using change function)
 and then set the value of the fields related to the select to populate the values of the field selected.
It seems complicated but a example should make it easier. Of course it's a very small example but I guess you will be able to do what you want with this example.
Hope it's a little light you can follow. :-)

Javascript/populate form fields


Excel modifed date is changing when running package

Question: I have a problem when loading data from excel source(excel 2010). When ever I run the package, the excel file modified date is changing to the current date. Even if I change the excel connection properties also, the file modified date is changing. How can I resolve this issue? I am using Dataflow task and excel source.
Answer: I could not find any other solution than setting read-only attribute on Excel and PowerPoint files to avoid that Excel (2010, 2007, 2003) and PowerPoint (2010, 2007, 2003) modify the binary data stream of the file without changing last modification date on just opening the file for reading and closing without making any change and therefore without explicit save.
I could see on comparing the binary files (*.xls, *.pps) before and after viewing the Excel/PowerPoint file with last modification date unchanged, but byte stream changed with (PowerPoint) or without (Excel) a change of file size, that those 2 applications from the Microsoft Office package always record in the file the name of the user who last opened the file, even when the file was not modified at all.
Microsoft Word (2010, 2007, 2003) does not modify the byte stream of *.doc files on just opening the document for reading. I could see this behavior only on Excel and PowerPoint.
I have not tested if other versions of Excel and PowerPoint than from Office 2010, 2007, 2003 make changes on file contents on just opening the file for viewing.
I would be really interested in if there is a registry value which could be set to avoid the modification of Excel and PowerPoint files on just viewing them.
See also How to prevent Excel from modifying the file on exit?


Are differences between powers of 2 equal to differences between powers of 3 infinitely often?

Question: Consider the equation $2^a-2^b=3^c-3^d$ where $a>b>0$, $c>d>0$, and $a,b,c,d$ are all integers. A computer search for solutions with $a,c\le20$ only finds 8-2=9-3, 32-8=27-3, and 256-16=243-3. I would really like there to be only finitely many solutions (even if these 3 aren't the only ones).
I have noted that the lower powers on both sides can be factored out, but since all the exponents are arbitrary, I don't think I can use a pattern in modular residues to get the result.
This feels vaguely reminiscent of Mihăilescu's theorem, but hopefully it's much easier to prove. Can someone point me towards a relevant reference or give me a nudge towards a method for solving it?

Edit:
I've read through Gottfried Helms's explanation, and come to some conclusions, but I'm afraid I'm a bit out of my depth, as I have little experience with Euler's totient theorem (and the related theorem of Carmichael), and no prior experience with Zsigmondy's theorem. I've worked on it a bit, and am presenting my thoughts/current understanding here, in the hopes that people can clarify things for me and bring me closer to a solution.
Firstly, I noticed that there was no good reason to disallow $b=0$ or $d=0$ in the problem, so I started allowing them. Ideally, I would like to produce a complete list of the finitely many tuples (a computer suggests five) of nonnegative integers $\left(a,b,c,d\right)$ with $a>b\ge0,c>d\ge0$ where the above equation holds (note that if we allowed $a=b$ or $c=d$, then we would have $a=b\Leftrightarrow c=d$ and that would be an infinite family of trivial solutions parametrized by $b$ and $d$). Throughout this discussion, I will follow Gottfried Helms in rewriting the equation as $$\frac{2^A-1}{3^d}=\frac{3^C-1}{2^b}\tag{1}$$where $A=a-b,C=c-d>0$, and both sides must be integers.
Quick Observations:

$2^{b}$ is the highest power of $2$ that divides $3^{C}-1$, as otherwise the left hand side of (1) is odd and the right side is even.
Thus, $b=0$ is impossible.
Note that $3^2\equiv1\mod8$, and $3-1\equiv2\mod8$ can't be divisible by $4$. Therefore, $3^{C}-1$ is divisible either by $8$ or by $2$ and not $4$. Hence, by 1., $b=2$ is impossible.
If $A=1$ then $d=1$ or else the left side of (1) wouldn't be an integer.
If $C=1$, then $b\le1$ to make the right side of (1) an integer, so $C=1\Rightarrow b=1$ by 2.

Zsigmondy's Theorem
Zsigmondy's Theorem is a deep theorem I has not heard of before Gottfried's post, and it solves many simpler problems of a similar flavor to this one. An good collection of example applications can be found in this issue of the HKUST Mathematical Excalibur. Two relevant corollaries for us are:

Each entry of the sequence $2^{n}-1$ has a new prime divisor the previous entries didn't except for $n=6$. For example: $2^{2}-1$ has the new prime factor $3$, which $2^{1}-1$ didn't have. $2^{3}-1$ has the new prime factor $7$ which the previous two didn't have. $2^{4}-1$ has the new prime factor $5$, and $2^{5}-1$ has the new prime factor $31$, but $2^{6}-1=3^{2}*7$.
Each entry of the sequence $3^{n}-1$ has a new prime divisor except for $n=2$. $3^{2}-1$=$\left(3^{1}-1\right)^{3}$, but $3^{3}-1$ has $13$, $3^{4}-1$ has $5$, etc.

More Special Cases:
With Zsigmondy's theorem in hand, we can easily handle some more special cases.
Case: $b=1$ and $d=0$:
In this case, the equation in the problem gives us $2^{a}-2=3^{c}-1$, so that $2^{a}-1=3^{c}$, but $2^{a}-1$ is getting new prime factors other than 3 by Zsigmondy unless $a=0,1,2$. Since $a>b=1$, only $a=2$ is allowed. This yields the solution "4-2=3-1
".
Case: $C=1$:
By quick observation 5., $b=1$, so we have $2^{A}-1=3^{d}$, which forces $A\le2$ by Zsigmondy. $A=1$ would force $d=0$ and give us the solution from the previous case. If $A=2$, then $d=1$ and we get "8-2=9-3". (Note, Mihăilescu's theorem could have been used as extreme overkill for this since $2^{A}-1=3^{d}$ is equivalent to $2^{A}-3^{d}=1$.)
Better arguments?
Gottfried seemed to be bringing up Carmichael's strengthening of Euler's totient theorem, but I don't understand how it's being used. The answer made it seem like they were saying something like $a^m\equiv 1\mod n$ for $a=3$ and $n$ coprime to $3$ exactly when $\lambda(n)\mid m$, which is false. $3^3\equiv1\mod13$, for instance. Carmichael's theorem may be very useful here, but I don't understand how to apply it.
I also don't understand how exactly to use Zsigmondy's theorem repeatedly. I can verify Jack Daurizio's comment manually with modular arithmetic, but it seemed like they were using these theorems to quickly make claims about divisibility in a way I couldn't follow.
Any elaboration/explanation on the methods of Gottfried's answer or a different step towards a solution would be much appreciated.
Interesting Corollary
As an aside, I forgot to mention the initial inspiration for this question. I was thinking about pairs of functions $f,g:\mathbb N\to\mathbb N$ such that $(n,m)\mapsto f(n)+g(m)$ is injective. One class of pairs I know is based on interleaving digits, but if the conjecture about powers of 2 and 3 is true, then $f(n)=2^{n+k}$ with $g(m)=3^{m+k}$ would work for some $k$.
Comment: My "divisibility chain" goes this way: assuming $d>1$, we have (with Gottfried notation) $6|A$, so $7|(2^A-1)$. This gives $7|(3^C-1)$, and since the order of $3\pmod{7}$ is $6$, $6|C$. This implies $(3^6-1)|(3^C-1)$, but in $(3^6-1)$ a new (Zsigmondy's) prime factor appears, $13$. So we have $13|3^C-1$, then $13|2^A-1$. Since the order of $2\pmod{13}$ is twelve, we have $12|A$, and the "divisibility chain" has begun - we can say $5|(2^{12}-1)|(2^A-1)$, so $5|3^C-1$, so $4|C\ldots$ - if we prove that a new prime pops up at each step, we are done.
Comment: Just two more short comments. 1) Carmichael-function: no, I did not use the Carmichael function - just the order of the cycles in $2^n - 1 \pmod p$ for some fixed primefactor $p$ when $n$ gets increased. That cycle-lengthes define then the exponents in the numerators in *(1)* depending on the exponents in the denominators in the way I've indicated in my answer. 2) Zsygmondi: The focus by his theorem is that if $2^p-1$ has some primefactors, and $2^q-1$ has some other primefactors, then $2^{pq}-1$ has that primefactors, but *also additionally ones* - except if $pq=6$. Analoguously for $3^n-1$
Comment: A newer discussion with a bit more explicite material (in the same spirit as the approaches here) can be found in: http://math.stackexchange.com/questions/1946621/finding-solutions-to-the-diophantine-equation-7a-3b100
Answer: I've not enough time to complete that answer at the  moment, but I can leave you in a position where you likely can proceed on your own.
The factoring-out is a good start: You get
$$ 2^b(2^A-1) = 3^d(3^C-1) $$
Then you rewrite
$$ {2^A-1\over 3^d} = {3^C-1 \over 2^b} $$
[lhs]: Then there is a little rule (see "Euler's totient theorem") , which values $A$ must assume for the numerator in the lhs to be divisible by $3$ or more precisely exactly by $3^d$:
$$A = \varphi(3^d) = 2 \cdot 3^{d-1} \qquad \text{ by Euler's totient theorem}$$
Sidenote: in this case, we deal with the primefactor $3$ and the $\varphi(3^d)$ is indeed the "order of the cyclic subgroup of $2^n \pmod 3$ - which is relevant here, since we want the exponent $A$ such that the denominator divides exactly. The situation here, with primefactor $3$ is easier than (and different from) some other primefactors like for instance $p=7$ where the $\varphi(7)=6$ but the order of the cyclic subgroup $ \pmod 7$ is smaller and actually $\lambda_7=3$ (Note, this is not the Carmichael-function!)   .
One can multiply additional factors to $A$ which only must not contain the primefactor 3: with $v$ where $\gcd(v,3)=1$ the complete expression is
$$A = \varphi(3^d) \cdot v = 2 \cdot 3^{d-1} \cdot v \qquad \qquad \gcd(v,3)=1 \tag 1$$
[rhs]: Similarly this is for the rhs:
$$ {C =  1 \cdot w \text{ for } b=1  \text{ and } \qquad \qquad \gcd(w,2)=0 \tag {2.1} } $$ $$  C=2^{b-2} \cdot w  \text{ for } b \ge 3 \qquad \qquad \gcd(w,2)=0 \tag {2.2}$$
Here a solution for $b=2$ does not exist; because any $3^C-1$ which is divisible by $2^2$ is also divisible by $2^3$ and thus one factor $2$ remains, and then this cannot equal the lhs which has an odd value. In effect, this blows up our equation to
$$ {2^{2 \cdot 3^{d-1} \cdot v} - 1\over 3^d} = {3^{1 \cdot w}-1 \over 2^1} \tag {3.1 when $b=1$}$$
$$ {2^{2 \cdot 3^{d-1} \cdot v} - 1\over 3^d} = {3^{2^{b-2} \cdot w}-1 \over 2^b} \tag {3.2 when  $b\ge 3$ }$$

I'm not going further at the moment; but now you might look for existence of different additionally primefactors on the lhs and the rhs for choices of $d$ and $b$ and $v$ and $w$. For instance, if $d \gt 1$ we have in the lhs additional primefactors with group-order $3,6,9,18$ which means the primefactors $7,-,73,19$ which must then also occur in the rhs. We know by a theorem of Szigmondy(?spell) that only for $A=2\cdot 3=6$ there is no other additional ("primitive") primefactor existent. This and the "trivial" cases should come out as the only possible solutions.
[update]
To make Jack's observation more explicite. First we observe, that in the exponent of the LHS there is unconditionally a factor 2 , so to improve readability a bit we write
$$ {4^{ 3^{d-1} \cdot v} - 1\over 3^d} = {3^{2^{b-2} \cdot w}-1 \over 2^b} \tag {3.2}$$
were we took the second version, assuming $b \ge 3$
Then we observe the table of cycle-lengthes for the first few primes for the numerator in the LHS and the RHS:
<code>  pf   4^A-1  3^C-1
 -------------------
    2    -    1
    3    1    -
    5    2    4
    7    3    6
   11    5    5
   13    6    3
   17    4   16
   19    9   18
   23   11   11
   29   14   28
   31    5   30
   37   18   18
   41   10    8
   43    7   42
   47   23   23
   53   26   52
   59   29   29
   61   30   10
   67   33   22
   71   35   35
   73    9   12
 ...    ...  ...
</code>
Now we discuss the possibility of equality, given that $d=2$. Then we look at the composition of $A$, see, what primefactors on the lhs are involved, conclude that they are involved in the rhs (note: must be to the same power!), that sets conditions on $C$ which includes more primefactors for the rhs thus also for the lhs, which then imposes a new composition of A, and so on, until we possibly get a contradiction. Here is a short decision-path-diagram. The "*" sign marks the inclusion of the primefactor due to compositions of $A$ or $C$:
<code>       A=3^1
         |
 *   3   1    0
 *   7   3    6 ==> C=2.3.w
              |
 *  13   6    3 ==> A=2.3
         |
 *   5   2    4 ==> C=4.3.w
              |
 * 73    9   12 ==> A=2.3^2  #####
contradiction, because exponent of 3 in A was assumed=1
</code>
So for the assumption of $d=2$ there is no solution of the original problem
Comment: Assuming $d>1$, a nice game starts. You have $7|(2^A-1)$, so $6|C$. This gives $13|(3^C-1)$, so $12|A$. This gives $5|(2^A-1)$, so $4|C$, then $12|C$. This gives $73|(3^C-1)$, so $9|A$, then $36|A$. This gives $19|(2^A-1)$, so $18|C$, then $36|C$. This gives $757|(3^C-1)$, so $756=2^2\cdot 3^3\cdot 7$ divides $A$. This gives that **a lot** of new primes divide $(3^C-1)$. Can we prove that the game never ends?
Comment: @Jack: I think so, because the Szigmondy-theorem says, that there are always "primitive" primefactors dividing $2^A-1$ resp $3^C-1$ if we compose A and C by any new factor. Another proof which I would attempt is to find a primefactor which creates a contradiction. Candidates are such, which have the same cyclic order for $2^A-1$ and $3^C-1$; the $A$ must be a multiple of $C$ and this requires more factors in ${2^{k C}-1\over 3^d}$ than in ${3^C-1 \over 2^b}$. Unfortunately I've at the moment not enough time to dig into this...
Comment: @JackD'Aurizio: Could you explain where the numbers in your game are coming from? I couldn't quite understand the reasoning that far (see my question edit for details of what I thought about).


Writing an equation from data

Question: Wendy, Elizabeth, and Charlie are all working on a math problem together and they are having a disagreement.:
    Ticket lines are huge at the Math Olympics ticket office. Pi, the local math team, is competing to be the Math Champions. When tickets went on sale, 500 were sold in the first hour alone. In the second hour 560 tickets were sold. After the second hour, the increase in ticket sales every hour was 20 more than the increase of the previous hour. Write an equation to model the number of ticket sales each hour for this event. If sales continue at this rate, in what hour will 11,000 tickets be sold for the championship match? Is this quadratic, linear, exponential, or something else? If it is, how do you know? If it is something else, why?
Wendy thinks this is a quadratic equation. Charlie thinks this is exponential. Elizabeth thinks it is something else. Who is right? Explain who is right, write an equation to model the number of ticket sales each hour for this event, and answer the following question: If sales continue at this rate, in what hour will 11,000 tickets be sold for the championship match?

Included was this table to get us started. I added what I could figure out in green.
I could figure out the y-intercept and the other values because I know the second difference. At first I thought it was quadratic, since I know if the second difference is constant, it is quadratic. I was able to write an equation, (if x=hour and y=#of tickets sold in that hour): y=10 x^2+30 x +460. However, I couldn't figure out how to find what I was asked, since I realized they wanted to know on what hour is the first difference +11,000, not when y=11,000. Now I'm starting to think it is something else, like a sequence. I am stuck here. Am I even on the the right track? If som where do I go next? If not, what am I supposed to do?
Comment: In your figure,the second difference should be $20$, not $\gt 20$.  That allows you to say it is quadratic.  If it is just $\gt 20$ it could be that Elizabeth is right and $11000$ tickets were sold in hour $3$.
Answer: If the second difference is a constant, the function must be a quadratic. So, let us write $$y(t)=a+b\,t+c\,t^2$$ and let us apply what we already know $$y(1)=a+b+c=500$$ $$y(2)=a+2 b+4 c=560$$ $$(y(3)-y(2))-(y(2)-y(1))=2c=20$$ So three linear equations in $a,b,c$, easy to solve by elimination, leading to $a=460$, $b=30$, $c=10$ (what you obviously obtained).
So, your green numbers are perfectly correct.
Last question : at what time will $11000$ tickets be solved ? This is given by $$460+30t+10t^2=11000$$ which is a simple quadratic equation; its roots are $-34$ (to be discarded since negative) and $31$ which is the solution.
Is this clear to you ?
Edit
As you properly thought, you could have been considering series writing the second difference as $$u_{n+2}-2u_{n+1}+u_n=20$$ the general solution of which being $$u_n=c_1+c_2 n+10 \left(n^2-n\right)$$ and apply the conditions $u_1=500$, $u_2=560$ to get the same result.
From this $u_{n+1}-u_n=40+20n$ and $11000$ tickets will be sold during the $548^{th}$ hour.

Writing an equation from data


Make proceeding functions remain uncalled when DioError

Question: I want any of the functions bellow the call of API request (with Dio) remain uncalled when Dio catches error on ErrorInterceptor.
child: TextButton(
     child: Text('Submit'),
     onPressed: () async {
           final client = Dio();
           final baseOptions = BaseOptions(baseUrl: BASEURL);
           client.options = baseOptions;
           client.interceptors.add(InterceptorWrapper(
                  onError: (error, handler) async { await FlutterToast.showToast(msg: error.toString); }));
           await getUserData(client);

           // Skip whatever follows if dio catches error.
           Navigator.pop(context);
           }
)

Does anyone know how to do this?
I guess using a provider of some sort of state management tool would be easy, but I am looking for something I can complete inside onError: for simplicity.
Comment: You don't need to intercept error in this case. Just wrap your code inside `try catch` and show error in the catch block.
 If you must use interceptor, You can call `handler.reject` inside the `onError` and wrap your whole code with the try catch and do nothing in the catch.
Comment: @umuieme You are right, `try catch` will do. But this makes me add as many `try catch` statements as I make a call on API, which I do not love about.

And `handler.reject` does not answer. It rejects other following error **interceptors** being executed. What I want is to reject execution of following **lines**.
Comment: You can make a helper class from which you can make app api call and have this effect. I will post a sample code as answer. Check if that works for you.
Answer: You can create a helper class from which you can redirect all your api call. In the helper you can pass which api function you want to call and an success function which gets executed if the api call is success. Below is the sample of the helper function.
class ApiHelper {
  static apiCallHelper(
      Future<dynamic> Function(Dio) apiCall, Function onSuccess) async {
    final client = Dio();
    final baseOptions = BaseOptions(baseUrl: BASEURL);
    client.options = baseOptions;
    client.interceptors
        .add(InterceptorsWrapper(onError: (error, handler) async {
      await FlutterToast.showToast(msg: error.toString);
    }));
    await apiCall(client);
    onSuccess();
  }
}

I have made a static function but you can make higher order function without class. I have put dynamic as a result for generic purpose. You can change it as per your need. Then you can make all api call through this.
onPressed() {
  ApiHelper.apiCallHelper(
    getUserData,
    (data) {
      // whatever you want to do when api call is success
    },
  );
}

This should work as you intended.


Como deixar os objetos lado-a-lado vindo do *ngFor?

Question: Eu tenho essa situação:

          {{ evento.titulo }}

{{ evento.data }}

{{ evento.descricao }}

        Saiba mais

Conforme o código acima eu possuo "3" (três) cartões um do lado do outro, porém meu problema é quando eu coloco o *ngFor conforme o primeiro cartão e eu gostaria que eles ficassem um do lado do outro usando o *ngFor independente de quantos objetos venham do BD. Se eu tirar *ngFor e deixar os cartões com textos quaisquer eles funcionam, ou seja, ficam conforme eu quero na viwer. Alguém tem alguma ideia?
Comment: vc esta usando a `class="col-lg-12"` e ela ocupa toda a extensão da tela
Comment: Sim, uso ela dentro de uma `class="row"` acho que é o certo!
Comment: porém quando vc abre os 3 cartões, fica um embaixo do outro
Comment: Sim usando o *ngFor sim, mas se eu tirar ele ai fica certo. Cara se eu achei a solução qual a melhor forma de eu sair desse sem perder meus pontinhos? :(
Answer: Layout de Bootstrap
O Boostrap funciona com um sistema de grelhas compostas por diversas linhas (.row) que depois são compostas por colunas de larguras variadas (ex.: .col-lg-8) sendo que cada .row tem 12 unidades de largura. Como o seu .card está dentro de uma coluna com 12 de largura (.col-lg-12) cada .card ocupará sempre a largura total da .row.
Como tal, para ficarem lado a lado, teria de ter algo como:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

          {{ evento.titulo }}

{{ evento.data }}

{{ evento.descricao }}

        Saiba mais

          {{ evento.titulo }}

{{ evento.data }}

{{ evento.descricao }}

        Saiba mais

          {{ evento.titulo }}

{{ evento.data }}

{{ evento.descricao }}

        Saiba mais

Potencial problema do layout
Ótimo! Agora se abrirmos num ecrã grande aparecem lado a lado! Mas e em tablets ou telemóveis? Irá aparecer uma por linha. Isto tem a haver com o seletor .col-lg-n em que ocupará n unidades de largura em ecrãs que sejam do tipo Large (>= 992px de largura) - mais informação sobre isso aqui.
Um exemplo em que ele mostraria sempre 3 itens por linha:

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

              {{ evento.titulo }}

{{ evento.data }}

{{ evento.descricao }}

            Saiba mais

              {{ evento.titulo }}

{{ evento.data }}

{{ evento.descricao }}

            Saiba mais

              {{ evento.titulo }}

{{ evento.data }}

{{ evento.descricao }}

            Saiba mais

Nota: mesmo estando na mesma .row, se a soma dos elementos não der
  os 12, o Bootstrap continua a colocar os elementos em baixo.

Solução com o Angular
Tendo em conta isto, o mais simple será fazer o *ngFor* dentro da sua .row com a largura do cartão que queira e deixar o Bootstrap tratar do resto:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

          {{ evento.titulo }}

{{ evento.data }}

{{ evento.descricao }}

        Saiba mais

Tenha em atenção que o espaçamento vertical pode não ficar bem, por isso na sua .borda-card acrescentaria uma margem para ter a certeza que eles ficariam bem sem trocar de .row.


Solution for SSL client certificates with user self service

Question: I'm administrating a linux-based small business network. User information is centrally stored in an OpenLDAP directory. There is an existing CA which is currently used to sign server certificates. It is managed using EasyRSA. My current project is to setup a VPN for remote access to the network as well as an 802.1X based WiFi. I'd like to use client certificates for both.
I'd like to avoid having to create each client certificate manually. Ideally, there would be a web service that authenticates users against LDAP and allows them to create a signed client certificate without administrator intervention. An intermediate CA for such a service could be made.
Is there a project, free or commercial, that allows me to do this? Ideally Linux based since that would fit the existing environment best. During research I stumbled upon OpenCA and EJBCA and those seem highly configurable. But it remains unclear whether or not those are capable of providing this functionality.
Addition:
I've found a guide mentioning Active Directory Certificate Services which seems to be basically what I need. Scroll down to "Generate User Certificate on Windows 7" which shows the process. However, since this is not a windows network, another solution without Active Directory is preferred.
Comment: I've created certs for years by hand with OpenSSL. It really doesn't take more than 10 minutes even when I have to review my notes and copy out the obscure command line syntax.
Answer: I created a Makefile to deal with this. So I never need to remember any openssl command! :-)
I used it to enroll server certs and client certs and even certificates on smartcards.
I can also revoke certificates and publish the CRL.
Hm, I just created a repo on github, so that you can take a look at.
OpenCA is rather cool and mighty. But I think it is not activley maintained anymore.
The user would enroll his certificate in the browser, but afterwards he would have to export the certificate...
Comment: The LDAP part is definitely interesting. I will look at this, thanks alot for sharing! It seems as if there is no fully automated solution. So having a half-automated makefile seems like a good compromise. Maybe I'll add this into easy-rsa.
Comment: ...or fork it on github and do a pull request ;-)


Pegar imagem selecionada e enviar para outra Activity

Question: Gostaria de saber se é possivel pegar uma imagem selecionada e enviar para outra activity. Estou usando fragments e queria que o layout ficasse como na imagem abaixo.
Queria que quando o usuario selecionar a imagem, pegar esta e enviar para outra activity e apresentar na tela.
Class Fragment:
public class Fragment1 extends Fragment {

GridView gridView;
int [] listaImagens = new int[]{R.drawable.eu, R.drawable.perguntas, R.drawable.respostas};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup conteiner, Bundle saveInstanceState) {

    View view = inflater.inflate(R.layout.layout_frag_1, conteiner, false);

    gridView = (GridView) view.findViewById(R.id.imageFrag1);
    gridView.setAdapter(new Adaptador(view.getContext(), listaImagens));

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            Toast.makeText(parent.getContext(), "Imagem " +listaImagens[position], Toast.LENGTH_SHORT).show();
        }
    });

    return (view);

}

}
Class Adapter:
public class Fragment1 extends Fragment {

GridView gridView;
int [] listaImagens = new int[]{R.drawable.eu, R.drawable.perguntas, R.drawable.respostas};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup conteiner, Bundle saveInstanceState) {

    View view = inflater.inflate(R.layout.layout_frag_1, conteiner, false);

    gridView = (GridView) view.findViewById(R.id.imageFrag1);
    gridView.setAdapter(new Adaptador(view.getContext(), listaImagens));

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            Toast.makeText(parent.getContext(), "Imagem " +listaImagens[position], Toast.LENGTH_SHORT).show();
        }
    });

    return (view);

}

}
Comment: Acho que você errou ao colar o adapter.
Answer: Você pode passar a posição dela.
Exemplo:
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

            Intent i = new Intent(getActivity(), Display_Image_Activity.class);
            i.putExtra("img", listaImagens[position]);
            getActivity().startActivity(i);

        }
    });

No Activity você vai pegar o valor dela, que será por exemplo:
String img;

Bundle extras = getIntent().getExtras();
if(extras != null) {
    img = extras.getString("img");
}

Resources res = getResources();
int resID = res.getIdentifier(img , "drawable", getPackageName());
Drawable drawable = res.getDrawable(resID);

ImageView iv = new ImageView(this);
iv.setImageDrawable(drawable);

A variável img terá o valor de R.drawable.perguntas, por exemplo.
Comment: Sua resposta está incompleta. Acho que ele quer saber também como receber esses dados em outra activity.
Comment: @seamusd Coloquei o complemento da segunda Activity, valeu pela dica
Comment: Você notou que ele diz que "...pegar esta e enviar para outra activity..." quando na verdade ele está em um Fragment. Como a pergunta ta mal formulada, você pensou nessas hipótese que ele pretende enviar de um fragment para um outro fragment?!
Comment: Verdade, não tinha reparado na confusão, editei a minha resposta, eu imagino que o primeiro caso seja um Fragment, e aonde irá receber os dados seja uma Activity
Comment: @seamusd me desculpe pela pergunta mal formulada e a todos que me ajudaram. Descobri como fazer o que queria com fragments.


Get text from pull down list - not working (HTML/JQuery)

Question: I am trying to get the selected item from a pull down list.   I am using the following code to attempt to get the item selected.  However, no matter what is selected in the pulldown menu (it has a checkmark indicating it is selected) I only get the first room listed (in this case "testing) and not the selected one.  Why would this happen?
Here is what I am using to select -
var value = $(".room").val()
Here is the html code of the list:
<select>
<option class="room" value="testing">testing</option>
<option class="room" value="hello">hello</option>
<option class="room" value="lobby">lobby</option>
<option class="room" value="this is a test room">this is a test room</option>
<option class="room" value="gabe and samsons cave">gabe and samsons cave</option>
<option class="room" value="gabe">gabe</option>
<option class="room" value="rfe2209">rfe2209</option>
</select>

Comment: may be you are trying to get the value of selected option, if so you need to grab the `select` element not the option. you can try this one too `$("select").change(function(){
    alert("Value: " + $(this).val());
  });`
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: Does this answer your question? [Get selected value of a dropdown's item using jQuery](https://stackoverflow.com/questions/2780566/get-selected-value-of-a-dropdowns-item-using-jquery)
Answer: You're selecting the value wrong. Only the <select>'s value will have the value of the selected <option>. Here's an example of working code:

$('#room').change(function() {
  const value = $('#room').val()
  console.log(value);
});

<select id="room">
  <option value="testing">testing</option>
  <option value="hello">hello</option>
  <option value="lobby">lobby</option>
  <option value="this is a test room">this is a test room</option>
  <option value="gabe and samsons cave">gabe and samsons cave</option>
  <option value="gabe">gabe</option>
  <option value="rfe2209">rfe2209</option>
</select>


Chords in Moonlight Sonata 1st movement

Question: From here:

In 1st measure - first chord - it's said that it is  C#min (i) but there are  C-C#-G.
I thought it should be  C#-E-G#  why is it C#min (i) if there are C-C#-G??
In 3st measure - first chord - it's said that it is  A (VI) but there are  A-A-A.
I thought it should be  A-C#-E  why is it A (VI) if there are  A-A-A??
In some measures (i.e. 4,12,13,25,48 etc.) there are 3 or 4 chords in one measure.
I thought, in general, chords could change only on strong beats(except for syncopation).
Does that mean there's a syncopation in there or what?
Answer: I see a problem right away in the way you are looking at the analysis. When you analyze something and notate either a chord or a Roman numeral the chord is meant to analyze all notes and pitches up to the next chord/Roman numeral change with the exception of a few non-harmonic tones that are typically notated. Also note you are in the key of C# minor so the notes F,C,G, and D are sharp unless otherwise noted.

The notes in the first measure are two C# notes in the lower staff and G#,
C#, and E in the top staff. This does in fact make a C#m chord.
The notes in the first half of measure 3 are two A notes in the lower staff and A,
C#, and E in the top staff. This does in fact make a A major chord.
It is typical to speed up the harmonic rhythm as you approach cadences. At every place you mention there being more chords I see a cadence so this is a very typical and expected pattern. I wouldn't call any part of this syncopation because even though the chords are changing at a faster rate, they are still changing on predictable on the beat fashion even though it is sometimes the weak beat. In syncopation, there would be chord changes that are off-beat which is different.

Chords in Moonlight Sonata 1st movement


How to call a URL in background using Android?

Question: I am looking to insert userdata to database by calling URL link to webservice on server:
ex:
this is the link:
http://mydomain.com/AndroidWebService.asmx/nInsertInfo?id=12&lat=23.2222&log=12322

So I want to call this url in hidden mode.
Answer: Use android android AsyncTask to post data. It work in android background when application is open.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

Like

AsyncTask

AsyncTask

AsyncTask

Thanks.
Comment: How can I achieve this using retrofit client?
Answer: Thanks all for your valuable solutions.
i have did it by creating WebView
WebView myWebView = (WebView) findViewById(R.id.view1);
myWebView.loadUrl(urll);

then i can manage my WebView as i want: hide it, alignment as error or result returns.
Answer: Maybe this example will help you :
public class URLConnectionTask <Result> extends AsyncTask<URL, Void, InputStream> {

        @Override
        protected InputStream doInBackground(URL... params) {
            InputStream is;
            HttpUriRequest request;
            URI uri;
            HttpResponse response;

            if (params.length == 0)
                return null;

            is = null;CredentialsProvider credProvider = new BasicCredentialsProvider();

        if (userName != null && userName.length() > 0 && password != null && password.length() > 0)
            credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(userName, password));

        //
        DefaultHttpClient http = new DefaultHttpClient();
        http.setCredentialsProvider(credProvider);
        //

        uri = URI.create(params[0].toString());

        if (isPost)
            request = new HttpPost(uri);
        else
            request = new HttpGet(uri);

        try {
            response = http.execute(request);
            is = response.getEntity().getContent();

            //Log.d(TAG, "doInBackground() response: "+EntityUtils.toString(response.getEntity()));
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

       if (processingHandler != null && is != null)
           processingResult = processingHandler.processResponse(is);// processingHandler is an instance which implements ProcessingHandler interface (ex. VizMarket). processResponse() is implemented on this class.

       return is;
    }

    @Override
        protected void onPostExecute (InputStream result) {
            input = result;

            if (result == null)
                return;
                    //instruction for inserting data on db ....

            try {
                result.close();
            } catch (IOException e) {
            }
        }
    }

Comment: this solution is advance,
but when i used it, it gave me runtime error ?? do you have any idea about ?
Comment: Man I give this example for creating an idea how AsyncTask works. I use this class on my android project for fetching json results, and showing them on ListActivity. I think it's normal to give runtime error to you, but if you give more details of what do you want to do exactly maybe I will help you.
Answer: You should call URL in AsyncTask. For instance: Return data from AsyncTask class
Answer: U have to use a thread to fetch data from server and insert into to DB or in android you can use AsyncTask.
Answer: You can have a search :ClickableSpan
And put your insert code into the OnClick body~
Just like:
String yourTextStr;
    SpannableString sp = new SpannableString(yourTextStr);
    int start;//the start of your url in the text;
    int end ;//the end of your url in the text;
    sp.setSpan(new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            //Your Insert Code
        }
    }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);


A zero-sum game is chosen at random, find the optimal strategy for player 1

Question: A zero-sum game is chosen at random (0.5,0.5), player 1 knows which game was chosen and player 2 doesn't. The game is played infinitely often (no discount factor). Players only know the actions taken, not the payoffs.
$G_1=\bigl(\begin{smallmatrix}
0 & 4 &-2 \\
 0&4  &2
\end{smallmatrix}\bigr)
$$
,G_2=\bigl(\begin{smallmatrix}
4& 0 &2 \\
 4&0  &-2
\end{smallmatrix}\bigr)
$

How would you play as player 1?

So if $G_1$ was chosen and I play {Bottom} too often, player 2 will realise at some point which matrix was chosen and then just play {Left} and we would get 0-0 from that point forward. The same claim is valid if $G_2$ was chosen just by replacing {Top} for {Bottom} and {Middle} for {Left}.
Is there a "best" strategy I can take to keep player 2 guessing which game was chosen and maximize my gain?
Comment: If I, as Player 2, saw you, as Player 1, play Bottom too often, I would be suspicious that you were trying to *trick* me into thinking $G_1$ had been chosen....
Comment: so what would you do?
Comment: If I knew, I'd post an answer!
Answer: Yes, an optimal strategy exists. We can compute exactly what player $1$'s payoffs under this optimal strategy (which I'll call the value of this game) will be.
Unfortunately, there are no general results showing how to actually construct those strategies, but once you've computed what the value of this game is, and you can find a strategy that attains this value, then clearly that strategy is optimal (but not necessarily uniquely so).
This result is due to Aumann and Maschler. The succeeding paragraphs summarise this result.
Let $p$ be the probability that $G_1$ is played.
Consider the game played only once, where $G_1$ is played with probability $p$, and only player $1$ is informed of which game is played. It is straightforward (albeit admittedly potentially tedious) to compute the value of this one-shot game. Call the value of this one-shot game $u(p)$.
Aumann and Maschler showed that the value of the infinitely repeated game you describe is given by
$$ cav[u(p)] $$
where $cav$ denotes the concavification operator. That is, $cav[f(x)]$ is the smallest concave function greater than or equal to $f$ (point-wise).
For more details on this result, I really do recommend the book linked above. Otherwise, Johannes Hörner also has a set of notes on repeated games with incomplete information, which covers this result.


How to add multiple custom post types under one page?

Question:
I'd like to add multiple custom post types under the setting: Posts page: then display 2 post pages.
I want to show all the resources posts and jobs posts which are both custom post types?
Answer: You can use the WP_Query class for a custom loop in a PHP template and list the desired custom post types in the arguments array like this:
$args = array(
  'post_type' => array( 'resources', 'jobs' )
);
$query = new WP_Query( $args );

The full documentation for it can be found here: https://developer.wordpress.org/reference/classes/wp_query/
Post Type parameters on this page are here: https://developer.wordpress.org/reference/classes/wp_query/#post-type-parameters


Intermediate value theorem

Question: Suppose $f$ is a continuous function on $[a,b]$ and $\lambda$ is a value between $f(a)$ and $f(b)$. Prove that $\exists c \in [a,b]$ s.t. $f( c) = \lambda$
Let, $$g(x) = f(x) - \lambda$$
$g$ is continuous on $[a,b]$
$$g(a) = f(a) - \lambda < 0$$
$$g(b) = f(b) - \lambda > 0$$
Since, $\exists c \in [a,b]$ s.t. $g( c) = 0$, we have $g( c) = f(c ) - \lambda => 0 = f(c ) - \lambda => f(c ) = \lambda$
So, is it this simple? Or, am I missing something here? Please correct me if I did wrong. Thanks.
Comment: You are using what you need to prove (when you assume that there is some $c\in[a,b]$ such that $g(c)=0$).
Comment: @CarlosIsraelJrl that is often how the intermediate value theorem is given, and the result derived here is technically a corollary
Comment: If you can apply the I.V.T: Then you are right!!
Comment: @CarlosIsraelJrl The $c$ I am using here was given as a hint.
Answer: The proof you have given is acceptable within the context you're working in assuming you are allowed to use the special case of the intermediate value theorem about sign changes implying the existence of a zero (as your proof shows, this special case is logically equivalent to the seemingly more general version). If you have not been given the "special case" as an admissible tool, then your proof is circular.
In any case, all the work is in proving the case where $f(a)$ and $f(b)$ have opposite sign and $\lambda=0$. Although, depending on your approach to your problem, and the degree of mathematical sophistication (e.g. some general topology), the "general" version of the IVT can be proved in a fairly straightforward way (using the notion of connectedness, specifically).

Intermediate value theorem


Interpretation of intercept in Helmert coding

Question: I have a general, presumably simple, question, but I couldn't find a conclusive answer so far.
Assume I have a simple case of a General Linear Model with one categorical predictor variable, that has 3 levels. This corresponds to a one-way ANOVA with 3 groups.
The Linear Model would then be: $Y_i = \beta_0 + \beta_1X_1 + \beta_2X_2$
I use the following standard Helmert contrast codes (I, II) for the three groups A, B, C:
<code>     A    B    C
I   -2    1    1
II   0   -1    1
</code>
Based on these contrast codes, will the intercept of the linear model represent the mean of all group means? More generally, does this always apply to Helmert contrast coded variables, regardless of the number of predictor variables or variable levels?
Obviously, the intercept represents the predicted value, when all predictor variables (in this case $X_1$ and $X_2$) equal zero, but I can't figure out if that represents the mean of the group means.
Comment: Yes it is the case. If you write down regression equations based on the contrast matrix returned by R and try to identify each regression coefficient, you will find that $\beta_0$ is the mean of all levels (like in deviation or sum contrast) while $\beta_i,\, i=1\dots j$, represent sequential comparisons between adjacent categories (2 vs. 1, 3 vs. {1,2}, etc.).
Comment: @chl, why not make that an official answer & show how it's done?
Comment: Does that help: http://www.ats.ucla.edu/stat/r/library/contrast_coding.htm?
Comment: I've come across this site before, but unfortunately it doesn't say whether the intercept in Helmert coding equals the mean of all group means.
Comment: Thanks! Does that also hold, when I have more than 1 categorical variable and consequently my model contains interaction terms?
Answer: Yes. You can easily verify this by carrying out the following steps:
First, express the means of $A$, $B$, and $C$, in terms of the model with the specified contrast:
\begin{eqnarray*}
1\hat{\beta}_{0}-2\hat{\beta}_{1}+0\hat{\beta}_{2} & = & \hat{\mu}_{A}=E(Y_{A})\\
1\hat{\beta}_{0}+1\hat{\beta}_{1}-1\hat{\beta}_{2} & = & \hat{\mu}_{B}=E(Y_{B})\\
1\hat{\beta}_{0}+1\hat{\beta}_{1}+1\hat{\beta}_{2} & = & \hat{\mu}_{C}=E(Y_{C})
\end{eqnarray*}
Here, each $\hat{\mu}_i$ represents the group mean of group $i$, $i=A, B, C$.
Next, place each beta coefficient into a matrix augmented with the
means on the right, and place the matrix in row-reduced echelon form
using Guass-Jordan elimination:
\begin{eqnarray*}
\begin{bmatrix}1 & -2 & 0 & | & \hat{\mu}_{A}\\
1 & 1 & -1 & | & \hat{\mu}_{B}\\
1 & 1 & 1 & | & \hat{\mu}_{C}
\end{bmatrix} & \sim & \begin{bmatrix}1 & -2 & 0 & | & \hat{\mu}_{A}\\
0 & 3 & -1 & | & \hat{\mu}_{B}-\hat{\mu}_{A}\\
0 & 3 & 1 & | & \hat{\mu}_{C}-\hat{\mu}_{A}
\end{bmatrix}\\
 & \sim & \begin{bmatrix}1 & -2 & 0 & | & \hat{\mu}_{A}\\
0 & 3 & -1 & | & \hat{\mu}_{B}-\hat{\mu}_{A}\\
0 & 0 & 2 & | & \left(\hat{\mu}_{C}-\hat{\mu}_{A}\right)-\left(\hat{\mu}_{B}-\hat{\mu}_{A}\right)
\end{bmatrix}\\
 & \sim & \begin{bmatrix}1 & -2 & 0 & | & \hat{\mu}_{A}\\
0 & 3 & -1 & | & \hat{\mu}_{B}-\hat{\mu}_{A}\\
0 & 0 & 1 & | & \frac{1}{2}\left[\left(\hat{\mu}_{C}-\hat{\mu}_{A}\right)-\left(\hat{\mu}_{B}-\hat{\mu}_{A}\right)\right]
\end{bmatrix}\\
 & \sim & \begin{bmatrix}1 & -2 & 0 & | & \hat{\mu}_{A}\\
0 & 1 & 0 & | & \frac{1}{3}\left\{ \left(\hat{\mu}_{B}-\hat{\mu}_{A}\right)+\frac{1}{2}\left[\left(\hat{\mu}_{C}-\hat{\mu}_{A}\right)-\left(\hat{\mu}_{B}-\hat{\mu}_{A}\right)\right]\right\} \\
0 & 0 & 1 & | & \frac{1}{2}\left[\left(\hat{\mu}_{C}-\hat{\mu}_{A}\right)-\left(\hat{\mu}_{B}-\hat{\mu}_{A}\right)\right]
\end{bmatrix}\\
 & \sim & \begin{bmatrix}1 & 0 & 0 & | & \hat{\mu}_{A}+\frac{2}{3}\left\{ \left(\hat{\mu}_{B}-\hat{\mu}_{A}\right)+\frac{1}{2}\left[\left(\hat{\mu}_{C}-\hat{\mu}_{A}\right)-\left(\hat{\mu}_{B}-\hat{\mu}_{A}\right)\right]\right\} \\
0 & 1 & 0 & | & \frac{1}{3}\left\{ \left(\hat{\mu}_{B}-\hat{\mu}_{A}\right)+\frac{1}{2}\left[\left(\hat{\mu}_{C}-\hat{\mu}_{A}\right)-\left(\hat{\mu}_{B}-\hat{\mu}_{A}\right)\right]\right\} \\
0 & 0 & 1 & | & \frac{1}{2}\left[\left(\hat{\mu}_{C}-\hat{\mu}_{A}\right)-\left(\hat{\mu}_{B}-\hat{\mu}_{A}\right)\right]
\end{bmatrix}
\end{eqnarray*}
So, now, we know that the first pivot position corresponds to:
\begin{eqnarray*}
\hat{\beta}{}_{0} & = & \hat{\mu}_{A}+\frac{2}{3}\left\{ \left(\hat{\mu}_{B}-\hat{\mu}_{A}\right)+\frac{1}{2}\left[\left(\hat{\mu}_{C}-\hat{\mu}_{A}\right)-\left(\hat{\mu}_{B}-\hat{\mu}_{A}\right)\right]\right\} \\
 & = & \hat{\mu}_{A}-\frac{2}{3}\hat{\mu}_{A}-\frac{1}{3}\hat{\mu}_{A}+\frac{1}{3}\hat{\mu}_{A}+\frac{2}{3}\hat{\mu}_{B}-\frac{1}{3}\hat{\mu}_{B}+\frac{1}{3}\hat{\mu}_{C}\\
 & = & \frac{1}{3}\hat{\mu}_{A}+\frac{1}{3}\hat{\mu}_{B}+\frac{1}{3}\hat{\mu}_{C}\\
 & = & \frac{\hat{\mu}_{A}+\hat{\mu}_{B}+\hat{\mu}_{C}}{3}
\end{eqnarray*}
The final expression indicates that $\hat{\beta}{}_{0}$, the intercept,
represents the simple mean of the group means.


schtasks.exe adding repeat every 10 min when not desired

Question: I am trying to create a scheduled task from the command line.  I need the task to run every day at 7:05pm and run for a maximum duration of 1 hour.  Just once until the next day.
Here is my command:
schtasks.exe /create /ru DeployUser /rp '********' /tn "Run All Tasks" /tr "'tasks.exe RunAllTasks'" /sc DAILY /st 19:05:00 /F /du 01:00

That command produces the following trigger.

At 7:05 PM every day - After triggered, repeat every 10 minutes for a duration of 1 hour.

The repeating every 10 minutes is not desirable and I do not see where in my command this was requested.  Maybe it is a default for using duration, is there a way to get rid of it?
Comment: It would have been nice if there was the option of cron syntax
Answer: Having the same problem here.  I've found it is a default setting when you use either the /ET or /DU switch.
Frustratingly I haven't yet figured out how to stop the repeat applying when using either of the switches.
Here's the bit from the technet that I found it in:
https://technet.microsoft.com/en-us/library/cc725744(v=ws.11).aspx#BKMK_change

/ri Specifies the repetition interval in minutes. This is not
  applicable for schedule types: MINUTE, HOURLY, ONSTART, ONLOGON, and
  ONIDLE. Valid range is 1 to 599940 minutes (599940 minutes = 9999
  hours). If either /ET or /DU is specified, then the repetition
  interval defaults to 10 minutes.

Doesn't answer the question but hopefully provides a bit of clarity.
The closest suggestion I've found to an answer is to create a second task that ends the first one: schtasks /end /tn TaskName
Answer: To suppress repeat period - use key "/ri 0"
Answer: From technet:

/ri <Interval>
Specifies the repetition interval in minutes. This is not applicable for schedule types: MINUTE, HOURLY, ONSTART, ONLOGON, and ONIDLE. Valid range is 1 to 599940 minutes (599940 minutes = 9999 hours). If either /ET or /DU is specified, then the repetition interval defaults to 10 minutes.

You should add /ri of 24 hours (/ri 1440). The wording of the quote implies that you can change the repeat interval from the default with /ri.
Comment: how will daylight savings time affect this setting?  I used /sc DAILY to assure I run at a specific time 7:05PM but with /ri 1440 it seems the run time would change from 7:05PM to 8:05PM (or 6:05PM) depending on when i initiate the task setup.  Am I wrong with this assumption?