Is the posterior distribution $P(\theta|\mathbf{X})$ a statistic?

Question: The textbook definition of a statistic is any function of the data, $g(\mathbf{X})$. Much of frequentist inference is concerned with deriving sampling distributions for various statistics under some null model, so it makes sense that the term "statistic" has a precise definition and is used quite often.
The goal of Bayesian inference, on the other hand, is to derive the posterior distribution $P(\theta | \mathbf{X})$ of some parameter $\theta$ upon observing data $\mathbf{X}$. The discussions I've seen on Bayesian inference tend not to give a definition for the term "statistic."
I have two questions:

Do Bayesians use the term "statistic" in the same way that frequentists do, or does Bayesian inference not depend as heavily on the concept of a statistic?
Is it accurate to say that the posterior distribution $P(\theta|\mathbf{X})$ is itself a statistic? Even if it is technically correct, is it "morally" correct?
Comment: Statistics are not ordinarily thought of as families of functions that depend on parameters.  The posterior distribution does, though: it depends on the prior distribution.
Comment: Reading "Deep Learning" by Goodfellow, Bengio, and Courville perhaps? ;)
Comment: @DarkCygnus no, but I would like to at some point.
Answer: Yes, a posterior is a statistic. As you point out a statistic is any function of the data and the posterior is a function of the data and thus a statistic. Yes, Bayesians use the notion of statistic but typically not describing the posterior as a statistic. We are certainly interested in sufficient statistics since a posterior, i.e. a distribution for a parameter given the data, is equivalent to the conditional distribution of the parameter given a sufficient statistic.
Yes it is technically correct and it is moral. You could even look at the sampling distribution of the posterior to understand properties of the posterior over different realizations of the data. Efron does this in this manuscript.
Comment: In connection with this issue, Don Fraser has argued in a [1962 paper](https://xianblog.wordpress.com/2010/08/07/seminar-in-stanford/) that the likelihood function is a sufficient statistic.
Answer: No, posterior distribution is not a statistic if you define it strictly and agree that there is a distinction between statistic and estimator. First of all, it is an estimator of the posterior distribution (see What is the difference between an estimator and a statistic?). Second, as already noticed in the comment by @whuber, a statistic is a function of the data, while posterior distribution is a function of the data and the priors, so it depends not only on the data.
Posterior distribution is an estimate of the distribution of the parameter of the assumed model; statistic would be a function of the sample that characterizes it. The problem is not with the fact that it is a distribution (e.g. one could argue that kernel density estimator, as well as histogram,  are statistics), but with your interest in the model, rather then the sample.
On another hand, the definition of statistic is very broad and many handbooks give only brief definitions ("function of the sample", or "numerical characteristic of a sample"), or like Leehman and Casella in Theory of Point Estimation say that "estimators are statistics" (p. 16). So when sticking to the definition that statistic is any function of the sample, the answer would be "yes".

Do Bayesians use the term "statistic" in the same way that frequentists do, or does Bayesian inference not depend as heavily on
  the concept of a statistic?

In general, Bayesians use all of the statistical terms the same way as other statisticians. They only differ in how they interpret the probability, while sticking to the same definitions (Kolomogorov axioms etc.). If they didn't, they wouldn't be able to communicate with the rest of statistical community and would not be considered as a part of statistics.
Comment: I know your answer has already been marked as correct, but I would appreciate a definition of a statistic since you appear to have a definition in mind beyond "a function of the data." Is the "sample average plus 2" a statistic? It seems you would say no since it "goes beyond the data".
Comment: Except that question does not have an answer marked correct. Your answer to that question provides a rigorous definition of a statistic from Casella and Berger which indicates that a statistic needs to be a "real-valued or vector-valued function". Is that the strict definition you allude to here? Since the posterior is not vector-valued, it cannot be a statistic, but any countable collection of quantiles would be a statistic?
Comment: @jaradniemi the question has two highly upvoted answers that I refer to. Lack of the "accepted" answer has nothing to do with answers being "correct" or not. As I said in my answer, while most of the authors give vague definitions of statistic, the actual *usage* of the term suggests that statistic is something different from estimator in the fact that statistic is used to describe the properties of the sample, while estimators estimate the quantities related to the model. What follows, statistic should depend on the data and only on the data if it is used to characterize the data.
Comment: @jaradniemi but this was discussed in the linked thread so there is probably no point in repeating the answers.
Comment: ... Moreover, in my answer I explicitly say that the definitions *are* vague and other interpretations are possible.
Answer: I don't agree with the view that the posterior is not a statistic because it is an estimator (e.g., in the accepted answer to this question, and the accompanying answer to the related question on alleged differences between a statistic and an estimator).  But for other reasons, set out in detail below, I would say that it is possible to form a "statistic" with this quantity, but the thing that is a statistic is not really the "posterior distribution".
To understand this, it is important to remember that a multivariate function can be viewed in many different ways, depending on which variables we are treating as arguments and which we are treating as fixed values.  In particular, a multivariate function can be a distribution with respect to one argument variable, but not a distribution with respect to another argument variable.  In the present case, the function $P(\theta | \boldsymbol{x})$ can be viewed in three different ways$^\dagger$:

As a function of both $\theta$ and $\boldsymbol{x}$, in which case it is a conditional distribution;
As a function of $\theta$ only (with $\boldsymbol{x}$ treated as fixed), in which case it is a single distribution; or
As a function of $\boldsymbol{x}$ only (with $\theta$ treated as fixed), in which case it is a statistic, but not a distribution.

From these three views, we see that it is possible to view this object as a "statistic" (holding one argument constant) or as the "posterior distribution" (holding the other argument constant), but it is not strictly correct to view it as both of these things at once.  Hence, it is very dubious to claim that the "posterior distribution" (which is a distribution) is also a "statistic".  A more detailed answer is given below, where I explore this issue as a mapping with a domain and codomain including distribution functions.

What is a "statistic": The standard definition of a statistic refers to a function of the data vector - i.e., a function whose domain is the support of the data vector.  The mere fact that a statistic can function as an estimator of some model parameter does not preclude it from being a statistic.  While it is arguable that an estimator is something more than a statistic (e.g., a statistic plus a specified parameter it is used to estimate), this does not imply that a statistic is not a statistic merely because it can be used as an estimator of something.
Now, some definitions of a "statistic" (in various textbooks) restrict the concept only to mappings that output a real number of real-vector (as opposed to a distribution or function), but this is usually a contextual definition, made to deal with standard real scalar or vector statistics in other contexts (e.g., when discussing the theory of statistical inference).  In my view, there is no reason in principle that a function cannot be considered a "statistic" if it maps a data vector to some other output such as a distribution.  Hence, if $\mathscr{X}$ is the support of our observable data vector in some inference problem, I would regard any mapping $f: \mathscr{X} \rightarrow \text{Codomain}$ to be a "statistic" on the specified codomain.  With this broad definition of a "statistic" let us now consider the question at issue.

Is the posterior distribution a "statistic"?  It is certainly true that the posterior is determined both by the data vector and the prior distribution.  Letting $\mathscr{X}$ be the support of the data vector and letting $\Pi$ be the space of allowable distributions for the parameter $\theta$, we can consider Bayes' rule to be a mapping $P: \mathscr{X} \times \Pi \rightarrow \Pi$ which maps a data vector and prior to the posterior distribution (with the latter considered as a function of $\theta$).  So here we have a mapping where the domain is not just the support of the data vector.
However, as with any function of two arguments, we can also treat one of these (the prior) as a fixed value and consider the mapping as a function only of the other argument (the data vector).  That is, for any fixed prior distribution $\pi \in \Pi$ we can consider the corresponding mapping $P_\pi: \mathscr{X} \rightarrow \Pi$ which maps a data vector to a posterior distribution (the one that results from our fixed prior).  So now we have a mapping where the domain is the support of the data vector, and hence, we have a "statistic" (in the broad sense defined above).
Although $P_\pi$ is a "statistic" in the sense specified above, it is a bit of a stretch to call it the "posterior distribution".  Effectively, it is the mapping you get if you treat the posterior distribution as a function only of its conditioning variable $\boldsymbol{x}$ for a fixed prior.  It is not really accurate to call this a "distribution" since it is not a distribution with respect to the argument variable $\boldsymbol{x}$.
I would argue that the mapping $P_\pi$ is a "statistic", insofar as it is a function whose domain is the support of the data vector.  It is not really accurate to call this function the "posterior distribution"; rather, it is the mapping that maps any allowable data vector to the corresponding posterior distribution.  The "posterior distribution" is the element $P_\pi(\boldsymbol{x})$ in the codomain, not the mapping itself.

$^\dagger$ The posterior is also implicitly dependent on an unstated prior distribution $\pi(\theta)$ and so we could also take an enlarged view of things, by looking at the multivariate function $P(\theta | \boldsymbol{x}, \pi)$, in which case there are even more interpretations.


Javascript - Utilização do reduce

Question: Boa tarde, pessoal! Tudo bem com vocês? Espero que sim.
Estou começando meus estudos em Java Script, porém estou com dificuldade para implementar uma função usando o reduce.
O código é o seguinte:
const cartasFrete = []

const sequencia = {
    _id: 0,
    get id() { return this._id++}
}

/*const getCartaFrete = (id) => {
    const aux = cartasFrete.filter((cartaFrete) => {
        return cartaFrete.id === id
    })
    return aux[0]
}
*/

const criarCartaFrete = (local, destino, valorFrete,porcentagem) => {
    return {
        id: sequencia.id,
        local: local,
        destino: destino,
        valorFrete: valorFrete,
        porcentagem: porcentagem,
        getValorFrete() {
            return this.valorFrete
        },

        getPorcentagem() {
            return this.porcentagem
        },
        getInformacoes() {
            return `
            Local: ${this.local}
            Destino: ${this.destino}
            Valor do Frete: ${this.valorFrete}
            Porcentagem: ${this.porcentagem * 100}
            `

        }
    }
}

const salvarCartaFrete = (...cartaFrete) => {
    cartaFrete.forEach((valor,indice) =>{
        cartasFrete[indice] = valor
    })
}

// ------------------------------------------------------ ## --------------------------------------------------//

let valoresCartas = []

const calcularCarta = (idCartaFrete, peso) => {
    const valorCarta = cartasFrete[idCartaFrete].getValorFrete()
    const valorTotal = valorCarta * peso
    const valorAbastecimento = valorTotal * cartasFrete[idCartaFrete].getPorcentagem()
    const valorTroco = valorTotal - valorAbastecimento
    return {
        total: valorTotal,
        troco: valorTroco,
        abastecimento: valorAbastecimento
    }

}

 const salvarCalculos = (...calculos) => {
    calculos.forEach((valor,indice) =>{
        valoresCartas[indice] = valor
    })
}

const calcularTodasCartas = (array) => {
    let valorGeral = array.reduce((acumulador,atual)=>{
        return acumulador + atual.total
    })
    return valorGeral
}

// ------------------------------------------------------ ## --------------------------------------------------//

salvarCartaFrete(
    criarCartaFrete('PMI','PEMA', 10.5, 0.5),
    criarCartaFrete('PMI','FILIAL', 14, 0.5),
    criarCartaFrete('SARZEDO','VDL', 22, 0.4)
)

salvarCalculos(
    calcularCarta(0,22),
    calcularCarta(1, 18),
    calcularCarta(2, 17)
)

console.log(valoresCartas)
console.log(calcularTodasCartas(valoresCartas))

O código funciona direitinho, até eu usar a função "calcularTodasCartas" .
A ideia desta função é somar os valores de todas as Cartas frentes dentro do array "valores Cartas".
Exemplo:
Neste código ele gera o seguinte array de objetos:
[ { total: 231, troco: 115.5, abastecimento: 115.5 },
  { total: 252, troco: 126, abastecimento: 126 },
  { total: 374, troco: 224.4, abastecimento: 149.6 } ]

Quero pegar os valores das chaves "total" de todas as posições do array e somar e retornar o valor acumulado,
pegar os valores das chaves "troco"  e somar voltar o valor acumulado, pegar os valores do abastecimento e somar e voltar acumulado.
Exemplo:
Total: 231 + 252 + 374 = 857
Seguindo essa lógica, escrevi o seguinte código:
const calcularTodasCartas = (array) => {
        let valorGeral = array.reduce((acumulador,atual)=>{
            return acumulador + atual.total
        })
        return valorGeral
    }

Mas o resultado é o seguinte:
[object Object]252374

Poderiam me dar uma luz?
Muito obrigado!
Answer: Resposta
Faltou você setar o valor inicial para 0:

let array = [
  { total: 231, troco: 115.5, abastecimento: 115.5 },
  { total: 252, troco: 126, abastecimento: 126 },
  { total: 374, troco: 224.4, abastecimento: 149.6 }
]

const calcularTodasCartas = (array) => {
    let valorGeral = array.reduce((acumulador, atual)=>{
        return acumulador + atual.total
    }, 0) // faltou setar o valor inicial
    return valorGeral;
}

console.log(calcularTodasCartas(array));

Assim, na primeira vez que rodar, ele irá fazer (0 + { total: 231}), o que resulta em 0 + 287, depois (287 + { total: 252 }), o que resulta em 287 + 252, na terceira vez 539 + { total: 374 }, o que resulta em 539 + 374, e por aí vai.
O que deu errado?
Do jeito anterior, você estava somando um objeto, no caso o acumulador com a o valor da propriedade atual.total, por isso dava aquele resultando com [object Object], ao setar o valor inicial para 0, o acumulador, passar a ser 0, como você pode ver no exemplo abaixo:

let array = [
  { total: 231, troco: 115.5, abastecimento: 115.5 },
  { total: 252, troco: 126, abastecimento: 126 },
  { total: 374, troco: 224.4, abastecimento: 149.6 }
]

// EXEMPLO SEM VALOR INICIAL
const calcularTodasCartasSemValorInicial = (array) => {
    let valorGeral = array.reduce((acumulador, atual)=>{
        console.log(acumulador);
        return acumulador + atual.total
    })
    return valorGeral;
}

// EXEMPLO COM VALOR INICIAL
const calcularTodasCartasComValorInicial = (array) => {
    let valorGeral = array.reduce((acumulador, atual)=>{
        console.log(acumulador);
        return acumulador + atual.total
    }, 0)
    return valorGeral;
}

console.log("Sem valor inicial: ", calcularTodasCartasSemValorInicial(array));
console.log("Com valor inicial: ", calcularTodasCartasComValorInicial(array));
Comment: Funcionou direitinho! Fiquei horas ontem e não encontrava o erro kkkkk muito obrigado!
Comment: Dá inclusive para fazer as 3 somas no mesmo reduce, inicializando o acumulador com `{total: 0, troco: 0, abastecimento: 0}` e somando assim `return {total: acumulador.total + atual.total, troco: acumulador.troco + atual.troco, abastecimento: acumulador.abastecimento + atual.abastecimento}`
Comment: Realmente, mas se eu fizer dessa forma eu não preciso setar o valor inicial como parâmetro no reduce, certo?

Javascript - Utilização do reduce


Postfix : Open relay to script

Question: What I want to do with postfix is have an open relay that accepts all emails. I then want it to push all the received emails to a script.
I have found solutions, but they never specifiy on how to do this for an open relay or how to accept all domains.
Comment: possible duplicate of [How to configure postfix to pipe all incoming email to a script?](http://serverfault.com/questions/258469/how-to-configure-postfix-to-pipe-all-incoming-email-to-a-script)
Comment: not really, since that one uses known hosts, and I want to accept all email
Comment: For this there is pcre or regex support in Postfix.
Answer: Oh, I wrote a little blog post about that: http://blog.malowa.de/2011/04/postfix-as-spam-trap-server.html
It is mainly about smtp-sink.
If you don't want that, see the dupe above.

Postfix : Open relay to script


Solve this 'Pigeonhole principle problem' without Pigeonhole principle

Question: The question goes like this:
Let $A = \{4,5,6,\ldots,61\}$.
We will create set $B$ by randomly choosing $9$ different numbers out of A.
We have to prove that there are at least 2 subset of $B$ that have the same sum of numbers.
The solution is possible using Pigeonhole principle as follows:(you can skip this if you want):
The maximum sum of subset of $B$ (which is not $B$ itself) is $8$ max numbers: $61+60+59+58+57+56+55+54 = 460$. the minimum of is $4$(subset contains this element alone).
So we have $457$ different possibilities for the sum of each subset of $B$.
However, we all know we have that we have $2^9$ different subset of $B$ - and for this specific case we neglect the empty and the complete set, so we have $510$ possibilities for subsets in $B$. because $510 > 457$ and  Pigeonhole principle we are done.

All good, but that method appear not to work in other cases, for example if we ask the same question with $A=\{1004,1005,\ldots,1061\}$ - it is easy to see that if it is good for the previous $A$ it should be good also with this $A$. but the method does not work this time.
so I guess there must be another way to solve that question that will be more general.
could you find it ?
Edit: thanks to Thomas, and other comments.. it appears that I missed a thing or two.. so I will change the question is it true at all the the new $A$
Comment: Is it true for that second $A$? It's not obvious it is.
Comment: It isn't so easy to see, since two subsets in the first question may have the same sum, but different numbers of elements (e.g. $4+16+25=45$. The sums of the obviously equivalent subsets in the second case will differ by a multiple of $1000$, so the problems are not the same.
Comment: well, I think...maybe i am wrong....that for every solution of each B i can find the corresponding solution to the second B. simply by adding 1000 to each element
Comment: That's only if the two subsets of $B$ have the same number of elements. Mark's comment. @d_e
Comment: @Thomas, you are right...should I delete the question then ?
Answer: Consider $$\begin{align}
B&=1003+\{1,2,4,8,16,32,55,57,58\}\\&=\{1004,1005,1007,1011,1019,1035,1058,1060,1061\}
\end{align}$$
There are no two subsets with the same sum here.


How to handle endpoint that does not return immediate results

Question: I have an endpoint that I bid/request some amount for a vehicle and then in the response body, I do not see that particular amount, I can only see the previous amounts that bidded.
But I can get the list of bidded amounts in the different endpoint.
So basically I request from 1 endpoint and verify the response of different Read auctions endpoints.
I do not how to maintain logic for API testing.
Can you please advise?
Thank you.
1st Request
it('bidding in external API', () => {
        cy.request({
            'method': 'POST',
            'url': `${Cypress.env('ampApiPrefixForExternalEndpoints')}/bid`,

            'headers': {
                'Authorization': Cypress.env('externalToken'),
                'content-type': Cypress.env('contentType'),
            },

            'body': {
                'id': 'bbbbbb',
                'bid': 42550,
                'auctionPlatformId': 'xxxx',
                'auctionPlatformUserId': 'aaaaa',
            },

            'failOnStatusCode': false,

        }).then((res) => {

            cy.log(JSON.stringify(res));
            expect(res.status).to.eq(200);

            })

        });

Response of Read auctions endpoints.
Received response (200):
{
    "data": {
        "auctions": [
            {
                "additionalCosts": xxx,
                "auctionCountryIso": "zxxc",
                "ahId": "12324",
                "auctionEndDatetime": "2022-03-20T06:03:47.394Z",
                "auctionStartDatetime": "2022-03-14T06:03:47.394Z",
                "auctionStatus": "ongoing",
                "auctionType": "type",
                "damageStatus": "normal",
                "bidStep": asddf,
                "bids": [
                    {
                        "amount": 29650,
                        "createdDatetime": "2022-03-15T05:56:47.394Z",
                        "externalData": [],
                        "isMaxBid": false,
                        "status": "accepted"
                    },
                    {
                        "amount": 29750,
                        "createdDatetime": "2022-03-15T05:57:47.394Z",
                        "externalData": [],
                        "isMaxBid": false,
                        "status": "accepted"
                    },
                    {
                        "amount": 29850,
                        "createdDatetime": "2022-03-15T05:58:47.394Z",
                        "externalData": [],
                        "isMaxBid": false,
                        "status": "accepted"
                    },
                    {
                        "amount": 29950,
                        "createdDatetime": "2022-03-15T05:59:47.394Z",
                        "externalData": [],
                        "isMaxBid": false,
                        "status": "accepted"
                    },
                    {
                        "amount": 30050,
                        "createdDatetime": "2022-03-15T06:00:47.395Z",
                        "externalData": [],
                        "isMaxBid": false,
                        "status": "accepted"
                    },
                    {
                        "amount": 30150,
                        "createdDatetime": "2022-03-15T06:01:47.395Z",
                        "externalData": [],
                        "isMaxBid": false,
                        "status": "accepted"
                    },
                    {
                        "amount": 30250,
                        "createdDatetime": "2022-03-15T06:02:47.395Z",
                        "externalData": [],
                        "isMaxBid": false,
                        "status": "accepted"
                    },
                    {
                        "amount": 44650,
                        "auctionPlatformId": "sdrwd",
                        "auctionPlatformUserId": "094c5519-bcaf-4100-8a40-904e04a7ecff",
                        "createdDatetime": "2022-03-15T14:34:54.432Z",
                        "externalData": {
                            "request_id": "saddsddse"
                        },
                        "isMaxBid": false,
                        "status": "accepted"
                    },
                    {
                        "amount": 44750,
                        "auctionPlatformId": "rwffffc",
                        "auctionPlatformUserId": "094c5519-bcaf-4100-8a40-904e04a7ecff",
                        "createdDatetime": "2022-03-15T14:35:11.596Z",
                        "externalData": {
                            "request_id": "adfds"
                        },
                        "isMaxBid": false,
                        "status": "accepted"
                    }
                ],

Answer: If you want to hit two endpoints in sequence, use .then() to chain the second one
cy.request({
  'method': 'POST',
  'url': `${Cypress.env('ampApiPrefixForExternalEndpoints')}/bid`,
  ...
}).then((res) => {
  // verify 1st endpoint
  expect(res.status).to.eq(200);
}).then(() => {
  // ensure sequential calling
  cy.request({
    'method': 'GET',
    'url': `${Cypress.env('ampApiPrefixForExternalEndpoints')}/read`,
    ...
  }).then((res) => {
    // verify 2nd endpoint
    expect(res.status).to.eq(200);
    ...
  })
})

Comment: I could be mistaken here, but couldn't we just chain the second `.request()` off of the first `.then()`, instead of wrapping it in another then? `cy.request().then().request().then()`?
Comment: I think the intention is to queue up each `.then()` separately so the most recent bid should be fetched in the next request.
Comment: @agoff you might be right. On the one hand you'd expect `cy.request().then().request().then()` to work sequentially because of subject passing, but on the other hand `.request()` is a parent command which doesn't accept a subject, so maybe Cypress fires it in parallel.
Comment: Hmm... I'll do some testing on my side. I think since they're in the same command chain they're sequential, similar to how a `cy.get().click().get().click()` doesn't fire in parallel. But agreed, Cypress is _weird_
Comment: Did a quick test on my end and I am fairly certain they fire sequentially.
Comment: Good to know, that is the implication as you said.


Overriding variables based on url

Question: At our university we have dev/test/live versions of our sites at urls like

dev.example.foo.edu
test.example.foo.edu
live.example.foo.edu (the real live url is example.foo.edu)

There are certain Drupal site variables (values in the variables table) that need to change depending on the environment (dev, test, live) where the site is running.
The first time the site is migrated to the live environment certain site variables need to magically change from their "dev" values to their "live" values.
After that initial migration we will periodically load the live database into the dev and test sites to update their content.  When this happens I want certain site variables to change to their "dev" values.
I don't want the site builder to have to do anything.  I want the variables to simply change to the correct values.
It's okay if the site admin wants to manually override these variables.  They shouldn't have to, but there could be a need for this...
I mainly need a Drupal 7 solution--bonus if it works with Drupal 6.
Possible solutions:
Does a module exist that will do this?
I haven't found one. I've looked at

http://drupal.org/project/tadaa (incomplete)
http://drupal.org/project/context_domain (provides a url "reaction" but  context can't provide the kind of variable condition I need.  Looked at http://drupal.org/project/context_var (provides a Reaction not a Condition)).
http://drupal.org/project/strongarm (can set variables...often used with Features...)

Use hook_update_N (http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_update_N/7)

This doesn't meet the requirement that the site builder doesn't have to do anything. They would have to copy paste a update_71234() in some install file. They would also have to remember to run update.php in various situations.

Write a custom module?
This works:
<code>/**
 * Implementation of hook_cron().
 */
function ucb_varenv_cron() {
    global $base_url;

    //if (variable_get('ucb_varenv', FALSE) === FALSE) {
        $parts = explode('.', $base_url);
        $vars = ucb_varenv_vars();
        $p1 = str_replace('http://', '', $parts[0]);
        while (list($k, $v) = each($vars[$p1])) {
            variable_set($k, $v);
        }
        //variable_set('ucb_varenv', TRUE);
    //}

}

function ucb_varenv_vars() {
    $vars = array(
      'dev' => array(
        'cas_server' => "TEST2.example.com",
    ),
       'live' => array(
         'cas_server' => "auth.example.edu",
    ),
    );
    return $vars;
}
</code>
Hook cron seems like a clumsy approach.  The commented ucb_varenv code was from and experiment where this would run one time only at hook_boot()--but that seemed like a bad idea.
The more I think about this, I wonder if there is some way to leverage strongarm to do what I need.
Comment: could just NOT including the variable table in your backup work?
Answer: Assuming I've parsed this all out correctly, you should be able to achieve what you're looking for using Rules. You'll need to install core's PHP Formatter for its integration with Rules to call variable_set() as an action, though beyond that it's pretty straightforward:

Event: When cron maintenance tasks are performed
Condition: Data comparison (Parameter: Data to compare: [site:url], Data value: http://example.foo.edu/)
Action: Execute custom PHP code (Code: variable_set('cas_server', 'auth.example.edu');)

Mind the trailing slash in the condition URLs - it's the path to the home page, not the domain name, so the slash is required.
Of course, you could bind it to whatever event you feel is most appropriate, and duplicate the same rule for your dev and test instances with the appropriate CAS servers (going this route would also mean you could export this with Features). I've tested the above reaction rule, and it seems to work on my own D7 instance (with the URL condition set accordingly):
<code># After cron
[dmw@seraph aqueduct]$ drush vget cas
cas_server: "auth.example.edu"
</code>
It's been a while since I've used the old Rules, though I don't see why something similar can't work for D6.
Comment: Rules! Of course!  I have this working.  We will be able to trigger cron when we sync the db, so this is a decent solution.
Answer: Thanks again for the Rules idea.
In the end, it was better to code conditional logic into settings.php.
I was thinking that the settings.php approach wouldn't be good because I'd loose my code when I upgrade Drupal. But since settings.php is not actually part of a Drupal release, as long as  you set up your version control correctly, you can carry this code forward.
This way we don't have to worry about cron failing to run.  We also don't have to maintain these rules in the future.
Comment: Clever; I hadn't considered this approach! We typically don't revision settings.php for security purposes (storing passwords and environment-specific config in VCS runs counter to best-practice). I'm interested to hear if you've found a way to mitigate this, perhaps using something like http://www.metaltoad.com/blog/stage-specific-drupal-settings-localsettingsphp. Either way, I'm glad you found something that works for you.  :>
Comment: In my case the version control setup is being done by http://gotpantheon.com.  The db user and pass is in my settings.php.  The Pantheon guys (joshk and davidstrauss) are pretty good, so I'm sure they've considered security.
Comment: Before moving to Pantheon I ran sites using Aegir.  Aegir was storing the db credentials in the vhost using SetEnv dbpass foo; SetEnv dbuser bar and then evaluating those variable in settings.php. Interesting approach...not sure how much security it buys...
Answer: I changed my mind again. I'm doing it in a module.  See the README for why: https://github.com/ucbdrupal/ucb_envconf/tree/7.x-1.x
Comment: The link is broken and this answer doesn't give the "why".

Overriding variables based on url


How can I split a string into a given number of lines?

Question: Here is my question:
Given a string, which is made up of space separated words, how can I split that into N strings of (roughly) even length, only breaking on spaces?
Here is what I've gathered from research:
I started by researching word-wrapping algorithms, because it seems to me that this is basically a word-wrapping problem. However, the majority of what I've found so far (and there is A LOT out there about word wrapping) assumes that the width of the line is a known input, and the number of lines is an output. I want the opposite.
I have found a (very) few questions, such as this that seem to be helpful. However, they are all focused on the problem as one of optimization - e.g. how can I split a sentence into a given number of lines, while minimizing the raggedness of the lines, or the wasted whitespace, or whatever, and do it in linear (or NlogN, or whatever) time. These questions seem mostly to be unanswered, as the optimization part of the problem is relatively "hard".
However, I don't care that much about optimization. As long as the lines are (in most cases) roughly even, I'm fine if the solution doesn't work in every single edge case, or can't be proven to be the least time complexity. I just need a real world solution that can take a string, and a number of lines (greater than 2), and give me back an array of strings that will usually look pretty even.
Here is what I've come up with:
I think I have a workable method for the case when N=3. I start by putting the first word on the first line, the last word on the last line, and then iteratively putting another word on the first and last lines, until my total width (measured by the length of the longest line) stops getting shorter. This usually works, but it gets tripped up if your longest words are in the middle of the line, and it doesn't seem very generalizable to more than 3 lines.
var getLongestHeaderLine = function(headerText) {
  //Utility function definitions
  var getLongest = function(arrayOfArrays) {
    return arrayOfArrays.reduce(function(a, b) {
      return a.length > b.length ? a : b;
    });
  };

  var sumOfLengths = function(arrayOfArrays) {
    return arrayOfArrays.reduce(function(a, b) {
      return a + b.length + 1;
    }, 0);
  };

  var getLongestLine = function(lines) {
    return lines.reduce(function(a, b) {
      return sumOfLengths(a) > sumOfLengths(b) ? a : b;
    });
  };

  var getHeaderLength = function(lines) {
    return sumOfLengths(getLongestLine(lines));
  }

  //first, deal with the degenerate cases
  if (!headerText)
    return headerText;

  headerText = headerText.trim();

  var headerWords = headerText.split(" ");

  if (headerWords.length === 1)
    return headerText;

  if (headerWords.length === 2)
    return getLongest(headerWords);

  //If we have more than 2 words in the header,
  //we need to split them into 3 lines
  var firstLine = headerWords.splice(0, 1);
  var lastLine = headerWords.splice(-1, 1);
  var lines = [firstLine, headerWords, lastLine];

  //The header length is the length of the longest
  //line in the header. We will keep iterating
  //until the header length stops getting shorter.
  var headerLength = getHeaderLength(lines);
  var lastHeaderLength = headerLength;
  while (true) {
    //Take the first word from the middle line,
    //and add it to the first line
    firstLine.push(headerWords.shift());
    headerLength = getHeaderLength(lines);
    if (headerLength > lastHeaderLength || headerWords.length === 0) {
      //If we stopped getting shorter, undo
      headerWords.unshift(firstLine.pop());
      break;
    }
    //Take the last word from the middle line,
    //and add it to the last line
    lastHeaderLength = headerLength;
    lastLine.unshift(headerWords.pop());
    headerLength = getHeaderLength(lines);
    if (headerLength > lastHeaderLength || headerWords.length === 0) {
      //If we stopped getting shorter, undo
      headerWords.push(lastLine.shift());
      break;
    }
    lastHeaderLength = headerLength;
  }

  return getLongestLine(lines).join(" ");
};

debugger;
var header = "an apple a day keeps the doctor away";

var longestHeaderLine = getLongestHeaderLine(header);
debugger;

EDIT: I tagged javascript, because ultimately I would like a solution I can implement in that language. It's not super critical to the problem though, and I would take any solution that works.
EDIT#2: While performance is not what I'm most concerned about here, I do need to be able to perform whatever solution I come up with ~100-200 times, on strings that can be up to ~250 characters long. This would be done during a page load, so it needs to not take forever. For example, I've found that trying to offload this problem to the rendering engine by putting each string into a DIV and playing with the dimensions doesn't work, since it (seems to be) incredibly expensive to measure rendered elements.
Comment: Are you looking for visual length (when rendered) or string length (number of characters)?
Comment: Could you post the code you have so far?
Comment: Not exactly what I'm using currently, but real close: https://jsfiddle.net/a546ova0/5/
Comment: @Mojtaba Not looking to have it done for me, just looking for some new ideas. Several paid programmers have already come up empty, so looking to crowdsource a little innovation here.
Comment: @tt.net, I updated your question with the code you provided
Comment: Confusion numero uno: You say the input is the text, and the desired number of lines - yet your example only shows you passing the text as an input.
Comment: @Jamiec Yeah, the code is what is referenced by this: "I think I have a workable method for the case when N=3". The code has a hard-coded first, last, and middle line, so it doesn't work in the general case. I've yet to figure out any way of generalizing the process of taking from the beginning and end of a "middle" line, if I don't know the actual number of lines.
Comment: @tt.net just a clarification, do you want the words in the broken up text to be in the same order as it was pre-broken up?
Comment: @Ted Yes, they should be in the same order when read left to right, up to down (normal English reading order)
Comment: @Bergi Honestly, I would be fine with either. I've been working under the assumption that number of characters would be the easier solution.
Comment: @tt.net A rather simple solution would be to try different box widths, let the browser render the text into each, and measure how many lines it takes.
Comment: @bergi Yeah, I've thought of that. When I said that optimization wasn't super important to me, I was talking about the problem from the # of chars angle. I could have up to 100 or so of this strings to process at a time, which in pure javascript should be pretty negligible even for an inefficient solution. However, when you add in the DOM access for measuring rendered elements, it seems to be incredibly time consuming. I'll update the question to better specify my performance constraints.
Comment: this js measures width of rendered text http://stackoverflow.com/questions/30940499/text-size-auto-resizing-on-div-width/30960832#30960832
Comment: @m69 Yeah, that's bascially what I've seen before. I don't have benchmarks handy right now, but the issue seems to be that the offsetWidth and offsetHeight calls are really (unexpectedly to me at least) expensive, so this doesn't work for even a hundred elements very well. I've seen those calls take 50-100ms each at times.
Comment: You could limit the number of calls, but even 10 x 100ms is too long, I guess.
Comment: @tt.net Added code demonstration for the binary search solution to my answer. You may need to adjust it a little to account for the spaces at the end of each line having no length as they are converted to line breaks. (Also the output is unpolished, adding a space after the last word on each line.)
Comment: @tt.net also, can you give us some data to test, maybe a pastebin?
Answer: Try this. For any reasonable N, it should do the job:
function format(srcString, lines) {
  var target = "";
  var  arr =  srcString.split(" ");
  var c = 0;
  var MAX = Math.ceil(srcString.length / lines);
  for (var i = 0, len = arr.length; i < len; i++) {
     var cur = arr[i];
     if(c + cur.length > MAX) {
        target += '\n' + cur;
     c = cur.length;
     }
     else {
       if(target.length > 0)
         target += " ";
       target += cur;
       c += cur.length;
     }
   }
  return target;
}

alert(format("this is a very very very very " +
             "long and convoluted way of creating " +
             "a very very very long string",7));

Comment: Thanks for the suggestion! This is essentially what was suggested on the question I linked to.
I have tried adapting traditional word-wrapping algorithms that take in a line length in this way before - unfortunately for me, I know very little about the input text, so, for example, any single word could be longer than length / lines. The most important thing is that the algorithm never use more lines than I specify. Trying your solution with something like this: "this should be three lines, but it has a loooooooooooooooooooooooooooooooong word" shows what I'm talking about.
Comment: What do you want to happen when the size of a word exceeds the allocated size for the line?
Comment: That's basically the problem with allocating a set size for each line in the first place. I don't have any specific width that the lines need to be, so algorithms that rely on figuring a line width, and then performing the word-wrapping don't seem to work well for my use-case.
Answer: You may want to give this solution a try, using canvas. It will need optimization and is only a quick shot, but I think canvas might be a good idea as you can calculate real widths. You can also adjust the font to the really used one, and so on. Important to note: This won't be the most performant way of doing things. It will create a lot of canvases.
DEMO
var t = `However, I don't care that much about optimization. As long as the lines are (in most cases) roughly even, I'm fine if the solution doesn't work in every single edge case, or can't be proven to be the least time complexity. I just need a real world solution that can take a string, and a number of lines (greater than 2), and give me back an array of strings that will usually look pretty even.`;

function getTextTotalWidth(text) {
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
  ctx.font = "12px Arial";
    ctx.fillText(text,0,12);
  return ctx.measureText(text).width;
}

function getLineWidth(lines, totalWidth) {
    return totalWidth / lines ;
}

function getAverageLetterSize(text) {
    var t = text.replace(/\s/g, "").split("");
  var sum = t.map(function(d) {
    return getTextTotalWidth(d);
  }).reduce(function(a, b) { return a + b; });
    return  sum / t.length;
}

function getLines(text, numberOfLines) {
    var lineWidth = getLineWidth(numberOfLines, getTextTotalWidth(text));
  var letterWidth = getAverageLetterSize(text);
  var t = text.split("");
  return createLines(t, letterWidth, lineWidth);
}

function createLines(t, letterWidth, lineWidth) {
    var i = 0;
  var res = t.map(function(d) {
    if (i < lineWidth || d != " ") {
        i+=letterWidth;
        return d;
    }
    i = 0;
    return "
";
  })
  return res.join("");
}

var div = document.createElement("div");
div.innerHTML = getLines(t, 7);
document.body.appendChild(div);

Comment: Thanks, I will play with this! I edited the question to be clear that I while I don't care too much about the time efficiency of the algorithm, I do need to be able to do this one - two hundred times on page load, which is why I've stayed away from rendering-based solutions so far. Haven't tried canvas yet though, so maybe this will work better.
Comment: Also, looks like this doesn't handle long words very well either (look at my comment on Milton's answer), which is something I've noticed about every solution I've tried of the type - "start on the first line, accumulate until you've passed some calculated size, go to a new line, repeat." (This is just an observation, not necessarily a deal breaker. Looks like this solution WILL respect the input number of lines, which is the most important part)
Comment: Yes, that's true. I'll play with it tomorrow again, it would have to check for the longest word too, to get better results. @tt.net
Comment: @tt.net I think something that makes the line length equal to the longest word if it's longer to the avg line width would work good
Answer: I'm sorry this is C#. I had created my project already when you updated your post with the Javascript tag.
Since you said all you care about is roughly the same line length... I came up with this. Sorry for the simplistic approach.
    private void DoIt() {

        List<string> listofwords = txtbx_Input.Text.Split(' ').ToList();
        int totalcharcount = 0;
        int neededLineCount = int.Parse(txtbx_LineCount.Text);

        foreach (string word in listofwords)
        {
            totalcharcount = totalcharcount + word.Count(char.IsLetter);
        }

        int averagecharcountneededperline = totalcharcount / neededLineCount;
        List<string> output = new List<string>();
        int positionsneeded = 0;

        while (output.Count < neededLineCount)
        {
            string tempstr = string.Empty;
            while (positionsneeded < listofwords.Count)
            {
                tempstr += " " + listofwords[positionsneeded];
                if ((positionsneeded != listofwords.Count - 1) && (tempstr.Count(char.IsLetter) + listofwords[positionsneeded + 1].Count(char.IsLetter) > averagecharcountneededperline))//if (this is not the last word) and (we are going to bust the average)
                {
                    if (output.Count + 1 == neededLineCount)//if we are writting the last line
                    {
                        //who cares about exceeding.
                    }
                    else
                    {
                        //we're going to exceed the allowed average, gotta force this loop to stop
                        positionsneeded++;//dont forget!
                        break;
                    }
                }
                positionsneeded++;//increment the needed position by one
            }

            output.Add(tempstr);//store the string in our list of string to output
        }

        //display the line on the screen
        foreach (string lineoftext in output)
        {
            txtbx_Output.AppendText(lineoftext + Environment.NewLine);
        }

    }

Answer: (Adapted from here, How to partition an array of integers in a way that minimizes the maximum of the sum of each partition?)
If we consider the word lengths as a list of numbers, we can binary search the partition.
Our max length ranges from 0 to sum (word-length list) + (num words - 1), meaning the spaces. mid = (range / 2). We check if mid can be achieved by partitioning into N sets in O(m) time: traverse the list, adding (word_length + 1) to the current part while the current sum is less than or equal to mid. When the sum passes mid, start a new part. If the result includes N or less parts, mid is achievable.
If mid can be achieved, try a lower range; otherwise, a higher range. The time complexity is O(m log num_chars). (You'll also have to consider how deleting a space per part, meaning where the line break would go, features into the calculation.)
JavaScript code (adapted from http://articles.leetcode.com/the-painters-partition-problem-part-ii):

function getK(arr,maxLength) {
  var total = 0,
      k = 1;

  for (var i=0; i<arr.length; i++) {
    total += arr[i] + 1;

    if (total > maxLength) {
      total = arr[i];
      k++;
    }
  }

  return k;
}

function partition(arr,n) {
  var lo = Math.max(...arr),
      hi = arr.reduce((a,b) => a + b);

  while (lo < hi) {
    var mid = lo + ((hi - lo) >> 1);

    var k = getK(arr,mid);

    if (k <= n){
      hi = mid;

    } else{
      lo = mid + 1;
    }
  }

  return lo;
}

var s = "this is a very very very very "
      + "long and convoluted way of creating "
      + "a very very very long string",
    n = 7;

var words = s.split(/\s+/),
    maxLength = partition(words.map(x => x.length),7);

console.log('max sentence length: ' + maxLength);
console.log(words.length + ' words');
console.log(n + ' lines')
console.log('')

var i = 0;

for (var j=0; j<n; j++){
  var str = '';

  while (true){
    if (!words[i] || str.length + words[i].length > maxLength){
      break
    }
    str += words[i++] + ' ';
  }
  console.log(str);
}
Answer: Using the Java String Split() Method to split a string we will discover How and Where to Apply This String Manipulation Technique:
We'll examine the Java Split() method's explanation and discover how to apply it. The principles are explained simply and with enough programming examples, either as a separate explanation or in the comment part of the programs.
The Java String Split() method is used to divide or split the calling Java String into pieces and return the Array, as the name implies. The delimiters("", " ", ) or regular expressions that we have supplied separately for each component or item of an array.
Syntax
String[ ] split(String regExp)
First Case: It involves initializing a Java String variable with a variety of words separated by spaces, using the Java String Split() method, and evaluating the results. We can effectively print each word without the space using the Java Split() function.
Second Case: In this case, we initialize a Java String variable and attempt to split or deconstruct the main String variable to use the String Split() method utilizing a substring of the initialized String variable.
Third Case: In this case, we will attempt to split a String using its character by taking a String variable (a single word).
You can check out other approaches to this problem on YouTube and even coding websites on google such as Coding Ninjas
Comment: Welcome to [so]! Please take the [tour], visit the [help] and read up on [answering questions well](https://stackoverflow.com/help/answering).
Answer: This old question was revived by a recent answer, and I think I have a simpler technique than the answers so far:

const evenSplit = (text = '', lines = 1) => {
  if (lines < 2) {return [text]}
  const baseIndex = Math .round (text .length / lines)
  const before = text .slice (0, baseIndex) .lastIndexOf (' ')
  const after = text .slice (baseIndex) .indexOf (' ') + baseIndex
  const index = after - baseIndex < baseIndex - before ? after : before
  return [
    text .slice (0, index),
    ... evenSplit (text .slice (index + (before > -1 ? 1 : 0)), lines - 1)
  ]
}

const text = `However, I don't care that much about optimization. As long as the lines are (in most cases) roughly even, I'm fine if the solution doesn't work in every single edge case, or can't be proven to be the least time complexity. I just need a real world solution that can take a string, and a number of lines (greater than 2), and give me back an array of strings that will usually look pretty even.`

const display = (lines) => console .log (lines .join ('\n'))

display (evenSplit (text, 7))
display (evenSplit (text, 5))
display (evenSplit (text, 12))
display (evenSplit (`this should be three lines, but it has a loooooooooooooooooooooooooooooooong word`, 3))
.as-console-wrapper {max-height: 100% !important; top: 0}

It works by finding the first line then recurring on the remaining text with one fewer lines.  The recursion bottoms out when we have a single line.  To calculate the first line, we take an initial target index which is just an equal share of the string based on its length and the number of lines.  We then check to find the closest space to that index, and split the string there.
It does no optimization, and could certainly be occasionally misled by long words, but mostly it just seems to work.


Anchor Constraints not Honored in Xcode 10 / iOS 12

Question: This all worked yesterday under Xcode 9 and iOS 11; however, after updating to Xcode 10 and iOS 12, the view is no longer showing. I was having a video displayed inside a view. Today I could hear but not see the video. I checked the frame and found it to be zero which explained the issue. However, nothing had changed from the prior version. I have removed the video stuff and have just looked at the view's frame after anchor constraints were applied and they are all zero.
import UIKit
import AVKit

class VideoView: UIView {

private var videoURL:URL!
private var parentView:UIView!
private var avPlayer:AVPlayer!
private var avPlayerLayer:AVPlayerLayer!

init(url:URL, parentView:UIView) {
    super.init(frame: .zero)

    self.videoURL = url
    self.parentView = parentView

    setup()
}

private func setup() {
    self.translatesAutoresizingMaskIntoConstraints = false
    self.parentView.addSubview(self)

    self.topAnchor.constraint(equalTo: self.parentView.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
    self.leadingAnchor.constraint(equalTo: self.parentView.leadingAnchor, constant: 8).isActive = true
    self.trailingAnchor.constraint(equalTo: self.parentView.trailingAnchor, constant: -8).isActive = true
    self.heightAnchor.constraint(equalToConstant: 200).isActive = true

    print(self.parentView.frame)
    print(self.frame)
}

override init(frame: CGRect) {
    super.init(frame: frame)
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}
}

notice the two print statements at the end of setup(). The parentView return 0,0,414,736. The self view returns 0,0,0,0.
If in Init I set the frame size it will respect it; however, it does not apply the anchor constraints so the size of the view will remain whatever it is I put into the init.
It appears that the anchor constraints are not at all being taken into account. There is no error in the debugger about them and as we can see, translatesAutoresizingMaskIntoConstraints is set to false and all constraints have the isActive set to true.
Only the Xcode and iOS version have changed. What am I missing?
Update 1:
If I create a label and add it to self, the label shows fine. If I create a background color for self that also shows fine including the proper height as set with the anchor constraints. However, the frame remains at zero. So when trying to add an AVPlayerLayer by setting its frame to the bounds of self it doesn't work because of course self remains at zero. So the question remains as to why the frame's dimensions are not changing after initialization.
Update 2:
I added a self.layoutIfNeeded() just after applying the anchor constraints and that seems to have solved the issue. Although looking at the frame for self and I get -199,-100,398,200 Cannot say I understand the values for X and Y. Nevertheless the layOutIfNeeded seems to have solved the problem although why this is required in Xcode 10/ iOS 12 is also a mystery.
Answer: I posted what seems to be the answer in my second update, but for clarity:
I added a self.layoutIfNeeded() just after applying the anchor constraints and that seems to have solved the issue. Although looking at the frame for self and I get -199,-100,398,200 Cannot say I understand the values for X and Y. Nevertheless the layOutIfNeeded seems to have solved the problem although why this is required in Xcode 10/ iOS 12 is also a mystery.


Prime spirals on surfaces of revolution

Question: This is an entirely naive question, and in addition, vague.  Apologies in advance!
Imagine wrapping the Ulam prime spiral around a surface in $\mathbb{R}^3$,
something like this:

This suggests this variation.
Let $S$ be a surface of revolution, touching the origin $(0,0,0)$ and rising
into the positive $z$-halfspace.
Wrap a monotonically rising "prime spiral" $\rho$ around $S$ so that the distance (measured on $S$)
between two successive
primes on $\rho$ is the difference between those two primes as integers.  But $\rho$ need not be a
geodesic on $S$.
Just as the various diagonals of the Ulam prime spiral reveal relationships and suggest conjectures concerning the primes, perhaps some particular $S$ would regularize or
"organize" the primes.
So, finally, my question is this:

Is there some surface of revolution $S$ and some $\rho$ so that the geodesics
  from the origin lying in vertical planes (the analogs of diagonals) reveal structure
  in the primes? Either provable or conjectural structure?
Comment: To quote from the Wikipedia article to which I link, "In their famous 1923 paper on the Goldbach Conjecture, Hardy and Littlewood stated a series of conjectures, one of which, if true, would explain some of the striking features of the Ulam spiral."
Comment: The pyramid figure you posted is not a surface of revolution. There may not be any reason to expect the more revealing spirals should be two-dimensional (as opposed to space/lattice filling in higher dimensions) or hypersurfaces with any particular symmetries. You don't have any prior notion of what a 'revealation' would be, nor a specification of what the "structure of primes" is, so this question is very much in the shop.
Answer: As far as I'm aware (in other words, since I'm not an expert don't take this answer too seriously) this has not been studied using the terminology or set up that you describe. However there are some general conjectures on primes which could be translated to this set up, so in some sense, yes, there are conjectures that predict what the patterns we will see are.
First, note that there is nothing special about the Ulam spiral. It's main feature is that it moves around integers that are values of quadratic polynomials in a way that they appear on a line. Similarly playing with the idea of using other (algebraic) surfaces we notice that the lines will become integer values polynomials (not necessarily quadratic).
So, as I see it, the problem reduces to conjectured densities of prime values of polynomials. Patterns emerge when some polynomial families are expected to have higher densities of primes than others. A precise form of this heuristic is the "Bateman-Horn" conjecture, which, needless to say, is very very open at the moment.
Comment: Thank you for this cogent answer.  And especially for pointing me to the Bateman–Horn conjecture.  Thanks!

Prime spirals on surfaces of revolution


Remove common code from functions

Question: I got nearly 10 functions in class having similar pattern like following function
    SQLiteDatabase database = this.getWritableDatabase();

    try {
          //Some different code , all other code(try,catch,finally) is same in all functions
    } catch (SQLiteException e) {
        Log.e(this.getClass().getName(), e.getMessage());
        return false;
    } finally {
        database.close();
    }

}

I want to remove that common code from all functions (try ,catch , finally) and move it to a single place
How can I achieve this?
Comment: You write a helper method.
Comment: @ChrisHayes: it could be refactored using an interface (with a single method) which is then passed to the helper method.
Comment: @ChrisHayes: The difference is that it's unlikely that the syntax for the anonymous inner class will need to change. Whereas if you need to change anything about the other boiler plate (e.g. exactly how you're logging) it means changing every single one of those methods. And it's not just a try/catch - it's an "acquire database connection" then try/catch/finally, and getting any of that wrong is going to cause pain.
Comment: If the code in the `try` is different, you aren't going to be able to usefully refactor it. The better pattern is to put *all* of your database interactions into a separate class(es)/set of methods so you almost never have to look at it.
Comment: @a_horse_with_no_name True, but I don't consider that to be a useful refactor, since it adds more boilerplate than it eliminates.
Comment: @ChrisHayes Yup I agree with you
Comment: @ChrisHayes: I don't think it would add a huge amount of boilerplate in this case using anonymous inner classes - and of course as soon as Java 8 comes out, refactoring those anonymous inner classes to lambda expressions would shrink it down further.
Comment: @JonSkeet True, but I personally find anonymous inner classes harder to read than a simple try/catch. I think it would be largely subjective. Agreed about lambdas, but you could be waiting quite a while for Java 8 to work its way into many corporate environments (and even longer for team members not used to lambdas to accept it!). :)
Comment: @Raheel what is the class of `this` in `this.getWritableDatabase()`? is it `Activity` or `FragmentActivity` or something else?
Comment: @ADTC its "SQLiteOpenHelper"
Answer: There are a number of frameworks out there that drastically simplify database interaction that you can use, but if you want to do things on your own, and are interested in the Java way to do things like this, here's the idea:
Make your "executor" like so:
public class Executor {
  public static void runOperation(Operation operation) {
    SQLiteDatabase database = this.getWritableDatabase();
    try {
      operation.run(database);
    } catch (SQLiteException e) {
      Log.e(operation.getClass().getName(), e.getMessage());
      return false;
    } finally {
      database.close();
  }
}

Now each of the 10 things you want to do will be operations:
public interface Operation {
  void run(SQLiteDatabase database) throws SQLiteException;
}

Here is what a particular operation would look like:
Operation increaseSalary = new Operation() {
  public void run(SQLiteDatabase database) throws SQLiteException {
    // .... write the new increased salary to the database
  }
};

And you run it with:
.
.
Executor.runOperation(increaseSalary);
.
.

You can also make the implementation of the interface an anonymous inner class, but that may make it a little less readable.
.
.
Executor.runOperation(new Operation() {
  public void run(SQLiteDatabase database) throws SQLiteException {
    // put the increase salary database-code in here
  }
});
.
.

You can look through a list of classic Design Patterns to find out which one this is.
Comment: I think you should put `Operation.run(database);` inside the `try` block... isn't that the intention?
Comment: And also declare `throws SQLiteException`.
Comment: The anonymous inner class will help avoid creating a *separate* class file for each operation. So his original class with 10 or so functions can remain the same way, except being refactored to use the `Executor` pattern. So in a way, it can be more readable as all the *"something"* code are still in the same place, not moved to separate class files.
Comment: Btw one more thing I noticed, is `this` in Executor. I think this should be changed to a private object populated by a constructor, since the original `this` referred to the original class the asker is referring to, not `Executor` class. Or **better,** pass it as an argument to the static method, in addition to the `Operation` object: `Executor.runOperation(this, new Operation() { ...`
Comment: @ADTC Even anonymous inner classes generate additional class files (ending in `$1.class`, `$2.class`, etc.)  I say _may_ be less readable because naming your subclasses can increase readability.  If an operation needs to be defined to increase someone's salary, for example, one can define `Operation increaseSalary = new Operation () {...}` and later say `runOperation(increaseSalary)`.  That IMHO is better than jamming in the increase salary logic in the middle of a larger operation. After all, that's why we write and name functions in the first place. :)
Comment: Yes that is true. Well anyway, I was talking from a source code perspective, in case the asker did not want to move the source code out into separate files - but on second thought, he could create all the classes in one source file too as inner classes. `:)` *There are so many ways to tackles this!*
Comment: Actually no, it's not `operation` but it's `SQLiteOpenHelper` as evidenced by asker's recent comment. Please see my answer on how I tackled the `this` problem. Also, the return type of the original methods is `boolean`, not `void`. *Let's avoid extended discussions.. S.O. is beating the drums already `:)`*
Comment: @ADTC You are correct that I overlooked the use of `this`. Thanks again!  I've changed my answer, but I think I've done it in such a way as to avoid passing the reference around.  The variable `operation` is accessible so we can get its class in the exception handler.  Does that look okay?
Answer: To expand further on Ray Toal's original answer, it is worth noting that using anonymous inner class will help avoid creating a separate class file for each operation. So the original class with 10 or so functions can remain the same way, except being refactored to use the Executor pattern.
Also, when using the Executor pattern, you have to take care of the usage of this in the original code. Assume the original functions are as follows:
public boolean operation1() {
    SQLiteDatabase database = this.getWritableDatabase();

    try {
        //Code for Operation 1
        return true;
    } catch (SQLiteException e) {
        Log.e(this.getClass().getName(), e.getMessage());
        return false;
    } finally {
        database.close();
    }

}

public boolean operation2() {
    SQLiteDatabase database = this.getWritableDatabase();

    try {
        //Code for Operation 2
        return true;
    } catch (SQLiteException e) {
        Log.e(this.getClass().getName(), e.getMessage());
        return false;
    } finally {
        database.close();
    }

}

With the Executor class defined as follows:
public class Executor {
  public static boolean runOperation(SQLiteOpenHelper helper, Operation operation) {
    SQLiteDatabase database = helper.getWritableDatabase();
    try {
      operation.run(database);
      return true;
    } catch (SQLiteException e) {
      Log.e(helper.getClass().getName(), e.getMessage());
      return false;
    } finally {
      database.close();
    }
  }
}

And the Operation interface defined as follows:
public interface Operation {
    public void run(SQLiteDatabase database) throws SQLiteException;
}

The original functions can now be rewritten as follows:
public boolean operation1() {
    return Executor.runOperation(this, new Operation() {
      public void run(SQLiteDatabase database) throws SQLiteException {
        //Code for Operation 1
      }
    });
}

public boolean operation2() {
    return Executor.runOperation(this, new Operation() {
      public void run(SQLiteDatabase database) throws SQLiteException {
        //Code for Operation 2
      }
    });
}

This expansion also corrects mistakes Ray has overlooked in his original answer.

Remove common code from functions


Where does UFW (uncomplicated firewall) save command-line rules to?

Question: You add a rule like this:
ufw allow 22/tcp

The rule is saved, and is applied even after reboot. But it's not written anywhere in /etc/ufw. Where is it saved to? (Ubuntu, using ufw as pre-installed.)
Answer: In my Ubuntu 11 server, the firewall rules are saved in /lib/ufw/user.rules
Comment: What a crazy location! I just spent 20 minutes looking for this :-(
Comment: user6.rules is for IP version 6 (ipv6) firewall rules.
Comment: Bingo, thanks. There's also a user6.rules (which doesn't have all the rules I created, but otherwise looks similar).
Comment: Still correct in Ubuntu 14, thank you.
Comment: I didn't, because I searched first on ServerFault :-) But I agree, it's anything but obvious...
Comment: ... also, these days, it's more common to find the active rules for _your_ system (as opposed to the original distro files) under `/etc/ufw` as [already answered here](https://serverfault.com/a/788489/133346) by @tivnet.
Answer: Ubuntu 16.04 LTS
/etc/ufw/user.rules
Debian 9
/etc/ufw/user.rules
In general, try:
locate user.rules
Should output something like:
/etc/ufw/user.rules
/usr/share/ufw/user.rules
/usr/share/ufw/user.rules.md5sum
/usr/share/ufw/iptables/user.rules

Comment: It's recommended to run `updatedb` at least once before using `locate`.
Comment: @ccpizza On Ubuntu, at least, `updatedb` is run daily by `cron`. See `/etc/cron.daily/mlocate`.
Comment: Still valid for Ubuntu 22.04 and Debian 11 as of 2022. Insane!
Answer: I believe it's under lib/ufw/rules[6].rules
Answer: In my version, 8.04 LTS Server the files are stored in /var/lib/ufw as /var/lib/ufw/user.rules and /var/lib/ufw/user6.rules.
Answer: This should work on all Linux systems assuming a ".rules" suffix and residing beneath a directory named "ufw":
sudo find / -name "*.rules" -exec ls -l {} \; | grep ufw

Using the "ls -l" shows that some of them are links to others, and which ones have been updated most recently (implying they are active?)
Comment: Assuming that Debian/Ubuntu have been consistently implementing their usual configuration for `ufw` as well, there is some logic implied: _original_ (raw from the distro) files should be under `/usr/share/ufw/`; locally changed/overridden files under `/etc/ufw`; dynamically changed rules (for some reason) ought to be under `/run` (I just have a lock file there). The exception to the usual configuration is `/lib/ufw` which should also have some rules in it, but just has a startup script for `ufw`.
Comment: The way `/etc` overrides what is on `/run` which overrides what is on `/lib` (which is usually a symlink to `/usr/share`) is pretty consistent among _most_ configurations in Debian & Ubuntu.
Answer: On Ubuntu 16 and up user firewall rules are stored in /etc/ufw/user.rules and /etc/ufw/user6.rules. Overall all UFW rules and configs located in /etc/ufw
Answer: As of September 2021, you can find all files and configuration of what is called the UFS Framework using man ufw-framework. It describes in detail where each file goes, what it does, and how the system works together to launch the ufw framework at boot time.
This is valid for at least Ubuntu 22.04 and Debian 11 (Debian has an older version of the man page installed by default, but saying essentially the same).


How to pass inputs from file to dns.resolver.Resolver.query() from file in dns python?

Question: I am writing a code to pass domain name and ip address from file to dns resolver query. But it does not seem to be working
import dns.resolver
import os
import sys

d = open(str(sys.argv[1]),'r') #contains the domain name list
ip = open(str(sys.argv[2]),'r') # contain the list of ip address as dns resolver

domain_list = d.readlines()
ip_list = ip.readlines()
my_resolver = dns.resolver.Resolver()
output_f = open("output.txt",'a')
for nameserv in ip_list:
        my_resolver.nameservers = [nameserv]
        for domain in domain_list:
                try:
                        answer = my_resolver.query(domain)
                        entry = "server : " + "   " + nameserv + " " + "query_result " + str(answer) + '\n'
                        output_f.write(entry)
                except :
                        print domain,nameserv
                        print "no domain"

d.close()
ip.close()
output_f.close()

My ip address list contains 184.108.40.206 and 127.0.1.1 which are both valid dns resolvers. domain list contain www.facebook.com,www.urltrends.com etc
Still i am getting error that no domain exists.
Answer: readlines() also reads the trailing \n, which then gets passed to the resolver.  Try this instead:
my_list = open(filename, 'r').read().splitlines()

Comment: Thanks a lot. It was exactly what i was looking for.


What is the right way to normalize satellite images to feed into a Nerual network?

Question: I am trying to feed small patches of satellite image data (landsat-8 Surface Reflectance Bands) into neural networks for my project. However the downloaded image values range from 1 to 65535.
So I tried dividing images by 65535(max value) but plotting them shows all black/brown image like this!

But most of the images do not have values near 65535
Without any normalization the image looks all white.

Dividing the image with 30k looks like this.

If the images are too dark or too light my network may not perform as intended.
Is dividing the image with max value possible (65535) the only solution or are there any other ways to normalize images especially for satellite data?
Comment: What was the normalization method used to train the NN? You use the same one.
Comment: i didn't yet train the model. I visualized these imgs and they turned to out to be like this after normalization.
Answer: There are other ways to normalize images. Standardization is the most common way (subtract the mean and divide by the standard deviation).
Using numpy...
<code>image = (image - np.mean(image)) / np.std(image)
</code>
As I mentioned in a clarifying comment, you want the normalization method to match how the NN training set.
Answer: There is a really good blog by Sentinel Hub on different normalization schemes that can be used to normalize satellite images https://medium.com/sentinel-hub/how-to-normalize-satellite-images-for-deep-learning-d5b668c885af
Main issue with these data is that they are heavy-tailed and therefore require special treatment to handle pixel values that lie in the tail end as they can greatly influence the normalization values. In the blog you can see that normalization based on min/max is the worst possible option and any scheme that are based on percentiles tend to perform well as they can handle outliers. In my personal experience, dynamic world method of using log normalization has given the best result because you perform normalization in the log space which converts the heavy-tailed distribution to a normal distribution.
Also, please note that even though the image is 16 bit, the almost all of the pixel values will be much smaller than 65535. This is because satellite images are reflectance values which are bounded away from 0. Majority of the objects on earth including vegetation don't have high reflectance.


Are these two theorems about algebraic varieties the same?

Question: In Artin's Algebra, there is a theorem (1) stated as the following:

Let $J\subset\Bbb{C}[x]$ be an ideal such that $J=(f_1,\cdots,f_r)$ where $f_1,\cdots,f_r\in\Bbb{C}[x_1,\cdots,x_n]$. Let $R=\Bbb{C}[x_1,\cdots,x_n]/J$. Let $V$ be the set of common zeros of $\{f_1,\cdots,f_r\}$. Then the maximal ideals of $R$ are in bijective correspondence with the points of $V$.

There is another statement (2) (I don't remember where I learned it from) I've seen before:

Let $V\subset{C}^n$ be a variety. Then there is a bijective correspondence between points in $V$ and maximal ideals in ${\Bbb C}[x_1,\cdots,c_n]/I(V)$, where
  $$
I(V):=\{f\in{\Bbb C}[x_1,\cdots,x_n]:\forall x\in V\ \ f(x)=0\}
$$
  is an ideal.

Here are my questions:

Are these two statements the same?
Can anyone come up with a reference for (2)? (If I state (2) in a wrong way, can somebody correct it?)

I know almost nothing about algebraic geometry and commutative algebra. I came up with this question when I read Artin's Algebra, in which there is a small section about algebraic geometry. I suspect that (2) is different from (1). Suppose in (2) $V$ is the set of common zeros of $\{f_1,\cdots, f_r\}$. Then $I(V)$ might be strictly bigger than $(f_1,\cdots, f_r)$.

The definition of algebraic variety $V\subset{\Bbb C}^n$ I use here (in Artin's book) is the set of common zeros of finitely many polynomials in $n$ variables.
Answer: Yes, these are the same theorems, basically. The theorem that ties the two together is the following (Nullstellensatz):
Theorem: There is a bijection between radical ideals $I\subseteq \mathbb{C}[x_1,\ldots,x_n]$ (that is, ideals that satisfy $I=\{f\in \mathbb{C}[x_1,\ldots,x_n]:f^r\in I\mbox{ for some }r\in\mbox{N}\}$) and sets that are of the form
$$\{a=(a_1,\ldots,a_n)\in \mathbb{C}^n:g_1(a)=\cdots=g_s(a)=0\}$$
for certain polynomials $g_1,\ldots,g_s$, given by $I\mapsto V(I)$, where $V(I)$ denotes the zero set of the polynomials in $I$.
The inverse map above is given by $\Phi:X\mapsto\{f\in \mathbb{C}[x_1,\ldots,x_n]:f(x)=0\mbox{ for all }x\in X\}$.
Basically, if $J$ is an ideal in $\mathbb{C}[x_1,\ldots,x_n]$, then $\Phi(V(J))=\mbox{rad}(J)$, where
$$\mbox{rad}(J)=\{f\in\mathbb{C}[x_1,\ldots,x_n]:f^r\in J\}.$$
Now the idea that ties your two theorems together is the following:
The maximal ideals of $\mathbb{C}[x_1,\ldots,x_n]/J$ are in bijection with the maximal ideals of $\mathbb{C}[x_1,\ldots,x_n]/\mbox{rad}(J)$.
Proof: Since $J\subseteq\mbox{rad}(J)$, if $\frak{m}$ is a maximal ideal that contains $\mbox{rad}(J)$, then $\frak{m}$ contains $J$. We must show that the converse is true. If $\frak{m}$ contains $J$, let $f\in\mbox{rad}(J)$. Then $f^r\in J$ for some $J$, and therefore $f^r\in \frak{m}$. Since $\frak{m}$ is prime, we have that $f$ must be in $\frak{m}$. $\Box$
Comment: The point is that they're not the same; we have that $I(V(J))=\mbox{rad}(J)$. For example, take $J=(x^2)$ in $\mathbb{C}[x]$. Then $V(J)=\{x\in\mathbb{C}:x^2=0\}=\{0\}$, and so $I(V(J))=(x)$. However, the maximal ideals that contain $J$ and $I(V(J))$ are the same, and so we have the bijection I put above.
Comment: As I see from the strong nullstellensatz, $J$ in (1) are different from $I(V)$ in (2). How does the nullstellensatz make (1) and (2) the same?
Comment: Fair enough. The first theorem you quoted is the strong nullstellensatz. I was confused by the second proposition that you also call it nullstellensatz.
Comment: You first say "The theorem that ties the two together is the folloing (Nullstellensatz)". And then you say "Now the idea that ties your two theorems together is the following (Nullstellensatz)".
Comment: Dear @Jack: Sorry about that! I only meant to put it on the first theorem but I think I accidentally copied and pasted it on the second one too. I edited the answer.


Argument of type 'Object' is not assignable to parameter of type 'string'

Question: My application works fine but I have the following error:

Argument of type 'Object' is not assignable to parameter of type
  'string')

Below my code:
public login(userData: any): Observable<any> {
    return this.http
      .post("/api/users/login", userData)
      .map(token => this.saveToken(token));
}

private saveToken(token: string): string {
    localStorage.setItem("car_auth", token);
    return token;
}

Answer: As the error say, you assign Object to string.
Try to replace your code like that:
public login(userData: any): Observable<string> {
    return this.http
      .post("/api/users/login", userData)
      .map((token: string) => this.saveToken(token));
}

private saveToken(token: string): string {
    localStorage.setItem("car_auth", token);
    return token;
}

Comment: it say cannot find name "token"
Comment: .map((token: string )=> this.saveToken(token));
Answer: Transcompiler needs a hint of what your  http.post returns because you typed the argument of saveToken. Transcompiler wants to make sure you're passing a string.
add explicit type :
public login(userData: any) {
  return this.http
    .post("/api/users/login", userData)
    .map((token: string) => this.saveToken(token));
}

Comment: it say cannot find name "token"
Comment: its work thanks first i create typo mistake thanks alot


How to intercept and change sql query dynamically in mybatis

Question: I use mybatis to perform sql queries in my project. I need to intercept sql query before executing to apply some changed dynamically. I've read about @Interseptors like this:
<code>@Intercepts({@Signature(type= Executor.class, method = "query", args = {...})})
public class ExamplePlugin implements Interceptor {
  public Object intercept(Invocation invocation) throws Throwable {
    return invocation.proceed();
  }
  public Object plugin(Object target) {
    return Plugin.wrap(target, this);
  }
  public void setProperties(Properties properties) {
  }
}
</code>
And it really intercepts executions, but there is no way to change sql query since appropriate field is not writable. Should I build new instance of whole object manually to just replace sql query? Where is the right place to intercept query execution to change it dynamically? Thank.
Answer: I hope it will help you:
<code>@Intercepts( { @Signature(type = Executor.class, method = "query", args = {
        MappedStatement.class, Object.class, RowBounds.class,
        ResultHandler.class
    })
})
public class SelectCountSqlInterceptor2 implements Interceptor
{
    public static String COUNT = "_count";
    private static int MAPPED_STATEMENT_INDEX = 0;
    private static int PARAMETER_INDEX = 1;
    @Override
    public Object intercept(Invocation invocation) throws Throwable
    {
        processCountSql(invocation.getArgs());
        return invocation.proceed();
    }
    @SuppressWarnings("rawtypes")
    private void processCountSql(final Object[] queryArgs)
    {
        if (queryArgs[PARAMETER_INDEX] instanceof Map)
        {
            Map parameter = (Map) queryArgs[PARAMETER_INDEX];
            if (parameter.containsKey(COUNT))
            {
                MappedStatement ms = (MappedStatement) queryArgs[MAPPED_STATEMENT_INDEX];
                BoundSql boundSql = ms.getBoundSql(parameter);
                String sql = ms.getBoundSql(parameter).getSql().trim();
                BoundSql newBoundSql = new BoundSql(ms.getConfiguration(),
                                                    getCountSQL(sql), boundSql.getParameterMappings(),
                                                    boundSql.getParameterObject());
                MappedStatement newMs = copyFromMappedStatement(ms,
                                        new OffsetLimitInterceptor.BoundSqlSqlSource(newBoundSql));
                queryArgs[MAPPED_STATEMENT_INDEX] = newMs;
            }
        }
    }
    // see: MapperBuilderAssistant
    @SuppressWarnings({ "unchecked", "rawtypes" })
    private MappedStatement copyFromMappedStatement(MappedStatement ms,
            SqlSource newSqlSource)
    {
        Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms
                .getId(), newSqlSource, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        // setStatementTimeout()
        builder.timeout(ms.getTimeout());
        // setParameterMap()
        builder.parameterMap(ms.getParameterMap());
        // setStatementResultMap()
        List<ResultMap> resultMaps = new ArrayList<ResultMap>();
        String id = "-inline";
        if (ms.getResultMaps() != null)
        {
            id = ms.getResultMaps().get(0).getId() + "-inline";
        }
        ResultMap resultMap = new ResultMap.Builder(null, id, Long.class,
                new ArrayList()).build();
        resultMaps.add(resultMap);
        builder.resultMaps(resultMaps);
        builder.resultSetType(ms.getResultSetType());
        // setStatementCache()
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }
    private String getCountSQL(String sql)
    {
        String lowerCaseSQL = sql.toLowerCase().replace("\n", " ").replace("\t", " ");
        int index = lowerCaseSQL.indexOf(" order ");
        if (index != -1)
        {
            sql = sql.substring(0, index);
        }
        return "SELECT COUNT(*) from ( select 1 as col_c " + sql.substring(lowerCaseSQL.indexOf(" from "))  + " )   cnt";
    }
    @Override
    public Object plugin(Object target)
    {
        return Plugin.wrap(target, this);
    }
    @Override
    public void setProperties(Properties properties)
    {
    }
}
</code>
Answer: You may consider using a string template library (eg Velocity, Handlebars, Mustache) to help you
As of to date, there is even MyBatis-Velocity (http://mybatis.github.io/velocity-scripting/) to help you to do scripting for the sql.
Comment: do you have an example for this? I don't find the document much usefull
Answer: Depending on the changes you want to make, you may want to use the dynamic sql feature of mybatis 3


Using the squeeze principle to evaluate the following limit

Question:
This is my teacher's work. I am stuck on the part where I circled it red. From what I understand, he squared every side, so (-1)^2, the cos^2, and the 1^2. Why did (-1)^2 change to 0?
Comment: $cos^2(3x+1)$ is non-negative.
Answer: the $-1$ did not turn into $0$, the inequality $0\leq \cos^2 (3x+1)$ comes from the fact that $x^2\geq0$ if $x$ is a real number.
The statement $0\leq \cos^2(3x+1) \leq 1$ is actually composed of two inequalities. One, $\cos^2(3x+1)\leq 1$, comes from the fact that $\cos(3x+1)$ is between $-1$ and $1$. The other, $\cos^2(3x+1)\geq 0$, comes from the fact that $\cos^2(3x+1)$ is the square of a real number, and squares of all real numbers are non-negative.
Comment: i still don't understand what you mean?
Comment: @Kaaagome How about now?
Comment: @bof Fixed it, thank you
Answer: Exercise: Let $a\geqslant0$ and $b\geqslant0$, then the following equivalences hold.

$a\leqslant x\leqslant b\iff a^2\leqslant x^2\leqslant b^2$
$-a\leqslant x\leqslant b\iff 0\leqslant x^2\leqslant\max(a,b)^2$

Hint: Plot a graph of the function $x\mapsto x^2$, say on the interval $[-4,3]$.
Comment: It's the most reasonable answer to be honest.
Comment: @ChantryCargill Thanks but please do not upvote to compensate other votes. (You know, that this answer is downvoted, being clearly absurd to anyone reading it (I think), is actually *useful* if it makes people think about the meaning of votes on the site.)
Comment: Sweet downvoters...
Comment: Let me even that out for you .. Edit: Ahh, I'm at my vote limit, never mind.
Comment: I think the downvoter only read the first part of your question, where it seems as though you only stated your two bullet points qwithout explaining them. I don't think this answer deserves a downvote.
Comment: @5xum Charitable conjecture: every answer on the page received two downvotes because two users think the question should not be answered, and none of them knows how to "close" a question, and only one of the pair thought about downvoting the question itself. Hmmm... Not sure that this explanation holds water, after all. :-)
Answer: Notice that $\cos(a) = 0$ when $a = \frac{\pi}{2} + n\pi$ for $n \in \mathbb{Z}$.
Thus, $\cos^2(a) = 0$. What does this say about the interval in question?
Another way to look at it is that the cosine function can evaluate to any value in $[-1,0] \cup [0,1]$. So when we square it, it becomes $[0,1]$.
What values are between $-1$ and $1$? Well, there's $-0.9$, which squares is $0.81$. There's $-0.5$, which squares is $0.25$. If we keep going we eventually get to $0$, which squared is still $0$. Then we have all the values from $0$ to $1$.
So as you can see, the interval becomes $[0,1]$. No matter how you look at it.


Stuck on large numbers

Question: i've got a problem. I need to prove that $43^{47}-17^{17}$ is divisible by $10$.
I think that somehow I have to prove that the number ends with a $0$.
Any ideas?
Comment: what does the title have to do with the question???
Comment: Welcome to math.SE! This question is missing context or other details: Please improve the question by providing additional context, which ideally includes your thoughts on the problem and any attempts you have made to solve it. This information helps others identify where you have difficulties and helps them write answers appropriate to your experience level.
Comment: When you say 43 times 47, you mean $43^{47}$ or $43\times 47$?
Comment: Assuming you meant $43*47-17*17$, this is easy enough to do by hand (and I assume you meant + instead of -).
Comment: sorry im not a native speaker. I meant in as  43*43*43*43....(total times of 47) - 17*17*17*17 (total times of 17). and i meant -

Sorry for the bad english.
Comment: Since the expression is clearly even you can work on divisibility by $5$ rather than $10$.
Answer: HINT:

$43^{47}\equiv3^{47}\equiv3^{4\cdot11+3}\equiv(3^4)^{11}\cdot3^3\equiv81^{11}\cdot27\equiv1^{11}\cdot7\equiv1\cdot7\equiv7\pmod{10}$
$17^{17}\equiv7^{17}\equiv7^{4\cdot4+1}\equiv(7^4)^{4}\cdot7^1\equiv2401^{4}\cdot7\equiv1^{4}\cdot7\equiv1\cdot7\equiv7\pmod{10}$
Comment: Looks more like a complete solution to me :-)
Comment: @A.G.: Yeah well let's just call it a "BIG HINT" :)
Answer: HINT:
As $43\equiv3\pmod{10},17\equiv7,\phi(10)=4$
$$43^{47}-17^{17}\equiv3^3-7^1\pmod{10}$$
Comment: @user37238, I believe it to be exponent as $43\cdot47-17\cdot17\equiv2\not\equiv0\pmod{10}$
Comment: When you see the question with "43 times 47", you immediately think that the author means $43^{47}$? Because I immediately think the author means $43\times 47$.
Comment: i meant it as (43*43*43*43*43*43....) total times of 47
Comment: @Arnas, That is same as $43^{47}$
Comment: @lab bhattacharjee yes

Stuck on large numbers


Matriz de Expressão

Question: Eu tenho a matriz a seguir no R:
 FC12h         FC10d        FC6w

-8.44770875  -0.37171750    0
-56.72384575  2.64778150    2.94636550
-3.00214850   2.64778150   -1.57755700

Eu preciso de alguma função que faça com que os numeros maiores que zero fiquem com valor igual a 1, menor que zero valor igual a -1, e quando 0 fique igual a 0:
  FC12h         FC10d        FC6w

   -1          -1             0
   -1           1             1
   -1           1            -1

Alguém sabe como posso fazer isso?
Answer: A maneira mais fácil é com a função sign. Mais simples não pode ser:
sign(dados)
#  FC12h FC10d FC6w
#1    -1    -1    0
#2    -1     1    1
#3    -1     1   -1

Dados.
dados <- read.table(text = "
FC12h         FC10d        FC6w
-8.44770875  -0.37171750    0
-56.72384575  2.64778150    2.94636550
-3.00214850   2.64778150   -1.57755700
", header = TRUE)

Comment: bem mais simples.
Comment: Muito interessante, não sabia dessa função. Vou testar.
Answer: Sendo dados sua matriz,
ifelse(dados < 0, -1, ifelse(dados > 0, 1, 0) )

vai retornar o que você espera.
A função ifelse está testando se os valores de dados são negativos (dados < 0). Caso seja verdadeira, será atribuído o valor -1, caso contrário, outro teste é realizado. Agora testamos se os valores de dados são positivos (dados > 0). Caso seja verdadeiro, atribuímos o valor 1, senão será igual a 0.
O código indentado, usando if e else fica:
for(i in 1:nrow(dados)){
  for(j in 1:ncol(dados)){
    if(dados[i,j] < 0){
      dados[i,j] <- -1
    } else{
      if(dados[i,j] > 0){
        dados[i,j] <- 1
      } else{
        dados[i,j] <- 0
      }
    }
  }
}

Comment: Oi, não entendi muito bem. Como seria seu código indentado?
Comment: Vlw, cara. Muito obrigado. Deu certo!!!!
Comment: Considere [aceitar](https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta) a resposta que te ajudou a resolver o problema.

Matriz de Expressão


Combinatorics: likelihood of a uniform draw

Question: An urn contains 10 kinds of pebbles, and 100 pebbles of each kind. We draw 100 pebbles (without replacement). What is the probability that we get between 8 and 12 pebbles of each kind?
Comment: wouldn't this mean that there is a probability to draw 12 pebbles of each kind, while we only draw 100 pebbles?
Comment: Find the probability that, say, Type A is picked 8 times, 9 times, 10 times, 11 times and 12 times. Add those up. Put the sum to the power of 10 and there's your answer.
Comment: @Alexis: Yes, that, and it would assume that these events are independent, which they aren't.
Comment: Do we draw with or without replacement?
Comment: without replacement (updated)
Answer: The most likely of the admissible combinations is the completely uniform one, with a probability of
$$
\frac{\binom{100}{10}^{10}}{\binom{1000}{100}^{\hphantom{10}}}\approx3.8\cdot10^{-8}
$$
(computation). Presumably the most unlikely of the admissible combinations is the most non-uniform one with $12$ pebbles of five kinds and $8$ of the others, with a probability of
$$
\frac{\binom{100}{12}^5\binom{100}8^5}{\binom{1000}{100}}\approx4.5\cdot10^{-9}
$$
(computation). The number of admissible combinations can be calculated using the formula at the bottom of this page as the number of ways of distributing $k=20$ excess pebbles over $m=10$ kinds with a capacity of $R=4$ each, which yields
$$
\sum_{t=0}^4(-1)^t\binom{10}t\binom{29-5t}9=856945
$$
(computation). Thus the desired probability $p$ satisfies
$$
0.03\approx 856945\cdot\frac{\binom{100}{10}^{10}}{\binom{1000}{100}^{\hphantom{10}}}\gt p\gt 856945\cdot\frac{\binom{100}{12}^5\binom{100}8^5}{\binom{1000}{100}}\approx0.004\;.
$$
The exact answer is
<code> 226031412377730730814344253428220298277915460779610728832457924491489212422618433457300376001429754322127222112213012269223936000000000
—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
18724490300969246403723903560710344364006715745998044509175019419801870086437214647777411833371759499800416660391039940703106220925825529
</code>
or about $0.012$, as computed by this code, which enumerates all admissible combinations and checks the result with a simulation (and also checks the number of admissible combinations).
Comment: So the geometric mean of the bounds $0.03$ and $0.004$, which is about $0.011$, isn't a bad estimate.
Comment: The "Balls In Bins With Limited Capacity" formula looks like a good tool I'll keep in mind! I was struggling to find a formula giving the final result but it seems that there would not be any satisfactory one. Thank you very much for this detailed answer, the estimate formula looks good enough to reuse. I'd thought the probability would be higher...
Comment: @Alexis: You're welcome!


c++ strange variable values

Question: I have a code snippet that is just originating two int values for the first time. Here's the line of code:
int xb2,yb2 = 0;

But, according to the debugger, when it hits this line of code, the value of xb2 is 4262504!
What could have caused this?
By the way, sorry if I am missing something obvious, I am new to C++.
Comment: Maybe, I think the latter one might be more likely. Thank for the input!
Answer: xb2 is set to 4262504 (some arbitrary value, usually whatever happened to be at that location on the stack beforehand) because you never initialized it to 0.
The correct way to do it is
int xb2 = 0, yb2 = 0;

In addition, you state it's a strange value "when it hits this line of code". Make sure you actually execute that line in the debugger. If the cursor position or highlight is on that line, it usually means it's the one to be executed next. In other words, you may need to do one more step operation.
Comment: Oh okay :) I thought, coming from other languages, that doing what I did above would set both the values to zero. Thank you!
Comment: I just tested it, and it doesn't appear to be working.
Comment: @CodeCube, then you have a _separate_ issue, the code provided will initialise `xb2` just fine.
Comment: @paxdiablo why not write your own answer?
Comment: looks like for some odd reason I have to put an additional line below that saying xb2 = 0;
Comment: @NeilKirk, because my answer would basically be the same as this one, with some added stuff. Where the answer is essentially correct, I prefer just to clean it up if I think it could be phrased better. In the early days, I may have put up my own answer to do a bit of rep-seeking but it's hardly necessary now :-)
Comment: @CodeCube, if that's truly the case then either your compiler is seriously broken, or you're doing something else wrong that's not immediately obvious from the code posted. My bet's on the latter :-)
Comment: Probably, for now I will just add xb2 = 0; as a separate line because it works.
Answer: Your code
int xb2,yb2 = 0;

is just setting the value 0 to yb2,
try this:
int xb2=0,yb2=0;

c++ strange variable values


Nilpotent element in Ring of continuous function.

Question: Let $C[0,1]$ denote the ring of continuous function on compact set $[0,1]$.
I have already checked that this ring is not an integral domain.
$$f(x)=\begin{cases}0&\text{if}\;\;\;0\leq x<\frac{1}{2}\\2x-1&\text{if}\;\;\;\frac{1}{2}\leq x\leq 1\end{cases}$$
$$g(x)=\begin{cases}-2x+1&\text{if}\;\;\;0\leq x<\frac{1}{2}\\0&\text{if}\;\;\;\frac{1}{2}\leq x\leq 1\end{cases}$$
Lemma: We can show that if $R $ is an integral domain then $0 $ is the only nilpotent element in the ring.
Proof: Let $a\in R, a\neq 0$ and suppose $a^n=0$ for some $n>1$
$$a^n=aa^{n-1}=0$$ which imply that $a=0$ as $R$ is integral domain.
Main Question
Since $R=C[0,1]$ is not an integral domain, should I expect some nilpotent elements. I am not able to construct such element.
May be I am wrong and this ring work as an counterexample to the converse of the above lemma.
Comment: Another example of a non-integral domain lacking nilpotents is $\mathbb Z/6\mathbb Z$
Answer: There are no nilpotent elements (save the zero element): $C[0,1]$ is a reduced ring.
The proof is immediate: if $f\in C[0,1]$ and $f^n=0$, then $f(x)^n=0$
for all $x\in[0,1]$, so that $f(x)=0$ for all $x\in[0,1]$.


Continuity of reciprocal norm fuction

Question: How can I prove by definition the continuity of $f(x,y)=\frac{1}{\sqrt{x^2+y^2}}$ where $(x,y)\ne (0,0)$. How can I set the value at $(0,0)$ to make it continuous?
I think that the continuity in $(0,0)$ is not possible, using trajectories, but I'm not able to see which is the $\delta$ in the definition given any $\varepsilon>0$.
Answer: You are right that there is no value at the origin that will make $f$ continuous since $f(x,y) \to +\infty$ as $(x,y)\to (0,0)$. Let's write $\vec x = (x,y) \ne (0,0) = \vec 0$ and let $\vec h = (h,k)$. I'll use $\|\vec x\|$ as shorthand for $\sqrt{x^2 + y^2}$. To prove continuity of $f$ at the point $\vec x$, we want to bound the difference
$$
\bigg|\frac{1}{\|\vec x + \vec h\|} - \frac{1}{\|\vec x\|}\bigg| = \frac{\big| \|\vec x + \vec h\| - \|\vec x\|\big|}{\|\vec x + \vec h\|\cdot\|\vec x\|}.
$$
Use the reverse triangle inequality to bound the numerator. If $\|\vec h\|$ is sufficiently small, say $\|\vec h\| < \|\vec x\|\big/2$, then $\|\vec x + \vec h\| > \|\vec x\|\big/2$. Try taking it from there.

Continuity of reciprocal norm fuction